10d30fc956
Comprehensive multi-area pass driven by a parallel 8-agent production
review. Frontend, backend, database, security, performance, operational,
plus a new self-monitoring feature.
## Critical fixes
- Planka webhook: reads bounded raw body (was NameError on every call)
- HA quiet hours: ha_state_changed/automation_triggered/service_called/
event_fired added to deferrable set (were silently dropped)
- DNS-rebinding SSRF: PinnedResolver wired into shared aiohttp session
- Telegram inbound webhook: secret now mandatory (401 without)
- Generic webhook: auth_mode="none" requires explicit
acknowledge_unauthenticated=true; per-IP rate limit 60/min
- svelte-check: 5 null-narrowing errors in EventDetailModal fixed
- Provider hardcoding: Immich-only block extracted to descriptor
featureDiscoveryHint
- command_sync: snapshot+expunge bot before exiting AsyncSession
## Bug fixes
- notifier asyncio.gather(return_exceptions=True) — one bad chat no longer
cancels peer sends
- NotificationDispatcher hoisted out of per-tracker loop
- Provider credential resolution unified across all 5 dispatch sites
- HA asyncio.shield now drains inner task on cancellation
- Provider construction switched from if/elif ladder to factory registry
- NUT first poll seeds silently (no spurious ups_on_battery)
- Quiet-hours gate: event-type-disabled now wins over deferral
- APScheduler drain job ID resolution upgraded to seconds
- HA on_status_change wired through to EventLog
- Webhook payload rollback failures now logged (not swallowed)
- Batched receivers/chats/bots in load_link_data (was per-target N+1)
- flag_modified on JSON column reassignments in deferred_dispatch
## Database
- UNIQUE indexes on service_provider.webhook_token,
telegram_bot.webhook_path_id, partial UNIQUE on telegram_bot.bot_id,
telegram_chat(bot_id, chat_id), notification_tracker_target unique link,
partial UNIQUE on bridge_self provider per user
- Composite ix_event_log_user_event_type_created index
- save_chat_from_webhook switched to ON CONFLICT DO UPDATE
- ondelete=CASCADE on user-id FKs (model annotation; app-side cascade
delete added for existing data)
- delete_notification_tracker converted from N+1 to bulk DELETE/UPDATE
- Module-level asyncio.Lock replaced with lazy _get_lock() pattern
- VACUUM INTO snapshot now PRAGMA integrity_check verified
## Performance
- Jinja2 template compilation LRU cached (lru_cache maxsize=512)
- Per-locale render cache in NotificationDispatcher (skips re-rendering
identical content for receivers sharing a locale)
- Tracker list cached per provider_id with 5s TTL + explicit invalidation
on tracker CRUD (relieves HA chat-bus rate query pressure)
- Nav-counts collapsed from 16 round-trips to single UNION ALL
- HA event_log: skip persisting empty assets_added/removed events
## Security hardening
- Mass-assignment guard on Action create/update; cron sub-minute reject
- Backup JSON depth/node-count cap (depth ≤ 10, nodes ≤ 100k)
- _sanitize_config extended to all JSON-typed fields on backup import
- Telegram _safe_get walks redirects manually with SSRF revalidation
- Bcrypt 72-byte password length cap with clear 422
- Webhook payload body redaction; sensitive substring set extended with
oauth/client_secret/webhook_secret/csrf in both header filter and
template extras filter
## Frontend
- 76 catch (err: any) sites converted to errMsg(err) helper
- globalProviderFilter: pure getter; reconciliation moved to one-time
$effect in +layout
- Provider-filter binding: removed paired $effects + _syncingFilter flag,
now one-way derived
- entity-cache: separate _refreshing flag for background re-fetches
- api.ts 401 handling: AuthRedirectError class + dedup _redirecting flag,
goto() instead of window.location.href
- a11y: aria-expanded on mobile More, role=switch + aria-checked on
Telegram bot toggles
## Tests & operations
- CI pytest gate added to .gitea/workflows/build.yml + release.yml
(wheel-built install to dodge editable-install slowness)
- /api/ready upgraded to deep healthcheck (db SELECT 1, scheduler.running,
HA supervisor presence) returning {ready, checks, errors, version}
- /api/metrics endpoint with prometheus_client (deferred_pending,
event_log_total, dispatch_duration, poll_failures, send_failures)
- New OPERATIONS.md covering deploy, healthchecks, metrics, backup/restore
procedures, log handling, common scenarios, upgrade flow
- New tests: test_bridge_self (11), test_gitea_parser (9),
test_planka_parser (6), test_immich_change_detector (6),
test_backup_roundtrip (1)
## New feature: bridge self-monitoring
- New bridge_self provider type — internal sink for bridge health events
- Three event types: bridge_self_poll_failures (consecutive tracker poll
failures), bridge_self_deferred_backlog (pending count crosses
threshold), bridge_self_target_failures (consecutive 5xx/network
failures per target)
- Per-user thresholds (defaults: 3 / 100 / 5) configurable via the
provider config form
- Auto-seeded on user create + /setup + boot backfill for existing users
- Anti-spam: counters reset after emission; backlog uses transition latch
- Self-loop guard: bridge_self failures don't count toward target-failure
thresholds (logged only) — wire to your own Telegram/Email/Matrix to
get notified when polls/dispatches/sends fail
- 6 default templates (3 events × 2 locales), tracking config columns
with backfill migration, frontend descriptor (excluded from "create
provider" wizard since auto-managed)
Operator-visible behavior changes (call out in release notes):
- NOTIFY_BRIDGE_TELEGRAM_WEBHOOK_SECRET now REQUIRED for webhook mode
- Existing webhook providers with auth_mode="none" need explicit opt-in
- Generic webhook endpoint rate-limited 60/min per source IP
- HA disconnect/reconnect writes ha_status_* EventLog rows
- Every user gets a bridge_self provider — wire it to a target to
receive failure alerts
Pre-existing test failures (test_ssrf, test_release_provider) on
Python 3.13 are unrelated; CI runs on 3.12.
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
514 lines
21 KiB
Svelte
514 lines
21 KiB
Svelte
<script lang="ts">
|
|
import { onMount, onDestroy } from 'svelte';
|
|
import { slide } from 'svelte/transition';
|
|
import { api , errMsg} from '$lib/api';
|
|
import { topbarAction } from '$lib/stores/topbar-action.svelte';
|
|
import { t } from '$lib/i18n';
|
|
import { providersCache, telegramBotsCache, commandConfigsCache } from '$lib/stores/caches.svelte';
|
|
import PageHeader from '$lib/components/PageHeader.svelte';
|
|
import Card from '$lib/components/Card.svelte';
|
|
import Loading from '$lib/components/Loading.svelte';
|
|
import IconPicker from '$lib/components/IconPicker.svelte';
|
|
import MdiIcon from '$lib/components/MdiIcon.svelte';
|
|
import EmptyState from '$lib/components/EmptyState.svelte';
|
|
import ConfirmModal from '$lib/components/ConfirmModal.svelte';
|
|
import Modal from '$lib/components/Modal.svelte';
|
|
import IconButton from '$lib/components/IconButton.svelte';
|
|
import CrossLink from '$lib/components/CrossLink.svelte';
|
|
import EntitySelect from '$lib/components/EntitySelect.svelte';
|
|
import { snackSuccess, snackError } from '$lib/stores/snackbar.svelte';
|
|
import { highlightFromUrl } from '$lib/highlight';
|
|
import { globalProviderFilter } from '$lib/stores/provider-filter.svelte';
|
|
import { providerDefaultIcon } from '$lib/grid-items';
|
|
import Button from '$lib/components/Button.svelte';
|
|
import MetaStrip, { type MetaTile } from '$lib/components/MetaStrip.svelte';
|
|
import type { ServiceProvider, TelegramBot } from '$lib/types';
|
|
|
|
let allCmdTrackers = $state<any[]>([]);
|
|
let filterText = $state('');
|
|
let filterProviderId = $state(0);
|
|
let effectiveProviderId = $derived(globalProviderFilter.id || filterProviderId);
|
|
let trackers = $derived(allCmdTrackers.filter((t: any) =>
|
|
(!filterText || t.name.toLowerCase().includes(filterText.toLowerCase())) &&
|
|
(!effectiveProviderId || t.provider_id === effectiveProviderId)
|
|
));
|
|
let providers = $derived(providersCache.items);
|
|
let commandConfigs = $derived(commandConfigsCache.items);
|
|
let telegramBots = $derived(telegramBotsCache.items);
|
|
const providerItems = $derived(providers
|
|
.filter(p => !globalProviderFilter.providerType || p.type === globalProviderFilter.providerType)
|
|
.map(p => ({ value: p.id, label: p.name, icon: providerDefaultIcon(p), desc: p.type })));
|
|
const botItems = $derived(telegramBots.map(b => ({ value: b.id, label: b.name, icon: b.icon || 'mdiRobot', desc: b.bot_username ? `@${b.bot_username}` : '' })));
|
|
let loaded = $state(false);
|
|
let showForm = $state(false);
|
|
let editing = $state<number | null>(null);
|
|
let error = $state('');
|
|
let submitting = $state(false);
|
|
let confirmDelete = $state<any>(null);
|
|
let toggling = $state<Record<number, boolean>>({});
|
|
|
|
// Listeners per tracker
|
|
let listeners = $state<Record<number, any[]>>({});
|
|
let listenersLoading = $state<Record<number, boolean>>({});
|
|
let expandedTracker = $state<number | null>(null);
|
|
let addingListener = $state<Record<number, boolean>>({});
|
|
let newListenerBotId = $state<Record<number, number>>({});
|
|
|
|
const defaultForm = () => ({
|
|
name: '',
|
|
icon: '',
|
|
provider_id: 0,
|
|
command_config_id: 0,
|
|
enabled: true,
|
|
});
|
|
let form = $state(defaultForm());
|
|
let nameManuallyEdited = $state(false);
|
|
|
|
$effect(() => {
|
|
if (showForm && !nameManuallyEdited && !editing) {
|
|
const provider = providers.find(p => p.id === form.provider_id);
|
|
form.name = provider ? `${provider.name} Commands` : 'Commands';
|
|
}
|
|
});
|
|
|
|
// Filter command configs by selected provider's type
|
|
let filteredConfigs = $derived.by(() => {
|
|
if (!form.provider_id) return commandConfigs;
|
|
const provider = providers.find(p => p.id === form.provider_id);
|
|
if (!provider) return commandConfigs;
|
|
return commandConfigs.filter(c => c.provider_type === provider.type);
|
|
});
|
|
const configItems = $derived(filteredConfigs
|
|
.filter((c: any) => !globalProviderFilter.providerType || c.provider_type === globalProviderFilter.providerType)
|
|
.map((c: any) => ({ value: c.id, label: c.name, icon: c.icon || 'mdiCog', desc: c.provider_type })));
|
|
|
|
onMount(() => {
|
|
topbarAction.set({
|
|
label: t('commandTracker.newTracker'),
|
|
onclick: () => { showForm ? (showForm = false, editing = null) : openNew(); },
|
|
});
|
|
load();
|
|
});
|
|
onDestroy(() => topbarAction.clear());
|
|
|
|
const headerPills = $derived.by(() => {
|
|
const pills: Array<{ label: string; tone: 'mint' | 'sky' | 'citrus' }> = [];
|
|
const armed = trackers.filter((tr: { enabled?: boolean }) => tr.enabled).length;
|
|
const paused = trackers.length - armed;
|
|
if (armed > 0) pills.push({ label: `${armed} ${t('notificationTracker.armed')}`, tone: 'mint' });
|
|
if (paused > 0) pills.push({ label: `${paused} ${t('notificationTracker.paused')}`, tone: 'citrus' });
|
|
return pills;
|
|
});
|
|
|
|
async function load() {
|
|
try {
|
|
[allCmdTrackers] = await Promise.all([
|
|
api('/command-trackers'),
|
|
providersCache.fetch(), commandConfigsCache.fetch(),
|
|
telegramBotsCache.fetch(),
|
|
]);
|
|
} catch (err: unknown) { error = errMsg(err, t('common.loadError')); snackError(error); }
|
|
finally { loaded = true; highlightFromUrl(); }
|
|
}
|
|
|
|
function openNew() {
|
|
form = defaultForm();
|
|
if (providers.length > 0) form.provider_id = providers[0].id;
|
|
const ptype = providers.find(p => p.id === form.provider_id)?.type || '';
|
|
if (ptype) {
|
|
const firstCfg = commandConfigs.find(c => c.provider_type === ptype);
|
|
if (firstCfg) form.command_config_id = firstCfg.id;
|
|
}
|
|
nameManuallyEdited = false;
|
|
editing = null;
|
|
showForm = true;
|
|
}
|
|
|
|
// Re-pick the command config when the provider changes. The previously
|
|
// selected id may belong to a different provider type and would no longer
|
|
// appear in the filtered EntitySelect, leaving the selector empty.
|
|
let _prevProviderId = $state(0);
|
|
$effect(() => {
|
|
if (showForm && form.provider_id && form.provider_id !== _prevProviderId) {
|
|
_prevProviderId = form.provider_id;
|
|
if (editing === null) {
|
|
const ptype = providers.find(p => p.id === form.provider_id)?.type || '';
|
|
if (ptype) {
|
|
const currentCfg = commandConfigs.find(c => c.id === form.command_config_id);
|
|
if (!currentCfg || currentCfg.provider_type !== ptype) {
|
|
const first = commandConfigs.find(c => c.provider_type === ptype);
|
|
form.command_config_id = first?.id ?? 0;
|
|
}
|
|
}
|
|
}
|
|
}
|
|
});
|
|
function editTracker(trk: any) {
|
|
form = {
|
|
name: trk.name,
|
|
icon: trk.icon || '',
|
|
provider_id: trk.provider_id,
|
|
command_config_id: trk.command_config_id,
|
|
enabled: trk.enabled,
|
|
};
|
|
nameManuallyEdited = true;
|
|
editing = trk.id;
|
|
showForm = true;
|
|
}
|
|
|
|
async function saveTracker(e: SubmitEvent) {
|
|
e.preventDefault(); error = ''; submitting = true;
|
|
try {
|
|
const body = JSON.stringify(form);
|
|
if (editing) {
|
|
await api(`/command-trackers/${editing}`, { method: 'PUT', body });
|
|
snackSuccess(t('snack.commandTrackerUpdated'));
|
|
} else {
|
|
await api('/command-trackers', { method: 'POST', body });
|
|
snackSuccess(t('snack.commandTrackerCreated'));
|
|
}
|
|
form = defaultForm(); nameManuallyEdited = false; showForm = false; editing = null; await load();
|
|
} catch (err: unknown) { const __m = errMsg(err); error = __m; snackError(__m); }
|
|
finally { submitting = false; }
|
|
}
|
|
|
|
function remove(trk: any) {
|
|
confirmDelete = {
|
|
id: trk.id,
|
|
onconfirm: async () => {
|
|
try {
|
|
await api(`/command-trackers/${trk.id}`, { method: 'DELETE' });
|
|
await load();
|
|
snackSuccess(t('snack.commandTrackerDeleted'));
|
|
} catch (err: unknown) { snackError(errMsg(err)); }
|
|
finally { confirmDelete = null; }
|
|
}
|
|
};
|
|
}
|
|
|
|
async function toggleEnabled(trk: any) {
|
|
toggling = { ...toggling, [trk.id]: true };
|
|
try {
|
|
const endpoint = trk.enabled ? 'disable' : 'enable';
|
|
await api(`/command-trackers/${trk.id}/${endpoint}`, { method: 'POST' });
|
|
snackSuccess(trk.enabled ? t('snack.commandTrackerDisabled') : t('snack.commandTrackerEnabled'));
|
|
await load();
|
|
} catch (err: unknown) { snackError(errMsg(err)); }
|
|
toggling = { ...toggling, [trk.id]: false };
|
|
}
|
|
|
|
function toggleListeners(trkId: number) {
|
|
if (expandedTracker === trkId) {
|
|
expandedTracker = null;
|
|
return;
|
|
}
|
|
expandedTracker = trkId;
|
|
loadListeners(trkId);
|
|
}
|
|
|
|
async function loadListeners(trkId: number) {
|
|
listenersLoading = { ...listenersLoading, [trkId]: true };
|
|
try {
|
|
listeners = { ...listeners, [trkId]: await api(`/command-trackers/${trkId}/listeners`) };
|
|
} catch { listeners = { ...listeners, [trkId]: [] }; }
|
|
listenersLoading = { ...listenersLoading, [trkId]: false };
|
|
}
|
|
|
|
async function addListener(trkId: number) {
|
|
const botId = newListenerBotId[trkId];
|
|
if (!botId) return;
|
|
addingListener = { ...addingListener, [trkId]: true };
|
|
try {
|
|
await api(`/command-trackers/${trkId}/listeners`, {
|
|
method: 'POST',
|
|
body: JSON.stringify({ listener_type: 'telegram_bot', listener_id: botId }),
|
|
});
|
|
snackSuccess(t('snack.listenerAdded'));
|
|
await loadListeners(trkId);
|
|
newListenerBotId = { ...newListenerBotId, [trkId]: 0 };
|
|
} catch (err: unknown) { snackError(errMsg(err)); }
|
|
addingListener = { ...addingListener, [trkId]: false };
|
|
}
|
|
|
|
async function removeListener(trkId: number, listenerId: number) {
|
|
try {
|
|
await api(`/command-trackers/${trkId}/listeners/${listenerId}`, { method: 'DELETE' });
|
|
snackSuccess(t('snack.listenerRemoved'));
|
|
await loadListeners(trkId);
|
|
} catch (err: unknown) { snackError(errMsg(err)); }
|
|
}
|
|
|
|
// Per-listener album scope editing
|
|
let scopeEditor = $state<{ trkId: number; listener: any; providerId: number; collections: any[]; selectedIds: string[]; inherit: boolean } | null>(null);
|
|
async function openScopeEditor(trkId: number, listener: any) {
|
|
const trk = allCmdTrackers.find((t: any) => t.id === trkId);
|
|
if (!trk) return;
|
|
let collections: any[] = [];
|
|
try { collections = await api(`/providers/${trk.provider_id}/collections`); } catch { /* ignore */ }
|
|
scopeEditor = {
|
|
trkId,
|
|
listener,
|
|
providerId: trk.provider_id,
|
|
collections,
|
|
selectedIds: [...(listener.allowed_album_ids || [])],
|
|
inherit: listener.allowed_album_ids === null || listener.allowed_album_ids === undefined,
|
|
};
|
|
}
|
|
async function saveScope() {
|
|
if (!scopeEditor) return;
|
|
const body = { allowed_album_ids: scopeEditor.inherit ? null : scopeEditor.selectedIds };
|
|
try {
|
|
await api(`/command-trackers/${scopeEditor.trkId}/listeners/${scopeEditor.listener.id}`, {
|
|
method: 'PATCH', body: JSON.stringify(body),
|
|
});
|
|
snackSuccess(t('snack.listenerScopeSaved'));
|
|
await loadListeners(scopeEditor.trkId);
|
|
scopeEditor = null;
|
|
} catch (err: unknown) { snackError(errMsg(err)); }
|
|
}
|
|
|
|
function providerName(id: number): string {
|
|
return providers.find(p => p.id === id)?.name || '?';
|
|
}
|
|
function configName(id: number): string {
|
|
return commandConfigs.find(c => c.id === id)?.name || '?';
|
|
}
|
|
|
|
function commandTrackerTiles(trk: any): MetaTile[] {
|
|
const tiles: MetaTile[] = [];
|
|
tiles.push(trk.enabled
|
|
? { icon: 'mdiCheckCircle', label: t('commandTracker.enabled'), tone: 'mint' }
|
|
: { icon: 'mdiCloseCircle', label: t('commandTracker.disabled'), tone: 'coral' });
|
|
tiles.push({
|
|
icon: 'mdiServer',
|
|
label: providerName(trk.provider_id),
|
|
tone: 'lavender',
|
|
});
|
|
tiles.push({
|
|
icon: 'mdiCog',
|
|
label: configName(trk.command_config_id),
|
|
tone: 'sky',
|
|
});
|
|
if (trk.listener_count !== undefined) {
|
|
tiles.push({
|
|
icon: 'mdiAccountMultipleOutline',
|
|
value: String(trk.listener_count),
|
|
label: t('commandTracker.listeners').toLowerCase(),
|
|
tone: trk.listener_count > 0 ? 'orchid' : 'default',
|
|
});
|
|
}
|
|
return tiles;
|
|
}
|
|
</script>
|
|
|
|
<PageHeader
|
|
title={t('commandTracker.title')}
|
|
emphasis={t('commandTracker.titleEmphasis')}
|
|
description={t('commandTracker.description')}
|
|
crumb={t('crumbs.routingCommands')}
|
|
count={trackers.length}
|
|
countLabel={t('dashboard.trackersShort')}
|
|
pills={headerPills}
|
|
>
|
|
<Button size="sm" onclick={() => { showForm ? (showForm = false, editing = null) : openNew(); }}>
|
|
{showForm ? t('common.cancel') : t('commandTracker.newTracker')}
|
|
</Button>
|
|
</PageHeader>
|
|
|
|
{#if !loaded}<Loading />{:else}
|
|
|
|
{#if showForm}
|
|
<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={saveTracker} class="space-y-3">
|
|
<div>
|
|
<label for="trk-name" class="block text-sm font-medium mb-1">{t('commandTracker.name')}</label>
|
|
<div class="flex gap-2">
|
|
<IconPicker value={form.icon} onselect={(v: string) => form.icon = v} />
|
|
<input id="trk-name" bind:value={form.name} oninput={() => nameManuallyEdited = true} required placeholder={t('commandTracker.namePlaceholder')}
|
|
class="flex-1 px-3 py-2 border border-[var(--color-border)] rounded-md text-sm bg-[var(--color-background)]" />
|
|
</div>
|
|
</div>
|
|
|
|
<div>
|
|
<div class="block text-sm font-medium mb-1">{t('commandTracker.provider')}</div>
|
|
<EntitySelect items={providerItems} bind:value={form.provider_id} placeholder={t('commandTracker.selectProvider')} />
|
|
</div>
|
|
|
|
<div>
|
|
<div class="block text-sm font-medium mb-1">{t('commandTracker.commandConfig')}</div>
|
|
<EntitySelect items={configItems} bind:value={form.command_config_id} placeholder={t('commandTracker.selectCommandConfig')} />
|
|
</div>
|
|
|
|
<Button type="submit" disabled={submitting}>
|
|
{submitting ? t('common.loading') : (editing ? t('common.save') : t('common.create'))}
|
|
</Button>
|
|
</form>
|
|
</Card>
|
|
{/if}
|
|
|
|
{#if !showForm && allCmdTrackers.length > 0}
|
|
<div class="flex items-center gap-2 mb-3">
|
|
<input type="text" bind:value={filterText} placeholder={t('common.filterByName')}
|
|
class="flex-1 px-3 py-1.5 border border-[var(--color-border)] rounded-md text-sm bg-[var(--color-background)]" />
|
|
{#if !globalProviderFilter.id}
|
|
<div class="w-48">
|
|
<EntitySelect items={[{value: 0, label: t('common.allProviders'), icon: 'mdiFilterOff'}, ...providerItems]} bind:value={filterProviderId} placeholder={t('common.allProviders')} />
|
|
</div>
|
|
{/if}
|
|
</div>
|
|
{/if}
|
|
|
|
{#if allCmdTrackers.length === 0 && !showForm}
|
|
<Card>
|
|
<EmptyState icon="mdiConsoleLine" message={t('commandTracker.noTrackers')} />
|
|
</Card>
|
|
{:else if trackers.length === 0 && !showForm}
|
|
<Card>
|
|
<EmptyState icon="mdiFilterOff" message={t('common.noFilterResults')} />
|
|
</Card>
|
|
{:else}
|
|
<div class="list-stack stagger-children">
|
|
{#each trackers as trk}
|
|
<Card hover entityId={trk.id}>
|
|
<div class="list-row">
|
|
<div class="list-row__identity">
|
|
<div class="flex items-center gap-2 min-w-0">
|
|
<span style="color: var(--color-primary);" class="shrink-0"><MdiIcon name={trk.icon || 'mdiConsoleLine'} size={20} /></span>
|
|
<p class="font-medium truncate">{trk.name}</p>
|
|
<span class="text-xs px-1.5 py-0.5 rounded font-mono shrink-0 {trk.enabled
|
|
? 'bg-[var(--color-success-bg)] text-[var(--color-success-fg)]'
|
|
: 'bg-[var(--color-error-bg)] text-[var(--color-error-fg)]'}">
|
|
{trk.enabled ? t('commandTracker.enabled') : t('commandTracker.disabled')}
|
|
</span>
|
|
</div>
|
|
<div class="list-row__secondary mt-0.5 flex items-center gap-2 flex-wrap">
|
|
<CrossLink href="/providers" icon="mdiServer" label={providerName(trk.provider_id)} entityId={trk.provider_id} />
|
|
<CrossLink href="/command-configs" icon="mdiCog" label={configName(trk.command_config_id)} entityId={trk.command_config_id} />
|
|
{#if trk.listener_count !== undefined}
|
|
<span class="text-xs text-[var(--color-muted-foreground)]">
|
|
{trk.listener_count} {t('commandTracker.listeners').toLowerCase()}
|
|
</span>
|
|
{/if}
|
|
</div>
|
|
</div>
|
|
<MetaStrip tiles={commandTrackerTiles(trk)} />
|
|
<div class="list-row__actions flex-wrap justify-end">
|
|
<IconButton icon="mdiPencil" title={t('common.edit')} onclick={() => editTracker(trk)} />
|
|
<IconButton icon={trk.enabled ? 'mdiPause' : 'mdiPlay'} title={trk.enabled ? t('notificationTracker.pause') : t('notificationTracker.resume')} onclick={() => toggleEnabled(trk)} disabled={toggling[trk.id]} />
|
|
<button onclick={() => toggleListeners(trk.id)}
|
|
class="text-xs text-[var(--color-muted-foreground)] hover:underline px-2 py-1">
|
|
{t('commandTracker.listeners')} {expandedTracker === trk.id ? 'в–І' : 'в–ј'}
|
|
</button>
|
|
<IconButton icon="mdiDelete" title={t('common.delete')} onclick={() => remove(trk)} variant="danger" />
|
|
</div>
|
|
</div>
|
|
|
|
<!-- Listeners section -->
|
|
{#if expandedTracker === trk.id}
|
|
<div class="mt-3 border-t border-[var(--color-border)] pt-3" transition:slide>
|
|
{#if listenersLoading[trk.id]}
|
|
<p class="text-xs text-[var(--color-muted-foreground)]">{t('common.loading')}</p>
|
|
{:else if (listeners[trk.id] || []).length === 0}
|
|
<p class="text-xs text-[var(--color-muted-foreground)]">{t('commandTracker.noListeners')}</p>
|
|
{:else}
|
|
<div class="space-y-1">
|
|
{#each listeners[trk.id] as listener}
|
|
<div class="flex items-center justify-between text-sm px-2 py-1 rounded hover:bg-[var(--color-muted)]">
|
|
<div class="flex items-center gap-2 min-w-0">
|
|
<MdiIcon name="mdiRobot" size={14} />
|
|
<CrossLink href="/bots?tab=telegram" icon="mdiRobot" label={listener.name || listener.listener_type} entityId={listener.listener_id} />
|
|
<span class="text-xs px-1.5 py-0.5 rounded bg-[var(--color-primary)]/10 text-[var(--color-primary)] font-mono">{listener.listener_type}</span>
|
|
<button type="button" onclick={() => openScopeEditor(trk.id, listener)}
|
|
class="flex items-center gap-1 text-xs px-1.5 py-0.5 rounded border border-[var(--color-border)] text-[var(--color-muted-foreground)] hover:bg-[var(--color-muted)]"
|
|
title={t('commandTracker.editScope')}>
|
|
<MdiIcon name="mdiImageMultiple" size={12} />
|
|
{listener.allowed_album_ids === null || listener.allowed_album_ids === undefined
|
|
? t('commandTracker.scopeAll')
|
|
: `${(listener.allowed_album_ids || []).length} ${t('commandTracker.albumsShort')}`}
|
|
</button>
|
|
</div>
|
|
<IconButton icon="mdiClose" title={t('commandTracker.removeListener')} size={14}
|
|
onclick={() => removeListener(trk.id, listener.id)} variant="danger" />
|
|
</div>
|
|
{/each}
|
|
</div>
|
|
{/if}
|
|
|
|
<!-- Add listener -->
|
|
<div class="flex items-center gap-2 mt-2">
|
|
<div class="flex-1">
|
|
<EntitySelect items={botItems} bind:value={newListenerBotId[trk.id]} placeholder={t('commandTracker.selectBot')} />
|
|
</div>
|
|
<Button size="sm" onclick={() => addListener(trk.id)} disabled={!newListenerBotId[trk.id] || addingListener[trk.id]}>
|
|
{addingListener[trk.id] ? t('common.loading') : t('commandTracker.addListener')}
|
|
</Button>
|
|
</div>
|
|
</div>
|
|
{/if}
|
|
</Card>
|
|
{/each}
|
|
</div>
|
|
{/if}
|
|
|
|
{/if}
|
|
|
|
<ConfirmModal open={confirmDelete !== null} message={t('commandTracker.confirmDelete')}
|
|
onconfirm={() => confirmDelete?.onconfirm()} oncancel={() => confirmDelete = null} />
|
|
|
|
<!-- Per-listener album scope editor -->
|
|
<Modal open={scopeEditor !== null} title={t('commandTracker.scopeTitle')} onclose={() => scopeEditor = null}>
|
|
{#if scopeEditor}
|
|
<p class="text-xs text-[var(--color-muted-foreground)] mb-3">{t('commandTracker.scopeDescription')}</p>
|
|
<label class="flex items-center gap-2 text-sm mb-3">
|
|
<input type="checkbox" bind:checked={scopeEditor.inherit} />
|
|
{t('commandTracker.scopeInherit')}
|
|
</label>
|
|
{#if !scopeEditor.inherit}
|
|
{#if scopeEditor.collections.length > 0}
|
|
<div class="flex items-center justify-between mb-1.5 text-xs" style="color: var(--color-muted-foreground);">
|
|
<span>{scopeEditor.selectedIds.length} / {scopeEditor.collections.length}</span>
|
|
<div class="flex items-center gap-2">
|
|
<button type="button" class="underline hover:text-[var(--color-primary)]"
|
|
onclick={() => { if (scopeEditor) scopeEditor.selectedIds = scopeEditor.collections.map((c: any) => c.id); }}>
|
|
{t('backup.selectAll')}
|
|
</button>
|
|
<span aria-hidden="true">В·</span>
|
|
<button type="button" class="underline hover:text-[var(--color-primary)]"
|
|
onclick={() => { if (scopeEditor) scopeEditor.selectedIds = []; }}>
|
|
{t('backup.deselectAll')}
|
|
</button>
|
|
</div>
|
|
</div>
|
|
{/if}
|
|
<div class="space-y-1 max-h-72 overflow-y-auto border border-[var(--color-border)] rounded-md p-2">
|
|
{#if scopeEditor.collections.length === 0}
|
|
<p class="text-xs text-[var(--color-muted-foreground)] py-3 text-center">{t('commandTracker.noCollections')}</p>
|
|
{:else}
|
|
{#each scopeEditor.collections as col}
|
|
{@const cid = col.id}
|
|
<label class="flex items-center gap-2 text-sm px-2 py-1 rounded hover:bg-[var(--color-muted)] cursor-pointer">
|
|
<input type="checkbox" checked={scopeEditor.selectedIds.includes(cid)}
|
|
onchange={(e) => {
|
|
if (!scopeEditor) return;
|
|
const target = e.target as HTMLInputElement;
|
|
scopeEditor.selectedIds = target.checked
|
|
? [...scopeEditor.selectedIds, cid]
|
|
: scopeEditor.selectedIds.filter((i) => i !== cid);
|
|
}} />
|
|
<span class="truncate min-w-0 flex-1" title={col.albumName || col.name || cid}>{col.albumName || col.name || cid}</span>
|
|
</label>
|
|
{/each}
|
|
{/if}
|
|
</div>
|
|
{/if}
|
|
<div class="flex gap-2 justify-end mt-4">
|
|
<button onclick={() => scopeEditor = null}
|
|
class="px-3 py-1.5 text-sm rounded-md border border-[var(--color-border)] hover:bg-[var(--color-muted)] transition-colors">
|
|
{t('common.cancel')}
|
|
</button>
|
|
<Button size="sm" onclick={saveScope}>{t('common.save')}</Button>
|
|
</div>
|
|
{/if}
|
|
</Modal>
|