diff --git a/web/src/locales/en.json b/web/src/locales/en.json index 2427e6c..8aa3d07 100644 --- a/web/src/locales/en.json +++ b/web/src/locales/en.json @@ -277,6 +277,7 @@ "apiKeysRevokeTitle": "Revoke API key", "apiKeysRevokeConfirm": "Revoke \"{{name}}\"? Scripts using this key will stop working immediately.", "apiKeysRevokeSuccess": "API key revoked", + "integrations": "Integrations", "backup": "Backup & restore" }, "about": { @@ -304,6 +305,7 @@ "sourceItem": "Item", "sourceApi": "API", "sourceTest": "Test", + "sourceVikunja": "Vikunja", "filterChannel": "Channel", "allChannels": "All channels", "filterAll": "All", @@ -453,6 +455,51 @@ "daysLeft": "remaining", "daysUnit": "d" }, + "integrations": { + "description": "Connect external services to eNotify. Vikunja is supported today: its task reminders and overdue events are pushed to you through your default channel.", + "vikunjaTitle": "Vikunja", + "createTitle": "Create a Vikunja integration", + "createDescription": "Creating one issues a webhook URL and secret for this account; paste them into a Vikunja webhook to start receiving task reminders.", + "create": "Create integration", + "createSuccess": "Integration created.", + "existsError": "This account already has a Vikunja integration.", + "notFound": "The integration no longer exists — it may have been deleted.", + "createdTitle": "Integration created", + "rotatedTitle": "Secret rotated", + "secretOnceWarning": "This is the only time the secret is shown. If you lose it you can only rotate a new one. Copy it into Vikunja now.", + "secretLabel": "Webhook secret", + "copy": "Copy", + "copied": "Copied", + "copyFailed": "Copy failed. Select the value and copy it manually.", + "saved": "I've saved it", + "webhookUrl": "Webhook URL", + "webhookUrlHint": "Paste this into the Target URL field of the Vikunja webhook.", + "enabledLabel": "Enable integration", + "enabledDescription": "While disabled, Vikunja deliveries are rejected (403); enabling restores them immediately.", + "enabledSuccess": "Integration enabled.", + "disabledSuccess": "Integration disabled.", + "baseUrl": "Vikunja URL", + "baseUrlPlaceholder": "https://vikunja.example.com", + "baseUrlHint": "Optional. When set, notifications link to the task (URL/tasks/{id}); leave it empty for no link.", + "baseUrlInvalid": "Enter a full URL starting with http:// or https://, or leave it empty.", + "baseUrlSuccess": "Vikunja URL saved.", + "createdAt": "Created", + "updatedAt": "Updated", + "rotate": "Rotate secret", + "rotateConfirm": "Rotating invalidates the old secret immediately — update it in Vikunja too, or deliveries will be rejected. Rotate now?", + "rotateSuccess": "Secret rotated.", + "delete": "Delete integration", + "deleteTitle": "Delete integration", + "deleteConfirm": "Deleting disables this webhook URL immediately, so Vikunja can no longer push to it. Delete?", + "deleteSuccess": "Integration deleted.", + "guideTitle": "Create the webhook in Vikunja", + "guideIntro": "Once the integration exists, set it up in Vikunja:", + "guideStep1": "Vikunja → Settings → Webhooks → New webhook.", + "guideStep2": "Paste the webhook URL into Target URL and the generated value into Secret.", + "guideStep3": "Select only the task.reminder.fired and tasks.overdue events.", + "guideStep4": "Do not also select task.overdue: it overlaps tasks.overdue, so the same overdue task arrives twice.", + "guideNote": "If the Webhooks page is missing in Vikunja, an administrator has to enable the webhooks feature on the Vikunja server first." + }, "backup": { "title": "Backup & restore", "userDescription": "Export your own eNotify data as a single JSON file, or restore / merge your own data from an export file.", diff --git a/web/src/locales/zh.json b/web/src/locales/zh.json index d518366..8c7c926 100644 --- a/web/src/locales/zh.json +++ b/web/src/locales/zh.json @@ -277,6 +277,7 @@ "apiKeysRevokeTitle": "吊销 API Key", "apiKeysRevokeConfirm": "确定吊销「{{name}}」?吊销后使用该 Key 的脚本将立即失效。", "apiKeysRevokeSuccess": "API Key 已吊销", + "integrations": "集成", "backup": "备份与恢复" }, "about": { @@ -304,6 +305,7 @@ "sourceItem": "事项", "sourceApi": "API", "sourceTest": "测试", + "sourceVikunja": "Vikunja", "filterChannel": "渠道", "allChannels": "全部渠道", "filterAll": "全部", @@ -453,6 +455,51 @@ "daysLeft": "剩余", "daysUnit": "天" }, + "integrations": { + "description": "把外部服务接到 eNotify。目前支持 Vikunja:它的任务提醒与逾期事件会经你的默认渠道推送给你。", + "vikunjaTitle": "Vikunja", + "createTitle": "创建 Vikunja 集成", + "createDescription": "创建后会生成本账号专属的 Webhook URL 与 Secret,填进 Vikunja 的 Webhook 表单即可开始接收任务提醒。", + "create": "创建集成", + "createSuccess": "集成已创建。", + "existsError": "本账号已创建过 Vikunja 集成,无需重复创建。", + "notFound": "集成不存在,可能已被删除。", + "createdTitle": "集成已创建", + "rotatedTitle": "Secret 已轮换", + "secretOnceWarning": "这是唯一一次显示 Secret 的机会,只显示这一次,丢了只能轮换。请立即复制并填进 Vikunja。", + "secretLabel": "Webhook Secret", + "copy": "复制", + "copied": "已复制", + "copyFailed": "复制失败,请手动选择并复制。", + "saved": "我已保存", + "webhookUrl": "Webhook URL", + "webhookUrlHint": "把这一串填进 Vikunja Webhook 的 Target URL。", + "enabledLabel": "启用集成", + "enabledDescription": "关闭后 Vikunja 的投递会被拒绝,重新启用立即恢复。", + "enabledSuccess": "集成已启用。", + "disabledSuccess": "集成已停用。", + "baseUrl": "Vikunja 地址", + "baseUrlPlaceholder": "https://vikunja.example.com", + "baseUrlHint": "可选。填写后推送里会带上任务链接(地址/tasks/任务 ID);留空则不带链接。", + "baseUrlInvalid": "请填写以 http:// 或 https:// 开头的完整地址,或留空。", + "baseUrlSuccess": "Vikunja 地址已保存。", + "createdAt": "创建时间", + "updatedAt": "最近更新", + "rotate": "轮换 Secret", + "rotateConfirm": "轮换后旧 Secret 立即失效,Vikunja 里也要同步改成新 Secret,否则投递会被拒绝。确定轮换?", + "rotateSuccess": "Secret 已轮换。", + "delete": "删除集成", + "deleteTitle": "删除集成", + "deleteConfirm": "删除后这个 Webhook URL 立即失效,Vikunja 将无法再推送。确定删除?", + "deleteSuccess": "集成已删除。", + "guideTitle": "在 Vikunja 里创建 Webhook", + "guideIntro": "创建集成后,按下面的步骤在 Vikunja 里配置:", + "guideStep1": "Vikunja → 设置 → Webhooks → 新建 Webhook。", + "guideStep2": "Target URL 粘贴上面的 Webhook URL,Secret 粘贴刚生成的 Secret。", + "guideStep3": "事件只勾选 task.reminder.fired 与 tasks.overdue。", + "guideStep4": "不要同时勾 task.overdue:它与 tasks.overdue 内容重叠,同一批逾期会收到两条提醒。", + "guideNote": "如果在 Vikunja 里看不到 Webhooks 页面,需要管理员先在 Vikunja 服务端开启 webhooks 功能。" + }, "backup": { "title": "备份与恢复", "userDescription": "导出你本人的 eNotify 数据为单个 JSON 文件,或从导出文件恢复 / 合并你自己的数据。", diff --git a/web/src/pages/history/HistoryPage.tsx b/web/src/pages/history/HistoryPage.tsx index 33f6935..e563726 100644 --- a/web/src/pages/history/HistoryPage.tsx +++ b/web/src/pages/history/HistoryPage.tsx @@ -25,6 +25,7 @@ const SOURCE_LABEL_KEYS: Record = { item: "history.sourceItem", api: "history.sourceApi", test: "history.sourceTest", + vikunja: "history.sourceVikunja", }; function SourceBadge({ source }: { source: string | null }) { diff --git a/web/src/pages/settings/SettingsPage.tsx b/web/src/pages/settings/SettingsPage.tsx index 2b2f0e1..28437d5 100644 --- a/web/src/pages/settings/SettingsPage.tsx +++ b/web/src/pages/settings/SettingsPage.tsx @@ -21,6 +21,8 @@ import { Check, AlertTriangle, DatabaseBackup, + Webhook, + Info, } from "lucide-react"; import QRCode from "qrcode"; import { api } from "@/lib/api"; @@ -31,6 +33,10 @@ import { useEmailConfigured } from "@/hooks/useEmailConfigured"; import { ConfirmDialog } from "@/components/ConfirmDialog"; import { PasswordPromptDialog } from "@/components/PasswordPromptDialog"; import { BackupSection } from "@/components/backup/BackupSection"; +import { Button } from "@/components/ui/button"; +import { Input } from "@/components/ui/input"; +import { Label } from "@/components/ui/label"; +import { Switch } from "@/components/ui/switch"; import { cn, serializeRegistrationCredential, @@ -46,6 +52,7 @@ type TabId = | "security" | "sessions" | "apiKeys" + | "integrations" | "backup" | "preferences"; @@ -1130,6 +1137,585 @@ function ApiKeysTab() { ); } +// --------------------------------------------------------------------------- +// Integrations Tab +// --------------------------------------------------------------------------- + +/** + * `GET /api/me/integrations/vikunja`: `{configured: false}` until the account + * creates one. The secret never comes back here (`secret_configured` only) — + * it is returned exactly once, by create and by regenerate-secret. + */ +interface VikunjaIntegrationResponse { + configured: boolean; + hook_token?: string; + base_url?: string | null; + enabled?: boolean; + secret_configured?: boolean; + created_at?: string; + updated_at?: string; +} + +interface VikunjaIntegration { + hook_token: string; + base_url: string; + enabled: boolean; + created_at: string; + updated_at: string; +} + +const VIKUNJA_INTEGRATION_PATH = "/me/integrations/vikunja"; +/** Inbound route served by the worker: token locates the account, the secret + * signs each delivery (HMAC-SHA256), so no session/API key is involved. */ +const VIKUNJA_WEBHOOK_PATH = "/api/integrations/vikunja"; +/** The backend accepts an http(s) URL, or an empty string to clear it. */ +const HTTP_URL_PATTERN = /^https?:\/\/\S+$/i; + +function formatDateTime(value: string) { + return value ? new Date(value).toLocaleString() : "-"; +} + +function IntegrationsTab() { + const { t } = useTranslation(); + + const [integration, setIntegration] = useState( + null, + ); + const [loading, setLoading] = useState(true); + const [error, setError] = useState(""); + const [successMsg, setSuccessMsg] = useState(""); + + // The plaintext secret lives in the browser only between create/rotate and + // the moment the one-time panel is dismissed (same rule as a new API key). + const [revealed, setRevealed] = useState<{ + secret: string; + kind: "created" | "rotated"; + } | null>(null); + const [copied, setCopied] = useState<"secret" | "url" | null>(null); + + const [baseUrl, setBaseUrl] = useState(""); + const [baseUrlError, setBaseUrlError] = useState(""); + + const [creating, setCreating] = useState(false); + const [savingBaseUrl, setSavingBaseUrl] = useState(false); + const [toggling, setToggling] = useState(false); + const [rotating, setRotating] = useState(false); + const [deleting, setDeleting] = useState(false); + const [confirmRotate, setConfirmRotate] = useState(false); + const [confirmDelete, setConfirmDelete] = useState(false); + + const flashTimerRef = useRef(null); + const copyTimerRef = useRef(null); + // One timer per feedback channel: a second copy/flash inside the previous + // window must not be cleared early by the stale timer of the first one. + useEffect( + () => () => { + if (flashTimerRef.current) window.clearTimeout(flashTimerRef.current); + if (copyTimerRef.current) window.clearTimeout(copyTimerRef.current); + }, + [], + ); + + const flash = (message: string) => { + setSuccessMsg(message); + if (flashTimerRef.current) window.clearTimeout(flashTimerRef.current); + flashTimerRef.current = window.setTimeout(() => setSuccessMsg(""), 3000); + }; + + /** + * `syncInput` seeds the address field from the server. Refreshes that follow + * a toggle / rotate leave it alone, so an in-progress edit is never discarded + * by an unrelated round-trip. + */ + const fetchIntegration = useCallback( + async ({ syncInput = false }: { syncInput?: boolean } = {}) => { + try { + const data = await api.get( + VIKUNJA_INTEGRATION_PATH, + ); + if (data.configured) { + const next: VikunjaIntegration = { + hook_token: data.hook_token ?? "", + base_url: data.base_url ?? "", + enabled: !!data.enabled, + created_at: data.created_at ?? "", + updated_at: data.updated_at ?? "", + }; + setIntegration(next); + if (syncInput) setBaseUrl(next.base_url); + } else { + setIntegration(null); + setBaseUrl(""); + } + } catch (err: any) { + setError(err.message || t("common.error")); + } finally { + setLoading(false); + } + }, + [t], + ); + + useEffect(() => { + fetchIntegration({ syncInput: true }); + }, [fetchIntegration]); + + const copyValue = async (kind: "secret" | "url", value: string) => { + try { + await navigator.clipboard.writeText(value); + setCopied(kind); + if (copyTimerRef.current) window.clearTimeout(copyTimerRef.current); + copyTimerRef.current = window.setTimeout(() => setCopied(null), 2000); + } catch { + setError(t("integrations.copyFailed")); + } + }; + + const handleCreate = async () => { + setError(""); + setSuccessMsg(""); + setCopied(null); + setCreating(true); + try { + const created = await api.post<{ secret: string }>( + VIKUNJA_INTEGRATION_PATH, + {}, + ); + setRevealed({ secret: created.secret, kind: "created" }); + flash(t("integrations.createSuccess")); + await fetchIntegration({ syncInput: true }); + } catch (err: any) { + if (err?.status === 409) { + setError(t("integrations.existsError")); + // 409 means the server already has one (e.g. the first GET failed), so + // this refresh must also seed the address field — otherwise the input + // shows empty and the next save would wipe the stored base_url. + await fetchIntegration({ syncInput: true }); + } else { + setError(err.message || t("common.error")); + } + } finally { + setCreating(false); + } + }; + + const handleToggle = async (enabled: boolean) => { + if (!integration) return; + setError(""); + setSuccessMsg(""); + setToggling(true); + // Optimistic, reverted below if the request fails. + setIntegration((prev) => (prev ? { ...prev, enabled } : prev)); + try { + // Only `enabled` goes out: the address is saved by its own form, so a + // toggle must neither persist an unsaved edit nor fail on its validation. + await api.put(VIKUNJA_INTEGRATION_PATH, { enabled }); + flash( + enabled + ? t("integrations.enabledSuccess") + : t("integrations.disabledSuccess"), + ); + await fetchIntegration(); + } catch (err: any) { + setIntegration((prev) => (prev ? { ...prev, enabled: !enabled } : prev)); + setError(err.message || t("common.error")); + } finally { + setToggling(false); + } + }; + + const handleSaveBaseUrl = async ( + e: React.SyntheticEvent, + ) => { + e.preventDefault(); + if (!integration) return; + const trimmed = baseUrl.trim().replace(/\/+$/, ""); + if (trimmed && !HTTP_URL_PATTERN.test(trimmed)) { + setBaseUrlError(t("integrations.baseUrlInvalid")); + return; + } + setBaseUrlError(""); + setError(""); + setSuccessMsg(""); + setSavingBaseUrl(true); + try { + await api.put(VIKUNJA_INTEGRATION_PATH, { base_url: trimmed }); + flash(t("integrations.baseUrlSuccess")); + // Reflect what was persisted (normalized, no trailing slash). + setBaseUrl(trimmed); + await fetchIntegration(); + } catch (err: any) { + setBaseUrlError(""); + setError(err.message || t("common.error")); + } finally { + setSavingBaseUrl(false); + } + }; + + const handleRotate = async () => { + setConfirmRotate(false); + setError(""); + setSuccessMsg(""); + setCopied(null); + setRotating(true); + try { + const data = await api.post<{ secret: string }>( + `${VIKUNJA_INTEGRATION_PATH}/regenerate-secret`, + ); + setRevealed({ secret: data.secret, kind: "rotated" }); + flash(t("integrations.rotateSuccess")); + await fetchIntegration(); + } catch (err: any) { + if (err?.status === 404) { + setError(t("integrations.notFound")); + await fetchIntegration(); + } else { + setError(err.message || t("common.error")); + } + } finally { + setRotating(false); + } + }; + + const handleDelete = async () => { + setConfirmDelete(false); + setError(""); + setSuccessMsg(""); + setCopied(null); + setDeleting(true); + try { + await api.delete(VIKUNJA_INTEGRATION_PATH); + setIntegration(null); + setRevealed(null); + setBaseUrl(""); + setBaseUrlError(""); + flash(t("integrations.deleteSuccess")); + } catch (err: any) { + if (err?.status === 404) { + setIntegration(null); + setRevealed(null); + setBaseUrl(""); + flash(t("integrations.deleteSuccess")); + } else { + setError(err.message || t("common.error")); + } + } finally { + setDeleting(false); + } + }; + + if (loading) { + return ( +
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+ ); + } + + const webhookUrl = integration + ? `${window.location.origin}${VIKUNJA_WEBHOOK_PATH}/${integration.hook_token}` + : ""; + + return ( +
+ void handleRotate()} + onCancel={() => setConfirmRotate(false)} + /> + void handleDelete()} + onCancel={() => setConfirmDelete(false)} + /> + +

