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
+85
View File
@@ -0,0 +1,85 @@
<script lang="ts">
import type { Snippet } from 'svelte';
let {
variant = 'primary',
size = 'md',
disabled = false,
type = 'button',
href,
onclick,
children,
class: extraClass = '',
}: {
variant?: 'primary' | 'secondary' | 'danger' | 'ghost';
size?: 'sm' | 'md';
disabled?: boolean;
type?: 'button' | 'submit';
href?: string;
onclick?: (e: MouseEvent) => void;
children: Snippet;
class?: string;
} = $props();
const baseClasses = 'inline-flex items-center justify-center gap-1.5 rounded-md text-sm font-medium transition-colors disabled:opacity-50';
const sizeClasses: Record<string, string> = {
sm: 'px-2.5 py-1 text-xs',
md: 'px-4 py-2',
};
const variantClasses: Record<string, string> = {
primary: 'btn-primary',
secondary: 'btn-secondary',
danger: 'btn-danger',
ghost: 'btn-ghost',
};
const classes = $derived(
`${baseClasses} ${sizeClasses[size]} ${variantClasses[variant]} ${extraClass}`.trim()
);
</script>
{#if href && !disabled}
<a {href} class={classes} onclick={onclick}>
{@render children()}
</a>
{:else}
<button {type} {disabled} class={classes} onclick={onclick}>
{@render children()}
</button>
{/if}
<style>
.btn-primary {
background: var(--color-primary);
color: var(--color-primary-foreground);
}
.btn-primary:hover:not(:disabled) {
opacity: 0.9;
}
.btn-secondary {
background: var(--color-muted);
color: var(--color-foreground);
border: 1px solid var(--color-border);
}
.btn-secondary:hover:not(:disabled) {
opacity: 0.8;
}
.btn-danger {
background: var(--color-error-fg);
color: white;
}
.btn-danger:hover:not(:disabled) {
opacity: 0.9;
}
.btn-ghost {
background: transparent;
color: var(--color-muted-foreground);
}
.btn-ghost:hover:not(:disabled) {
background: var(--color-muted);
color: var(--color-foreground);
}
</style>
@@ -1,5 +1,6 @@
<script lang="ts">
import MdiIcon from './MdiIcon.svelte';
import { t } from '$lib/i18n';
export interface EntityItem {
value: string | number;
@@ -142,7 +143,7 @@
<div class="ep-list" bind:this={listEl} role="listbox">
{#if filtered.length === 0}
<div class="ep-empty">No matches</div>
<div class="ep-empty">{t('common.noMatches')}</div>
{:else}
{#each filtered as item, i}
<button
@@ -0,0 +1,13 @@
<script lang="ts">
interface Props {
message: string;
class?: string;
}
let { message, class: className = '' }: Props = $props();
</script>
{#if message}
<div class="bg-[var(--color-error-bg)] text-[var(--color-error-fg)] text-sm rounded-md p-3 mb-4 {className}">
{message}
</div>
{/if}
@@ -1,5 +1,6 @@
<script lang="ts">
import MdiIcon from './MdiIcon.svelte';
import { t } from '$lib/i18n';
export interface GridItem {
value: string | number;
@@ -117,7 +118,7 @@
</button>
{/each}
{#if filtered.length === 0}
<div class="icon-grid-empty" style="grid-column: 1 / -1; text-align: center; padding: 0.75rem; color: var(--color-muted-foreground); font-size: 0.75rem;">No matches</div>
<div class="icon-grid-empty" style="grid-column: 1 / -1; text-align: center; padding: 0.75rem; color: var(--color-muted-foreground); font-size: 0.75rem;">{t('common.noMatches')}</div>
{/if}
</div>
</div>
+2 -1
View File
@@ -1,6 +1,7 @@
<script lang="ts">
import { onMount } from 'svelte';
import MdiIcon from './MdiIcon.svelte';
import { t } from '$lib/i18n';
let { open = false, title = '', onclose, children } = $props<{
open: boolean;
@@ -93,7 +94,7 @@
>
<div style="display: flex; align-items: center; justify-content: space-between; padding: 1.5rem 1.5rem 1rem;">
<h3 id="modal-title-{uniqueId}" style="font-size: 1.125rem; font-weight: 600;">{title}</h3>
<button class="modal-close" onclick={onclose} aria-label="Close">
<button class="modal-close" onclick={onclose} aria-label={t('common.close')}>
<MdiIcon name="mdiClose" size={18} />
</button>
</div>
@@ -1,5 +1,6 @@
<script lang="ts">
import MdiIcon from './MdiIcon.svelte';
import { t } from '$lib/i18n';
export interface MultiEntityItem {
value: string;
@@ -132,7 +133,7 @@
<div class="mes-list" bind:this={listEl} role="listbox">
{#if filtered.length === 0}
<div class="mes-empty">No matches</div>
<div class="mes-empty">{t('common.noMatches')}</div>
{:else}
{#each filtered as item, i}
{@const checked = (values || []).includes(item.value)}
+1 -1
View File
@@ -56,7 +56,7 @@
{/if}
{/if}
</div>
<button class="snack-close" onclick={() => removeSnack(snack.id)} aria-label="Dismiss">
<button class="snack-close" onclick={() => removeSnack(snack.id)} aria-label={t('common.dismiss')}>
<MdiIcon name="mdiClose" size={14} />
</button>
</div>
+2
View File
@@ -110,6 +110,8 @@ export const previewTargetTypeItems = (): GridItem[] => [
{ value: 'email', icon: 'mdiEmailOutline', label: 'Email', desc: t('gridDesc.previewEmail') },
{ value: 'discord', icon: 'mdiChat', label: 'Discord', desc: t('gridDesc.previewDiscord') },
{ value: 'slack', icon: 'mdiSlack', label: 'Slack', desc: t('gridDesc.previewSlack') },
{ value: 'ntfy', icon: 'mdiBellOutline', label: 'ntfy', desc: t('gridDesc.previewNtfy') },
{ value: 'matrix', icon: 'mdiMatrix', label: 'Matrix', desc: t('gridDesc.previewMatrix') },
];
// --- Provider type items (derived from descriptor registry) ---
+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": "Страница не найдена",