Files
leocrm/app/plugins/builtins/mail/plugin.py
T
Agent Zero 98eb1d0d89
Check Cross-Plugin Imports / check (push) Has been cancelled
feat: Plugin-System Umbau — 6 Phasen komplett abgeschlossen
Phase 1: Contracts konsequent nutzen
- 12 neue contracts.py erstellt (alle 19 Plugins haben jetzt contracts)
- 4 bestehende contracts.py an zentrale ContractRegistry angepasst
- Alle 19 Plugins haben on_deactivate mit Contract-Unregister
- 0 echte problematische INTER-Plugin Imports

Phase 2: Hooks/Filters-System
- app/core/hooks.py (HookRegistry mit actions + filters)
- 15 Hook-Punkte in Core-Services (contact, auth, mail, calendar, user, dms)
- BasePlugin.on_deactivate meldet alle Hooks ab

Phase 3: Plugin-Isolation
- scripts/check_cross_plugin_imports.py (Linting-Regel)
- .github/workflows/check-cross-plugin-imports.yml (CI/CD)
- .pre-commit-cross-plugin.yaml (Pre-commit Hook)
- 155 Dateien geprueft, 0 Verstoesse

Phase 4: Plugin-Versioning
- app/plugins/semver.py (SemVer mit Parse, Compare, Pre-release)
- migration_runner.py erweitert: run_migration_down, rollback_to_version
- manifest.py: min_app_version Feld
- registry.py: App-Version-Compatibility-Check bei Installation
- GET /api/v1/plugins/updates Endpoint

Phase 5: Marketplace-Vorbereitung
- app/plugins/signature.py (Ed25519 Signatur-Validierung)
- app/plugins/quarantine.py (Plugin-Quarantine mit Validierung)
- app/models/plugin_allowlist.py + Migration 0046
- manifest.py: author, license, homepage, icon, screenshots, changelog, marketplace_tags, price
- registry.py: discover_external(), discover_all()
- POST /api/v1/plugins/install-marketplace (deaktiviert)

Phase 6: Manifest-Anpassung
- manifest.py: 12 neue Felder + SemVer/Hook-Name Validierung
- MANIFEST_SCHEMA_DOC aktualisiert
- Alle 19 Plugin-Manifeste aktualisiert
- Frontend PluginUiManifest Typ erweitert

Zusaetzliche Bug-Fixes:
- test_sample-Modul erstellt
- conftest.py Deadlock-Prevention
- SESSION_COOKIE_SECURE=true
- dump.rdb aus Git entfernt + .gitignore
- backup.py datetime.utcnow -> func.now()
- system_settings.py JSONB-Import nach oben
- tax.py Mapped[float] -> Mapped[Decimal]
- notification.py type_key-Laengen vereinheitlicht

Tests: 91 neue Tests, alle bestanden
2026-07-26 23:15:34 +02:00

121 lines
6.1 KiB
Python

