feat: UX improvements — secure webhooks, locale fixes, dynamic languages, UI polish
- Remove top paginator from dashboard events, keep only bottom - Fix test message locale: pass UI locale to email/matrix bot tests - Convert webhook auth mode from text input to icon grid selector - Generate secure UUID tokens for webhook URLs instead of sequential IDs - Move Recent Payloads into per-provider expandable container (lazy-loaded) - Make template config languages dynamic via app settings instead of hardcoded - Change default dev port to 5175
This commit is contained in:
@@ -58,6 +58,14 @@ export const memorySourceItems = (): GridItem[] => [
|
||||
{ value: 'native', icon: 'mdiMemory', label: t('trackingConfig.memorySourceNative'), desc: t('gridDesc.memorySourceNative') },
|
||||
];
|
||||
|
||||
// --- Webhook auth mode ---
|
||||
|
||||
export const webhookAuthModeItems = (): GridItem[] => [
|
||||
{ value: 'none', icon: 'mdiLockOpen', label: t('providers.authNone'), desc: t('gridDesc.authNone') },
|
||||
{ value: 'bearer_token', icon: 'mdiKey', label: t('providers.authBearer'), desc: t('gridDesc.authBearer') },
|
||||
{ value: 'hmac_sha256', icon: 'mdiShieldKey', label: t('providers.authHmac'), desc: t('gridDesc.authHmac') },
|
||||
];
|
||||
|
||||
// --- Locale ---
|
||||
|
||||
export const localeItems = (): GridItem[] => [
|
||||
|
||||
@@ -133,6 +133,9 @@
|
||||
"plankaWebhookUrlHint": "Set this as the Webhook URL in Planka environment config (relative to your bridge host).",
|
||||
"authMode": "Authentication Mode",
|
||||
"authModeHint": "Choose hmac_sha256, bearer_token, or none",
|
||||
"authNone": "None",
|
||||
"authBearer": "Bearer Token",
|
||||
"authHmac": "HMAC-SHA256",
|
||||
"genericWebhookSecretHint": "Secret for HMAC-SHA256 or Bearer token authentication. Leave empty for no authentication.",
|
||||
"maxStoredPayloads": "Max stored payloads",
|
||||
"maxStoredPayloadsHint": "Number of recent payloads to keep for debugging (0 = disabled, max 100)",
|
||||
@@ -658,6 +661,9 @@
|
||||
"webhookSecretHint": "Secret token to verify webhook requests from Telegram",
|
||||
"cacheTtl": "Media Cache TTL (hours)",
|
||||
"cacheTtlHint": "How long to cache uploaded Telegram file_ids before re-uploading",
|
||||
"locales": "Template Languages",
|
||||
"supportedLocales": "Supported Locales",
|
||||
"supportedLocalesHint": "Comma-separated locale codes for template editing (e.g. en,ru,de,fr)",
|
||||
"saved": "Settings saved"
|
||||
},
|
||||
"hints": {
|
||||
@@ -926,6 +932,9 @@
|
||||
"message_ups_overload": "UPS load exceeded capacity"
|
||||
},
|
||||
"gridDesc": {
|
||||
"authNone": "No authentication required",
|
||||
"authBearer": "Verify requests with a Bearer token",
|
||||
"authHmac": "Verify payload signature with HMAC-SHA256",
|
||||
"sortNone": "No sorting applied",
|
||||
"sortDate": "Sort by creation date",
|
||||
"sortRating": "Sort by star rating",
|
||||
|
||||
@@ -133,6 +133,9 @@
|
||||
"plankaWebhookUrlHint": "Укажите этот URL в конфигурации Planka (относительно хоста bridge).",
|
||||
"authMode": "Режим аутентификации",
|
||||
"authModeHint": "Выберите hmac_sha256, bearer_token или none",
|
||||
"authNone": "Без аутентификации",
|
||||
"authBearer": "Bearer Token",
|
||||
"authHmac": "HMAC-SHA256",
|
||||
"genericWebhookSecretHint": "Секрет для HMAC-SHA256 или Bearer token аутентификации. Оставьте пустым для режима без аутентификации.",
|
||||
"maxStoredPayloads": "Макс. сохранённых запросов",
|
||||
"maxStoredPayloadsHint": "Количество сохраняемых запросов для отладки (0 = отключено, макс. 100)",
|
||||
@@ -658,6 +661,9 @@
|
||||
"webhookSecretHint": "Секретный токен для проверки запросов вебхука от Telegram",
|
||||
"cacheTtl": "TTL кэша медиа (часы)",
|
||||
"cacheTtlHint": "Сколько хранить кэш Telegram file_id перед повторной загрузкой",
|
||||
"locales": "Языки шаблонов",
|
||||
"supportedLocales": "Поддерживаемые локали",
|
||||
"supportedLocalesHint": "Коды локалей через запятую для редактирования шаблонов (например en,ru,de,fr)",
|
||||
"saved": "Настройки сохранены"
|
||||
},
|
||||
"hints": {
|
||||
@@ -926,6 +932,9 @@
|
||||
"message_ups_overload": "ИБП перегружен"
|
||||
},
|
||||
"gridDesc": {
|
||||
"authNone": "Аутентификация не требуется",
|
||||
"authBearer": "Проверка запросов по Bearer-токену",
|
||||
"authHmac": "Проверка подписи через HMAC-SHA256",
|
||||
"sortNone": "Без сортировки",
|
||||
"sortDate": "По дате создания",
|
||||
"sortRating": "По рейтингу",
|
||||
|
||||
@@ -56,5 +56,5 @@ export const giteaDescriptor: ProviderDescriptor = {
|
||||
desc: () => '',
|
||||
},
|
||||
|
||||
webhookUrlPattern: '/api/webhooks/gitea/{id}',
|
||||
webhookUrlPattern: '/api/webhooks/gitea/{token}',
|
||||
};
|
||||
|
||||
@@ -62,5 +62,5 @@ export const plankaDescriptor: ProviderDescriptor = {
|
||||
desc: () => '',
|
||||
},
|
||||
|
||||
webhookUrlPattern: '/api/webhooks/planka/{id}',
|
||||
webhookUrlPattern: '/api/webhooks/planka/{token}',
|
||||
};
|
||||
|
||||
@@ -20,7 +20,10 @@ export interface ConfigField {
|
||||
configKey?: string;
|
||||
/** i18n key for the field label. */
|
||||
label: string;
|
||||
type: 'text' | 'password' | 'number';
|
||||
type: 'text' | 'password' | 'number' | 'grid-select';
|
||||
/** Grid-select item source function name from grid-items.ts. */
|
||||
gridItems?: string;
|
||||
gridColumns?: number;
|
||||
placeholder?: string;
|
||||
/**
|
||||
* - `true` → always required
|
||||
|
||||
@@ -10,10 +10,10 @@ export const webhookDescriptor: ProviderDescriptor = {
|
||||
{
|
||||
key: 'auth_mode', configKey: 'auth_mode',
|
||||
label: 'providers.authMode',
|
||||
type: 'text',
|
||||
placeholder: 'hmac_sha256 | bearer_token | none',
|
||||
type: 'grid-select',
|
||||
gridItems: 'webhookAuthModeItems',
|
||||
gridColumns: 3,
|
||||
defaultValue: 'none',
|
||||
hint: 'providers.authModeHint',
|
||||
},
|
||||
{
|
||||
key: 'webhook_secret', configKey: 'webhook_secret',
|
||||
@@ -57,6 +57,6 @@ export const webhookDescriptor: ProviderDescriptor = {
|
||||
|
||||
collectionMeta: null,
|
||||
webhookBased: true,
|
||||
webhookUrlPattern: '/api/webhooks/webhook/{id}',
|
||||
webhookUrlPattern: '/api/webhooks/webhook/{token}',
|
||||
payloadHistory: true,
|
||||
};
|
||||
|
||||
@@ -74,6 +74,23 @@ export const capabilitiesCache = (() => {
|
||||
};
|
||||
})();
|
||||
|
||||
/** Supported template locales — fetched from app settings. */
|
||||
export const supportedLocalesCache = (() => {
|
||||
let data = $state<string[]>(['en', 'ru']);
|
||||
let fetchedAt = $state(0);
|
||||
const TTL = 300_000; // 5 minutes
|
||||
return {
|
||||
get items() { return data; },
|
||||
async fetch(force = false): Promise<string[]> {
|
||||
if (!force && fetchedAt > 0 && Date.now() - fetchedAt < TTL) return data;
|
||||
const { api } = await import('$lib/api');
|
||||
data = await api('/settings/locales');
|
||||
fetchedAt = Date.now();
|
||||
return data;
|
||||
},
|
||||
};
|
||||
})();
|
||||
|
||||
/**
|
||||
* All caches keyed by entity type — for search palette and crosslink resolution.
|
||||
*/
|
||||
|
||||
@@ -6,6 +6,7 @@ export interface ServiceProvider {
|
||||
name: string;
|
||||
icon: string;
|
||||
config: Record<string, any>;
|
||||
webhook_token: string;
|
||||
created_at: string;
|
||||
}
|
||||
|
||||
|
||||
@@ -319,10 +319,6 @@
|
||||
</div>
|
||||
{/snippet}
|
||||
|
||||
<div class="mb-3">
|
||||
{@render paginator()}
|
||||
</div>
|
||||
|
||||
{#if eventsLoading}
|
||||
<Card><p class="text-sm text-center py-4" style="color: var(--color-muted-foreground);">{t('dashboard.loadingEvents')}</p></Card>
|
||||
{:else if status.recent_events.length === 0}
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
<script lang="ts">
|
||||
import { api } from '$lib/api';
|
||||
import { t } from '$lib/i18n';
|
||||
import { t, getLocale } from '$lib/i18n';
|
||||
import { emailBotsCache } from '$lib/stores/caches.svelte';
|
||||
import PageHeader from '$lib/components/PageHeader.svelte';
|
||||
import Card from '$lib/components/Card.svelte';
|
||||
@@ -72,7 +72,7 @@
|
||||
async function testEmailBot(botId: number) {
|
||||
emailTesting = { ...emailTesting, [botId]: true };
|
||||
try {
|
||||
const res = await api(`/email-bots/${botId}/test`, { method: 'POST' });
|
||||
const res = await api(`/email-bots/${botId}/test?locale=${getLocale()}`, { method: 'POST' });
|
||||
if (res.success) snackSuccess(t('snack.emailBotTestSent'));
|
||||
else snackError(res.error || t('emailBot.operationFailed'));
|
||||
} catch (err: any) { snackError(err.message); }
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
<script lang="ts">
|
||||
import { api } from '$lib/api';
|
||||
import { t } from '$lib/i18n';
|
||||
import { t, getLocale } from '$lib/i18n';
|
||||
import { matrixBotsCache } from '$lib/stores/caches.svelte';
|
||||
import PageHeader from '$lib/components/PageHeader.svelte';
|
||||
import Card from '$lib/components/Card.svelte';
|
||||
@@ -70,7 +70,7 @@
|
||||
async function testMatrixBot(botId: number) {
|
||||
matrixTesting = { ...matrixTesting, [botId]: true };
|
||||
try {
|
||||
const res = await api(`/matrix-bots/${botId}/test`, { method: 'POST' });
|
||||
const res = await api(`/matrix-bots/${botId}/test?locale=${getLocale()}`, { method: 'POST' });
|
||||
if (res.success) snackSuccess(t('snack.matrixBotTestOk'));
|
||||
else snackError(res.error || t('matrixBot.operationFailed'));
|
||||
} catch (err: any) { snackError(err.message); }
|
||||
|
||||
@@ -4,7 +4,7 @@
|
||||
import { api } from '$lib/api';
|
||||
import { t } from '$lib/i18n';
|
||||
import { sanitizePreview } from '$lib/sanitize';
|
||||
import { commandTemplateConfigsCache } from '$lib/stores/caches.svelte';
|
||||
import { commandTemplateConfigsCache, supportedLocalesCache } 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';
|
||||
@@ -38,7 +38,7 @@
|
||||
description: string;
|
||||
}
|
||||
|
||||
const LOCALES = ['en', 'ru'] as const;
|
||||
let LOCALES = $derived(supportedLocalesCache.items);
|
||||
|
||||
let allCmdTplConfigs = $state<CmdTemplateConfig[]>([]);
|
||||
let filterText = $state('');
|
||||
@@ -132,6 +132,7 @@
|
||||
commandTemplateConfigsCache.fetch(true),
|
||||
api('/providers/capabilities'),
|
||||
api('/command-template-configs/variables'),
|
||||
supportedLocalesCache.fetch(),
|
||||
]);
|
||||
allCmdTplConfigs = cfgs;
|
||||
allCapabilities = caps;
|
||||
|
||||
@@ -14,7 +14,9 @@
|
||||
import IconButton from '$lib/components/IconButton.svelte';
|
||||
import ErrorBanner from '$lib/components/ErrorBanner.svelte';
|
||||
import IconGridSelect from '$lib/components/IconGridSelect.svelte';
|
||||
import { providerTypeItems, providerDefaultIcon } from '$lib/grid-items';
|
||||
import { providerTypeItems, providerDefaultIcon, webhookAuthModeItems } from '$lib/grid-items';
|
||||
|
||||
const gridItemSources: Record<string, () => any[]> = { webhookAuthModeItems };
|
||||
import { globalProviderFilter } from '$lib/stores/provider-filter.svelte';
|
||||
import { snackSuccess, snackError } from '$lib/stores/snackbar.svelte';
|
||||
import { highlightFromUrl } from '$lib/highlight';
|
||||
@@ -189,7 +191,9 @@
|
||||
{t(editing && field.editLabel ? field.editLabel : field.label)}
|
||||
{#if field.optional}<span class="text-xs text-[var(--color-muted-foreground)]">({t('providers.optional')})</span>{/if}
|
||||
</label>
|
||||
{#if field.type === 'number'}
|
||||
{#if field.type === 'grid-select' && field.gridItems}
|
||||
<IconGridSelect items={gridItemSources[field.gridItems]()} bind:value={form[field.key]} columns={field.gridColumns ?? 2} compact />
|
||||
{:else if field.type === 'number'}
|
||||
<input id="prv-{field.key}" type="number" bind:value={form[field.key]}
|
||||
min={field.min} max={field.max}
|
||||
class="w-full px-3 py-2 border border-[var(--color-border)] rounded-md text-sm bg-[var(--color-background)]" />
|
||||
@@ -207,7 +211,7 @@
|
||||
{#if descriptor?.webhookUrlPattern && editing}
|
||||
<div class="bg-[var(--color-muted)] rounded-md p-3">
|
||||
<label class="block text-sm font-medium mb-1">{t('providers.webhookUrl')}</label>
|
||||
<code class="text-xs select-all break-all">{descriptor.webhookUrlPattern.replace('{id}', String(editing))}</code>
|
||||
<code class="text-xs select-all break-all">{descriptor.webhookUrlPattern.replace('{token}', providers.find(p => p.id === editing)?.webhook_token ?? '')}</code>
|
||||
<p class="text-xs text-[var(--color-muted-foreground)] mt-1">{t('providers.webhookUrlHint')}</p>
|
||||
</div>
|
||||
{/if}
|
||||
@@ -254,7 +258,7 @@
|
||||
<p class="text-xs text-[var(--color-muted-foreground)] font-mono">{provider.config.host}:{provider.config.port || 3493}</p>
|
||||
{/if}
|
||||
{#if provDesc?.webhookUrlPattern}
|
||||
<p class="text-xs text-[var(--color-muted-foreground)] font-mono mt-0.5">{t('providers.webhookUrl')}: <span class="select-all">{provDesc.webhookUrlPattern.replace('{id}', String(provider.id))}</span></p>
|
||||
<p class="text-xs text-[var(--color-muted-foreground)] font-mono mt-0.5">{t('providers.webhookUrl')}: <span class="select-all">{provDesc.webhookUrlPattern.replace('{token}', provider.webhook_token)}</span></p>
|
||||
{/if}
|
||||
</div>
|
||||
</div>
|
||||
@@ -263,10 +267,10 @@
|
||||
<IconButton icon="mdiDelete" title={t('common.delete')} onclick={() => startDelete(provider)} variant="danger" />
|
||||
</div>
|
||||
</div>
|
||||
</Card>
|
||||
{#if provDesc?.payloadHistory && !showForm}
|
||||
<WebhookPayloadHistory providerId={provider.id} />
|
||||
{/if}
|
||||
</Card>
|
||||
{/each}
|
||||
</div>
|
||||
{/if}
|
||||
|
||||
@@ -2,7 +2,6 @@
|
||||
import { t } from '$lib/i18n';
|
||||
import { api } from '$lib/api';
|
||||
import MdiIcon from '$lib/components/MdiIcon.svelte';
|
||||
import Card from '$lib/components/Card.svelte';
|
||||
import ConfirmModal from '$lib/components/ConfirmModal.svelte';
|
||||
import type { WebhookPayloadLog } from '$lib/types';
|
||||
|
||||
@@ -12,7 +11,9 @@
|
||||
let { providerId }: Props = $props();
|
||||
|
||||
let logs = $state<WebhookPayloadLog[]>([]);
|
||||
let loading = $state(true);
|
||||
let loading = $state(false);
|
||||
let loaded = $state(false);
|
||||
let expanded = $state(false);
|
||||
let expandedId = $state<number | null>(null);
|
||||
let showClearConfirm = $state(false);
|
||||
|
||||
@@ -25,6 +26,12 @@
|
||||
logs = [];
|
||||
}
|
||||
loading = false;
|
||||
loaded = true;
|
||||
}
|
||||
|
||||
function toggle() {
|
||||
expanded = !expanded;
|
||||
if (expanded && !loaded) loadLogs();
|
||||
}
|
||||
|
||||
async function clearLogs() {
|
||||
@@ -60,36 +67,32 @@
|
||||
function formatTime(iso: string): string {
|
||||
return new Date(iso).toLocaleString();
|
||||
}
|
||||
|
||||
$effect(() => {
|
||||
void providerId;
|
||||
loadLogs();
|
||||
});
|
||||
</script>
|
||||
|
||||
<Card>
|
||||
<div class="flex items-center justify-between mb-3">
|
||||
<div class="flex items-center gap-2">
|
||||
<h3 class="text-sm font-semibold">{t('webhookLogs.title')}</h3>
|
||||
{#if logs.length > 0}
|
||||
<div class="border-t border-[var(--color-border)] mt-3 pt-2">
|
||||
<button onclick={toggle} class="w-full flex items-center gap-2 text-sm font-medium py-1 hover:opacity-80 transition-opacity">
|
||||
<MdiIcon name={expanded ? 'mdiChevronDown' : 'mdiChevronRight'} size={16} />
|
||||
{t('webhookLogs.title')}
|
||||
{#if loaded && logs.length > 0}
|
||||
<span class="text-xs px-1.5 py-0.5 rounded-full bg-[var(--color-muted)] text-[var(--color-muted-foreground)]">{logs.length}</span>
|
||||
{/if}
|
||||
</div>
|
||||
{#if logs.length > 0}
|
||||
</button>
|
||||
|
||||
{#if expanded}
|
||||
<div class="mt-2">
|
||||
{#if loading}
|
||||
<div class="text-sm text-[var(--color-muted-foreground)] py-3 text-center">{t('common.loading')}</div>
|
||||
{:else if logs.length === 0}
|
||||
<div class="text-sm text-[var(--color-muted-foreground)] py-3 text-center">{t('webhookLogs.empty')}</div>
|
||||
{:else}
|
||||
<div class="flex justify-end mb-2">
|
||||
<button
|
||||
onclick={() => showClearConfirm = true}
|
||||
class="text-xs px-2 py-1 rounded-md transition-colors hover:bg-[var(--color-error-bg)] text-[var(--color-error-fg)]"
|
||||
>
|
||||
{t('webhookLogs.clear')}
|
||||
</button>
|
||||
{/if}
|
||||
</div>
|
||||
|
||||
{#if loading}
|
||||
<div class="text-sm text-[var(--color-muted-foreground)] py-4 text-center">{t('common.loading')}</div>
|
||||
{:else if logs.length === 0}
|
||||
<div class="text-sm text-[var(--color-muted-foreground)] py-4 text-center">{t('webhookLogs.empty')}</div>
|
||||
{:else}
|
||||
<div class="space-y-1">
|
||||
{#each logs as log}
|
||||
<button
|
||||
@@ -113,7 +116,6 @@
|
||||
|
||||
{#if expandedId === log.id}
|
||||
<div class="ml-6 mr-2 mb-2 space-y-2">
|
||||
<!-- Headers -->
|
||||
{#if Object.keys(log.headers).length > 0}
|
||||
<div>
|
||||
<div class="text-xs font-medium text-[var(--color-muted-foreground)] mb-1">{t('webhookLogs.headers')}</div>
|
||||
@@ -125,13 +127,11 @@
|
||||
</div>
|
||||
{/if}
|
||||
|
||||
<!-- Body -->
|
||||
<div>
|
||||
<div class="text-xs font-medium text-[var(--color-muted-foreground)] mb-1">{t('webhookLogs.body')}</div>
|
||||
<pre class="bg-[var(--color-background)] border border-[var(--color-border)] rounded-md p-2 text-xs font-mono overflow-x-auto whitespace-pre-wrap break-all" style="max-height: 300px; overflow-y: auto;">{JSON.stringify(log.body, null, 2)}</pre>
|
||||
</div>
|
||||
|
||||
<!-- Extracted fields -->
|
||||
{#if log.status === 'matched' && Object.keys(log.extracted_fields).length > 0}
|
||||
<div>
|
||||
<div class="text-xs font-medium text-[var(--color-muted-foreground)] mb-1">{t('webhookLogs.extractedFields')}</div>
|
||||
@@ -143,7 +143,6 @@
|
||||
</div>
|
||||
{/if}
|
||||
|
||||
<!-- Error message -->
|
||||
{#if log.status === 'error' && log.error_message}
|
||||
<div>
|
||||
<div class="text-xs font-medium text-[var(--color-error-fg)] mb-1">{t('webhookLogs.errorMessage')}</div>
|
||||
@@ -155,7 +154,9 @@
|
||||
{/each}
|
||||
</div>
|
||||
{/if}
|
||||
</Card>
|
||||
</div>
|
||||
{/if}
|
||||
</div>
|
||||
|
||||
<ConfirmModal
|
||||
open={showClearConfirm}
|
||||
|
||||
@@ -6,7 +6,9 @@
|
||||
import IconPicker from '$lib/components/IconPicker.svelte';
|
||||
import IconGridSelect from '$lib/components/IconGridSelect.svelte';
|
||||
import { goto } from '$app/navigation';
|
||||
import { providerTypeItems } from '$lib/grid-items';
|
||||
import { providerTypeItems, webhookAuthModeItems } from '$lib/grid-items';
|
||||
|
||||
const gridItemSources: Record<string, () => any[]> = { webhookAuthModeItems };
|
||||
import { getDescriptor, buildProviderFormDefaults } from '$lib/providers';
|
||||
import Button from '$lib/components/Button.svelte';
|
||||
import ErrorBanner from '$lib/components/ErrorBanner.svelte';
|
||||
@@ -100,7 +102,9 @@
|
||||
{t(field.label)}
|
||||
{#if field.optional}<span class="text-xs text-[var(--color-muted-foreground)]">({t('providers.optional')})</span>{/if}
|
||||
</label>
|
||||
{#if field.type === 'number'}
|
||||
{#if field.type === 'grid-select' && field.gridItems}
|
||||
<IconGridSelect items={gridItemSources[field.gridItems]()} bind:value={form[field.key]} columns={field.gridColumns ?? 2} compact />
|
||||
{:else if field.type === 'number'}
|
||||
<input id="prv-{field.key}" type="number" bind:value={form[field.key]} min={field.min} max={field.max}
|
||||
class="w-full px-3 py-2 border border-[var(--color-border)] rounded-md text-sm bg-[var(--color-background)]" />
|
||||
{:else}
|
||||
|
||||
@@ -18,6 +18,7 @@
|
||||
external_url: '',
|
||||
telegram_webhook_secret: '',
|
||||
telegram_cache_ttl_hours: '48',
|
||||
supported_locales: 'en,ru',
|
||||
});
|
||||
|
||||
onMount(async () => {
|
||||
@@ -79,6 +80,21 @@
|
||||
</div>
|
||||
</Card>
|
||||
|
||||
<!-- Locales section -->
|
||||
<Card>
|
||||
<h3 class="text-sm font-semibold mb-4 flex items-center gap-2">
|
||||
<MdiIcon name="mdiTranslate" size={18} />
|
||||
{t('settings.locales')}
|
||||
</h3>
|
||||
<div class="space-y-3">
|
||||
<div>
|
||||
<label class="block text-xs font-medium mb-1">{t('settings.supportedLocales')}<Hint text={t('settings.supportedLocalesHint')} /></label>
|
||||
<input bind:value={settings.supported_locales} placeholder="en,ru,de,fr"
|
||||
class="w-full max-w-md px-3 py-1.5 text-sm border border-[var(--color-border)] rounded-md bg-[var(--color-background)] font-mono" />
|
||||
</div>
|
||||
</div>
|
||||
</Card>
|
||||
|
||||
<Button onclick={save} disabled={saving}>
|
||||
{saving ? t('common.loading') : t('common.save')}
|
||||
</Button>
|
||||
|
||||
@@ -4,7 +4,7 @@
|
||||
import { api } from '$lib/api';
|
||||
import { t } from '$lib/i18n';
|
||||
import { sanitizePreview } from '$lib/sanitize';
|
||||
import { templateConfigsCache, capabilitiesCache } from '$lib/stores/caches.svelte';
|
||||
import { templateConfigsCache, capabilitiesCache, supportedLocalesCache } 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';
|
||||
@@ -57,7 +57,7 @@
|
||||
let slotFilter = $state('');
|
||||
let showPreviewFor = $state<Set<string>>(new Set());
|
||||
|
||||
const LOCALES = ['en', 'ru'] as const;
|
||||
let LOCALES = $derived(supportedLocalesCache.items);
|
||||
let activeLocale = $state<string>('en');
|
||||
|
||||
function toggleSlot(key: string) {
|
||||
@@ -202,6 +202,7 @@
|
||||
templateConfigsCache.fetch(true),
|
||||
api('/template-configs/variables'),
|
||||
capabilitiesCache.fetch(),
|
||||
supportedLocalesCache.fetch(),
|
||||
]);
|
||||
} catch (err: any) { error = err.message || t('common.loadError'); snackError(error); }
|
||||
finally { loaded = true; highlightFromUrl(); }
|
||||
|
||||
@@ -5,6 +5,7 @@ import { defineConfig } from 'vite';
|
||||
export default defineConfig({
|
||||
plugins: [tailwindcss(), sveltekit()],
|
||||
server: {
|
||||
port: 5175,
|
||||
proxy: {
|
||||
'/api': 'http://localhost:8420',
|
||||
'/docs': 'http://localhost:8420',
|
||||
|
||||
@@ -8,7 +8,7 @@ from pydantic import BaseModel
|
||||
from sqlmodel import select
|
||||
from sqlmodel.ext.asyncio.session import AsyncSession
|
||||
|
||||
from ..auth.dependencies import require_admin
|
||||
from ..auth.dependencies import get_current_user, require_admin
|
||||
from ..database.engine import get_session
|
||||
from ..database.models import AppSetting, TelegramBot, User
|
||||
|
||||
@@ -21,12 +21,14 @@ _SETTING_KEYS = {
|
||||
"external_url": "NOTIFY_BRIDGE_EXTERNAL_URL",
|
||||
"telegram_webhook_secret": "NOTIFY_BRIDGE_TELEGRAM_WEBHOOK_SECRET",
|
||||
"telegram_cache_ttl_hours": None, # no env fallback, default 48
|
||||
"supported_locales": None, # comma-separated locale codes
|
||||
}
|
||||
|
||||
_DEFAULTS = {
|
||||
"external_url": "",
|
||||
"telegram_webhook_secret": "",
|
||||
"telegram_cache_ttl_hours": "48",
|
||||
"supported_locales": "en,ru",
|
||||
}
|
||||
|
||||
|
||||
@@ -47,6 +49,7 @@ class SettingsUpdate(BaseModel):
|
||||
external_url: str | None = None
|
||||
telegram_webhook_secret: str | None = None
|
||||
telegram_cache_ttl_hours: str | None = None
|
||||
supported_locales: str | None = None
|
||||
|
||||
|
||||
@router.get("")
|
||||
@@ -105,6 +108,17 @@ async def update_settings(
|
||||
return result
|
||||
|
||||
|
||||
@router.get("/locales")
|
||||
async def get_supported_locales(
|
||||
user: User = Depends(get_current_user),
|
||||
session: AsyncSession = Depends(get_session),
|
||||
):
|
||||
"""Return list of supported template locales (available to all users)."""
|
||||
raw = await get_setting(session, "supported_locales")
|
||||
locales = [loc.strip() for loc in raw.split(",") if loc.strip()]
|
||||
return locales or ["en"]
|
||||
|
||||
|
||||
async def _reregister_webhooks(
|
||||
session: AsyncSession, base_url: str, secret: str
|
||||
) -> None:
|
||||
|
||||
@@ -2,7 +2,7 @@
|
||||
|
||||
import logging
|
||||
|
||||
from fastapi import APIRouter, Depends, HTTPException, status
|
||||
from fastapi import APIRouter, Depends, HTTPException, Query, status
|
||||
from pydantic import BaseModel
|
||||
from sqlmodel import select
|
||||
from sqlmodel.ext.asyncio.session import AsyncSession
|
||||
@@ -117,12 +117,16 @@ async def delete_email_bot(
|
||||
@router.post("/{bot_id}/test")
|
||||
async def test_email_bot(
|
||||
bot_id: int,
|
||||
locale: str = Query("en"),
|
||||
user: User = Depends(get_current_user),
|
||||
session: AsyncSession = Depends(get_session),
|
||||
):
|
||||
"""Send a test email to the bot's own address to verify SMTP connection."""
|
||||
bot = await _get_user_bot(session, bot_id, user.id)
|
||||
|
||||
from ..services.notifier import _get_test_message
|
||||
msg = _get_test_message(locale, "email")
|
||||
|
||||
from notify_bridge_core.notifications.email.client import EmailClient, SmtpConfig
|
||||
client = EmailClient(SmtpConfig(
|
||||
host=bot.smtp_host,
|
||||
@@ -135,8 +139,8 @@ async def test_email_bot(
|
||||
))
|
||||
result = await client.send(
|
||||
to_email=bot.email,
|
||||
subject="Notify Bridge — Test Connection",
|
||||
body_text="This is a test email from Notify Bridge. Your SMTP settings are working correctly.",
|
||||
subject=f"Notify Bridge — {msg}",
|
||||
body_text=msg,
|
||||
)
|
||||
return result
|
||||
|
||||
|
||||
@@ -2,7 +2,7 @@
|
||||
|
||||
import logging
|
||||
|
||||
from fastapi import APIRouter, Depends, HTTPException, status
|
||||
from fastapi import APIRouter, Depends, HTTPException, Query, status
|
||||
from pydantic import BaseModel
|
||||
from sqlmodel import select
|
||||
from sqlmodel.ext.asyncio.session import AsyncSession
|
||||
@@ -99,6 +99,7 @@ async def delete_matrix_bot(
|
||||
async def test_matrix_bot(
|
||||
bot_id: int,
|
||||
room_id: str = "",
|
||||
locale: str = Query("en"),
|
||||
user: User = Depends(get_current_user),
|
||||
session: AsyncSession = Depends(get_session),
|
||||
):
|
||||
@@ -127,12 +128,14 @@ async def test_matrix_bot(
|
||||
|
||||
# Optionally send a test message
|
||||
if room_id:
|
||||
from ..services.notifier import _get_test_message
|
||||
from notify_bridge_core.notifications.matrix.client import MatrixClient
|
||||
msg = _get_test_message(locale, "matrix")
|
||||
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",
|
||||
msg,
|
||||
html_message=f"<b>{msg}</b>",
|
||||
)
|
||||
result["send_result"] = send_result
|
||||
|
||||
|
||||
@@ -447,6 +447,7 @@ def _provider_response(p: ServiceProvider) -> dict:
|
||||
"name": p.name,
|
||||
"icon": p.icon,
|
||||
"config": config,
|
||||
"webhook_token": p.webhook_token,
|
||||
"created_at": p.created_at.isoformat(),
|
||||
}
|
||||
|
||||
|
||||
@@ -34,6 +34,22 @@ _LOGGER = logging.getLogger(__name__)
|
||||
router = APIRouter(prefix="/api/webhooks", tags=["webhooks"])
|
||||
|
||||
|
||||
async def _get_provider_by_token(
|
||||
session: AsyncSession, token: str, expected_type: str,
|
||||
) -> ServiceProvider:
|
||||
"""Look up a provider by its webhook_token and expected type."""
|
||||
result = await session.exec(
|
||||
select(ServiceProvider).where(
|
||||
ServiceProvider.webhook_token == token,
|
||||
ServiceProvider.type == expected_type,
|
||||
)
|
||||
)
|
||||
provider = result.first()
|
||||
if not provider:
|
||||
raise HTTPException(status_code=404, detail="Provider not found")
|
||||
return provider
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# HMAC-SHA256 validation
|
||||
# ---------------------------------------------------------------------------
|
||||
@@ -168,16 +184,14 @@ async def _dispatch_webhook_event(
|
||||
# Gitea webhook endpoint
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
@router.post("/gitea/{provider_id}")
|
||||
async def gitea_webhook(provider_id: int, request: Request):
|
||||
@router.post("/gitea/{token}")
|
||||
async def gitea_webhook(token: str, request: Request):
|
||||
"""Receive a Gitea webhook, parse it, filter, and dispatch notifications."""
|
||||
engine = get_engine()
|
||||
|
||||
# --- Load provider and validate signature ---
|
||||
async with AsyncSession(engine) as session:
|
||||
provider = await session.get(ServiceProvider, provider_id)
|
||||
if not provider or provider.type != "gitea":
|
||||
raise HTTPException(status_code=404, detail="Provider not found")
|
||||
provider = await _get_provider_by_token(session, token, "gitea")
|
||||
|
||||
webhook_secret = (provider.config or {}).get("webhook_secret", "")
|
||||
|
||||
@@ -211,7 +225,7 @@ async def gitea_webhook(provider_id: int, request: Request):
|
||||
# --- Dispatch ---
|
||||
dispatched = await _dispatch_webhook_event(
|
||||
engine=engine,
|
||||
provider_id=provider_id,
|
||||
provider_id=provider.id,
|
||||
provider_name=provider.name,
|
||||
provider_config=provider.config or {},
|
||||
event=event,
|
||||
@@ -239,16 +253,14 @@ def _verify_planka_token(expected_token: str, request: Request) -> bool:
|
||||
return False
|
||||
|
||||
|
||||
@router.post("/planka/{provider_id}")
|
||||
async def planka_webhook(provider_id: int, request: Request):
|
||||
@router.post("/planka/{token}")
|
||||
async def planka_webhook(token: str, request: Request):
|
||||
"""Receive a Planka webhook, parse it, filter, and dispatch notifications."""
|
||||
engine = get_engine()
|
||||
|
||||
# --- Load provider and validate token ---
|
||||
async with AsyncSession(engine) as session:
|
||||
provider = await session.get(ServiceProvider, provider_id)
|
||||
if not provider or provider.type != "planka":
|
||||
raise HTTPException(status_code=404, detail="Provider not found")
|
||||
provider = await _get_provider_by_token(session, token, "planka")
|
||||
|
||||
webhook_secret = (provider.config or {}).get("webhook_secret", "")
|
||||
|
||||
@@ -279,7 +291,7 @@ async def planka_webhook(provider_id: int, request: Request):
|
||||
# --- Dispatch ---
|
||||
dispatched = await _dispatch_webhook_event(
|
||||
engine=engine,
|
||||
provider_id=provider_id,
|
||||
provider_id=provider.id,
|
||||
provider_name=provider.name,
|
||||
provider_config=provider.config or {},
|
||||
event=event,
|
||||
@@ -394,17 +406,16 @@ async def _save_webhook_log(
|
||||
_LOGGER.warning("Failed to save webhook payload log for provider %d", provider_id, exc_info=True)
|
||||
|
||||
|
||||
@router.post("/webhook/{provider_id}")
|
||||
async def generic_webhook(provider_id: int, request: Request):
|
||||
@router.post("/webhook/{token}")
|
||||
async def generic_webhook(token: str, request: Request):
|
||||
"""Receive a generic webhook, extract variables via JSONPath, and dispatch notifications."""
|
||||
engine = get_engine()
|
||||
|
||||
# --- Load provider and validate auth ---
|
||||
async with AsyncSession(engine) as session:
|
||||
provider = await session.get(ServiceProvider, provider_id)
|
||||
if not provider or provider.type != "webhook":
|
||||
raise HTTPException(status_code=404, detail="Provider not found")
|
||||
provider = await _get_provider_by_token(session, token, "webhook")
|
||||
|
||||
provider_id = provider.id
|
||||
provider_config = provider.config or {}
|
||||
provider_name = provider.name
|
||||
|
||||
|
||||
@@ -33,7 +33,7 @@ class Settings(BaseSettings):
|
||||
|
||||
telegram_webhook_secret: str = ""
|
||||
|
||||
cors_allowed_origins: str = "http://localhost:5173"
|
||||
cors_allowed_origins: str = "http://localhost:5175"
|
||||
"""Comma-separated allowed origins for CORS (e.g. 'http://localhost:5173,https://myapp.com')."""
|
||||
|
||||
static_dir: str = ""
|
||||
|
||||
@@ -272,6 +272,24 @@ async def migrate_schema(engine: AsyncEngine) -> None:
|
||||
)
|
||||
logger.info("Added commands_enabled column to telegram_chat table")
|
||||
|
||||
# Add webhook_token to service_provider if missing
|
||||
if await _has_table(conn, "service_provider"):
|
||||
if not await _has_column(conn, "service_provider", "webhook_token"):
|
||||
await conn.execute(
|
||||
text("ALTER TABLE service_provider ADD COLUMN webhook_token TEXT DEFAULT ''")
|
||||
)
|
||||
logger.info("Added webhook_token column to service_provider table")
|
||||
# Backfill existing providers with unique tokens
|
||||
import uuid
|
||||
providers = (await conn.execute(text("SELECT id FROM service_provider"))).fetchall()
|
||||
for row in providers:
|
||||
await conn.execute(
|
||||
text("UPDATE service_provider SET webhook_token = :tok WHERE id = :pid"),
|
||||
{"tok": uuid.uuid4().hex, "pid": row[0]},
|
||||
)
|
||||
if providers:
|
||||
logger.info("Backfilled webhook_token for %d existing providers", len(providers))
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Legacy tracker_target migration (pre-Phase 1)
|
||||
|
||||
@@ -33,6 +33,7 @@ class ServiceProvider(SQLModel, table=True):
|
||||
name: str
|
||||
icon: str = Field(default="")
|
||||
config: dict[str, Any] = Field(default_factory=dict, sa_column=Column(JSON))
|
||||
webhook_token: str = Field(default_factory=lambda: uuid4().hex)
|
||||
created_at: datetime = Field(default_factory=_utcnow)
|
||||
|
||||
|
||||
|
||||
@@ -11,14 +11,15 @@ if [ -n "$PID" ]; then
|
||||
sleep 1
|
||||
fi
|
||||
|
||||
# Resolve python — py launcher needs absolute path for nohup on Windows
|
||||
if command -v python3 &>/dev/null; then
|
||||
# Resolve python — prefer py launcher on Windows (python3 may be the Store stub)
|
||||
if command -v py &>/dev/null; then
|
||||
PYTHON=$(py -3 -c "import sys; print(sys.executable)" 2>/dev/null)
|
||||
elif command -v python3 &>/dev/null && python3 --version &>/dev/null; then
|
||||
PYTHON=python3
|
||||
elif command -v python &>/dev/null; then
|
||||
elif command -v python &>/dev/null && python --version &>/dev/null; then
|
||||
PYTHON=python
|
||||
else
|
||||
PYTHON=$(py -3.13 -c "import sys; print(sys.executable)" 2>/dev/null \
|
||||
|| py -3 -c "import sys; print(sys.executable)")
|
||||
echo "Python not found"; exit 1
|
||||
fi
|
||||
|
||||
# Start backend
|
||||
|
||||
@@ -6,7 +6,7 @@ set -e
|
||||
cd "$(dirname "$0")/.."
|
||||
|
||||
# Kill existing frontend
|
||||
PID=$(netstat -ano 2>/dev/null | grep ':5173.*LISTENING' | awk '{print $5}' | head -1)
|
||||
PID=$(netstat -ano 2>/dev/null | grep ':5175.*LISTENING' | awk '{print $5}' | head -1)
|
||||
if [ -n "$PID" ]; then
|
||||
taskkill //F //PID "$PID" 2>/dev/null || true
|
||||
sleep 1
|
||||
@@ -14,8 +14,8 @@ fi
|
||||
|
||||
# Start frontend
|
||||
cd frontend
|
||||
npx vite dev --port 5173 --host > /dev/null 2>&1 &
|
||||
npx vite dev --port 5175 --host > /dev/null 2>&1 &
|
||||
cd ..
|
||||
|
||||
sleep 4
|
||||
curl -s -o /dev/null -w "Frontend: %{http_code}\n" http://localhost:5173/
|
||||
curl -s -o /dev/null -w "Frontend: %{http_code}\n" http://localhost:5175/
|
||||
|
||||
Reference in New Issue
Block a user