refactor: comprehensive codebase review — security, performance, quality, UX

Security:
- Fix NUT protocol command injection (validate names against safe regex)
- Enable Jinja2 autoescape=True to prevent HTML injection via external data
- Add WebhookProviderConfig validation model

Performance:
- Shared aiohttp.ClientSession singleton (replaces 40+ per-request sessions)
- Fix 4 N+1 queries with batch IN loads (poller, scheduler, memory, broadcast)
- asyncio.gather for Gitea commands and notification dispatcher
- Add DB indexes on NotificationTrackerState.tracker_id, CommandTrackerListener
- LRU cache for compiled Jinja2 templates
- Daily EventLog cleanup job (90-day retention)
- 30s HTTP timeout on all external calls
- GROUP BY for target type counts (replaces 7 sequential queries)

Code quality:
- Extract get_owned_entity() helper (replaces 11 duplicate functions)
- Extract slot_helpers.py (load_slots, save_slots, render_template_preview)
- Extract command_utils.py (tracker lookup, last event, collection IDs)
- Extract http_session.py (shared session lifecycle)
- Provider connection validation dedup (3x → 1 helper)
- Command dispatch tables replacing if/elif chains
- Album+links fetch helper (fetch_albums_with_links)
- Provider dispatch polymorphism (list_provider_collections)
- Immutable _enrich_assets (no longer mutates in-place)
- Fix _format_assets return type + handler unpacking

Frontend:
- Fix 18+ hardcoded English strings → t() with new i18n keys (en + ru)
- Mobile "More" nav panel with provider filter and search
- Shared Button.svelte component (4 variants, 2 sizes)
- Shared ErrorBanner.svelte component (8 pages updated)
- SvelteKit goto() replacing window.location.href
- Dashboard grid fixed for 4 cards, paginator opacity consistency