+ {t("integrations.description")} +

+ + {error && ( +

+ {error} +

+ )} + {successMsg && ( +

+ {successMsg} +

+ )} + + {/* Secret revealed once, on create and on rotate */} + {revealed && ( +
+
+ +
+

+ {revealed.kind === "created" + ? t("integrations.createdTitle") + : t("integrations.rotatedTitle")} +

+

+ {t("integrations.secretOnceWarning")} +

+
+
+
+

+ {t("integrations.secretLabel")} +

+
+ + {revealed.secret} + + +
+
+
+ +
+
+ )} + + {!integration ? ( +
+
+ +

+ {t("integrations.createTitle")} +

+
+

+ {t("integrations.createDescription")} +

+ +
+ ) : ( +
+
+
+ +

+ {t("integrations.vikunjaTitle")} +

+
+ +
+ + {/* Enable / disable */} +
+
+ +

+ {t("integrations.enabledDescription")} +

+
+ void handleToggle(checked)} + /> +
+ + {/* Webhook URL */} +
+

+ {t("integrations.webhookUrl")} +

+
+ + {webhookUrl} + + +
+

+ {t("integrations.webhookUrlHint")} +

+
+ + {/* Vikunja base URL, used for task links */} +
+ +
+ { + setBaseUrl(e.target.value); + setBaseUrlError(""); + }} + placeholder={t("integrations.baseUrlPlaceholder")} + aria-invalid={!!baseUrlError} + aria-describedby={ + baseUrlError + ? "vikunja-base-url-error" + : "vikunja-base-url-hint" + } + className="flex-1" + /> + +
+ {baseUrlError ? ( +

+ {baseUrlError} +

+ ) : ( +

+ {t("integrations.baseUrlHint")} +

+ )} +
+ +
+