"""Mail plugin — IMAP/SMTP, threading, templates, rules, PGP, delegates."""
from __future__ import annotations
import asyncio
import logging
from typing import Any
from app.plugins.base import BasePlugin
from app.plugins.manifest import PluginManifest, PluginRouteDef, FrontendMenuItem, FrontendPageRoute, FrontendDetailTab, FrontendSettingsPage
logger = logging.getLogger(__name__)
async def _auto_sync_loop() -> None:
"""Background loop: process pending sync queue, then sync all active mail accounts every 5 minutes."""
from app.plugins.builtins.mail.services import auto_sync_all_accounts, process_sync_queue
from app.core.db import get_session_factory
while True:
try:
factory = get_session_factory()
async with factory() as db:
await process_sync_queue(db)
await db.commit()
except Exception as exc:
logger.warning("process_sync_queue error: %s", exc)
try:
await auto_sync_all_accounts()
except Exception as exc:
logger.warning("auto_sync error: %s", exc)
await asyncio.sleep(60)
class MailPlugin(BasePlugin):
"""Mail plugin for email management: IMAP sync, SMTP send, threading, rules, PGP."""
_auto_sync_task: asyncio.Task | None = None
manifest = PluginManifest(
name="mail",
version="1.3.0",
display_name="Mail",
description=(
"Email management: IMAP sync, SMTP send, threading, "
"templates, rules, vacation, PGP, delegates, labels."
),
dependencies=[],
routes=[
PluginRouteDef(
path="/api/v1/mail",
module="app.plugins.builtins.mail.routes",
router_attr="router",
),
],
events=[],
migrations=["0001_initial.sql", "0006_flag_type.sql", "0007_sync_queue.sql", "0008_sync_queue_deleted_at.sql", "0009_remove_mail_soft_delete.sql", "0010_add_deleted_at.sql"],
permissions=["mail:read", "mail:send", "mail:config", "mail:share", "mail:write", "mail:delete"],
menu_items=[
FrontendMenuItem(label_key='nav.mail', label='E-Mail', path='/mail', icon='Mail', order=30),
],
page_routes=[
FrontendPageRoute(path='/mail', component='@/pages/Mail', protected=True),
FrontendPageRoute(path='/mail/settings', component='@/pages/MailSettings', protected=True),
],
settings_pages=[
FrontendSettingsPage(path='mail', label_key='settings.mail', label='Mail', component='@/pages/MailSettings', icon='Mail', order=50),
],
detail_tabs=[
FrontendDetailTab(entity_type='contact', label_key='tabs.email', label='E-Mails', component='@/components/contact/ContactMailTab', icon='Mail', order=20, permission='mail:read'),
],
author="LeoCRM Team",
min_app_version="1.0.0",
hooks=["mail.before_send", "mail.after_send"],
contract_version="1.0.0",
)
async def on_activate(
self, db, service_container, event_bus
) -> None:
"""Activate plugin: register events + start auto-sync background task."""
await super().on_activate(db, service_container, event_bus)
if self._auto_sync_task is None or self._auto_sync_task.done():
self._auto_sync_task = asyncio.create_task(_auto_sync_loop())
logger.info("Mail plugin: auto-sync background task started")
def get_notification_types(self) -> list[dict[str, Any]]:
"""Return the notification types this mail plugin registers."""
return [
{"type_key": "mail_new", "category": "mail", "label": "Neue E-Mail empfangen", "description": "Benachrichtigung bei neuen E-Mails", "is_enabled_by_default": True},
{"type_key": "mail_error", "category": "mail", "label": "IMAP-Verbindungsfehler", "description": "Fehler bei der Verbindung zum Mailserver", "is_enabled_by_default": True},
{"type_key": "mail_auth", "category": "mail", "label": "IMAP-Login-Fehler", "description": "Anmeldung am Mailserver fehlgeschlagen", "is_enabled_by_default": True},
{"type_key": "mail_quota", "category": "mail", "label": "Postfach fast voll", "description": "Warnung bei hohem Postfach-Füllstand", "is_enabled_by_default": True},
{"type_key": "mail_sync_error", "category": "mail", "label": "Sync-Fehler", "description": "Synchronisierung fehlgeschlagen", "is_enabled_by_default": True},
{"type_key": "mail_sent", "category": "mail", "label": "E-Mail gesendet", "description": "Bestätigung beim Senden einer E-Mail", "is_enabled_by_default": False},
{"type_key": "mail_send_error", "category": "mail", "label": "SMTP-Sendefehler", "description": "E-Mail konnte nicht gesendet werden", "is_enabled_by_default": True},
{"type_key": "mail_draft", "category": "mail", "label": "Entwurf gespeichert", "description": "Bestätigung beim Speichern eines Entwurfs", "is_enabled_by_default": False},
{"type_key": "mail_account", "category": "mail", "label": "Account deaktiviert", "description": "Warnung bei deaktiviertem Mail-Account", "is_enabled_by_default": True},
{"type_key": "mail_folder", "category": "mail", "label": "Ordner erstellt/gelöscht", "description": "Bestätigung bei Ordner-Operationen", "is_enabled_by_default": False},
]
async def on_deactivate(
self, db, service_container, event_bus
) -> None:
"""Deactivate plugin: stop auto-sync task + unregister events."""
# Contract abmelden
from app.plugins.builtins.contracts import get_contract_registry
get_contract_registry().unregister(self.manifest.name)
if self._auto_sync_task is not None and not self._auto_sync_task.done():
self._auto_sync_task.cancel()
try:
await self._auto_sync_task
except asyncio.CancelledError:
pass
self._auto_sync_task = None
logger.info("Mail plugin: auto-sync background task stopped")
await super().on_deactivate(db, service_container, event_bus)