feat: Discord/Slack/ntfy/Matrix targets, command templates, delete protection, email/matrix bots
- Discord, Slack, ntfy, Matrix notification target types with clients and dispatch - MatrixBot model + API + frontend in Bots tab - Command template system fully wired into all handler commands - Default command templates seeded (EN/RU, 14 slots each) - Command template editor with variables reference including child fields - Delete protection on all 10 entity types (409 with consumer details) - Provider type selector on template config forms - Target type selector as dropdown with all 7 types - Response template selector on command config form - CLAUDE.md: mandatory server restart rule, child properties rule
This commit is contained in:
@@ -2,7 +2,7 @@
|
||||
|
||||
## Development Servers
|
||||
|
||||
**IMPORTANT**: When the user requests it OR when backend code changes are made (files in `packages/server/`), you MUST restart the standalone server using this one-liner:
|
||||
**MANDATORY**: You MUST restart the backend server IMMEDIATELY after ANY backend code change (files in `packages/server/` or `packages/core/`). Do NOT wait for the user to ask — restart automatically every time. Failure to restart means the user will test against stale code and encounter bugs that don't exist. Use this one-liner:
|
||||
```bash
|
||||
PID=$(netstat -ano 2>/dev/null | grep ':8420.*LISTENING' | awk '{print $5}' | head -1) && [ -n "$PID" ] && taskkill //F //PID $PID 2>/dev/null; sleep 1 && cd packages/server && pip install -e . 2>&1 | tail -1 && cd ../.. && NOTIFY_BRIDGE_DATA_DIR=./test-data NOTIFY_BRIDGE_SECRET_KEY=test-secret-key-minimum-32chars nohup python -m uvicorn notify_bridge_server.main:app --host 0.0.0.0 --port 8420 > /dev/null 2>&1 & sleep 3 && curl -s http://localhost:8420/api/health
|
||||
```
|
||||
@@ -71,3 +71,6 @@ TelegramBot → token, update_mode, bot_username (used as notification target ba
|
||||
3. **`packages/server/.../api/template_configs.py`** — `get_template_variables()` endpoint (`event_vars`, `asset_fields`, `album_fields`, `scheduled_vars`, per-slot variable dicts)
|
||||
4. **`packages/core/.../templates/defaults/{en,ru}/*.jinja2`** — default template files using the new variables
|
||||
5. **`packages/core/.../providers/immich/provider.py`** — `IMMICH_VARIABLES` list (provider-specific variable definitions)
|
||||
6. **`packages/server/.../api/command_template_configs.py`** — `get_command_variables()` endpoint (for command response templates)
|
||||
|
||||
**IMPORTANT**: Variable reference endpoints MUST document child/nested properties, not only top-level variables. When a variable is a list of dicts (e.g. `assets`, `albums`, `events`, `commands`), the endpoint MUST include a corresponding `*_fields` dict describing the child properties (e.g. `asset_fields: {"id": "...", "filename": "..."}`) so the frontend can show them (e.g. `{{ asset.id }}`, `{{ album.name }}`). Never list only `"assets": "List of asset dicts"` — always specify what fields each dict contains.
|
||||
|
||||
@@ -178,7 +178,7 @@
|
||||
},
|
||||
"targets": {
|
||||
"title": "Targets",
|
||||
"description": "Notification destinations (Telegram, webhooks)",
|
||||
"description": "Notification destinations (Telegram, Discord, Slack, Email, ntfy, Matrix, Webhooks)",
|
||||
"addTarget": "Add Target",
|
||||
"cancel": "Cancel",
|
||||
"type": "Type",
|
||||
@@ -203,7 +203,16 @@
|
||||
"disableUrlPreview": "Disable link previews",
|
||||
"sendLargeAsDocuments": "Send large photos as documents",
|
||||
"chatAction": "Chat action",
|
||||
"chatActionNone": "None (no action)"
|
||||
"chatActionNone": "None (no action)",
|
||||
"overrideUsername": "Override bot username",
|
||||
"ntfyServer": "ntfy Server URL",
|
||||
"ntfyTopic": "Topic",
|
||||
"ntfyToken": "Auth Token",
|
||||
"ntfyTokenPlaceholder": "Optional (for protected topics)",
|
||||
"selectEmailBot": "Select Email Bot",
|
||||
"selectMatrixBot": "Select Matrix Bot",
|
||||
"recipientEmail": "Recipient Email",
|
||||
"matrixRoomId": "Room ID"
|
||||
},
|
||||
"users": {
|
||||
"title": "Users",
|
||||
@@ -345,6 +354,7 @@
|
||||
"templateConfig": {
|
||||
"title": "Template Configs",
|
||||
"description": "Define how notification messages are formatted",
|
||||
"providerType": "Service Provider Type",
|
||||
"newConfig": "New Config",
|
||||
"name": "Name",
|
||||
"namePlaceholder": "Default EN",
|
||||
@@ -479,6 +489,21 @@
|
||||
"botLocale": "Language for command descriptions in Telegram's menu and bot response messages.",
|
||||
"rateLimits": "Cooldown in seconds between uses of each command category per chat. 0 = no limit."
|
||||
},
|
||||
"matrixBot": {
|
||||
"title": "Matrix Bots",
|
||||
"description": "Matrix homeserver connections for room notifications",
|
||||
"addBot": "Add Matrix Bot",
|
||||
"name": "Name",
|
||||
"namePlaceholder": "Home Server Bot",
|
||||
"homeserverUrl": "Homeserver URL",
|
||||
"accessToken": "Access Token",
|
||||
"tokenPlaceholder": "syt_...",
|
||||
"tokenUnchanged": "(unchanged)",
|
||||
"displayName": "Display Name",
|
||||
"testConnection": "Test connection",
|
||||
"noBots": "No Matrix bots yet.",
|
||||
"confirmDelete": "Delete this Matrix bot?"
|
||||
},
|
||||
"emailBot": {
|
||||
"title": "Email Bots",
|
||||
"description": "SMTP email senders for notifications",
|
||||
@@ -527,7 +552,9 @@
|
||||
"defaultCooldown": "Default cooldown (s)",
|
||||
"noConfigs": "No command configs yet.",
|
||||
"confirmDelete": "Delete this command config?",
|
||||
"commands": "commands"
|
||||
"commands": "commands",
|
||||
"responseTemplate": "Response Template",
|
||||
"noTemplate": "Default (hardcoded)"
|
||||
},
|
||||
"commandTracker": {
|
||||
"title": "Command Trackers",
|
||||
@@ -595,7 +622,11 @@
|
||||
"emailBotCreated": "Email bot created",
|
||||
"emailBotUpdated": "Email bot updated",
|
||||
"emailBotDeleted": "Email bot deleted",
|
||||
"emailBotTestSent": "Test email sent successfully"
|
||||
"emailBotTestSent": "Test email sent successfully",
|
||||
"matrixBotCreated": "Matrix bot created",
|
||||
"matrixBotUpdated": "Matrix bot updated",
|
||||
"matrixBotDeleted": "Matrix bot deleted",
|
||||
"matrixBotTestOk": "Matrix connection verified"
|
||||
},
|
||||
"common": {
|
||||
"loading": "Loading...",
|
||||
|
||||
@@ -178,7 +178,7 @@
|
||||
},
|
||||
"targets": {
|
||||
"title": "Получатели",
|
||||
"description": "Адреса уведомлений (Telegram, вебхуки)",
|
||||
"description": "Адреса уведомлений (Telegram, Discord, Slack, Email, ntfy, Matrix, вебхуки)",
|
||||
"addTarget": "Добавить получателя",
|
||||
"cancel": "Отмена",
|
||||
"type": "Тип",
|
||||
@@ -203,7 +203,16 @@
|
||||
"disableUrlPreview": "Отключить превью ссылок",
|
||||
"sendLargeAsDocuments": "Отправлять большие фото как документы",
|
||||
"chatAction": "Действие в чате",
|
||||
"chatActionNone": "Нет (без действия)"
|
||||
"chatActionNone": "Нет (без действия)",
|
||||
"overrideUsername": "Переопределить имя бота",
|
||||
"ntfyServer": "URL сервера ntfy",
|
||||
"ntfyTopic": "Тема",
|
||||
"ntfyToken": "Токен авторизации",
|
||||
"ntfyTokenPlaceholder": "Необязательно (для защищённых тем)",
|
||||
"selectEmailBot": "Выберите Email бот",
|
||||
"selectMatrixBot": "Выберите Matrix бот",
|
||||
"recipientEmail": "Email получателя",
|
||||
"matrixRoomId": "ID комнаты"
|
||||
},
|
||||
"users": {
|
||||
"title": "Пользователи",
|
||||
@@ -345,6 +354,7 @@
|
||||
"templateConfig": {
|
||||
"title": "Конфигурации шаблонов",
|
||||
"description": "Определите формат уведомлений",
|
||||
"providerType": "Тип сервис-провайдера",
|
||||
"newConfig": "Новая конфигурация",
|
||||
"name": "Название",
|
||||
"namePlaceholder": "По умолчанию RU",
|
||||
@@ -479,6 +489,21 @@
|
||||
"botLocale": "Язык описаний команд в меню Telegram и ответов бота.",
|
||||
"rateLimits": "Кулдаун в секундах между использованиями команд в каждом чате. 0 = без ограничений."
|
||||
},
|
||||
"matrixBot": {
|
||||
"title": "Matrix боты",
|
||||
"description": "Подключения к Matrix серверам для уведомлений в комнаты",
|
||||
"addBot": "Добавить Matrix бот",
|
||||
"name": "Название",
|
||||
"namePlaceholder": "Бот для дома",
|
||||
"homeserverUrl": "URL сервера",
|
||||
"accessToken": "Токен доступа",
|
||||
"tokenPlaceholder": "syt_...",
|
||||
"tokenUnchanged": "(без изменений)",
|
||||
"displayName": "Отображаемое имя",
|
||||
"testConnection": "Проверить подключение",
|
||||
"noBots": "Matrix ботов пока нет.",
|
||||
"confirmDelete": "Удалить этот Matrix бот?"
|
||||
},
|
||||
"emailBot": {
|
||||
"title": "Email боты",
|
||||
"description": "SMTP отправители для уведомлений по email",
|
||||
@@ -527,7 +552,9 @@
|
||||
"defaultCooldown": "Кулдаун по умолчанию (с)",
|
||||
"noConfigs": "Конфигураций команд пока нет.",
|
||||
"confirmDelete": "Удалить эту конфигурацию команд?",
|
||||
"commands": "команд"
|
||||
"commands": "команд",
|
||||
"responseTemplate": "Шаблон ответов",
|
||||
"noTemplate": "По умолчанию (встроенный)"
|
||||
},
|
||||
"commandTracker": {
|
||||
"title": "Трекеры команд",
|
||||
@@ -595,7 +622,11 @@
|
||||
"emailBotCreated": "Email бот создан",
|
||||
"emailBotUpdated": "Email бот обновлён",
|
||||
"emailBotDeleted": "Email бот удалён",
|
||||
"emailBotTestSent": "Тестовое письмо отправлено"
|
||||
"emailBotTestSent": "Тестовое письмо отправлено",
|
||||
"matrixBotCreated": "Matrix бот создан",
|
||||
"matrixBotUpdated": "Matrix бот обновлён",
|
||||
"matrixBotDeleted": "Matrix бот удалён",
|
||||
"matrixBotTestOk": "Подключение к Matrix проверено"
|
||||
},
|
||||
"common": {
|
||||
"loading": "Загрузка...",
|
||||
|
||||
@@ -13,6 +13,7 @@
|
||||
import { snackSuccess, snackError } from '$lib/stores/snackbar.svelte';
|
||||
|
||||
let configs = $state<any[]>([]);
|
||||
let cmdTemplateConfigs = $state<any[]>([]);
|
||||
let loaded = $state(false);
|
||||
let showForm = $state(false);
|
||||
let editing = $state<number | null>(null);
|
||||
@@ -46,13 +47,17 @@
|
||||
response_mode: 'media',
|
||||
default_count: 5,
|
||||
rate_limits: { search: 30, default: 10 },
|
||||
command_template_config_id: null as number | null,
|
||||
});
|
||||
let form = $state(defaultForm());
|
||||
|
||||
onMount(load);
|
||||
async function load() {
|
||||
try {
|
||||
configs = await api('/command-configs');
|
||||
[configs, cmdTemplateConfigs] = await Promise.all([
|
||||
api('/command-configs'),
|
||||
api('/command-template-configs'),
|
||||
]);
|
||||
} catch (err: any) { error = err.message || t('common.loadError'); snackError(error); }
|
||||
finally { loaded = true; }
|
||||
}
|
||||
@@ -68,6 +73,7 @@
|
||||
response_mode: cfg.response_mode || 'media',
|
||||
default_count: cfg.default_count || 5,
|
||||
rate_limits: { search: cfg.rate_limits?.search || 30, default: cfg.rate_limits?.default || 10 },
|
||||
command_template_config_id: cfg.command_template_config_id || null,
|
||||
};
|
||||
editing = cfg.id;
|
||||
showForm = true;
|
||||
@@ -157,6 +163,17 @@
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div>
|
||||
<label for="cc-template" class="block text-sm font-medium mb-1">{t('commandConfig.responseTemplate')}</label>
|
||||
<select id="cc-template" bind:value={form.command_template_config_id}
|
||||
class="w-full px-3 py-2 border border-[var(--color-border)] rounded-md text-sm bg-[var(--color-background)]">
|
||||
<option value={null}>— {t('commandConfig.noTemplate')} —</option>
|
||||
{#each cmdTemplateConfigs.filter((c: any) => c.provider_type === form.provider_type) as tpl}
|
||||
<option value={tpl.id}>{tpl.name}{tpl.user_id === 0 ? ' (System)' : ''}</option>
|
||||
{/each}
|
||||
</select>
|
||||
</div>
|
||||
|
||||
<div class="grid grid-cols-2 sm:grid-cols-4 gap-3">
|
||||
<div>
|
||||
<label class="block text-xs mb-1">{t('commandConfig.locale')}</label>
|
||||
|
||||
@@ -42,9 +42,15 @@
|
||||
let slotErrorLines = $state<Record<string, number | null>>({});
|
||||
let slotErrorTypes = $state<Record<string, string>>({});
|
||||
let validateTimers: Record<string, ReturnType<typeof setTimeout>> = {};
|
||||
let varsRef = $state<Record<string, any>>({});
|
||||
let showVarsFor = $state<string | null>(null);
|
||||
|
||||
// Load command slot definitions from capabilities
|
||||
let commandSlots = $state<SlotDef[]>([]);
|
||||
// Provider capabilities
|
||||
let allCapabilities = $state<Record<string, any>>({});
|
||||
let providerTypes = $derived(Object.keys(allCapabilities));
|
||||
let commandSlots = $derived<SlotDef[]>(
|
||||
allCapabilities[form.provider_type]?.command_slots || []
|
||||
);
|
||||
|
||||
const defaultForm = () => ({
|
||||
provider_type: 'immich',
|
||||
@@ -59,12 +65,14 @@
|
||||
|
||||
async function load() {
|
||||
try {
|
||||
const [cfgs, caps] = await Promise.all([
|
||||
const [cfgs, caps, vars] = await Promise.all([
|
||||
api('/command-template-configs'),
|
||||
api('/providers/capabilities/immich'),
|
||||
api('/providers/capabilities'),
|
||||
api('/command-template-configs/variables'),
|
||||
]);
|
||||
configs = cfgs;
|
||||
commandSlots = caps.command_slots || [];
|
||||
allCapabilities = caps;
|
||||
varsRef = vars;
|
||||
} catch (err: any) {
|
||||
error = err.message || t('common.loadError');
|
||||
snackError(error);
|
||||
@@ -218,6 +226,23 @@
|
||||
class="w-full px-3 py-2 border border-[var(--color-border)] rounded-md text-sm bg-[var(--color-background)]" />
|
||||
</div>
|
||||
|
||||
{#if !editing}
|
||||
<div>
|
||||
<label for="ct-provider" class="block text-sm font-medium mb-1">{t('templateConfig.providerType')}</label>
|
||||
<select id="ct-provider" bind:value={form.provider_type}
|
||||
class="w-full px-3 py-2 border border-[var(--color-border)] rounded-md text-sm bg-[var(--color-background)]">
|
||||
{#each providerTypes as pt}
|
||||
<option value={pt}>{allCapabilities[pt]?.display_name || pt} ({pt})</option>
|
||||
{/each}
|
||||
</select>
|
||||
</div>
|
||||
{:else}
|
||||
<div>
|
||||
<span class="block text-sm font-medium mb-1">{t('templateConfig.providerType')}</span>
|
||||
<span class="text-sm text-[var(--color-muted-foreground)]">{allCapabilities[form.provider_type]?.display_name || form.provider_type}</span>
|
||||
</div>
|
||||
{/if}
|
||||
|
||||
<fieldset class="border border-[var(--color-border)] rounded-md p-3">
|
||||
<legend class="text-sm font-medium px-1">{t('cmdTemplateConfig.commandResponses')}</legend>
|
||||
<p class="text-xs text-[var(--color-muted-foreground)] mb-3">{t('cmdTemplateConfig.commandResponsesHint')}</p>
|
||||
@@ -225,8 +250,11 @@
|
||||
{#each commandSlots as slot}
|
||||
<div>
|
||||
<div class="flex items-center justify-between mb-1">
|
||||
<label class="text-xs text-[var(--color-muted-foreground)]">/{slot.name}</label>
|
||||
<span class="text-xs text-[var(--color-muted-foreground)]">{slot.description}</span>
|
||||
<label class="text-xs text-[var(--color-muted-foreground)]">/{slot.name} — {slot.description}</label>
|
||||
{#if varsRef[slot.name]}
|
||||
<button type="button" onclick={() => showVarsFor = slot.name}
|
||||
class="text-xs text-[var(--color-muted-foreground)] hover:underline">{t('templateConfig.variables')}</button>
|
||||
{/if}
|
||||
</div>
|
||||
<JinjaEditor
|
||||
value={form.slots[slot.name] || ''}
|
||||
@@ -272,6 +300,7 @@
|
||||
<div class="flex items-center gap-2">
|
||||
<span style="color: var(--color-primary);"><MdiIcon name={config.icon || 'mdiConsoleLine'} size={20} /></span>
|
||||
<p class="font-medium">{config.name}</p>
|
||||
<span class="text-xs px-1.5 py-0.5 rounded bg-[var(--color-muted)] text-[var(--color-muted-foreground)]">{config.provider_type}</span>
|
||||
{#if config.user_id === 0}
|
||||
<span class="text-xs px-1.5 py-0.5 rounded bg-[var(--color-muted)] text-[var(--color-muted-foreground)]">System</span>
|
||||
{/if}
|
||||
@@ -296,3 +325,37 @@
|
||||
|
||||
<ConfirmModal open={confirmDelete !== null} message={t('cmdTemplateConfig.confirmDelete')}
|
||||
onconfirm={() => confirmDelete?.onconfirm()} oncancel={() => confirmDelete = null} />
|
||||
|
||||
<!-- Variables reference modal -->
|
||||
<Modal open={showVarsFor !== null} title="{t('templateConfig.variables')}: /{showVarsFor || ''}" onclose={() => showVarsFor = null}>
|
||||
{#if showVarsFor && varsRef[showVarsFor]}
|
||||
<p class="text-sm text-[var(--color-muted-foreground)] mb-3">{varsRef[showVarsFor].description}</p>
|
||||
<div class="space-y-1">
|
||||
<p class="text-xs font-medium mb-1">{t('templateConfig.variables')}:</p>
|
||||
{#each Object.entries(varsRef[showVarsFor].variables || {}) as [name, desc]}
|
||||
<div class="flex items-start gap-2 text-sm">
|
||||
<code class="text-xs bg-[var(--color-muted)] px-1 py-0.5 rounded font-mono whitespace-nowrap">{'{{ ' + name + ' }}'}</code>
|
||||
<span class="text-xs text-[var(--color-muted-foreground)]">{desc}</span>
|
||||
</div>
|
||||
{/each}
|
||||
</div>
|
||||
{#each [
|
||||
['asset_fields', 'asset', 'Asset fields'],
|
||||
['album_fields', 'album', 'Album fields'],
|
||||
['command_fields', 'cmd', 'Command fields'],
|
||||
['event_fields', 'event', 'Event fields'],
|
||||
] as [fieldKey, prefix, title]}
|
||||
{#if varsRef[showVarsFor][fieldKey]}
|
||||
<div class="mt-3 pt-3 border-t border-[var(--color-border)]">
|
||||
<p class="text-xs font-medium mb-1">{title} <span class="font-normal text-[var(--color-muted-foreground)]">(use {prefix}.field)</span>:</p>
|
||||
{#each Object.entries(varsRef[showVarsFor][fieldKey]) as [name, desc]}
|
||||
<div class="flex items-start gap-2 text-sm">
|
||||
<code class="text-xs bg-[var(--color-muted)] px-1 py-0.5 rounded font-mono whitespace-nowrap">{'{{ ' + prefix + '.' + name + ' }}'}</code>
|
||||
<span class="text-xs text-[var(--color-muted-foreground)]">{desc}</span>
|
||||
</div>
|
||||
{/each}
|
||||
</div>
|
||||
{/if}
|
||||
{/each}
|
||||
{/if}
|
||||
</Modal>
|
||||
|
||||
@@ -13,17 +13,35 @@
|
||||
import Hint from '$lib/components/Hint.svelte';
|
||||
import IconButton from '$lib/components/IconButton.svelte';
|
||||
import { snackSuccess, snackError } from '$lib/stores/snackbar.svelte';
|
||||
import type { NotificationTarget, TelegramBot, TelegramChat } from '$lib/types';
|
||||
import type { NotificationTarget, TelegramBot, TelegramChat, EmailBot, MatrixBot } from '$lib/types';
|
||||
|
||||
const ALL_TYPES = ['telegram', 'webhook', 'email', 'discord', 'slack', 'ntfy', 'matrix'] as const;
|
||||
type TargetType = typeof ALL_TYPES[number];
|
||||
const TYPE_ICONS: Record<string, string> = {
|
||||
telegram: 'mdiSend', webhook: 'mdiWebhook', email: 'mdiEmailOutline',
|
||||
discord: 'mdiChat', slack: 'mdiSlack', ntfy: 'mdiBell', matrix: 'mdiMatrix',
|
||||
};
|
||||
|
||||
let targets = $state<NotificationTarget[]>([]);
|
||||
let bots = $state<TelegramBot[]>([]);
|
||||
let emailBots = $state<EmailBot[]>([]);
|
||||
let matrixBots = $state<MatrixBot[]>([]);
|
||||
let botChats = $state<Record<number, TelegramChat[]>>({});
|
||||
let showForm = $state(false);
|
||||
let editing = $state<number | null>(null);
|
||||
let formType = $state<'telegram' | 'webhook'>('telegram');
|
||||
let formType = $state<TargetType>('telegram');
|
||||
const defaultForm = () => ({ name: '', icon: '', bot_id: 0, chat_id: '', bot_token: '', url: '', headers: '',
|
||||
max_media_to_send: 50, max_media_per_group: 10, media_delay: 500, max_asset_size: 50,
|
||||
disable_url_preview: false, send_large_photos_as_documents: false, ai_captions: false, chat_action: 'typing' });
|
||||
disable_url_preview: false, send_large_photos_as_documents: false, ai_captions: false, chat_action: 'typing',
|
||||
// Discord/Slack
|
||||
webhook_url: '', username: '',
|
||||
// ntfy
|
||||
server_url: 'https://ntfy.sh', topic: '', auth_token: '', priority: 3,
|
||||
// Matrix
|
||||
matrix_bot_id: 0, room_id: '',
|
||||
// Email
|
||||
email_bot_id: 0, email: '',
|
||||
});
|
||||
let form = $state(defaultForm());
|
||||
let error = $state('');
|
||||
let headersError = $state('');
|
||||
@@ -36,7 +54,9 @@
|
||||
onMount(load);
|
||||
async function load() {
|
||||
try {
|
||||
[targets, bots] = await Promise.all([api('/targets'), api('/telegram-bots')]);
|
||||
[targets, bots, emailBots, matrixBots] = await Promise.all([
|
||||
api('/targets'), api('/telegram-bots'), api('/email-bots'), api('/matrix-bots'),
|
||||
]);
|
||||
loadError = '';
|
||||
} catch (err: any) { loadError = err.message || t('common.loadError'); snackError(loadError); } finally { loaded = true; }
|
||||
}
|
||||
@@ -51,11 +71,24 @@
|
||||
formType = tgt.type;
|
||||
const c = tgt.config || {};
|
||||
form = {
|
||||
name: tgt.name, icon: tgt.icon || '', bot_id: c.bot_id || 0, bot_token: '', chat_id: c.chat_id || '', url: c.url || '', headers: '',
|
||||
name: tgt.name, icon: tgt.icon || '',
|
||||
// telegram
|
||||
bot_id: c.bot_id || 0, bot_token: '', chat_id: c.chat_id || '',
|
||||
max_media_to_send: c.max_media_to_send ?? 50, max_media_per_group: c.max_media_per_group ?? 10,
|
||||
media_delay: c.media_delay ?? 500, max_asset_size: c.max_asset_size ?? 50,
|
||||
disable_url_preview: c.disable_url_preview ?? false, send_large_photos_as_documents: c.send_large_photos_as_documents ?? false,
|
||||
ai_captions: c.ai_captions ?? false, chat_action: c.chat_action ?? 'typing',
|
||||
// webhook
|
||||
url: c.url || '', headers: '',
|
||||
// discord/slack
|
||||
webhook_url: c.webhook_url || '', username: c.username || '',
|
||||
// ntfy
|
||||
server_url: c.server_url || 'https://ntfy.sh', topic: c.topic || '',
|
||||
auth_token: c.auth_token || '', priority: c.priority ?? 3,
|
||||
// email
|
||||
email_bot_id: c.email_bot_id || 0, email: c.email || '',
|
||||
// matrix
|
||||
matrix_bot_id: c.matrix_bot_id || 0, room_id: c.room_id || '',
|
||||
};
|
||||
editing = tgt.id; showTelegramSettings = false; showForm = true;
|
||||
if (form.bot_id) await loadBotChats();
|
||||
@@ -66,24 +99,36 @@
|
||||
if (submitting) return;
|
||||
submitting = true;
|
||||
try {
|
||||
let botToken = form.bot_token;
|
||||
if (formType === 'telegram' && form.bot_id && !botToken) {
|
||||
const tokenRes = await api(`/telegram-bots/${form.bot_id}/token`);
|
||||
botToken = tokenRes.token;
|
||||
}
|
||||
let parsedHeaders = {};
|
||||
if (formType === 'webhook' && form.headers) {
|
||||
try { parsedHeaders = JSON.parse(form.headers); }
|
||||
catch { headersError = t('common.headersInvalid'); return; }
|
||||
}
|
||||
const config = formType === 'telegram'
|
||||
? { ...(botToken ? { bot_token: botToken } : {}), chat_id: form.chat_id,
|
||||
let config: Record<string, any> = {};
|
||||
|
||||
if (formType === 'telegram') {
|
||||
let botToken = form.bot_token;
|
||||
if (form.bot_id && !botToken) {
|
||||
const tokenRes = await api(`/telegram-bots/${form.bot_id}/token`);
|
||||
botToken = tokenRes.token;
|
||||
}
|
||||
config = { ...(botToken ? { bot_token: botToken } : {}), chat_id: form.chat_id,
|
||||
bot_id: form.bot_id || undefined,
|
||||
max_media_to_send: form.max_media_to_send, max_media_per_group: form.max_media_per_group,
|
||||
media_delay: form.media_delay, max_asset_size: form.max_asset_size,
|
||||
disable_url_preview: form.disable_url_preview, send_large_photos_as_documents: form.send_large_photos_as_documents,
|
||||
ai_captions: form.ai_captions, chat_action: form.chat_action || undefined }
|
||||
: { url: form.url, headers: parsedHeaders, ai_captions: form.ai_captions };
|
||||
ai_captions: form.ai_captions, chat_action: form.chat_action || undefined };
|
||||
} else if (formType === 'webhook') {
|
||||
let parsedHeaders = {};
|
||||
if (form.headers) {
|
||||
try { parsedHeaders = JSON.parse(form.headers); }
|
||||
catch { headersError = t('common.headersInvalid'); return; }
|
||||
}
|
||||
config = { url: form.url, headers: parsedHeaders, ai_captions: form.ai_captions };
|
||||
} else if (formType === 'discord' || formType === 'slack') {
|
||||
config = { webhook_url: form.webhook_url, username: form.username || undefined };
|
||||
} else if (formType === 'ntfy') {
|
||||
config = { server_url: form.server_url, topic: form.topic, auth_token: form.auth_token || undefined };
|
||||
} else if (formType === 'email') {
|
||||
config = { email_bot_id: form.email_bot_id, email: form.email };
|
||||
} else if (formType === 'matrix') {
|
||||
config = { matrix_bot_id: form.matrix_bot_id, room_id: form.room_id };
|
||||
}
|
||||
if (editing) {
|
||||
await api(`/targets/${editing}`, { method: 'PUT', body: JSON.stringify({ name: form.name, icon: form.icon, config }) });
|
||||
} else {
|
||||
@@ -126,11 +171,13 @@
|
||||
{#if error}<div class="bg-[var(--color-error-bg)] text-[var(--color-error-fg)] text-sm rounded-md p-3 mb-4">{error}</div>{/if}
|
||||
<form onsubmit={save} class="space-y-4">
|
||||
<div>
|
||||
<span class="block text-sm font-medium mb-1">{t('targets.type')}</span>
|
||||
<div class="flex gap-4">
|
||||
<label class="flex items-center gap-1 text-sm"><input type="radio" bind:group={formType} value="telegram" /> Telegram</label>
|
||||
<label class="flex items-center gap-1 text-sm"><input type="radio" bind:group={formType} value="webhook" /> Webhook</label>
|
||||
</div>
|
||||
<label for="tgt-type" class="block text-sm font-medium mb-1">{t('targets.type')}</label>
|
||||
<select id="tgt-type" bind:value={formType}
|
||||
class="w-full px-3 py-2 border border-[var(--color-border)] rounded-md text-sm bg-[var(--color-background)]">
|
||||
{#each ALL_TYPES as tt}
|
||||
<option value={tt}>{tt.charAt(0).toUpperCase() + tt.slice(1)}</option>
|
||||
{/each}
|
||||
</select>
|
||||
</div>
|
||||
<div>
|
||||
<label for="tgt-name" class="block text-sm font-medium mb-1">{t('targets.name')}</label>
|
||||
@@ -216,7 +263,7 @@
|
||||
</div>
|
||||
{/if}
|
||||
</div>
|
||||
{:else}
|
||||
{:else if formType === 'webhook'}
|
||||
<div>
|
||||
<label for="tgt-url" class="block text-sm font-medium mb-1">{t('targets.webhookUrl')}</label>
|
||||
<input id="tgt-url" bind:value={form.url} required placeholder="https://..." class="w-full px-3 py-2 border border-[var(--color-border)] rounded-md text-sm bg-[var(--color-background)]" />
|
||||
@@ -226,9 +273,72 @@
|
||||
<input id="tgt-headers" bind:value={form.headers} placeholder={'{"Authorization": "Bearer ..."}'} class="w-full px-3 py-2 border border-[var(--color-border)] rounded-md text-sm bg-[var(--color-background)]" style={headersError ? 'border-color: var(--color-error-fg)' : ''} />
|
||||
{#if headersError}<p class="text-xs text-[var(--color-error-fg)] mt-1">{headersError}</p>{/if}
|
||||
</div>
|
||||
{:else if formType === 'discord' || formType === 'slack'}
|
||||
<div>
|
||||
<label for="tgt-wh" class="block text-sm font-medium mb-1">{formType === 'discord' ? 'Discord' : 'Slack'} Webhook URL</label>
|
||||
<input id="tgt-wh" bind:value={form.webhook_url} required placeholder={formType === 'discord' ? 'https://discord.com/api/webhooks/...' : 'https://hooks.slack.com/services/...'}
|
||||
class="w-full px-3 py-2 border border-[var(--color-border)] rounded-md text-sm bg-[var(--color-background)]" />
|
||||
</div>
|
||||
<div>
|
||||
<label for="tgt-user" class="block text-sm font-medium mb-1">{t('targets.overrideUsername')}</label>
|
||||
<input id="tgt-user" bind:value={form.username} placeholder="Notify Bridge"
|
||||
class="w-full px-3 py-2 border border-[var(--color-border)] rounded-md text-sm bg-[var(--color-background)]" />
|
||||
</div>
|
||||
{:else if formType === 'ntfy'}
|
||||
<div>
|
||||
<label for="tgt-ntfy-server" class="block text-sm font-medium mb-1">{t('targets.ntfyServer')}</label>
|
||||
<input id="tgt-ntfy-server" bind:value={form.server_url} required placeholder="https://ntfy.sh"
|
||||
class="w-full px-3 py-2 border border-[var(--color-border)] rounded-md text-sm bg-[var(--color-background)]" />
|
||||
</div>
|
||||
<div>
|
||||
<label for="tgt-ntfy-topic" class="block text-sm font-medium mb-1">{t('targets.ntfyTopic')}</label>
|
||||
<input id="tgt-ntfy-topic" bind:value={form.topic} required placeholder="my-notifications"
|
||||
class="w-full px-3 py-2 border border-[var(--color-border)] rounded-md text-sm bg-[var(--color-background)]" />
|
||||
</div>
|
||||
<div>
|
||||
<label for="tgt-ntfy-token" class="block text-sm font-medium mb-1">{t('targets.ntfyToken')}</label>
|
||||
<input id="tgt-ntfy-token" bind:value={form.auth_token} placeholder={t('targets.ntfyTokenPlaceholder')}
|
||||
class="w-full px-3 py-2 border border-[var(--color-border)] rounded-md text-sm bg-[var(--color-background)]" />
|
||||
</div>
|
||||
{:else if formType === 'email'}
|
||||
<div>
|
||||
<label for="tgt-emailbot" class="block text-sm font-medium mb-1">{t('targets.selectEmailBot')}</label>
|
||||
<select id="tgt-emailbot" bind:value={form.email_bot_id} required
|
||||
class="w-full px-3 py-2 border border-[var(--color-border)] rounded-md text-sm bg-[var(--color-background)]">
|
||||
<option value={0} disabled>— {t('targets.selectEmailBot')} —</option>
|
||||
{#each emailBots as bot}<option value={bot.id}>{bot.name} ({bot.email})</option>{/each}
|
||||
</select>
|
||||
{#if emailBots.length === 0}
|
||||
<p class="text-xs text-[var(--color-muted-foreground)] mt-1">{t('emailBot.noBots')} <a href="/telegram-bots" class="underline">→</a></p>
|
||||
{/if}
|
||||
</div>
|
||||
<div>
|
||||
<label for="tgt-email" class="block text-sm font-medium mb-1">{t('targets.recipientEmail')}</label>
|
||||
<input id="tgt-email" bind:value={form.email} required type="email" placeholder="recipient@example.com"
|
||||
class="w-full px-3 py-2 border border-[var(--color-border)] rounded-md text-sm bg-[var(--color-background)]" />
|
||||
</div>
|
||||
{:else if formType === 'matrix'}
|
||||
<div>
|
||||
<label for="tgt-mxbot" class="block text-sm font-medium mb-1">{t('targets.selectMatrixBot')}</label>
|
||||
<select id="tgt-mxbot" bind:value={form.matrix_bot_id} required
|
||||
class="w-full px-3 py-2 border border-[var(--color-border)] rounded-md text-sm bg-[var(--color-background)]">
|
||||
<option value={0} disabled>— {t('targets.selectMatrixBot')} —</option>
|
||||
{#each matrixBots as bot}<option value={bot.id}>{bot.name} ({bot.homeserver_url})</option>{/each}
|
||||
</select>
|
||||
{#if matrixBots.length === 0}
|
||||
<p class="text-xs text-[var(--color-muted-foreground)] mt-1">{t('matrixBot.noBots')} <a href="/telegram-bots" class="underline">→</a></p>
|
||||
{/if}
|
||||
</div>
|
||||
<div>
|
||||
<label for="tgt-room" class="block text-sm font-medium mb-1">{t('targets.matrixRoomId')}</label>
|
||||
<input id="tgt-room" bind:value={form.room_id} required placeholder="!abc123:matrix.org"
|
||||
class="w-full px-3 py-2 border border-[var(--color-border)] rounded-md text-sm bg-[var(--color-background)] font-mono" />
|
||||
</div>
|
||||
{/if}
|
||||
|
||||
<label class="flex items-center gap-2 text-sm"><input type="checkbox" bind:checked={form.ai_captions} /> {t('targets.aiCaptions')}<Hint text={t('hints.aiCaptions')} /></label>
|
||||
{#if formType === 'telegram'}
|
||||
<label class="flex items-center gap-2 text-sm"><input type="checkbox" bind:checked={form.ai_captions} /> {t('targets.aiCaptions')}<Hint text={t('hints.aiCaptions')} /></label>
|
||||
{/if}
|
||||
|
||||
<button type="submit" disabled={submitting} class="px-4 py-2 bg-[var(--color-primary)] text-[var(--color-primary-foreground)] rounded-md text-sm font-medium hover:opacity-90 disabled:opacity-50">{submitting ? t('common.loading') : (editing ? t('common.save') : t('targets.create'))}</button>
|
||||
</form>
|
||||
@@ -247,9 +357,10 @@
|
||||
<div class="flex items-center justify-between">
|
||||
<div>
|
||||
<div class="flex items-center gap-2">
|
||||
<span style="color: var(--color-primary);"><MdiIcon name={target.icon || (target.type === 'telegram' ? 'mdiSend' : 'mdiWebhook')} size={20} /></span>
|
||||
<span style="color: var(--color-primary);"><MdiIcon name={target.icon || TYPE_ICONS[target.type] || 'mdiTarget'} size={20} /></span>
|
||||
<p class="font-medium">{target.name}</p>
|
||||
<span class="text-xs px-1.5 py-0.5 rounded bg-[var(--color-muted)] text-[var(--color-muted-foreground)]">{target.type}</span>
|
||||
{#if target.receiver_count}<span class="text-xs px-1.5 py-0.5 rounded bg-[var(--color-muted)] text-[var(--color-muted-foreground)]">{target.receiver_count} receiver(s)</span>{/if}
|
||||
</div>
|
||||
<p class="text-sm text-[var(--color-muted-foreground)]">
|
||||
{#if target.type === 'telegram'}
|
||||
@@ -257,8 +368,16 @@
|
||||
{#if target.config?.chat_action}
|
||||
<span class="text-xs px-1.5 py-0.5 ml-1 rounded bg-[var(--color-muted)] text-[var(--color-muted-foreground)]">{target.config.chat_action}</span>
|
||||
{/if}
|
||||
{:else}
|
||||
{:else if target.type === 'webhook'}
|
||||
{target.config?.url || ''}
|
||||
{:else if target.type === 'discord' || target.type === 'slack'}
|
||||
{target.config?.webhook_url ? target.config.webhook_url.substring(0, 50) + '...' : ''}
|
||||
{:else if target.type === 'ntfy'}
|
||||
{target.config?.server_url || 'ntfy.sh'} / {target.config?.topic || ''}
|
||||
{:else if target.type === 'email'}
|
||||
{target.config?.email || ''}
|
||||
{:else if target.type === 'matrix'}
|
||||
{target.config?.room_id || ''}
|
||||
{/if}
|
||||
</p>
|
||||
</div>
|
||||
|
||||
@@ -12,10 +12,11 @@
|
||||
import ConfirmModal from '$lib/components/ConfirmModal.svelte';
|
||||
import IconButton from '$lib/components/IconButton.svelte';
|
||||
import { snackSuccess, snackError, snackInfo } from '$lib/stores/snackbar.svelte';
|
||||
import type { TelegramBot, TelegramChat, EmailBot } from '$lib/types';
|
||||
import type { TelegramBot, TelegramChat, EmailBot, MatrixBot } from '$lib/types';
|
||||
|
||||
let bots = $state<TelegramBot[]>([]);
|
||||
let emailBots = $state<EmailBot[]>([]);
|
||||
let matrixBots = $state<MatrixBot[]>([]);
|
||||
let loaded = $state(false);
|
||||
let showForm = $state(false);
|
||||
let editing = $state<number | null>(null);
|
||||
@@ -38,10 +39,11 @@
|
||||
onMount(load);
|
||||
async function load() {
|
||||
try {
|
||||
[bots, settings, emailBots] = await Promise.all([
|
||||
[bots, settings, emailBots, matrixBots] = await Promise.all([
|
||||
api('/telegram-bots'),
|
||||
api('/settings'),
|
||||
api('/email-bots'),
|
||||
api('/matrix-bots'),
|
||||
]);
|
||||
} catch (err: any) { error = err.message || t('common.loadError'); snackError(error); }
|
||||
finally { loaded = true; }
|
||||
@@ -278,6 +280,65 @@
|
||||
} catch (err: any) { snackError(err.message); }
|
||||
emailTesting = { ...emailTesting, [botId]: false };
|
||||
}
|
||||
|
||||
// --- Matrix Bot state ---
|
||||
let showMatrixForm = $state(false);
|
||||
let editingMatrix = $state<number | null>(null);
|
||||
let matrixSubmitting = $state(false);
|
||||
let matrixTesting = $state<Record<number, boolean>>({});
|
||||
let confirmDeleteMatrix = $state<any>(null);
|
||||
const defaultMatrixForm = () => ({
|
||||
name: '', icon: '', homeserver_url: '', access_token: '', display_name: '',
|
||||
});
|
||||
let matrixForm = $state(defaultMatrixForm());
|
||||
|
||||
function openNewMatrix() { matrixForm = defaultMatrixForm(); editingMatrix = null; showMatrixForm = true; }
|
||||
function editMatrixBot(bot: MatrixBot) {
|
||||
matrixForm = {
|
||||
name: bot.name, icon: bot.icon || '',
|
||||
homeserver_url: bot.homeserver_url, access_token: '',
|
||||
display_name: bot.display_name || '',
|
||||
};
|
||||
editingMatrix = bot.id; showMatrixForm = true;
|
||||
}
|
||||
|
||||
async function saveMatrixBot(e: SubmitEvent) {
|
||||
e.preventDefault(); error = ''; matrixSubmitting = true;
|
||||
try {
|
||||
const body = { ...matrixForm };
|
||||
if (editingMatrix && !body.access_token) delete (body as any).access_token;
|
||||
if (editingMatrix) {
|
||||
await api(`/matrix-bots/${editingMatrix}`, { method: 'PUT', body: JSON.stringify(body) });
|
||||
snackSuccess(t('snack.matrixBotUpdated'));
|
||||
} else {
|
||||
await api('/matrix-bots', { method: 'POST', body: JSON.stringify(body) });
|
||||
snackSuccess(t('snack.matrixBotCreated'));
|
||||
}
|
||||
matrixForm = defaultMatrixForm(); showMatrixForm = false; editingMatrix = null; await load();
|
||||
} catch (err: any) { error = err.message; snackError(err.message); }
|
||||
finally { matrixSubmitting = false; }
|
||||
}
|
||||
|
||||
function removeMatrix(id: number) {
|
||||
confirmDeleteMatrix = {
|
||||
id,
|
||||
onconfirm: async () => {
|
||||
try { await api(`/matrix-bots/${id}`, { method: 'DELETE' }); await load(); snackSuccess(t('snack.matrixBotDeleted')); }
|
||||
catch (err: any) { error = err.message; snackError(err.message); }
|
||||
finally { confirmDeleteMatrix = null; }
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
async function testMatrixBot(botId: number) {
|
||||
matrixTesting = { ...matrixTesting, [botId]: true };
|
||||
try {
|
||||
const res = await api(`/matrix-bots/${botId}/test`, { method: 'POST' });
|
||||
if (res.success) snackSuccess(t('snack.matrixBotTestOk'));
|
||||
else snackError(res.error || 'Failed');
|
||||
} catch (err: any) { snackError(err.message); }
|
||||
matrixTesting = { ...matrixTesting, [botId]: false };
|
||||
}
|
||||
</script>
|
||||
|
||||
<PageHeader title={t('telegramBot.title')} description={t('telegramBot.description')}>
|
||||
@@ -601,3 +662,85 @@
|
||||
|
||||
<ConfirmModal open={confirmDeleteEmail !== null} message={t('emailBot.confirmDelete')}
|
||||
onconfirm={() => confirmDeleteEmail?.onconfirm()} oncancel={() => confirmDeleteEmail = null} />
|
||||
|
||||
<!-- ======= Matrix Bots Section ======= -->
|
||||
<div class="mt-8">
|
||||
<PageHeader title={t('matrixBot.title')} description={t('matrixBot.description')}>
|
||||
<button onclick={() => { showMatrixForm ? (showMatrixForm = false, editingMatrix = null) : openNewMatrix(); }}
|
||||
class="px-3 py-1.5 bg-[var(--color-primary)] text-[var(--color-primary-foreground)] rounded-md text-sm font-medium hover:opacity-90">
|
||||
{showMatrixForm ? t('common.cancel') : t('matrixBot.addBot')}
|
||||
</button>
|
||||
</PageHeader>
|
||||
|
||||
{#if showMatrixForm}
|
||||
<Card class="mb-6">
|
||||
{#if error}<div class="bg-[var(--color-error-bg)] text-[var(--color-error-fg)] text-sm rounded-md p-3 mb-4">{error}</div>{/if}
|
||||
<form onsubmit={saveMatrixBot} class="space-y-3">
|
||||
<div>
|
||||
<label for="mbot-name" class="block text-sm font-medium mb-1">{t('matrixBot.name')}</label>
|
||||
<div class="flex gap-2">
|
||||
<IconPicker value={matrixForm.icon} onselect={(v: string) => matrixForm.icon = v} />
|
||||
<input id="mbot-name" bind:value={matrixForm.name} required placeholder={t('matrixBot.namePlaceholder')}
|
||||
class="flex-1 px-3 py-2 border border-[var(--color-border)] rounded-md text-sm bg-[var(--color-background)]" />
|
||||
</div>
|
||||
</div>
|
||||
<div>
|
||||
<label for="mbot-hs" class="block text-sm font-medium mb-1">{t('matrixBot.homeserverUrl')}</label>
|
||||
<input id="mbot-hs" bind:value={matrixForm.homeserver_url} required placeholder="https://matrix.org"
|
||||
class="w-full px-3 py-2 border border-[var(--color-border)] rounded-md text-sm bg-[var(--color-background)]" />
|
||||
</div>
|
||||
<div>
|
||||
<label for="mbot-token" class="block text-sm font-medium mb-1">{t('matrixBot.accessToken')}</label>
|
||||
<input id="mbot-token" bind:value={matrixForm.access_token} type="password"
|
||||
required={!editingMatrix}
|
||||
placeholder={editingMatrix ? t('matrixBot.tokenUnchanged') : t('matrixBot.tokenPlaceholder')}
|
||||
class="w-full px-3 py-2 border border-[var(--color-border)] rounded-md text-sm bg-[var(--color-background)] font-mono" />
|
||||
</div>
|
||||
<div>
|
||||
<label for="mbot-display" class="block text-sm font-medium mb-1">{t('matrixBot.displayName')}</label>
|
||||
<input id="mbot-display" bind:value={matrixForm.display_name} placeholder="Notify Bridge"
|
||||
class="w-full px-3 py-2 border border-[var(--color-border)] rounded-md text-sm bg-[var(--color-background)]" />
|
||||
</div>
|
||||
<button type="submit" disabled={matrixSubmitting}
|
||||
class="px-4 py-2 bg-[var(--color-primary)] text-[var(--color-primary-foreground)] rounded-md text-sm font-medium hover:opacity-90 disabled:opacity-50">
|
||||
{matrixSubmitting ? t('common.loading') : (editingMatrix ? t('common.save') : t('matrixBot.addBot'))}
|
||||
</button>
|
||||
</form>
|
||||
</Card>
|
||||
{/if}
|
||||
|
||||
{#if matrixBots.length === 0 && !showMatrixForm}
|
||||
<Card>
|
||||
<EmptyState icon="mdiMatrix" message={t('matrixBot.noBots')} />
|
||||
</Card>
|
||||
{:else}
|
||||
<div class="space-y-3 stagger-children">
|
||||
{#each matrixBots as bot}
|
||||
<Card hover>
|
||||
<div class="flex items-center justify-between">
|
||||
<div>
|
||||
<div class="flex items-center gap-2">
|
||||
<span style="color: var(--color-primary);"><MdiIcon name={bot.icon || 'mdiMatrix'} size={20} /></span>
|
||||
<p class="font-medium">{bot.name}</p>
|
||||
</div>
|
||||
<div class="flex items-center gap-2 mt-1 flex-wrap">
|
||||
<span class="text-xs text-[var(--color-muted-foreground)] font-mono">{bot.homeserver_url}</span>
|
||||
{#if bot.display_name}
|
||||
<span class="text-xs px-1.5 py-0.5 rounded bg-[var(--color-muted)] text-[var(--color-muted-foreground)]">{bot.display_name}</span>
|
||||
{/if}
|
||||
</div>
|
||||
</div>
|
||||
<div class="flex items-center gap-1">
|
||||
<IconButton icon="mdiConnection" title={t('matrixBot.testConnection')} onclick={() => testMatrixBot(bot.id)} disabled={matrixTesting[bot.id]} />
|
||||
<IconButton icon="mdiPencil" title={t('common.edit')} onclick={() => editMatrixBot(bot)} />
|
||||
<IconButton icon="mdiDelete" title={t('common.delete')} onclick={() => removeMatrix(bot.id)} variant="danger" />
|
||||
</div>
|
||||
</div>
|
||||
</Card>
|
||||
{/each}
|
||||
</div>
|
||||
{/if}
|
||||
</div>
|
||||
|
||||
<ConfirmModal open={confirmDeleteMatrix !== null} message={t('matrixBot.confirmDelete')}
|
||||
onconfirm={() => confirmDeleteMatrix?.onconfirm()} oncancel={() => confirmDeleteMatrix = null} />
|
||||
|
||||
@@ -105,31 +105,38 @@
|
||||
let form = $state(defaultForm());
|
||||
let previewTargetType = $state('telegram');
|
||||
|
||||
const templateSlots = [
|
||||
{ group: 'eventMessages', slots: [
|
||||
{ key: 'message_assets_added', label: 'assetsAdded', rows: 10 },
|
||||
{ key: 'message_assets_removed', label: 'assetsRemoved', rows: 3 },
|
||||
{ key: 'message_collection_renamed', label: 'albumRenamed', rows: 2 },
|
||||
{ key: 'message_collection_deleted', label: 'albumDeleted', rows: 2 },
|
||||
{ key: 'message_sharing_changed', label: 'sharingChanged', rows: 2 },
|
||||
]},
|
||||
{ group: 'scheduledMessages', slots: [
|
||||
{ key: 'periodic_summary_message', label: 'periodicSummary', rows: 6 },
|
||||
{ key: 'scheduled_assets_message', label: 'scheduledAssets', rows: 6 },
|
||||
{ key: 'memory_mode_message', label: 'memoryMode', rows: 6 },
|
||||
]},
|
||||
// Provider capabilities: loaded dynamically
|
||||
let allCapabilities = $state<Record<string, any>>({});
|
||||
let providerTypes = $derived(Object.keys(allCapabilities));
|
||||
|
||||
// Dynamic slot definitions based on selected provider_type
|
||||
let notificationSlots = $derived<{name: string, description: string}[]>(
|
||||
allCapabilities[form.provider_type]?.notification_slots || []
|
||||
);
|
||||
|
||||
// Group slots into event messages vs scheduled messages based on slot name prefix
|
||||
let templateSlots = $derived([
|
||||
{ group: 'eventMessages', slots: notificationSlots
|
||||
.filter(s => s.name.startsWith('message_'))
|
||||
.map(s => ({ key: s.name, label: s.name.replace('message_', '').replace(/_/g, ' '), description: s.description, rows: s.name === 'message_assets_added' ? 10 : 3 }))
|
||||
},
|
||||
{ group: 'scheduledMessages', slots: notificationSlots
|
||||
.filter(s => !s.name.startsWith('message_'))
|
||||
.map(s => ({ key: s.name, label: s.name.replace(/_/g, ' '), description: s.description, rows: 6 }))
|
||||
},
|
||||
{ group: 'settings', slots: [
|
||||
{ key: 'date_format', label: 'dateFormat', rows: 1, isDateFormat: true },
|
||||
{ key: 'date_only_format', label: 'dateOnlyFormat', rows: 1, isDateFormat: true },
|
||||
{ key: 'date_format', label: 'dateFormat', description: 'Date+time format', rows: 1, isDateFormat: true },
|
||||
{ key: 'date_only_format', label: 'dateOnlyFormat', description: 'Date-only format', rows: 1, isDateFormat: true },
|
||||
]},
|
||||
];
|
||||
]);
|
||||
|
||||
onMount(load);
|
||||
async function load() {
|
||||
try {
|
||||
[configs, varsRef] = await Promise.all([
|
||||
[configs, varsRef, allCapabilities] = await Promise.all([
|
||||
api('/template-configs'),
|
||||
api('/template-configs/variables'),
|
||||
api('/providers/capabilities'),
|
||||
]);
|
||||
} catch (err: any) { error = err.message || t('common.loadError'); snackError(error); }
|
||||
finally { loaded = true; }
|
||||
@@ -233,6 +240,23 @@
|
||||
class="w-full px-3 py-2 border border-[var(--color-border)] rounded-md text-sm bg-[var(--color-background)]" />
|
||||
</div>
|
||||
|
||||
{#if !editing}
|
||||
<div>
|
||||
<label for="tpc-provider" class="block text-sm font-medium mb-1">{t('templateConfig.providerType')}</label>
|
||||
<select id="tpc-provider" bind:value={form.provider_type}
|
||||
class="w-full px-3 py-2 border border-[var(--color-border)] rounded-md text-sm bg-[var(--color-background)]">
|
||||
{#each providerTypes as pt}
|
||||
<option value={pt}>{allCapabilities[pt]?.display_name || pt} ({pt})</option>
|
||||
{/each}
|
||||
</select>
|
||||
</div>
|
||||
{:else}
|
||||
<div>
|
||||
<span class="block text-sm font-medium mb-1">{t('templateConfig.providerType')}</span>
|
||||
<span class="text-sm text-[var(--color-muted-foreground)]">{allCapabilities[form.provider_type]?.display_name || form.provider_type}</span>
|
||||
</div>
|
||||
{/if}
|
||||
|
||||
<div class="flex items-center gap-2">
|
||||
<label for="preview-target" class="text-sm font-medium">{t('templateConfig.previewAs')}:</label>
|
||||
<select id="preview-target" bind:value={previewTargetType} onchange={refreshAllPreviews}
|
||||
@@ -249,7 +273,7 @@
|
||||
{#each group.slots as slot}
|
||||
<div>
|
||||
<div class="flex items-center justify-between mb-1">
|
||||
<label class="text-xs text-[var(--color-muted-foreground)]">{t(`templateConfig.${slot.label}`)}</label>
|
||||
<label class="text-xs text-[var(--color-muted-foreground)]">{slot.description || t(`templateConfig.${slot.label}`, slot.label)}</label>
|
||||
<div class="flex items-center gap-2">
|
||||
{#if varsRef[slot.key]}
|
||||
<button type="button" onclick={() => showVarsFor = slot.key}
|
||||
@@ -308,6 +332,7 @@
|
||||
<div class="flex items-center gap-2">
|
||||
<span style="color: var(--color-primary);"><MdiIcon name={config.icon || 'mdiFileDocumentEdit'} size={20} /></span>
|
||||
<p class="font-medium">{config.name}</p>
|
||||
<span class="text-xs px-1.5 py-0.5 rounded bg-[var(--color-muted)] text-[var(--color-muted-foreground)]">{config.provider_type}</span>
|
||||
{#if config.user_id === 0}
|
||||
<span class="text-xs px-1.5 py-0.5 rounded bg-[var(--color-muted)] text-[var(--color-muted-foreground)]">System</span>
|
||||
{/if}
|
||||
|
||||
@@ -0,0 +1,5 @@
|
||||
"""Discord webhook notification client."""
|
||||
|
||||
from .client import DiscordClient
|
||||
|
||||
__all__ = ["DiscordClient"]
|
||||
@@ -0,0 +1,88 @@
|
||||
"""Discord webhook client."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import asyncio
|
||||
import logging
|
||||
from typing import Any
|
||||
|
||||
import aiohttp
|
||||
|
||||
_LOGGER = logging.getLogger(__name__)
|
||||
|
||||
# Discord webhook content limit
|
||||
MAX_CONTENT_LENGTH = 2000
|
||||
|
||||
|
||||
class DiscordClient:
|
||||
"""Sends messages via Discord webhook URLs."""
|
||||
|
||||
def __init__(self, session: aiohttp.ClientSession) -> None:
|
||||
self._session = session
|
||||
|
||||
async def send(
|
||||
self,
|
||||
webhook_url: str,
|
||||
message: str,
|
||||
username: str | None = None,
|
||||
avatar_url: str | None = None,
|
||||
) -> dict[str, Any]:
|
||||
"""Send a message to a Discord webhook.
|
||||
|
||||
If message exceeds 2000 chars, it's split into chunks.
|
||||
"""
|
||||
if not webhook_url:
|
||||
return {"success": False, "error": "Missing webhook_url"}
|
||||
|
||||
chunks = _split_message(message, MAX_CONTENT_LENGTH)
|
||||
for chunk in chunks:
|
||||
payload: dict[str, Any] = {"content": chunk}
|
||||
if username:
|
||||
payload["username"] = username
|
||||
if avatar_url:
|
||||
payload["avatar_url"] = avatar_url
|
||||
|
||||
result = await self._post(webhook_url, payload)
|
||||
if not result["success"]:
|
||||
return result
|
||||
|
||||
# Small delay between chunks to respect rate limits
|
||||
if len(chunks) > 1:
|
||||
await asyncio.sleep(0.5)
|
||||
|
||||
return {"success": True}
|
||||
|
||||
async def _post(self, url: str, payload: dict) -> dict[str, Any]:
|
||||
try:
|
||||
async with self._session.post(
|
||||
url, json=payload, headers={"Content-Type": "application/json"}
|
||||
) as resp:
|
||||
if resp.status == 429:
|
||||
retry_after = float(resp.headers.get("Retry-After", "2"))
|
||||
_LOGGER.warning("Discord rate limited, retrying after %.1fs", retry_after)
|
||||
await asyncio.sleep(retry_after)
|
||||
return await self._post(url, payload)
|
||||
if 200 <= resp.status < 300:
|
||||
return {"success": True}
|
||||
body = await resp.text()
|
||||
return {"success": False, "error": f"HTTP {resp.status}: {body[:200]}"}
|
||||
except aiohttp.ClientError as e:
|
||||
return {"success": False, "error": str(e)}
|
||||
|
||||
|
||||
def _split_message(text: str, limit: int) -> list[str]:
|
||||
"""Split message into chunks respecting the character limit."""
|
||||
if len(text) <= limit:
|
||||
return [text]
|
||||
chunks = []
|
||||
while text:
|
||||
if len(text) <= limit:
|
||||
chunks.append(text)
|
||||
break
|
||||
# Try to split at newline
|
||||
split_at = text.rfind("\n", 0, limit)
|
||||
if split_at <= 0:
|
||||
split_at = limit
|
||||
chunks.append(text[:split_at])
|
||||
text = text[split_at:].lstrip("\n")
|
||||
return chunks
|
||||
@@ -25,7 +25,7 @@ DEFAULT_TEMPLATE = '{{ event_type }}: "{{ collection_name }}"'
|
||||
class TargetConfig:
|
||||
"""Configuration for a notification target."""
|
||||
|
||||
type: str # "telegram", "webhook", or "email"
|
||||
type: str # "telegram", "webhook", "email", "discord", "slack", "ntfy", "matrix"
|
||||
config: dict[str, Any] # target-level config (bot_token, settings, etc.)
|
||||
template_slots: dict[str, str] | None = None # event_type -> template string
|
||||
date_format: str = "%d.%m.%Y, %H:%M UTC"
|
||||
@@ -87,12 +87,17 @@ class NotificationDispatcher:
|
||||
)
|
||||
message = render_template(template_str, ctx)
|
||||
|
||||
if target.type == "telegram":
|
||||
return await self._send_telegram(target, message, event)
|
||||
elif target.type == "webhook":
|
||||
return await self._send_webhook(target, message, event)
|
||||
elif target.type == "email":
|
||||
return await self._send_email(target, message, event)
|
||||
send_method = {
|
||||
"telegram": self._send_telegram,
|
||||
"webhook": self._send_webhook,
|
||||
"email": self._send_email,
|
||||
"discord": self._send_discord,
|
||||
"slack": self._send_slack,
|
||||
"ntfy": self._send_ntfy,
|
||||
"matrix": self._send_matrix,
|
||||
}.get(target.type)
|
||||
if send_method:
|
||||
return await send_method(target, message, event)
|
||||
return {"success": False, "error": f"Unknown target type: {target.type}"}
|
||||
|
||||
async def _send_telegram(
|
||||
@@ -172,15 +177,7 @@ class NotificationDispatcher:
|
||||
|
||||
results.append(text_result)
|
||||
|
||||
# Return aggregate result
|
||||
successes = sum(1 for r in results if r.get("success"))
|
||||
if successes == len(results):
|
||||
return {"success": True, "receivers": len(results)}
|
||||
elif successes > 0:
|
||||
return {"success": True, "receivers": len(results), "partial_failures": len(results) - successes}
|
||||
elif results:
|
||||
return results[0] # All failed — return first error
|
||||
return {"success": False, "error": "No receivers configured"}
|
||||
return self._aggregate_results(results)
|
||||
|
||||
async def _send_webhook(
|
||||
self, target: TargetConfig, message: str, event: ServiceEvent
|
||||
@@ -208,14 +205,7 @@ class NotificationDispatcher:
|
||||
client = WebhookClient(session, url, headers)
|
||||
results.append(await client.send(payload))
|
||||
|
||||
successes = sum(1 for r in results if r.get("success"))
|
||||
if successes == len(results):
|
||||
return {"success": True, "receivers": len(results)}
|
||||
elif successes > 0:
|
||||
return {"success": True, "receivers": len(results), "partial_failures": len(results) - successes}
|
||||
elif results:
|
||||
return results[0]
|
||||
return {"success": False, "error": "No receivers configured"}
|
||||
return self._aggregate_results(results)
|
||||
|
||||
async def _send_email(
|
||||
self, target: TargetConfig, message: str, event: ServiceEvent
|
||||
@@ -254,6 +244,104 @@ class NotificationDispatcher:
|
||||
)
|
||||
results.append(result)
|
||||
|
||||
return self._aggregate_results(results)
|
||||
|
||||
async def _send_discord(
|
||||
self, target: TargetConfig, message: str, event: ServiceEvent
|
||||
) -> dict[str, Any]:
|
||||
from .discord.client import DiscordClient
|
||||
|
||||
receivers = target.receivers or [{"webhook_url": target.config.get("webhook_url", "")}]
|
||||
username = target.config.get("username")
|
||||
|
||||
results: list[dict[str, Any]] = []
|
||||
async with aiohttp.ClientSession() as session:
|
||||
client = DiscordClient(session)
|
||||
for receiver in receivers:
|
||||
webhook_url = receiver.get("webhook_url")
|
||||
if not webhook_url:
|
||||
results.append({"success": False, "error": "Missing webhook_url"})
|
||||
continue
|
||||
results.append(await client.send(webhook_url, message, username=username))
|
||||
|
||||
return self._aggregate_results(results)
|
||||
|
||||
async def _send_slack(
|
||||
self, target: TargetConfig, message: str, event: ServiceEvent
|
||||
) -> dict[str, Any]:
|
||||
from .slack.client import SlackClient
|
||||
|
||||
receivers = target.receivers or [{"webhook_url": target.config.get("webhook_url", "")}]
|
||||
username = target.config.get("username")
|
||||
|
||||
results: list[dict[str, Any]] = []
|
||||
async with aiohttp.ClientSession() as session:
|
||||
client = SlackClient(session)
|
||||
for receiver in receivers:
|
||||
webhook_url = receiver.get("webhook_url")
|
||||
if not webhook_url:
|
||||
results.append({"success": False, "error": "Missing webhook_url"})
|
||||
continue
|
||||
results.append(await client.send(webhook_url, message, username=username))
|
||||
|
||||
return self._aggregate_results(results)
|
||||
|
||||
async def _send_ntfy(
|
||||
self, target: TargetConfig, message: str, event: ServiceEvent
|
||||
) -> dict[str, Any]:
|
||||
from .ntfy.client import NtfyClient
|
||||
|
||||
server_url = target.config.get("server_url", "https://ntfy.sh")
|
||||
auth_token = target.config.get("auth_token")
|
||||
receivers = target.receivers or [{"topic": target.config.get("topic", "")}]
|
||||
|
||||
title = f"{event.event_type.value}: {event.collection_name}"
|
||||
|
||||
results: list[dict[str, Any]] = []
|
||||
async with aiohttp.ClientSession() as session:
|
||||
client = NtfyClient(session)
|
||||
for receiver in receivers:
|
||||
topic = receiver.get("topic")
|
||||
if not topic:
|
||||
results.append({"success": False, "error": "Missing topic"})
|
||||
continue
|
||||
priority = receiver.get("priority", 3)
|
||||
results.append(await client.send(
|
||||
server_url, topic, message,
|
||||
title=title, priority=priority, auth_token=auth_token,
|
||||
))
|
||||
|
||||
return self._aggregate_results(results)
|
||||
|
||||
async def _send_matrix(
|
||||
self, target: TargetConfig, message: str, event: ServiceEvent
|
||||
) -> dict[str, Any]:
|
||||
from .matrix.client import MatrixClient
|
||||
|
||||
homeserver = target.config.get("homeserver_url")
|
||||
access_token = target.config.get("access_token")
|
||||
if not homeserver or not access_token:
|
||||
return {"success": False, "error": "Missing Matrix homeserver_url or access_token"}
|
||||
|
||||
receivers = target.receivers or [{"room_id": target.config.get("room_id", "")}]
|
||||
|
||||
results: list[dict[str, Any]] = []
|
||||
async with aiohttp.ClientSession() as session:
|
||||
client = MatrixClient(session, homeserver, access_token)
|
||||
for receiver in receivers:
|
||||
room_id = receiver.get("room_id")
|
||||
if not room_id:
|
||||
results.append({"success": False, "error": "Missing room_id"})
|
||||
continue
|
||||
results.append(await client.send_message(
|
||||
room_id, message, html_message=message,
|
||||
))
|
||||
|
||||
return self._aggregate_results(results)
|
||||
|
||||
@staticmethod
|
||||
def _aggregate_results(results: list[dict[str, Any]]) -> dict[str, Any]:
|
||||
"""Aggregate broadcast results into a single result dict."""
|
||||
successes = sum(1 for r in results if r.get("success"))
|
||||
if successes == len(results) and results:
|
||||
return {"success": True, "receivers": len(results)}
|
||||
|
||||
@@ -0,0 +1,5 @@
|
||||
"""Matrix notification client."""
|
||||
|
||||
from .client import MatrixClient
|
||||
|
||||
__all__ = ["MatrixClient"]
|
||||
@@ -0,0 +1,79 @@
|
||||
"""Matrix client-server API client for sending messages."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import logging
|
||||
import time
|
||||
from typing import Any
|
||||
|
||||
import aiohttp
|
||||
|
||||
_LOGGER = logging.getLogger(__name__)
|
||||
|
||||
# Monotonically increasing transaction counter for idempotent sends
|
||||
_txn_counter = int(time.time() * 1000)
|
||||
|
||||
|
||||
def _next_txn_id() -> str:
|
||||
global _txn_counter
|
||||
_txn_counter += 1
|
||||
return str(_txn_counter)
|
||||
|
||||
|
||||
class MatrixClient:
|
||||
"""Sends messages to Matrix rooms via the client-server API."""
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
session: aiohttp.ClientSession,
|
||||
homeserver_url: str,
|
||||
access_token: str,
|
||||
) -> None:
|
||||
self._session = session
|
||||
self._homeserver = homeserver_url.rstrip("/")
|
||||
self._token = access_token
|
||||
|
||||
async def send_message(
|
||||
self,
|
||||
room_id: str,
|
||||
message: str,
|
||||
html_message: str | None = None,
|
||||
) -> dict[str, Any]:
|
||||
"""Send a text message to a Matrix room.
|
||||
|
||||
Args:
|
||||
room_id: Internal room ID (e.g. !abc:matrix.org)
|
||||
message: Plain text body
|
||||
html_message: Optional HTML-formatted body
|
||||
"""
|
||||
if not room_id:
|
||||
return {"success": False, "error": "Missing room_id"}
|
||||
|
||||
txn_id = _next_txn_id()
|
||||
# URL-encode the room_id (! and : need encoding)
|
||||
encoded_room = room_id.replace("!", "%21").replace(":", "%3A")
|
||||
url = f"{self._homeserver}/_matrix/client/v3/rooms/{encoded_room}/send/m.room.message/{txn_id}"
|
||||
|
||||
body: dict[str, Any] = {
|
||||
"msgtype": "m.text",
|
||||
"body": message,
|
||||
}
|
||||
if html_message:
|
||||
body["format"] = "org.matrix.custom.html"
|
||||
body["formatted_body"] = html_message
|
||||
|
||||
headers = {
|
||||
"Authorization": f"Bearer {self._token}",
|
||||
"Content-Type": "application/json",
|
||||
}
|
||||
|
||||
try:
|
||||
async with self._session.put(url, json=body, headers=headers) as resp:
|
||||
if 200 <= resp.status < 300:
|
||||
return {"success": True}
|
||||
resp_body = await resp.text()
|
||||
if resp.status == 429:
|
||||
_LOGGER.warning("Matrix rate limited: %s", resp_body[:200])
|
||||
return {"success": False, "error": f"HTTP {resp.status}: {resp_body[:200]}"}
|
||||
except aiohttp.ClientError as e:
|
||||
return {"success": False, "error": str(e)}
|
||||
@@ -0,0 +1,5 @@
|
||||
"""ntfy push notification client."""
|
||||
|
||||
from .client import NtfyClient
|
||||
|
||||
__all__ = ["NtfyClient"]
|
||||
@@ -0,0 +1,60 @@
|
||||
"""ntfy push notification client."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import logging
|
||||
from typing import Any
|
||||
|
||||
import aiohttp
|
||||
|
||||
_LOGGER = logging.getLogger(__name__)
|
||||
|
||||
|
||||
class NtfyClient:
|
||||
"""Sends push notifications via ntfy server."""
|
||||
|
||||
def __init__(self, session: aiohttp.ClientSession) -> None:
|
||||
self._session = session
|
||||
|
||||
async def send(
|
||||
self,
|
||||
server_url: str,
|
||||
topic: str,
|
||||
message: str,
|
||||
title: str | None = None,
|
||||
priority: int = 3,
|
||||
tags: list[str] | None = None,
|
||||
click_url: str | None = None,
|
||||
auth_token: str | None = None,
|
||||
) -> dict[str, Any]:
|
||||
"""Send a push notification to an ntfy topic."""
|
||||
if not server_url or not topic:
|
||||
return {"success": False, "error": "Missing server_url or topic"}
|
||||
|
||||
url = f"{server_url.rstrip('/')}"
|
||||
payload: dict[str, Any] = {
|
||||
"topic": topic,
|
||||
"message": message,
|
||||
"markdown": True,
|
||||
}
|
||||
if title:
|
||||
payload["title"] = title
|
||||
if priority != 3:
|
||||
payload["priority"] = priority
|
||||
if tags:
|
||||
payload["tags"] = tags
|
||||
if click_url:
|
||||
payload["click"] = click_url
|
||||
|
||||
headers: dict[str, str] = {"Content-Type": "application/json"}
|
||||
if auth_token:
|
||||
headers["Authorization"] = f"Bearer {auth_token}"
|
||||
|
||||
try:
|
||||
async with self._session.post(url, json=payload, headers=headers) as resp:
|
||||
if 200 <= resp.status < 300:
|
||||
return {"success": True}
|
||||
body = await resp.text()
|
||||
return {"success": False, "error": f"HTTP {resp.status}: {body[:200]}"}
|
||||
except aiohttp.ClientError as e:
|
||||
return {"success": False, "error": str(e)}
|
||||
@@ -0,0 +1,5 @@
|
||||
"""Slack webhook notification client."""
|
||||
|
||||
from .client import SlackClient
|
||||
|
||||
__all__ = ["SlackClient"]
|
||||
@@ -0,0 +1,50 @@
|
||||
"""Slack incoming webhook client."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import logging
|
||||
from typing import Any
|
||||
|
||||
import aiohttp
|
||||
|
||||
_LOGGER = logging.getLogger(__name__)
|
||||
|
||||
|
||||
class SlackClient:
|
||||
"""Sends messages via Slack incoming webhook URLs."""
|
||||
|
||||
def __init__(self, session: aiohttp.ClientSession) -> None:
|
||||
self._session = session
|
||||
|
||||
async def send(
|
||||
self,
|
||||
webhook_url: str,
|
||||
message: str,
|
||||
username: str | None = None,
|
||||
icon_emoji: str | None = None,
|
||||
) -> dict[str, Any]:
|
||||
"""Send a message to a Slack incoming webhook."""
|
||||
if not webhook_url:
|
||||
return {"success": False, "error": "Missing webhook_url"}
|
||||
|
||||
payload: dict[str, Any] = {"text": message}
|
||||
if username:
|
||||
payload["username"] = username
|
||||
if icon_emoji:
|
||||
payload["icon_emoji"] = icon_emoji
|
||||
|
||||
try:
|
||||
async with self._session.post(
|
||||
webhook_url,
|
||||
json=payload,
|
||||
headers={"Content-Type": "application/json"},
|
||||
) as resp:
|
||||
if resp.status == 429:
|
||||
_LOGGER.warning("Slack rate limited")
|
||||
return {"success": False, "error": "Rate limited by Slack"}
|
||||
if 200 <= resp.status < 300:
|
||||
return {"success": True}
|
||||
body = await resp.text()
|
||||
return {"success": False, "error": f"HTTP {resp.status}: {body[:200]}"}
|
||||
except aiohttp.ClientError as e:
|
||||
return {"success": False, "error": str(e)}
|
||||
@@ -0,0 +1,5 @@
|
||||
"""Default command template loader."""
|
||||
|
||||
from .loader import load_default_command_templates
|
||||
|
||||
__all__ = ["load_default_command_templates"]
|
||||
@@ -0,0 +1,8 @@
|
||||
📚 Tracked albums:
|
||||
{%- if albums %}
|
||||
{%- for album in albums %}
|
||||
• {{ album.name }} ({{ album.asset_count }} assets)
|
||||
{%- endfor %}
|
||||
{%- else %}
|
||||
(none)
|
||||
{%- endif %}
|
||||
@@ -0,0 +1,7 @@
|
||||
📋 Last {{ events | length }} events:
|
||||
{%- for event in events %}
|
||||
{{ event.date }} — {{ event.type }}: {{ event.album }}
|
||||
{%- endfor %}
|
||||
{%- if not events %}
|
||||
No events yet.
|
||||
{%- endif %}
|
||||
@@ -0,0 +1,4 @@
|
||||
⭐ Favorites:
|
||||
{%- for asset in assets %}
|
||||
• {{ asset.originalFileName }}
|
||||
{%- endfor %}
|
||||
@@ -0,0 +1,4 @@
|
||||
Available commands:
|
||||
{%- for cmd in commands %}
|
||||
/{{ cmd.name }} — {{ cmd.description }}
|
||||
{%- endfor %}
|
||||
@@ -0,0 +1,4 @@
|
||||
📸 Latest:
|
||||
{%- for asset in assets %}
|
||||
• {{ asset.originalFileName }}{% if asset.year %} ({{ asset.year }}){% endif %}
|
||||
{%- endfor %}
|
||||
@@ -0,0 +1,4 @@
|
||||
📅 On this day:
|
||||
{%- for asset in assets %}
|
||||
• {{ asset.originalFileName }}{% if asset.year %} ({{ asset.year }}){% endif %}
|
||||
{%- endfor %}
|
||||
@@ -0,0 +1 @@
|
||||
No results found.
|
||||
@@ -0,0 +1,5 @@
|
||||
👥 {{ people | length }} people:
|
||||
{{ people | join(", ") }}
|
||||
{%- if not people %}
|
||||
No people detected.
|
||||
{%- endif %}
|
||||
@@ -0,0 +1,4 @@
|
||||
🎲 Random:
|
||||
{%- for asset in assets %}
|
||||
• {{ asset.originalFileName }}
|
||||
{%- endfor %}
|
||||
@@ -0,0 +1 @@
|
||||
Please wait {{ wait }}s before using this command again.
|
||||
@@ -0,0 +1,8 @@
|
||||
{%- if command == "find" %}📄 Files matching "{{ query }}":
|
||||
{%- elif command == "person" %}👤 Photos of {{ query }}:
|
||||
{%- elif command == "place" %}📍 Photos from {{ query }}:
|
||||
{%- else %}🔍 Results for "{{ query }}":
|
||||
{%- endif %}
|
||||
{%- for asset in assets %}
|
||||
• {{ asset.originalFileName }}{% if asset.year %} ({{ asset.year }}){% endif %}
|
||||
{%- endfor %}
|
||||
@@ -0,0 +1 @@
|
||||
Hi! I'm your Notify Bridge bot. Use /help to see available commands.
|
||||
@@ -0,0 +1,4 @@
|
||||
📊 Status
|
||||
Trackers: {{ trackers_active }}/{{ trackers_total }} active
|
||||
Albums: {{ total_albums }}
|
||||
Last event: {{ last_event }}
|
||||
@@ -0,0 +1,4 @@
|
||||
📋 Album summary ({{ albums | length }}):
|
||||
{%- for album in albums %}
|
||||
• {{ album.name }}: {{ album.asset_count }} assets
|
||||
{%- endfor %}
|
||||
@@ -0,0 +1,36 @@
|
||||
"""Load default command templates from .jinja2 files."""
|
||||
|
||||
import logging
|
||||
from pathlib import Path
|
||||
|
||||
_LOGGER = logging.getLogger(__name__)
|
||||
|
||||
_DEFAULTS_DIR = Path(__file__).parent
|
||||
|
||||
# All command template slot names (file stem = slot name)
|
||||
COMMAND_SLOT_NAMES = [
|
||||
"start", "help", "status", "albums", "events", "people",
|
||||
"search", "latest", "favorites", "random", "summary", "memory",
|
||||
"rate_limited", "no_results",
|
||||
]
|
||||
|
||||
|
||||
def load_default_command_templates(locale: str = "en") -> dict[str, str]:
|
||||
"""Load default command template strings for a locale.
|
||||
|
||||
Returns dict mapping slot_name -> template string.
|
||||
"""
|
||||
locale_dir = _DEFAULTS_DIR / locale
|
||||
if not locale_dir.is_dir():
|
||||
_LOGGER.warning("No default command templates for locale '%s'", locale)
|
||||
return {}
|
||||
|
||||
templates: dict[str, str] = {}
|
||||
for slot_name in COMMAND_SLOT_NAMES:
|
||||
filepath = locale_dir / f"{slot_name}.jinja2"
|
||||
if filepath.exists():
|
||||
templates[slot_name] = filepath.read_text(encoding="utf-8").strip()
|
||||
else:
|
||||
_LOGGER.debug("Missing default command template: %s/%s.jinja2", locale, slot_name)
|
||||
|
||||
return templates
|
||||
@@ -0,0 +1,8 @@
|
||||
📚 Отслеживаемые альбомы:
|
||||
{%- if albums %}
|
||||
{%- for album in albums %}
|
||||
• {{ album.name }} ({{ album.asset_count }} файлов)
|
||||
{%- endfor %}
|
||||
{%- else %}
|
||||
(нет)
|
||||
{%- endif %}
|
||||
@@ -0,0 +1,7 @@
|
||||
📋 Последние {{ events | length }} событий:
|
||||
{%- for event in events %}
|
||||
{{ event.date }} — {{ event.type }}: {{ event.album }}
|
||||
{%- endfor %}
|
||||
{%- if not events %}
|
||||
Пока нет событий.
|
||||
{%- endif %}
|
||||
@@ -0,0 +1,4 @@
|
||||
⭐ Избранное:
|
||||
{%- for asset in assets %}
|
||||
• {{ asset.originalFileName }}
|
||||
{%- endfor %}
|
||||
@@ -0,0 +1,4 @@
|
||||
Доступные команды:
|
||||
{%- for cmd in commands %}
|
||||
/{{ cmd.name }} — {{ cmd.description }}
|
||||
{%- endfor %}
|
||||
@@ -0,0 +1,4 @@
|
||||
📸 Последние:
|
||||
{%- for asset in assets %}
|
||||
• {{ asset.originalFileName }}{% if asset.year %} ({{ asset.year }}){% endif %}
|
||||
{%- endfor %}
|
||||
@@ -0,0 +1,4 @@
|
||||
📅 В этот день:
|
||||
{%- for asset in assets %}
|
||||
• {{ asset.originalFileName }}{% if asset.year %} ({{ asset.year }}){% endif %}
|
||||
{%- endfor %}
|
||||
@@ -0,0 +1 @@
|
||||
Ничего не найдено.
|
||||
@@ -0,0 +1,5 @@
|
||||
👥 {{ people | length }} людей:
|
||||
{{ people | join(", ") }}
|
||||
{%- if not people %}
|
||||
Люди не обнаружены.
|
||||
{%- endif %}
|
||||
@@ -0,0 +1,4 @@
|
||||
🎲 Случайные:
|
||||
{%- for asset in assets %}
|
||||
• {{ asset.originalFileName }}
|
||||
{%- endfor %}
|
||||
@@ -0,0 +1 @@
|
||||
Подождите {{ wait }} сек. перед повторным использованием.
|
||||
@@ -0,0 +1,8 @@
|
||||
{%- if command == "find" %}📄 Файлы по запросу "{{ query }}":
|
||||
{%- elif command == "person" %}👤 Фото {{ query }}:
|
||||
{%- elif command == "place" %}📍 Фото из {{ query }}:
|
||||
{%- else %}🔍 Результаты для "{{ query }}":
|
||||
{%- endif %}
|
||||
{%- for asset in assets %}
|
||||
• {{ asset.originalFileName }}{% if asset.year %} ({{ asset.year }}){% endif %}
|
||||
{%- endfor %}
|
||||
@@ -0,0 +1 @@
|
||||
Привет! Я бот Notify Bridge. Используйте /help для списка команд.
|
||||
@@ -0,0 +1,4 @@
|
||||
📊 Статус
|
||||
Трекеры: {{ trackers_active }}/{{ trackers_total }} активных
|
||||
Альбомы: {{ total_albums }}
|
||||
Последнее событие: {{ last_event }}
|
||||
@@ -0,0 +1,4 @@
|
||||
📋 Сводка альбомов ({{ albums | length }}):
|
||||
{%- for album in albums %}
|
||||
• {{ album.name }}: {{ album.asset_count }} файлов
|
||||
{%- endfor %}
|
||||
@@ -107,18 +107,9 @@ async def delete_command_config(
|
||||
session: AsyncSession = Depends(get_session),
|
||||
):
|
||||
"""Delete a command config. Fails if in use by any command tracker."""
|
||||
from .delete_protection import check_command_config, raise_if_used
|
||||
config = await _get_user_config(session, config_id, user.id)
|
||||
|
||||
# Check if any command tracker references this config
|
||||
result = await session.exec(
|
||||
select(CommandTracker).where(CommandTracker.command_config_id == config_id)
|
||||
)
|
||||
if result.first():
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_409_CONFLICT,
|
||||
detail="Cannot delete: command config is in use by a command tracker",
|
||||
)
|
||||
|
||||
raise_if_used(await check_command_config(session, config.id), config.name)
|
||||
await session.delete(config)
|
||||
await session.commit()
|
||||
|
||||
|
||||
@@ -95,6 +95,103 @@ async def _get(session: AsyncSession, config_id: int, user_id: int) -> CommandTe
|
||||
# Routes
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
@router.get("/variables")
|
||||
async def get_command_variables():
|
||||
"""Get variable reference for each command template slot."""
|
||||
common_vars = {
|
||||
"locale": "Current locale (en/ru)",
|
||||
}
|
||||
asset_fields = {
|
||||
"id": "Asset ID (UUID)",
|
||||
"originalFileName": "Original filename",
|
||||
"type": "IMAGE or VIDEO",
|
||||
"createdAt": "Creation date/time (ISO 8601)",
|
||||
"year": "Year of the memory (memory command only)",
|
||||
}
|
||||
album_fields = {
|
||||
"name": "Album name",
|
||||
"asset_count": "Number of assets in the album",
|
||||
"id": "Album ID (UUID)",
|
||||
}
|
||||
command_fields = {
|
||||
"name": "Command name (e.g. status, albums)",
|
||||
"description": "Command description text",
|
||||
}
|
||||
event_fields = {
|
||||
"type": "Event type (assets_added, assets_removed, etc.)",
|
||||
"album": "Album/collection name",
|
||||
"count": "Number of affected assets",
|
||||
"date": "Event date/time string (MM/DD HH:MM)",
|
||||
}
|
||||
|
||||
assets_slot = lambda desc: {
|
||||
"description": desc,
|
||||
"variables": {**common_vars, "assets": "List of asset dicts (use {% for asset in assets %})", "count": "Number of results"},
|
||||
"asset_fields": asset_fields,
|
||||
}
|
||||
|
||||
return {
|
||||
"start": {
|
||||
"description": "/start greeting message",
|
||||
"variables": {**common_vars, "bot_name": "Bot display name"},
|
||||
},
|
||||
"help": {
|
||||
"description": "/help command listing",
|
||||
"variables": {**common_vars, "commands": "List of command dicts (use {% for cmd in commands %})"},
|
||||
"command_fields": command_fields,
|
||||
},
|
||||
"status": {
|
||||
"description": "/status tracker summary",
|
||||
"variables": {
|
||||
**common_vars,
|
||||
"trackers_active": "Number of active trackers",
|
||||
"trackers_total": "Total tracker count",
|
||||
"total_albums": "Total tracked albums",
|
||||
"last_event": "Last event timestamp string",
|
||||
},
|
||||
},
|
||||
"albums": {
|
||||
"description": "/albums tracked albums list",
|
||||
"variables": {**common_vars, "albums": "List of album dicts (use {% for album in albums %})"},
|
||||
"album_fields": album_fields,
|
||||
},
|
||||
"events": {
|
||||
"description": "/events recent events",
|
||||
"variables": {**common_vars, "events": "List of event dicts (use {% for event in events %})"},
|
||||
"event_fields": event_fields,
|
||||
},
|
||||
"people": {
|
||||
"description": "/people detected people",
|
||||
"variables": {**common_vars, "people": "List of name strings (use {% for name in people %})"},
|
||||
},
|
||||
"search": {
|
||||
**assets_slot("/search, /find, /person, /place results"),
|
||||
"variables": {**common_vars, "assets": "List of asset dicts (use {% for asset in assets %})", "query": "Search query", "command": "Actual command name (search/find/person/place)", "count": "Number of results"},
|
||||
},
|
||||
"latest": assets_slot("/latest recent photos"),
|
||||
"favorites": assets_slot("/favorites starred items"),
|
||||
"random": assets_slot("/random random photos"),
|
||||
"summary": {
|
||||
"description": "/summary album summary",
|
||||
"variables": {**common_vars, "albums": "List of album dicts (use {% for album in albums %})"},
|
||||
"album_fields": album_fields,
|
||||
},
|
||||
"memory": {
|
||||
"description": "/memory On This Day photos",
|
||||
"variables": {**common_vars, "assets": "List of asset dicts with year field (use {% for asset in assets %})", "count": "Number of results"},
|
||||
"asset_fields": asset_fields,
|
||||
},
|
||||
"rate_limited": {
|
||||
"description": "Rate limit warning message",
|
||||
"variables": {**common_vars, "wait": "Seconds to wait before retry"},
|
||||
},
|
||||
"no_results": {
|
||||
"description": "Empty results fallback",
|
||||
"variables": {**common_vars, "command": "Command name", "query": "Search query (empty for non-search commands)"},
|
||||
},
|
||||
}
|
||||
|
||||
|
||||
@router.get("")
|
||||
async def list_configs(
|
||||
provider_type: str | None = None,
|
||||
@@ -168,7 +265,9 @@ async def delete_config(
|
||||
user: User = Depends(get_current_user),
|
||||
session: AsyncSession = Depends(get_session),
|
||||
):
|
||||
from .delete_protection import check_command_template_config, raise_if_used
|
||||
config = await _get(session, config_id, user.id)
|
||||
raise_if_used(await check_command_template_config(session, config.id), config.name)
|
||||
slot_result = await session.exec(
|
||||
select(CommandTemplateSlot).where(CommandTemplateSlot.config_id == config.id)
|
||||
)
|
||||
@@ -189,28 +288,42 @@ async def preview_raw(
|
||||
):
|
||||
"""Render arbitrary Jinja2 template text with sample command context."""
|
||||
sample_ctx = {
|
||||
# /start
|
||||
"bot_name": "NotifyBridgeBot",
|
||||
"locale": "en",
|
||||
# /status
|
||||
"trackers_active": 2,
|
||||
"trackers_total": 3,
|
||||
"total_albums": 5,
|
||||
"last_event": "2026-03-19 14:30",
|
||||
# /help
|
||||
"commands": [
|
||||
{"name": "status", "description": "Show tracker status"},
|
||||
{"name": "albums", "description": "List tracked albums"},
|
||||
{"name": "latest", "description": "Show latest photos"},
|
||||
],
|
||||
# /albums, /summary
|
||||
"albums": [
|
||||
{"name": "Family Photos", "asset_count": 142, "url": "https://example.com/albums/1"},
|
||||
{"name": "Vacation 2025", "asset_count": 87, "url": "https://example.com/albums/2"},
|
||||
{"name": "Family Photos", "asset_count": 142, "id": "abc-123"},
|
||||
{"name": "Vacation 2025", "asset_count": 87, "id": "def-456"},
|
||||
],
|
||||
# /events
|
||||
"events": [
|
||||
{"type": "assets_added", "album": "Family Photos", "count": 3, "date": "2026-03-19 14:30"},
|
||||
{"type": "assets_removed", "album": "Vacation 2025", "count": 1, "date": "2026-03-19 12:00"},
|
||||
{"type": "assets_added", "album": "Family Photos", "count": 3, "date": "03/19 14:30"},
|
||||
{"type": "assets_removed", "album": "Vacation 2025", "count": 1, "date": "03/19 12:00"},
|
||||
],
|
||||
# /people
|
||||
"people": ["Alice", "Bob", "Charlie"],
|
||||
# /search, /find, /person, /place, /latest, /favorites, /random, /memory
|
||||
"assets": [
|
||||
{"filename": "IMG_001.jpg", "type": "IMAGE", "created_at": "2026-03-19T14:30:00"},
|
||||
{"filename": "VID_002.mp4", "type": "VIDEO", "created_at": "2026-03-19T15:00:00"},
|
||||
{"id": "a1", "originalFileName": "IMG_001.jpg", "type": "IMAGE", "createdAt": "2026-03-19T14:30:00", "year": 2024},
|
||||
{"id": "a2", "originalFileName": "VID_002.mp4", "type": "VIDEO", "createdAt": "2026-03-19T15:00:00", "year": 2023},
|
||||
],
|
||||
"search_query": "sunset",
|
||||
"search_results_count": 5,
|
||||
"command": "status",
|
||||
"bot_name": "NotifyBridgeBot",
|
||||
"locale": "en",
|
||||
"query": "sunset",
|
||||
"command": "search",
|
||||
"count": 2,
|
||||
# /rate_limited
|
||||
"wait": 15,
|
||||
}
|
||||
|
||||
try:
|
||||
|
||||
@@ -0,0 +1,179 @@
|
||||
"""Delete protection — prevents deletion of entities that are in use.
|
||||
|
||||
Each check function returns a list of consumer descriptions. If non-empty,
|
||||
the entity cannot be deleted.
|
||||
"""
|
||||
|
||||
from fastapi import HTTPException, status
|
||||
from sqlmodel import select
|
||||
from sqlmodel.ext.asyncio.session import AsyncSession
|
||||
|
||||
from ..database.models import (
|
||||
CommandConfig,
|
||||
CommandTracker,
|
||||
CommandTrackerListener,
|
||||
NotificationTarget,
|
||||
NotificationTracker,
|
||||
NotificationTrackerTarget,
|
||||
TargetReceiver,
|
||||
TelegramChat,
|
||||
)
|
||||
|
||||
|
||||
def raise_if_used(consumers: list[str], entity_name: str) -> None:
|
||||
"""Raise 409 Conflict if the entity has consumers."""
|
||||
if consumers:
|
||||
detail = f"Cannot delete {entity_name}: used by {len(consumers)} consumer(s). " + "; ".join(consumers)
|
||||
raise HTTPException(status_code=status.HTTP_409_CONFLICT, detail=detail)
|
||||
|
||||
|
||||
async def check_service_provider(session: AsyncSession, provider_id: int) -> list[str]:
|
||||
"""Check if a ServiceProvider is used by any trackers."""
|
||||
consumers = []
|
||||
result = await session.exec(
|
||||
select(NotificationTracker).where(NotificationTracker.provider_id == provider_id)
|
||||
)
|
||||
for t in result.all():
|
||||
consumers.append(f"Notification Tracker: {t.name}")
|
||||
result = await session.exec(
|
||||
select(CommandTracker).where(CommandTracker.provider_id == provider_id)
|
||||
)
|
||||
for t in result.all():
|
||||
consumers.append(f"Command Tracker: {t.name}")
|
||||
return consumers
|
||||
|
||||
|
||||
async def check_telegram_bot(session: AsyncSession, bot_id: int) -> list[str]:
|
||||
"""Check if a TelegramBot is used by any targets or command listeners."""
|
||||
consumers = []
|
||||
# Check notification targets with this bot in config
|
||||
result = await session.exec(select(NotificationTarget))
|
||||
for t in result.all():
|
||||
if t.config.get("bot_id") == bot_id or t.config.get("bot_token"):
|
||||
# Need to verify it's actually this bot
|
||||
if t.config.get("bot_id") == bot_id:
|
||||
consumers.append(f"Target: {t.name}")
|
||||
# Check command tracker listeners
|
||||
result = await session.exec(
|
||||
select(CommandTrackerListener).where(
|
||||
CommandTrackerListener.listener_type == "telegram_bot",
|
||||
CommandTrackerListener.listener_id == bot_id,
|
||||
)
|
||||
)
|
||||
for listener in result.all():
|
||||
tracker = await session.get(CommandTracker, listener.command_tracker_id)
|
||||
name = tracker.name if tracker else f"#{listener.command_tracker_id}"
|
||||
consumers.append(f"Command Tracker Listener: {name}")
|
||||
return consumers
|
||||
|
||||
|
||||
async def check_email_bot(session: AsyncSession, bot_id: int) -> list[str]:
|
||||
"""Check if an EmailBot is used by any targets."""
|
||||
consumers = []
|
||||
result = await session.exec(
|
||||
select(NotificationTarget).where(NotificationTarget.type == "email")
|
||||
)
|
||||
for t in result.all():
|
||||
if t.config.get("email_bot_id") == bot_id:
|
||||
consumers.append(f"Target: {t.name}")
|
||||
return consumers
|
||||
|
||||
|
||||
async def check_matrix_bot(session: AsyncSession, bot_id: int) -> list[str]:
|
||||
"""Check if a MatrixBot is used by any targets."""
|
||||
consumers = []
|
||||
result = await session.exec(
|
||||
select(NotificationTarget).where(NotificationTarget.type == "matrix")
|
||||
)
|
||||
for t in result.all():
|
||||
if t.config.get("matrix_bot_id") == bot_id:
|
||||
consumers.append(f"Target: {t.name}")
|
||||
return consumers
|
||||
|
||||
|
||||
async def check_tracking_config(session: AsyncSession, config_id: int) -> list[str]:
|
||||
"""Check if a TrackingConfig is used by any tracker-target links."""
|
||||
consumers = []
|
||||
result = await session.exec(
|
||||
select(NotificationTrackerTarget).where(
|
||||
NotificationTrackerTarget.tracking_config_id == config_id
|
||||
)
|
||||
)
|
||||
for tt in result.all():
|
||||
tracker = await session.get(NotificationTracker, tt.tracker_id)
|
||||
target = await session.get(NotificationTarget, tt.target_id)
|
||||
tracker_name = tracker.name if tracker else f"#{tt.tracker_id}"
|
||||
target_name = target.name if target else f"#{tt.target_id}"
|
||||
consumers.append(f"Tracker Link: {tracker_name} → {target_name}")
|
||||
return consumers
|
||||
|
||||
|
||||
async def check_template_config(session: AsyncSession, config_id: int) -> list[str]:
|
||||
"""Check if a TemplateConfig is used by any tracker-target links."""
|
||||
consumers = []
|
||||
result = await session.exec(
|
||||
select(NotificationTrackerTarget).where(
|
||||
NotificationTrackerTarget.template_config_id == config_id
|
||||
)
|
||||
)
|
||||
for tt in result.all():
|
||||
tracker = await session.get(NotificationTracker, tt.tracker_id)
|
||||
target = await session.get(NotificationTarget, tt.target_id)
|
||||
tracker_name = tracker.name if tracker else f"#{tt.tracker_id}"
|
||||
target_name = target.name if target else f"#{tt.target_id}"
|
||||
consumers.append(f"Tracker Link: {tracker_name} → {target_name}")
|
||||
return consumers
|
||||
|
||||
|
||||
async def check_command_template_config(session: AsyncSession, config_id: int) -> list[str]:
|
||||
"""Check if a CommandTemplateConfig is used by any command configs."""
|
||||
consumers = []
|
||||
result = await session.exec(
|
||||
select(CommandConfig).where(
|
||||
CommandConfig.command_template_config_id == config_id
|
||||
)
|
||||
)
|
||||
for c in result.all():
|
||||
consumers.append(f"Command Config: {c.name}")
|
||||
return consumers
|
||||
|
||||
|
||||
async def check_command_config(session: AsyncSession, config_id: int) -> list[str]:
|
||||
"""Check if a CommandConfig is used by any command trackers."""
|
||||
consumers = []
|
||||
result = await session.exec(
|
||||
select(CommandTracker).where(CommandTracker.command_config_id == config_id)
|
||||
)
|
||||
for t in result.all():
|
||||
consumers.append(f"Command Tracker: {t.name}")
|
||||
return consumers
|
||||
|
||||
|
||||
async def check_notification_target(session: AsyncSession, target_id: int) -> list[str]:
|
||||
"""Check if a NotificationTarget is used by any tracker-target links."""
|
||||
consumers = []
|
||||
result = await session.exec(
|
||||
select(NotificationTrackerTarget).where(
|
||||
NotificationTrackerTarget.target_id == target_id
|
||||
)
|
||||
)
|
||||
for tt in result.all():
|
||||
tracker = await session.get(NotificationTracker, tt.tracker_id)
|
||||
name = tracker.name if tracker else f"#{tt.tracker_id}"
|
||||
consumers.append(f"Notification Tracker: {name}")
|
||||
return consumers
|
||||
|
||||
|
||||
async def check_notification_tracker(session: AsyncSession, tracker_id: int) -> list[str]:
|
||||
"""Check if a NotificationTracker has any linked targets."""
|
||||
consumers = []
|
||||
result = await session.exec(
|
||||
select(NotificationTrackerTarget).where(
|
||||
NotificationTrackerTarget.tracker_id == tracker_id
|
||||
)
|
||||
)
|
||||
for tt in result.all():
|
||||
target = await session.get(NotificationTarget, tt.target_id)
|
||||
name = target.name if target else f"#{tt.target_id}"
|
||||
consumers.append(f"Linked Target: {name}")
|
||||
return consumers
|
||||
@@ -94,7 +94,9 @@ async def delete_email_bot(
|
||||
user: User = Depends(get_current_user),
|
||||
session: AsyncSession = Depends(get_session),
|
||||
):
|
||||
from .delete_protection import check_email_bot, raise_if_used
|
||||
bot = await _get_user_bot(session, bot_id, user.id)
|
||||
raise_if_used(await check_email_bot(session, bot.id), bot.name)
|
||||
await session.delete(bot)
|
||||
await session.commit()
|
||||
|
||||
|
||||
@@ -0,0 +1,156 @@
|
||||
"""Matrix bot management API routes."""
|
||||
|
||||
import logging
|
||||
|
||||
from fastapi import APIRouter, Depends, HTTPException, status
|
||||
from pydantic import BaseModel
|
||||
from sqlmodel import select
|
||||
from sqlmodel.ext.asyncio.session import AsyncSession
|
||||
|
||||
from ..auth.dependencies import get_current_user
|
||||
from ..database.engine import get_session
|
||||
from ..database.models import MatrixBot, User
|
||||
|
||||
_LOGGER = logging.getLogger(__name__)
|
||||
|
||||
router = APIRouter(prefix="/api/matrix-bots", tags=["matrix-bots"])
|
||||
|
||||
|
||||
class MatrixBotCreate(BaseModel):
|
||||
name: str
|
||||
icon: str = ""
|
||||
homeserver_url: str
|
||||
access_token: str
|
||||
display_name: str = ""
|
||||
|
||||
|
||||
class MatrixBotUpdate(BaseModel):
|
||||
name: str | None = None
|
||||
icon: str | None = None
|
||||
homeserver_url: str | None = None
|
||||
access_token: str | None = None
|
||||
display_name: str | None = None
|
||||
|
||||
|
||||
@router.get("")
|
||||
async def list_matrix_bots(
|
||||
user: User = Depends(get_current_user),
|
||||
session: AsyncSession = Depends(get_session),
|
||||
):
|
||||
result = await session.exec(
|
||||
select(MatrixBot).where(MatrixBot.user_id == user.id)
|
||||
)
|
||||
return [_response(b) for b in result.all()]
|
||||
|
||||
|
||||
@router.post("", status_code=status.HTTP_201_CREATED)
|
||||
async def create_matrix_bot(
|
||||
body: MatrixBotCreate,
|
||||
user: User = Depends(get_current_user),
|
||||
session: AsyncSession = Depends(get_session),
|
||||
):
|
||||
bot = MatrixBot(user_id=user.id, **body.model_dump())
|
||||
session.add(bot)
|
||||
await session.commit()
|
||||
await session.refresh(bot)
|
||||
return _response(bot)
|
||||
|
||||
|
||||
@router.get("/{bot_id}")
|
||||
async def get_matrix_bot(
|
||||
bot_id: int,
|
||||
user: User = Depends(get_current_user),
|
||||
session: AsyncSession = Depends(get_session),
|
||||
):
|
||||
return _response(await _get_user_bot(session, bot_id, user.id))
|
||||
|
||||
|
||||
@router.put("/{bot_id}")
|
||||
async def update_matrix_bot(
|
||||
bot_id: int,
|
||||
body: MatrixBotUpdate,
|
||||
user: User = Depends(get_current_user),
|
||||
session: AsyncSession = Depends(get_session),
|
||||
):
|
||||
bot = await _get_user_bot(session, bot_id, user.id)
|
||||
for field, value in body.model_dump(exclude_unset=True).items():
|
||||
setattr(bot, field, value)
|
||||
session.add(bot)
|
||||
await session.commit()
|
||||
await session.refresh(bot)
|
||||
return _response(bot)
|
||||
|
||||
|
||||
@router.delete("/{bot_id}", status_code=status.HTTP_204_NO_CONTENT)
|
||||
async def delete_matrix_bot(
|
||||
bot_id: int,
|
||||
user: User = Depends(get_current_user),
|
||||
session: AsyncSession = Depends(get_session),
|
||||
):
|
||||
from .delete_protection import check_matrix_bot, raise_if_used
|
||||
bot = await _get_user_bot(session, bot_id, user.id)
|
||||
raise_if_used(await check_matrix_bot(session, bot.id), bot.name)
|
||||
await session.delete(bot)
|
||||
await session.commit()
|
||||
|
||||
|
||||
@router.post("/{bot_id}/test")
|
||||
async def test_matrix_bot(
|
||||
bot_id: int,
|
||||
room_id: str = "",
|
||||
user: User = Depends(get_current_user),
|
||||
session: AsyncSession = Depends(get_session),
|
||||
):
|
||||
"""Test Matrix bot connection by sending a message to a room.
|
||||
|
||||
If room_id is not provided, just verifies the access token by calling /whoami.
|
||||
"""
|
||||
bot = await _get_user_bot(session, bot_id, user.id)
|
||||
|
||||
import aiohttp
|
||||
async with aiohttp.ClientSession() as http:
|
||||
# Verify token with /whoami
|
||||
whoami_url = f"{bot.homeserver_url.rstrip('/')}/_matrix/client/v3/account/whoami"
|
||||
headers = {"Authorization": f"Bearer {bot.access_token}"}
|
||||
try:
|
||||
async with http.get(whoami_url, headers=headers) as resp:
|
||||
if resp.status != 200:
|
||||
body = await resp.text()
|
||||
return {"success": False, "error": f"Auth failed: HTTP {resp.status} — {body[:200]}"}
|
||||
whoami = await resp.json()
|
||||
except aiohttp.ClientError as e:
|
||||
return {"success": False, "error": f"Connection failed: {e}"}
|
||||
|
||||
result = {"success": True, "user_id": whoami.get("user_id", "")}
|
||||
|
||||
# Optionally send a test message
|
||||
if room_id:
|
||||
from notify_bridge_core.notifications.matrix.client import MatrixClient
|
||||
client = MatrixClient(http, bot.homeserver_url, bot.access_token)
|
||||
send_result = await client.send_message(
|
||||
room_id,
|
||||
"Test message from Notify Bridge",
|
||||
html_message="<b>Test message</b> from Notify Bridge",
|
||||
)
|
||||
result["send_result"] = send_result
|
||||
|
||||
return result
|
||||
|
||||
|
||||
def _response(bot: MatrixBot) -> dict:
|
||||
return {
|
||||
"id": bot.id,
|
||||
"name": bot.name,
|
||||
"icon": bot.icon,
|
||||
"homeserver_url": bot.homeserver_url,
|
||||
"access_token": f"{bot.access_token[:8]}...{bot.access_token[-4:]}" if len(bot.access_token) > 12 else "***",
|
||||
"display_name": bot.display_name,
|
||||
"created_at": bot.created_at.isoformat(),
|
||||
}
|
||||
|
||||
|
||||
async def _get_user_bot(session: AsyncSession, bot_id: int, user_id: int) -> MatrixBot:
|
||||
bot = await session.get(MatrixBot, bot_id)
|
||||
if not bot or bot.user_id != user_id:
|
||||
raise HTTPException(status_code=404, detail="Matrix bot not found")
|
||||
return bot
|
||||
@@ -111,7 +111,9 @@ async def delete_notification_tracker(
|
||||
user: User = Depends(get_current_user),
|
||||
session: AsyncSession = Depends(get_session),
|
||||
):
|
||||
from .delete_protection import check_notification_tracker, raise_if_used
|
||||
tracker = await _get_user_tracker(session, tracker_id, user.id)
|
||||
raise_if_used(await check_notification_tracker(session, tracker.id), tracker.name)
|
||||
# Delete associated tracker-target links
|
||||
result = await session.exec(
|
||||
select(NotificationTrackerTarget).where(NotificationTrackerTarget.tracker_id == tracker_id)
|
||||
|
||||
@@ -189,7 +189,9 @@ async def delete_provider(
|
||||
session: AsyncSession = Depends(get_session),
|
||||
):
|
||||
"""Delete a service provider."""
|
||||
from .delete_protection import check_service_provider, raise_if_used
|
||||
provider = await _get_user_provider(session, provider_id, user.id)
|
||||
raise_if_used(await check_service_provider(session, provider.id), provider.name)
|
||||
await session.delete(provider)
|
||||
await session.commit()
|
||||
|
||||
|
||||
@@ -31,13 +31,17 @@ class ReceiverUpdate(BaseModel):
|
||||
|
||||
def _receiver_key(target_type: str, config: dict[str, Any]) -> str:
|
||||
"""Derive a unique key for deduplication from receiver config."""
|
||||
if target_type == "telegram":
|
||||
return str(config.get("chat_id", ""))
|
||||
elif target_type == "webhook":
|
||||
return config.get("url", "")
|
||||
elif target_type == "email":
|
||||
return config.get("email", "")
|
||||
return ""
|
||||
key_fields = {
|
||||
"telegram": "chat_id",
|
||||
"webhook": "url",
|
||||
"email": "email",
|
||||
"discord": "webhook_url",
|
||||
"slack": "webhook_url",
|
||||
"ntfy": "topic",
|
||||
"matrix": "room_id",
|
||||
}
|
||||
field = key_fields.get(target_type, "")
|
||||
return str(config.get(field, "")) if field else ""
|
||||
|
||||
|
||||
@router.get("")
|
||||
|
||||
@@ -79,10 +79,11 @@ async def create_target(
|
||||
session: AsyncSession = Depends(get_session),
|
||||
):
|
||||
"""Create a new notification target."""
|
||||
if body.type not in ("telegram", "webhook", "email"):
|
||||
valid_types = ("telegram", "webhook", "email", "discord", "slack", "ntfy", "matrix")
|
||||
if body.type not in valid_types:
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_400_BAD_REQUEST,
|
||||
detail="Type must be 'telegram', 'webhook', or 'email'",
|
||||
detail=f"Type must be one of: {', '.join(valid_types)}",
|
||||
)
|
||||
target = NotificationTarget(
|
||||
user_id=user.id,
|
||||
@@ -132,15 +133,11 @@ async def delete_target(
|
||||
user: User = Depends(get_current_user),
|
||||
session: AsyncSession = Depends(get_session),
|
||||
):
|
||||
"""Delete a notification target, its tracker links, and receivers."""
|
||||
"""Delete a notification target. Fails if linked to any tracker."""
|
||||
from .delete_protection import check_notification_target, raise_if_used
|
||||
target = await _get_user_target(session, target_id, user.id)
|
||||
# Delete associated tracker-target links
|
||||
result = await session.exec(
|
||||
select(NotificationTrackerTarget).where(NotificationTrackerTarget.target_id == target_id)
|
||||
)
|
||||
for tt in result.all():
|
||||
await session.delete(tt)
|
||||
# Delete receivers
|
||||
raise_if_used(await check_notification_target(session, target.id), target.name)
|
||||
# Delete child receivers
|
||||
recv_result = await session.exec(
|
||||
select(TargetReceiver).where(TargetReceiver.target_id == target_id)
|
||||
)
|
||||
|
||||
@@ -124,7 +124,9 @@ async def delete_bot(
|
||||
session: AsyncSession = Depends(get_session),
|
||||
):
|
||||
"""Delete a registered bot and its chats."""
|
||||
from .delete_protection import check_telegram_bot, raise_if_used
|
||||
bot = await _get_user_bot(session, bot_id, user.id)
|
||||
raise_if_used(await check_telegram_bot(session, bot.id), bot.name)
|
||||
# Delete associated chats
|
||||
result = await session.exec(select(TelegramChat).where(TelegramChat.bot_id == bot_id))
|
||||
for chat in result.all():
|
||||
|
||||
@@ -300,7 +300,9 @@ async def delete_config(
|
||||
user: User = Depends(get_current_user),
|
||||
session: AsyncSession = Depends(get_session),
|
||||
):
|
||||
from .delete_protection import check_template_config, raise_if_used
|
||||
config = await _get(session, config_id, user.id)
|
||||
raise_if_used(await check_template_config(session, config.id), config.name)
|
||||
# Delete child slots first
|
||||
slot_result = await session.exec(
|
||||
select(TemplateSlot).where(TemplateSlot.config_id == config.id)
|
||||
|
||||
@@ -152,7 +152,9 @@ async def delete_config(
|
||||
user: User = Depends(get_current_user),
|
||||
session: AsyncSession = Depends(get_session),
|
||||
):
|
||||
from .delete_protection import check_tracking_config, raise_if_used
|
||||
config = await _get(session, config_id, user.id)
|
||||
raise_if_used(await check_tracking_config(session, config.id), config.name)
|
||||
await session.delete(config)
|
||||
await session.commit()
|
||||
|
||||
|
||||
@@ -192,31 +192,40 @@ async def handle_command(
|
||||
for _, _, provider in ctx_tuples:
|
||||
providers_map[provider.id] = provider
|
||||
|
||||
# Dispatch
|
||||
# Dispatch — each handler returns (fallback_text, template_context)
|
||||
# Template is tried first; if no template, fallback is returned.
|
||||
if cmd == "help":
|
||||
return _cmd_help(enabled, locale)
|
||||
if cmd == "status":
|
||||
return await _cmd_status(bot, providers_map, locale)
|
||||
if cmd == "albums":
|
||||
return await _cmd_albums(bot, providers_map, locale)
|
||||
if cmd == "events":
|
||||
return await _cmd_events(bot, providers_map, count, locale)
|
||||
if cmd == "people":
|
||||
return await _cmd_people(providers_map, locale)
|
||||
if cmd in ("search", "find", "person", "place", "latest", "random",
|
||||
"favorites", "summary", "memory"):
|
||||
return await _cmd_immich(bot, cmd, args, count, locale, response_mode, providers_map)
|
||||
fallback, ctx = _cmd_help(enabled, locale)
|
||||
elif cmd == "status":
|
||||
fallback, ctx = await _cmd_status(bot, providers_map, locale)
|
||||
elif cmd == "albums":
|
||||
fallback, ctx = await _cmd_albums(bot, providers_map, locale)
|
||||
elif cmd == "events":
|
||||
fallback, ctx = await _cmd_events(bot, providers_map, count, locale)
|
||||
elif cmd == "people":
|
||||
fallback, ctx = await _cmd_people(providers_map, locale)
|
||||
elif cmd in ("search", "find", "person", "place", "latest", "random",
|
||||
"favorites", "summary", "memory"):
|
||||
return await _cmd_immich(bot, cmd, args, count, locale, response_mode, providers_map, cmd_templates)
|
||||
else:
|
||||
return None
|
||||
|
||||
return None
|
||||
# Try template, fall back to hardcoded
|
||||
rendered = _render_cmd_template(cmd_templates, cmd, {**ctx, "locale": locale})
|
||||
return rendered if rendered else fallback
|
||||
|
||||
|
||||
def _cmd_help(enabled: list[str], locale: str) -> str:
|
||||
def _cmd_help(enabled: list[str], locale: str) -> tuple[str, dict]:
|
||||
commands = []
|
||||
lines = []
|
||||
for cmd in enabled:
|
||||
desc = COMMAND_DESCRIPTIONS.get(cmd, {})
|
||||
lines.append(f"/{cmd} — {desc.get(locale, desc.get('en', ''))}")
|
||||
desc_text = desc.get(locale, desc.get("en", ""))
|
||||
commands.append({"name": cmd, "description": desc_text})
|
||||
lines.append(f"/{cmd} — {desc_text}")
|
||||
header = {"en": "Available commands:", "ru": "Доступные команды:"}
|
||||
return header.get(locale, header["en"]) + "\n" + "\n".join(lines)
|
||||
fallback = header.get(locale, header["en"]) + "\n" + "\n".join(lines)
|
||||
return fallback, {"commands": commands}
|
||||
|
||||
|
||||
async def _get_notification_trackers_for_providers(
|
||||
@@ -264,7 +273,7 @@ async def _check_native_memory(bot: TelegramBot) -> bool:
|
||||
return False
|
||||
|
||||
|
||||
async def _cmd_status(bot: TelegramBot, providers_map: dict[int, ServiceProvider], locale: str) -> str:
|
||||
async def _cmd_status(bot: TelegramBot, providers_map: dict[int, ServiceProvider], locale: str) -> tuple[str, dict]:
|
||||
provider_ids = set(providers_map.keys())
|
||||
trackers = await _get_notification_trackers_for_providers(provider_ids)
|
||||
active = sum(1 for t in trackers if t.enabled)
|
||||
@@ -279,27 +288,33 @@ async def _cmd_status(bot: TelegramBot, providers_map: dict[int, ServiceProvider
|
||||
last_event = result.first()
|
||||
last_str = last_event.created_at.strftime("%Y-%m-%d %H:%M") if last_event else "-"
|
||||
|
||||
ctx = {"trackers_active": active, "trackers_total": total, "total_albums": total_albums, "last_event": last_str}
|
||||
|
||||
if locale == "ru":
|
||||
return (
|
||||
fallback = (
|
||||
f"📊 Статус\n"
|
||||
f"Трекеры: {active}/{total} активных\n"
|
||||
f"Альбомы: {total_albums}\n"
|
||||
f"Последнее событие: {last_str}"
|
||||
)
|
||||
return (
|
||||
f"📊 Status\n"
|
||||
f"Trackers: {active}/{total} active\n"
|
||||
f"Albums: {total_albums}\n"
|
||||
f"Last event: {last_str}"
|
||||
)
|
||||
else:
|
||||
fallback = (
|
||||
f"📊 Status\n"
|
||||
f"Trackers: {active}/{total} active\n"
|
||||
f"Albums: {total_albums}\n"
|
||||
f"Last event: {last_str}"
|
||||
)
|
||||
return fallback, ctx
|
||||
|
||||
|
||||
async def _cmd_albums(bot: TelegramBot, providers_map: dict[int, ServiceProvider], locale: str) -> str:
|
||||
async def _cmd_albums(bot: TelegramBot, providers_map: dict[int, ServiceProvider], locale: str) -> tuple[str, dict]:
|
||||
provider_ids = set(providers_map.keys())
|
||||
trackers = await _get_notification_trackers_for_providers(provider_ids)
|
||||
if not trackers:
|
||||
return "No tracked albums." if locale == "en" else "Нет отслеживаемых альбомов."
|
||||
fallback = "No tracked albums." if locale == "en" else "Нет отслеживаемых альбомов."
|
||||
return fallback, {"albums": []}
|
||||
|
||||
albums_data: list[dict] = []
|
||||
lines = []
|
||||
async with aiohttp.ClientSession() as http:
|
||||
for tracker in trackers:
|
||||
@@ -311,20 +326,23 @@ async def _cmd_albums(bot: TelegramBot, providers_map: dict[int, ServiceProvider
|
||||
try:
|
||||
album = await immich.client.get_album(album_id)
|
||||
if album:
|
||||
albums_data.append({"name": album.name, "asset_count": album.asset_count, "id": album_id})
|
||||
lines.append(f" • {album.name} ({album.asset_count} assets)")
|
||||
except Exception:
|
||||
lines.append(f" • {album_id[:8]}... (error)")
|
||||
|
||||
header = "📚 Tracked albums:" if locale == "en" else "📚 Отслеживаемые альбомы:"
|
||||
return header + "\n" + "\n".join(lines) if lines else header + "\n (none)"
|
||||
fallback = header + "\n" + "\n".join(lines) if lines else header + "\n (none)"
|
||||
return fallback, {"albums": albums_data}
|
||||
|
||||
|
||||
async def _cmd_events(bot: TelegramBot, providers_map: dict[int, ServiceProvider], count: int, locale: str) -> str:
|
||||
async def _cmd_events(bot: TelegramBot, providers_map: dict[int, ServiceProvider], count: int, locale: str) -> tuple[str, dict]:
|
||||
provider_ids = set(providers_map.keys())
|
||||
trackers = await _get_notification_trackers_for_providers(provider_ids)
|
||||
tracker_ids = [t.id for t in trackers]
|
||||
if not tracker_ids:
|
||||
return "No events." if locale == "en" else "Нет событий."
|
||||
fallback = "No events." if locale == "en" else "Нет событий."
|
||||
return fallback, {"events": []}
|
||||
|
||||
engine = get_engine()
|
||||
async with AsyncSession(engine) as session:
|
||||
@@ -337,17 +355,22 @@ async def _cmd_events(bot: TelegramBot, providers_map: dict[int, ServiceProvider
|
||||
events = result.all()
|
||||
|
||||
if not events:
|
||||
return "No events yet." if locale == "en" else "Пока нет событий."
|
||||
fallback = "No events yet." if locale == "en" else "Пока нет событий."
|
||||
return fallback, {"events": []}
|
||||
|
||||
events_data = [{"type": e.event_type, "album": e.collection_name, "count": e.assets_count,
|
||||
"date": e.created_at.strftime("%m/%d %H:%M")} for e in events]
|
||||
|
||||
header = f"📋 Last {len(events)} events:" if locale == "en" else f"📋 Последние {len(events)} событий:"
|
||||
lines = []
|
||||
for e in events:
|
||||
ts = e.created_at.strftime("%m/%d %H:%M")
|
||||
lines.append(f" {ts} — {e.event_type}: {e.collection_name}")
|
||||
return header + "\n" + "\n".join(lines)
|
||||
fallback = header + "\n" + "\n".join(lines)
|
||||
return fallback, {"events": events_data}
|
||||
|
||||
|
||||
async def _cmd_people(providers_map: dict[int, ServiceProvider], locale: str) -> str:
|
||||
async def _cmd_people(providers_map: dict[int, ServiceProvider], locale: str) -> tuple[str, dict]:
|
||||
all_people: dict[str, str] = {}
|
||||
|
||||
async with aiohttp.ClientSession() as http:
|
||||
@@ -359,16 +382,19 @@ async def _cmd_people(providers_map: dict[int, ServiceProvider], locale: str) ->
|
||||
all_people.update(people)
|
||||
|
||||
if not all_people:
|
||||
return "No people detected." if locale == "en" else "Люди не обнаружены."
|
||||
fallback = "No people detected." if locale == "en" else "Люди не обнаружены."
|
||||
return fallback, {"people": []}
|
||||
|
||||
names = sorted(all_people.values())
|
||||
header = f"👥 {len(names)} people:" if locale == "en" else f"👥 {len(names)} людей:"
|
||||
return header + "\n" + ", ".join(names)
|
||||
fallback = header + "\n" + ", ".join(names)
|
||||
return fallback, {"people": names}
|
||||
|
||||
|
||||
async def _cmd_immich(
|
||||
bot: TelegramBot, cmd: str, args: str, count: int, locale: str,
|
||||
response_mode: str, providers_map: dict[int, ServiceProvider],
|
||||
cmd_templates: dict[str, str] | None = None,
|
||||
) -> str | list[dict[str, Any]]:
|
||||
"""Handle commands that need Immich API access and may return media."""
|
||||
if not providers_map:
|
||||
@@ -398,13 +424,13 @@ async def _cmd_immich(
|
||||
if not args:
|
||||
return "Usage: /search <query>" if locale == "en" else "Использование: /search <запрос>"
|
||||
assets = await client.search_smart(args, album_ids=all_album_ids, limit=count)
|
||||
return _format_assets(assets, cmd, args, locale, response_mode, client)
|
||||
return _format_assets(assets, cmd, args, locale, response_mode, client, cmd_templates)
|
||||
|
||||
if cmd == "find":
|
||||
if not args:
|
||||
return "Usage: /find <text>" if locale == "en" else "Использование: /find <текст>"
|
||||
assets = await client.search_metadata(args, album_ids=all_album_ids, limit=count)
|
||||
return _format_assets(assets, cmd, args, locale, response_mode, client)
|
||||
return _format_assets(assets, cmd, args, locale, response_mode, client, cmd_templates)
|
||||
|
||||
if cmd == "person":
|
||||
if not args:
|
||||
@@ -418,7 +444,7 @@ async def _cmd_immich(
|
||||
if not person_id:
|
||||
return f"Person '{args}' not found." if locale == "en" else f"Человек '{args}' не найден."
|
||||
assets = await client.search_by_person(person_id, limit=count)
|
||||
return _format_assets(assets, cmd, args, locale, response_mode, client)
|
||||
return _format_assets(assets, cmd, args, locale, response_mode, client, cmd_templates)
|
||||
|
||||
if cmd == "place":
|
||||
if not args:
|
||||
@@ -426,7 +452,7 @@ async def _cmd_immich(
|
||||
assets = await client.search_smart(
|
||||
f"photos taken in {args}", album_ids=all_album_ids, limit=count
|
||||
)
|
||||
return _format_assets(assets, cmd, args, locale, response_mode, client)
|
||||
return _format_assets(assets, cmd, args, locale, response_mode, client, cmd_templates)
|
||||
|
||||
if cmd == "favorites":
|
||||
fav_assets: list[dict[str, Any]] = []
|
||||
@@ -444,7 +470,7 @@ async def _cmd_immich(
|
||||
pass
|
||||
if len(fav_assets) >= count:
|
||||
break
|
||||
return _format_assets(fav_assets, cmd, "", locale, response_mode, client)
|
||||
return _format_assets(fav_assets, cmd, "", locale, response_mode, client, cmd_templates)
|
||||
|
||||
if cmd == "latest":
|
||||
latest_assets: list[dict[str, Any]] = []
|
||||
@@ -460,7 +486,7 @@ async def _cmd_immich(
|
||||
except Exception:
|
||||
pass
|
||||
latest_assets.sort(key=lambda a: a.get("createdAt", ""), reverse=True)
|
||||
return _format_assets(latest_assets[:count], cmd, "", locale, response_mode, client)
|
||||
return _format_assets(latest_assets[:count], cmd, "", locale, response_mode, client, cmd_templates)
|
||||
|
||||
if cmd == "random":
|
||||
random_assets: list[dict[str, Any]] = []
|
||||
@@ -478,17 +504,22 @@ async def _cmd_immich(
|
||||
except Exception:
|
||||
pass
|
||||
rng.shuffle(random_assets)
|
||||
return _format_assets(random_assets[:count], cmd, "", locale, response_mode, client)
|
||||
return _format_assets(random_assets[:count], cmd, "", locale, response_mode, client, cmd_templates)
|
||||
|
||||
if cmd == "summary":
|
||||
albums_data: list[dict] = []
|
||||
lines = []
|
||||
for album_id in all_album_ids:
|
||||
try:
|
||||
album = await client.get_album(album_id)
|
||||
if album:
|
||||
albums_data.append({"name": album.name, "asset_count": album.asset_count, "id": album_id})
|
||||
lines.append(f" • {album.name}: {album.asset_count} assets")
|
||||
except Exception:
|
||||
pass
|
||||
rendered = _render_cmd_template(cmd_templates or {}, "summary", {"albums": albums_data, "locale": locale})
|
||||
if rendered:
|
||||
return rendered
|
||||
header = f"📋 Album summary ({len(lines)}):" if locale == "en" else f"📋 Сводка альбомов ({len(lines)}):"
|
||||
return header + "\n" + "\n".join(lines) if lines else header
|
||||
|
||||
@@ -542,7 +573,7 @@ async def _cmd_immich(
|
||||
memory_assets = memory_assets[:count]
|
||||
if not memory_assets:
|
||||
return "No memories for today." if locale == "en" else "Нет воспоминаний за сегодня."
|
||||
return _format_assets(memory_assets, cmd, "", locale, response_mode, client)
|
||||
return _format_assets(memory_assets, cmd, "", locale, response_mode, client, cmd_templates)
|
||||
|
||||
return "Unknown command." if locale == "en" else "Неизвестная команда."
|
||||
|
||||
@@ -550,9 +581,13 @@ async def _cmd_immich(
|
||||
def _format_assets(
|
||||
assets: list[dict[str, Any]], cmd: str, query: str,
|
||||
locale: str, response_mode: str, client: Any,
|
||||
cmd_templates: dict[str, str] | None = None,
|
||||
) -> str | list[dict[str, Any]]:
|
||||
"""Format asset results as text or media payload."""
|
||||
if not assets:
|
||||
rendered = _render_cmd_template(cmd_templates or {}, "no_results", {"command": cmd, "query": query, "locale": locale})
|
||||
if rendered:
|
||||
return rendered
|
||||
return {"en": "No results found.", "ru": "Ничего не найдено."}.get(locale, "No results found.")
|
||||
|
||||
if response_mode == "media":
|
||||
@@ -571,7 +606,17 @@ def _format_assets(
|
||||
})
|
||||
return media_items
|
||||
|
||||
# Text mode
|
||||
# Text mode — try template first
|
||||
# Map command names to template slot names (search/find/person/place share "search" slot)
|
||||
slot_map = {"find": "search", "person": "search", "place": "search"}
|
||||
slot_name = slot_map.get(cmd, cmd)
|
||||
rendered = _render_cmd_template(cmd_templates or {}, slot_name, {
|
||||
"assets": assets, "query": query, "command": cmd, "count": len(assets), "locale": locale,
|
||||
})
|
||||
if rendered:
|
||||
return rendered
|
||||
|
||||
# Hardcoded fallback
|
||||
header_map = {
|
||||
"search": {"en": f'🔍 Results for "{query}":', "ru": f'🔍 Результаты для "{query}":'},
|
||||
"find": {"en": f'📄 Files matching "{query}":', "ru": f'📄 Файлы по запросу "{query}":'},
|
||||
|
||||
@@ -53,6 +53,21 @@ class TelegramBot(SQLModel, table=True):
|
||||
created_at: datetime = Field(default_factory=_utcnow)
|
||||
|
||||
|
||||
class MatrixBot(SQLModel, table=True):
|
||||
"""Matrix bot — homeserver connection for sending messages to rooms."""
|
||||
|
||||
__tablename__ = "matrix_bot"
|
||||
|
||||
id: int | None = Field(default=None, primary_key=True)
|
||||
user_id: int = Field(foreign_key="user.id")
|
||||
name: str
|
||||
icon: str = Field(default="")
|
||||
homeserver_url: str # e.g. https://matrix.org
|
||||
access_token: str
|
||||
display_name: str = Field(default="")
|
||||
created_at: datetime = Field(default_factory=_utcnow)
|
||||
|
||||
|
||||
class EmailBot(SQLModel, table=True):
|
||||
"""Email sender — SMTP connection for sending email notifications."""
|
||||
|
||||
@@ -190,7 +205,7 @@ class NotificationTarget(SQLModel, table=True):
|
||||
|
||||
id: int | None = Field(default=None, primary_key=True)
|
||||
user_id: int = Field(foreign_key="user.id")
|
||||
type: str # "telegram", "webhook", or "email"
|
||||
type: str # "telegram", "webhook", "email", "discord", "slack", "ntfy", "matrix"
|
||||
name: str
|
||||
icon: str = Field(default="")
|
||||
config: dict[str, Any] = Field(default_factory=dict, sa_column=Column(JSON))
|
||||
|
||||
@@ -23,6 +23,7 @@ from .api.targets import router as targets_router
|
||||
from .api.target_receivers import router as target_receivers_router
|
||||
from .api.telegram_bots import router as telegram_bots_router
|
||||
from .api.email_bots import router as email_bots_router
|
||||
from .api.matrix_bots import router as matrix_bots_router
|
||||
from .api.users import router as users_router
|
||||
from .api.status import router as status_router
|
||||
from .api.template_vars import router as template_vars_router
|
||||
@@ -46,6 +47,7 @@ async def lifespan(app: FastAPI):
|
||||
await migrate_template_slots(engine)
|
||||
await migrate_target_receivers(engine)
|
||||
await _seed_default_templates()
|
||||
await _seed_default_command_templates()
|
||||
# Configure webhook secret from DB setting (falls back to env var)
|
||||
from sqlmodel.ext.asyncio.session import AsyncSession as _AS
|
||||
from .api.app_settings import get_setting as _get_setting
|
||||
@@ -71,6 +73,7 @@ app.include_router(targets_router)
|
||||
app.include_router(target_receivers_router)
|
||||
app.include_router(telegram_bots_router)
|
||||
app.include_router(email_bots_router)
|
||||
app.include_router(matrix_bots_router)
|
||||
app.include_router(users_router)
|
||||
app.include_router(status_router)
|
||||
app.include_router(app_settings_router)
|
||||
@@ -155,6 +158,72 @@ async def _seed_default_templates():
|
||||
await session.commit()
|
||||
|
||||
|
||||
async def _seed_default_command_templates():
|
||||
"""Seed or update default command response templates on startup."""
|
||||
from sqlmodel import func, select
|
||||
from sqlmodel.ext.asyncio.session import AsyncSession
|
||||
from .database.engine import get_engine
|
||||
from .database.models import CommandTemplateConfig, CommandTemplateSlot
|
||||
from notify_bridge_core.templates.command_defaults import load_default_command_templates
|
||||
|
||||
engine = get_engine()
|
||||
async with AsyncSession(engine) as session:
|
||||
result = await session.exec(select(func.count()).select_from(CommandTemplateConfig))
|
||||
count = result.one()
|
||||
|
||||
if count == 0:
|
||||
# First startup — seed EN and RU defaults
|
||||
for locale in ("en", "ru"):
|
||||
slots = load_default_command_templates(locale)
|
||||
if not slots:
|
||||
continue
|
||||
name = f"Default Commands ({locale.upper()})"
|
||||
config = CommandTemplateConfig(
|
||||
user_id=0,
|
||||
provider_type="immich",
|
||||
name=name,
|
||||
description=f"Default Immich command templates ({locale.upper()})",
|
||||
)
|
||||
session.add(config)
|
||||
await session.flush()
|
||||
for slot_name, template_text in slots.items():
|
||||
session.add(CommandTemplateSlot(
|
||||
config_id=config.id,
|
||||
slot_name=slot_name,
|
||||
template=template_text,
|
||||
))
|
||||
else:
|
||||
# Update existing system-owned command templates from files
|
||||
result = await session.exec(
|
||||
select(CommandTemplateConfig).where(CommandTemplateConfig.user_id == 0)
|
||||
)
|
||||
system_configs = result.all()
|
||||
for config in system_configs:
|
||||
locale = "ru" if "(RU)" in config.name else "en"
|
||||
slots = load_default_command_templates(locale)
|
||||
if not slots:
|
||||
continue
|
||||
for slot_name, template_text in slots.items():
|
||||
slot_result = await session.exec(
|
||||
select(CommandTemplateSlot).where(
|
||||
CommandTemplateSlot.config_id == config.id,
|
||||
CommandTemplateSlot.slot_name == slot_name,
|
||||
)
|
||||
)
|
||||
existing = slot_result.first()
|
||||
if existing:
|
||||
existing.template = template_text
|
||||
session.add(existing)
|
||||
else:
|
||||
session.add(CommandTemplateSlot(
|
||||
config_id=config.id,
|
||||
slot_name=slot_name,
|
||||
template=template_text,
|
||||
))
|
||||
|
||||
await session.commit()
|
||||
|
||||
|
||||
def run():
|
||||
import uvicorn
|
||||
uvicorn.run(app, host="0.0.0.0", port=8420)
|
||||
|
||||
@@ -17,10 +17,20 @@ _TEST_MESSAGES: dict[str, dict[str, str]] = {
|
||||
"en": {
|
||||
"telegram": "\u2705 Test message from <b>Notify Bridge</b>",
|
||||
"webhook": "Test notification from Notify Bridge",
|
||||
"email": "Test email from Notify Bridge",
|
||||
"discord": "Test message from **Notify Bridge**",
|
||||
"slack": "Test message from *Notify Bridge*",
|
||||
"ntfy": "Test notification from Notify Bridge",
|
||||
"matrix": "Test message from Notify Bridge",
|
||||
},
|
||||
"ru": {
|
||||
"telegram": "\u2705 Тестовое сообщение от <b>Notify Bridge</b>",
|
||||
"webhook": "Тестовое уведомление от Notify Bridge",
|
||||
"email": "Тестовое письмо от Notify Bridge",
|
||||
"discord": "Тестовое сообщение от **Notify Bridge**",
|
||||
"slack": "Тестовое сообщение от *Notify Bridge*",
|
||||
"ntfy": "Тестовое уведомление от Notify Bridge",
|
||||
"matrix": "Тестовое сообщение от Notify Bridge",
|
||||
},
|
||||
}
|
||||
|
||||
@@ -50,12 +60,17 @@ async def send_to_target(target: NotificationTarget, message: str) -> dict:
|
||||
"""
|
||||
try:
|
||||
receivers = await _load_receivers(target.id)
|
||||
if target.type == "telegram":
|
||||
return await _send_telegram_broadcast(target, message, receivers)
|
||||
elif target.type == "webhook":
|
||||
return await _send_webhook_broadcast(target, message, receivers)
|
||||
elif target.type == "email":
|
||||
return await _send_email_broadcast(target, message, receivers)
|
||||
send_fn = {
|
||||
"telegram": _send_telegram_broadcast,
|
||||
"webhook": _send_webhook_broadcast,
|
||||
"email": _send_email_broadcast,
|
||||
"discord": _send_webhook_like_broadcast,
|
||||
"slack": _send_webhook_like_broadcast,
|
||||
"ntfy": _send_ntfy_broadcast,
|
||||
"matrix": _send_matrix_broadcast,
|
||||
}.get(target.type)
|
||||
if send_fn:
|
||||
return await send_fn(target, message, receivers)
|
||||
return {"success": False, "error": f"Unknown target type: {target.type}"}
|
||||
except Exception as e:
|
||||
_LOGGER.error("Send failed: %s", e)
|
||||
@@ -188,6 +203,107 @@ async def _send_email_broadcast(target: NotificationTarget, message: str, receiv
|
||||
return {"success": False, "error": "No valid email receivers"}
|
||||
|
||||
|
||||
async def _send_webhook_like_broadcast(target: NotificationTarget, message: str, receivers: list[dict]) -> dict:
|
||||
"""Broadcast for Discord and Slack — both use webhook URLs as receivers."""
|
||||
if not receivers:
|
||||
webhook_url = target.config.get("webhook_url")
|
||||
if webhook_url:
|
||||
receivers = [{"webhook_url": webhook_url}]
|
||||
else:
|
||||
return {"success": False, "error": "No receivers configured"}
|
||||
|
||||
results: list[dict] = []
|
||||
async with aiohttp.ClientSession() as session:
|
||||
if target.type == "discord":
|
||||
from notify_bridge_core.notifications.discord.client import DiscordClient
|
||||
client = DiscordClient(session)
|
||||
for recv in receivers:
|
||||
url = recv.get("webhook_url")
|
||||
if url:
|
||||
results.append(await client.send(url, message, username=target.config.get("username")))
|
||||
elif target.type == "slack":
|
||||
from notify_bridge_core.notifications.slack.client import SlackClient
|
||||
client = SlackClient(session)
|
||||
for recv in receivers:
|
||||
url = recv.get("webhook_url")
|
||||
if url:
|
||||
results.append(await client.send(url, message, username=target.config.get("username")))
|
||||
|
||||
return _aggregate(results)
|
||||
|
||||
|
||||
async def _send_ntfy_broadcast(target: NotificationTarget, message: str, receivers: list[dict]) -> dict:
|
||||
"""Broadcast to ntfy topics."""
|
||||
server_url = target.config.get("server_url", "https://ntfy.sh")
|
||||
auth_token = target.config.get("auth_token")
|
||||
|
||||
if not receivers:
|
||||
topic = target.config.get("topic")
|
||||
if topic:
|
||||
receivers = [{"topic": topic}]
|
||||
else:
|
||||
return {"success": False, "error": "No receivers configured"}
|
||||
|
||||
from notify_bridge_core.notifications.ntfy.client import NtfyClient
|
||||
results: list[dict] = []
|
||||
async with aiohttp.ClientSession() as session:
|
||||
client = NtfyClient(session)
|
||||
for recv in receivers:
|
||||
topic = recv.get("topic")
|
||||
if topic:
|
||||
results.append(await client.send(
|
||||
server_url, topic, message,
|
||||
title="Notify Bridge",
|
||||
priority=recv.get("priority", 3),
|
||||
auth_token=auth_token,
|
||||
))
|
||||
|
||||
return _aggregate(results)
|
||||
|
||||
|
||||
async def _send_matrix_broadcast(target: NotificationTarget, message: str, receivers: list[dict]) -> dict:
|
||||
"""Broadcast to Matrix rooms."""
|
||||
from notify_bridge_core.notifications.matrix.client import MatrixClient
|
||||
from ..database.models import MatrixBot
|
||||
|
||||
matrix_bot_id = target.config.get("matrix_bot_id")
|
||||
if not matrix_bot_id:
|
||||
return {"success": False, "error": "No Matrix bot configured for this target"}
|
||||
|
||||
engine = get_engine()
|
||||
async with AsyncSession(engine) as session:
|
||||
bot = await session.get(MatrixBot, matrix_bot_id)
|
||||
if not bot:
|
||||
return {"success": False, "error": "Matrix bot not found"}
|
||||
homeserver = bot.homeserver_url
|
||||
access_token = bot.access_token
|
||||
|
||||
if not receivers:
|
||||
return {"success": False, "error": "No receivers configured"}
|
||||
|
||||
results: list[dict] = []
|
||||
async with aiohttp.ClientSession() as http:
|
||||
client = MatrixClient(http, homeserver, access_token)
|
||||
for recv in receivers:
|
||||
room_id = recv.get("room_id")
|
||||
if room_id:
|
||||
results.append(await client.send_message(room_id, message, html_message=message))
|
||||
|
||||
return _aggregate(results)
|
||||
|
||||
|
||||
def _aggregate(results: list[dict]) -> dict:
|
||||
"""Aggregate broadcast results."""
|
||||
successes = sum(1 for r in results if r.get("success"))
|
||||
if successes == len(results) and results:
|
||||
return {"success": True, "receivers": len(results)}
|
||||
elif successes > 0:
|
||||
return {"success": True, "receivers": len(results), "partial_failures": len(results) - successes}
|
||||
elif results:
|
||||
return results[0]
|
||||
return {"success": False, "error": "No valid receivers"}
|
||||
|
||||
|
||||
# --- Public API used by routes ---
|
||||
|
||||
|
||||
|
||||
@@ -19,6 +19,7 @@ from ..database.engine import get_engine
|
||||
from ..database.models import (
|
||||
EmailBot,
|
||||
EventLog,
|
||||
MatrixBot,
|
||||
NotificationTarget,
|
||||
NotificationTracker,
|
||||
NotificationTrackerState,
|
||||
@@ -162,7 +163,7 @@ async def check_tracker(tracker_id: int) -> dict[str, Any]:
|
||||
template_slots[event_key] = tmpl_text
|
||||
|
||||
target_config = dict(target.config)
|
||||
# Inject SMTP config for email targets from EmailBot
|
||||
# Inject bot credentials for bot-backed target types
|
||||
if target.type == "email":
|
||||
email_bot_id = target.config.get("email_bot_id")
|
||||
if email_bot_id:
|
||||
@@ -177,6 +178,13 @@ async def check_tracker(tracker_id: int) -> dict[str, Any]:
|
||||
"from_name": email_bot.name,
|
||||
"use_tls": email_bot.smtp_use_tls,
|
||||
}
|
||||
elif target.type == "matrix":
|
||||
matrix_bot_id = target.config.get("matrix_bot_id")
|
||||
if matrix_bot_id:
|
||||
matrix_bot = await session.get(MatrixBot, matrix_bot_id)
|
||||
if matrix_bot:
|
||||
target_config["homeserver_url"] = matrix_bot.homeserver_url
|
||||
target_config["access_token"] = matrix_bot.access_token
|
||||
|
||||
link_data.append({
|
||||
"target_type": target.type,
|
||||
|
||||
Reference in New Issue
Block a user