+ {t("integrations.createdAt")}:{" "} + {formatDateTime(integration.created_at)} +

+

+ {t("integrations.updatedAt")}:{" "} + {formatDateTime(integration.updated_at)} +

+
+ +
+ + +
+
+ )} + + {/* How to wire it up in Vikunja — only once there is something to paste */} + {integration && ( +
+

+ {t("integrations.guideTitle")} +

+

+ {t("integrations.guideIntro")} +

+
    +
  1. {t("integrations.guideStep1")}
  2. +
  3. {t("integrations.guideStep2")}
  4. +
  5. {t("integrations.guideStep3")}
  6. +
  7. {t("integrations.guideStep4")}
  8. +
+
+ +

{t("integrations.guideNote")}

+
+
+ )} +
+ ); +} + // --------------------------------------------------------------------------- // Preferences Tab // --------------------------------------------------------------------------- @@ -1362,6 +1948,7 @@ export function SettingsPage() { "account", "security", "apiKeys", + "integrations", "backup", "sessions", "preferences", @@ -1377,18 +1964,45 @@ export function SettingsPage() { // Sliding underline for the desktop tab bar (contract §5: 200ms, // transform/width-only). Position is measured from the active button so - // label-length / language changes re-center correctly. + // label-length / language changes re-center correctly, and the vertical + // offset follows the button's row when the bar wraps. const tabBarRef = useRef(null); const tabRefs = useRef>>({}); - const [underline, setUnderline] = useState({ left: 0, width: 0 }); - useLayoutEffect(() => { + const [underline, setUnderline] = useState({ left: 0, top: 0, width: 0 }); + const measureUnderline = useCallback(() => { const btn = tabRefs.current[activeTab]; const bar = tabBarRef.current; if (!btn || !bar) return; const b = btn.getBoundingClientRect(); const r = bar.getBoundingClientRect(); - setUnderline({ left: b.left - r.left + bar.scrollLeft, width: b.width }); + const next = { + left: b.left - r.left, + top: b.bottom - r.top - 2, + width: b.width, + }; + // Keep the previous object when nothing moved: the observer below can fire + // more than once for a single layout change. + setUnderline((prev) => + prev.left === next.left && + prev.top === next.top && + prev.width === next.width + ? prev + : next, + ); }, [activeTab]); + useLayoutEffect(() => { + measureUnderline(); + // Re-measure whenever the strip or any tab changes size: switching the app + // language re-labels every tab (new widths, and the wrapped bar can change + // row count, so the line would otherwise stay under the wrong row), and a + // window resize can move the active tab to another row as well. + const observer = new ResizeObserver(measureUnderline); + if (tabBarRef.current) observer.observe(tabBarRef.current); + for (const el of Object.values(tabRefs.current)) { + if (el) observer.observe(el); + } + return () => observer.disconnect(); + }, [measureUnderline]); const tabs: { id: TabId; label: string; icon: React.ReactNode }[] = [ { @@ -1406,6 +2020,11 @@ export function SettingsPage() { label: t("settings.apiKeys"), icon: , }, + { + id: "integrations", + label: t("settings.integrations"), + icon: , + }, { id: "backup", label: t("settings.backup"), @@ -1427,6 +2046,11 @@ export function SettingsPage() { { id: "account" as TabId, label: t("settings.account"), icon: User }, { id: "security" as TabId, label: t("settings.security"), icon: Shield }, { id: "apiKeys" as TabId, label: t("settings.apiKeys"), icon: KeyRound }, + { + id: "integrations" as TabId, + label: t("settings.integrations"), + icon: Webhook, + }, { id: "backup" as TabId, label: t("settings.backup"), @@ -1476,10 +2100,12 @@ export function SettingsPage() { )} {/* Tab bar - desktop only: shared underline slides to the active tab - (contract §5: 200ms ease-out, transform/width-only) */} + (contract §5: 200ms ease-out, transform/width-only). Seven tabs do + not fit on one line in every language, so the bar wraps instead of + scrolling off-screen behind an invisible scrollbar. */}
{tabs.map((tab) => (
@@ -1514,6 +2140,7 @@ export function SettingsPage() { {activeTab === "account" && } {activeTab === "security" && } {activeTab === "apiKeys" && } + {activeTab === "integrations" && } {activeTab === "backup" && } {activeTab === "sessions" && } {activeTab === "preferences" && }