Functionality:
- max_instances=1 on scheduler jobs (prevents duplicate events)
- Webhook provider in watcher (prevents error spam)
- Fix stale SQLModel reference in poller
- Gitea get_repo() direct API call
This commit is contained in:
2026-03-28 13:22:26 +03:00
parent 616b221c92
commit b803d004e1
65 changed files with 1934 additions and 1498 deletions
+28 -10
View File
@@ -36,7 +36,8 @@
"targetMatrix": "Matrix",
"targetBroadcast": "Broadcast",
"automation": "Automation",
"actions": "Actions"
"actions": "Actions",
"more": "More"
},
"auth": {
"signIn": "Sign in",
@@ -51,7 +52,9 @@
"creatingAccount": "Creating account...",
"passwordMismatch": "Passwords do not match",
"passwordTooShort": "Password must be at least 8 characters",
"or": "or"
"or": "or",
"loginFailed": "Login failed",
"setupFailed": "Setup failed"
},
"dashboard": {
"title": "Dashboard",
@@ -150,7 +153,9 @@
"gpRefreshTokenHint": "Obtain from Google OAuth Playground (developers.google.com/oauthplayground) with the Photos Library API scope.",
"gpAllFieldsRequired": "Client ID, Client Secret, and Refresh Token are all required",
"testAndSave": "Test & Save",
"saveWithoutTest": "Save without testing"
"saveWithoutTest": "Save without testing",
"selectType": "Select a provider type",
"testFailed": "Connection test failed"
},
"notificationTracker": {
"title": "Notification Trackers",
@@ -231,7 +236,8 @@
"noLink": "No Link",
"saveWithoutLinks": "Save without links",
"createLinks": "Create {count} link(s)",
"linksNote": "You can also create links manually in Immich."
"linksNote": "You can also create links manually in Immich.",
"createdLinks": "Created {count} public link(s)"
},
"templates": {
"title": "Templates",
@@ -409,7 +415,9 @@
"cacheTtl": "Media cache TTL (hours)",
"cacheTtlHint": "How long to cache uploaded Telegram file_ids before re-uploading (default: 48h)",
"settingsSaved": "Settings saved",
"noExternalDomain": "External domain URL not configured"
"noExternalDomain": "External domain URL not configured",
"saveFailed": "Failed to save bot",
"webhookFailed": "Failed to register webhook"
},
"trackingConfig": {
"title": "Tracking Configs",
@@ -584,7 +592,7 @@
"added_assets": "List of asset dicts (use {% for asset in added_assets %})",
"removed_assets": "List of removed asset IDs (strings)",
"shared": "Whether album is shared (boolean)",
"target_type": "Target type: 'telegram' or 'webhook'",
"target_type": "Target type: telegram, webhook, email, discord, slack, ntfy, or matrix",
"has_videos": "Whether added assets contain videos (boolean)",
"has_photos": "Whether added assets contain photos (boolean)",
"old_name": "Previous album name (rename events)",
@@ -675,7 +683,8 @@
"displayName": "Display Name",
"testConnection": "Test connection",
"noBots": "No Matrix bots yet.",
"confirmDelete": "Delete this Matrix bot?"
"confirmDelete": "Delete this Matrix bot?",
"operationFailed": "Operation failed"
},
"emailBot": {
"title": "Email Bots",
@@ -693,7 +702,8 @@
"useTls": "Use TLS/SSL",
"testConnection": "Send test email",
"noBots": "No email bots yet.",
"confirmDelete": "Delete this email bot?"
"confirmDelete": "Delete this email bot?",
"operationFailed": "Operation failed"
},
"cmdTemplateConfig": {
"title": "Command Templates",
@@ -841,7 +851,12 @@
"allTypes": "All types",
"allProviders": "All providers",
"noFilterResults": "No items match the current filter.",
"redirecting": "Redirecting..."
"redirecting": "Redirecting...",
"noMatches": "No matches",
"saveFailed": "Save failed",
"loadFailed": "Failed to load data",
"dismiss": "Dismiss",
"systemSuffix": " (System)"
},
"templateSlot": {
"message_assets_added": "New assets added to album",
@@ -926,12 +941,15 @@
"previewEmail": "Preview with email HTML format",
"previewDiscord": "Preview with Discord markdown",
"previewSlack": "Preview with Slack markdown",
"previewNtfy": "Preview as ntfy notification",
"previewMatrix": "Preview with Matrix HTML format",
"providerImmich": "Self-hosted photo server",
"providerGitea": "Self-hosted Git service",
"providerPlanka": "Self-hosted Kanban board",
"providerScheduler": "Time-based scheduled messages",
"providerNut": "Network UPS monitoring",
"providerGooglePhotos": "Google Photos albums & shared libraries"
"providerGooglePhotos": "Google Photos albums & shared libraries",
"providerWebhook": "Receive events via HTTP POST"
},
"error": {
"notFound": "Page not found",
+28 -10
View File
@@ -36,7 +36,8 @@
"targetMatrix": "Matrix",
"targetBroadcast": "Рассылка",
"automation": "Автоматизация",
"actions": "Действия"
"actions": "Действия",
"more": "Ещё"
},
"auth": {
"signIn": "Войти",
@@ -51,7 +52,9 @@
"creatingAccount": "Создание...",
"passwordMismatch": "Пароли не совпадают",
"passwordTooShort": "Пароль должен быть не менее 8 символов",
"or": "или"
"or": "или",
"loginFailed": "Ошибка входа",
"setupFailed": "Ошибка настройки"
},
"dashboard": {
"title": "Главная",
@@ -150,7 +153,9 @@
"gpRefreshTokenHint": "Получите через Google OAuth Playground (developers.google.com/oauthplayground) с областью Photos Library API.",
"gpAllFieldsRequired": "Client ID, Client Secret и Refresh Token обязательны",
"testAndSave": "Проверить и сохранить",
"saveWithoutTest": "Сохранить без проверки"
"saveWithoutTest": "Сохранить без проверки",
"selectType": "Выберите тип провайдера",
"testFailed": "Ошибка проверки подключения"
},
"notificationTracker": {
"title": "Трекеры уведомлений",
@@ -231,7 +236,8 @@
"noLink": "Нет ссылки",
"saveWithoutLinks": "Сохранить без ссылок",
"createLinks": "Создать {count} ссылку(и)",
"linksNote": "Вы также можете создать ссылки вручную в Immich."
"linksNote": "Вы также можете создать ссылки вручную в Immich.",
"createdLinks": "Создано публичных ссылок: {count}"
},
"templates": {
"title": "Шаблоны",
@@ -409,7 +415,9 @@
"cacheTtl": "TTL кэша медиа (часы)",
"cacheTtlHint": "Сколько хранить кэш Telegram file_id перед повторной загрузкой (по умолчанию: 48ч)",
"settingsSaved": "Настройки сохранены",
"noExternalDomain": "Внешний URL домена не настроен"
"noExternalDomain": "Внешний URL домена не настроен",
"saveFailed": "Не удалось сохранить бота",
"webhookFailed": "Не удалось зарегистрировать webhook"
},
"trackingConfig": {
"title": "Конфигурации отслеживания",
@@ -584,7 +592,7 @@
"added_assets": "Список файлов ({% for asset in added_assets %})",
"removed_assets": "Список ID удалённых файлов (строки)",
"shared": "Общий альбом (boolean)",
"target_type": "Тип получателя: 'telegram' или 'webhook'",
"target_type": "Тип получателя: telegram, webhook, email, discord, slack, ntfy или matrix",
"has_videos": "Содержат ли добавленные файлы видео (boolean)",
"has_photos": "Содержат ли добавленные файлы фото (boolean)",
"old_name": "Прежнее название альбома (при переименовании)",
@@ -675,7 +683,8 @@
"displayName": "Отображаемое имя",
"testConnection": "Проверить подключение",
"noBots": "Matrix ботов пока нет.",
"confirmDelete": "Удалить этот Matrix бот?"
"confirmDelete": "Удалить этот Matrix бот?",
"operationFailed": "Операция не удалась"
},
"emailBot": {
"title": "Email боты",
@@ -693,7 +702,8 @@
"useTls": "Использовать TLS/SSL",
"testConnection": "Отправить тестовое письмо",
"noBots": "Email ботов пока нет.",
"confirmDelete": "Удалить этот email бот?"
"confirmDelete": "Удалить этот email бот?",
"operationFailed": "Операция не удалась"
},
"cmdTemplateConfig": {
"title": "Шаблоны команд",
@@ -841,7 +851,12 @@
"allTypes": "Все типы",
"allProviders": "Все провайдеры",
"noFilterResults": "Нет элементов, соответствующих фильтру.",
"redirecting": "Перенаправление..."
"redirecting": "Перенаправление...",
"noMatches": "Ничего не найдено",
"saveFailed": "Не удалось сохранить",
"loadFailed": "Не удалось загрузить данные",
"dismiss": "Закрыть",
"systemSuffix": " (Системный)"
},
"templateSlot": {
"message_assets_added": "Новые файлы добавлены в альбом",
@@ -926,12 +941,15 @@
"previewEmail": "Предпросмотр в формате Email HTML",
"previewDiscord": "Предпросмотр в формате Discord",
"previewSlack": "Предпросмотр в формате Slack",
"previewNtfy": "Предпросмотр уведомления ntfy",
"previewMatrix": "Предпросмотр в формате Matrix HTML",
"providerImmich": "Фотосервер для самостоятельного размещения",
"providerGitea": "Git-сервер для самостоятельного размещения",
"providerPlanka": "Канбан-доска для самостоятельного размещения",
"providerScheduler": "Запланированные сообщения по расписанию",
"providerNut": "Мониторинг ИБП через NUT",
"providerGooglePhotos": "Альбомы и общие библиотеки Google Фото"
"providerGooglePhotos": "Альбомы и общие библиотеки Google Фото",
"providerWebhook": "Приём событий через HTTP POST"
},
"error": {
"notFound": "Страница не найдена",