feat(notifications): durable per-user inbox (P1) + maintenance schema

Add a server-backed notification center that coexists with the client-side
transient bell: a per-user `notifications` table (type/title/body/data JSON/
read/dismissed), a `/api/me/notifications` CRUD API (list, unread_count, read,
read_all, dismiss, clear), and a left-nav inbox module with a live unread badge
polled via useLiveQuery. Known types render trilingual text from type+data
(English stored text is the fallback); read rows are trimmed past a soft cap.

Also adds the schema the maintenance job builds on: videos.list?part=status
columns (embeddable/privacy_status/upload_status) and the validation lifecycle
columns (last_checked_at, unavailable_since, unavailable_reason).

Page-id validation is centralized in one PAGES source of truth (isPage) so the
new page survives reload without a second allowlist to keep in sync.
This commit is contained in:
npeter83 2026-06-18 03:20:17 +02:00
parent 74d46f61eb
commit 3ae42409b3
14 changed files with 649 additions and 22 deletions

View file

@ -10,7 +10,7 @@ import {
saveLocalTheme,
type ThemePrefs,
} from "./lib/theme";
import { hasFilterParams, paramsToFilters, readPage, stripUrlParams, type Page } from "./lib/urlState";
import { hasFilterParams, isPage, paramsToFilters, readPage, stripUrlParams, type Page } from "./lib/urlState";
import {
loadLayout,
normalizeLayout,
@ -29,6 +29,7 @@ import Playlists from "./components/Playlists";
import Stats from "./components/Stats";
import Scheduler from "./components/Scheduler";
import SettingsPanel from "./components/SettingsPanel";
import NotificationsPanel from "./components/NotificationsPanel";
import OnboardingWizard from "./components/OnboardingWizard";
import { shouldAutoOpenOnboarding } from "./lib/onboarding";
import Toaster from "./components/Toaster";
@ -60,15 +61,7 @@ function loadInitialPage(): Page {
const params = new URLSearchParams(window.location.search);
if (params.has("page")) return readPage();
const stored = localStorage.getItem(PAGE_KEY);
if (
stored === "channels" ||
stored === "stats" ||
stored === "playlists" ||
stored === "settings" ||
stored === "scheduler"
)
return stored;
return "feed";
return isPage(stored) ? stored : "feed";
}
function loadStoredFilters(): FeedFilters {
@ -311,6 +304,8 @@ export default function App() {
<Scheduler />
) : page === "playlists" ? (
<Playlists canWrite={meQuery.data!.can_write} />
) : page === "notifications" ? (
<NotificationsPanel />
) : page === "settings" ? (
<SettingsPanel
me={meQuery.data!}

View file

@ -5,6 +5,7 @@ import { useQuery } from "@tanstack/react-query";
import {
Activity,
BarChart3,
Bell,
ChevronLeft,
ChevronRight,
Home,
@ -17,6 +18,7 @@ import {
UserPlus,
} from "lucide-react";
import { api, type FeedFilters, type Me } from "../lib/api";
import { useLiveQuery } from "../lib/useLiveQuery";
import type { Page } from "../lib/urlState";
import { type LangCode } from "../i18n";
import AvatarImg from "./Avatar";
@ -116,12 +118,22 @@ export default function NavSidebar({
}
}
type NavItem = { page: Page; icon: typeof Home; label: string };
// Durable, server-backed unread count for the inbox badge. Polled live (pauses when the
// tab is hidden); coexists with the client-side transient bell at the bottom of the rail.
const unreadQuery = useLiveQuery(
["notif-unread"],
api.notificationUnreadCount,
{ intervalMs: 30000 }
);
const unread = unreadQuery.data?.count ?? 0;
type NavItem = { page: Page; icon: typeof Home; label: string; badge?: number };
// User-facing content modules vs. admin/system modules, separated by a divider in the rail.
const userItems: NavItem[] = [
{ page: "feed", icon: Home, label: t("header.account.feed") },
{ page: "channels", icon: Tv, label: t("header.account.channels") },
{ page: "playlists", icon: ListVideo, label: t("header.account.playlists") },
{ page: "notifications", icon: Bell, label: t("inbox.navLabel"), badge: unread },
];
const systemItems: NavItem[] =
me.role === "admin"
@ -135,18 +147,29 @@ export default function NavSidebar({
"w-full flex items-center gap-3 rounded-lg px-2.5 py-2 text-sm transition";
const name = me.display_name ?? me.email.split("@")[0];
const renderItem = ({ page: p, icon: Icon, label }: NavItem) => (
const renderItem = ({ page: p, icon: Icon, label, badge }: NavItem) => (
<button
key={p}
onClick={() => setPage(p)}
title={collapsed ? label : undefined}
aria-current={page === p ? "page" : undefined}
className={`${rowBase} ${collapsed ? "justify-center px-0" : ""} ${
className={`${rowBase} ${collapsed ? "justify-center px-0" : ""} relative ${
page === p ? "bg-accent text-accent-fg" : "text-muted hover:text-fg hover:bg-card"
}`}
>
<Icon className="w-[18px] h-[18px] shrink-0" />
<span className="relative shrink-0">
<Icon className="w-[18px] h-[18px]" />
{/* Collapsed rail: a small dot on the icon; expanded: a numeric pill at the row end. */}
{!!badge && badge > 0 && collapsed && (
<span className="absolute -top-1 -right-1 w-2 h-2 rounded-full bg-accent ring-2 ring-bg" />
)}
</span>
{!collapsed && <span className="truncate">{label}</span>}
{!!badge && badge > 0 && !collapsed && (
<span className="ml-auto min-w-[18px] h-[18px] px-1 rounded-full bg-accent text-accent-fg text-[11px] font-semibold inline-flex items-center justify-center tabular-nums">
{badge > 99 ? "99+" : badge}
</span>
)}
</button>
);

View file

@ -0,0 +1,176 @@
import { useTranslation } from "react-i18next";
import { useMutation, useQueryClient } from "@tanstack/react-query";
import { Bell, Check, CheckCheck, Trash2, X } from "lucide-react";
import { api, type AppNotification } from "../lib/api";
import { useLiveQuery } from "../lib/useLiveQuery";
// The durable, server-backed notification center (inbox phase 1). It COEXISTS with the
// client-side transient bell in the nav rail: the bell is a quick peek at recent toasts kept
// in localStorage, this is the full, filterable, clearable history synced from the server.
const POLL_MS = 8000;
function relativeTime(iso: string | null, t: (k: string, o?: any) => string): string {
if (!iso) return "";
const then = new Date(iso).getTime();
const secs = Math.max(0, Math.round((Date.now() - then) / 1000));
// Reuse the bell's relative-time strings (notifications.time.*) — same format, no dupes.
if (secs < 60) return t("notifications.time.justNow");
const mins = Math.round(secs / 60);
if (mins < 60) return t("notifications.time.minutes", { count: mins });
const hours = Math.round(mins / 60);
if (hours < 24) return t("notifications.time.hours", { count: hours });
const days = Math.round(hours / 24);
return t("notifications.time.days", { count: days });
}
export default function NotificationsPanel() {
const { t } = useTranslation();
const qc = useQueryClient();
const q = useLiveQuery<{ items: AppNotification[]; total: number }>(
["notifications"],
() => api.notifications(),
{ intervalMs: POLL_MS }
);
const items = q.data?.items ?? [];
// Any mutation refreshes both the list and the nav badge's unread count.
const refresh = () => {
qc.invalidateQueries({ queryKey: ["notifications"] });
qc.invalidateQueries({ queryKey: ["notif-unread"] });
};
const readMut = useMutation({ mutationFn: api.markNotificationRead, onSuccess: refresh });
const readAllMut = useMutation({ mutationFn: api.markAllNotificationsRead, onSuccess: refresh });
const dismissMut = useMutation({ mutationFn: api.dismissNotification, onSuccess: refresh });
const clearMut = useMutation({ mutationFn: api.clearNotifications, onSuccess: refresh });
const hasUnread = items.some((n) => !n.read);
return (
<div className="p-4 max-w-3xl w-full mx-auto space-y-4">
<div className="glass rounded-2xl p-4 flex items-center gap-3">
<Bell className="w-5 h-5 text-accent shrink-0" />
<div className="flex-1 min-w-0">
<div className="font-semibold">{t("inbox.title")}</div>
<div className="text-xs text-muted">{t("inbox.subtitle")}</div>
</div>
{items.length > 0 && (
<div className="flex items-center gap-2">
<button
onClick={() => readAllMut.mutate()}
disabled={!hasUnread || readAllMut.isPending}
className="inline-flex items-center gap-1.5 text-xs px-2.5 py-1.5 rounded-lg text-muted hover:text-fg hover:bg-card transition disabled:opacity-40"
>
<CheckCheck className="w-4 h-4" />
{t("inbox.markAllRead")}
</button>
<button
onClick={() => clearMut.mutate()}
disabled={clearMut.isPending}
className="inline-flex items-center gap-1.5 text-xs px-2.5 py-1.5 rounded-lg text-muted hover:text-fg hover:bg-card transition disabled:opacity-40"
>
<Trash2 className="w-4 h-4" />
{t("inbox.clearAll")}
</button>
</div>
)}
</div>
{q.isLoading && !q.data ? (
<div className="p-8 text-muted text-center">{t("common.loading")}</div>
) : items.length === 0 ? (
<div className="glass rounded-2xl p-10 text-center text-muted">
<Bell className="w-8 h-8 mx-auto mb-3 opacity-40" />
{t("inbox.empty")}
</div>
) : (
<div className="flex flex-col gap-2">
{items.map((n) => (
<NotificationRow
key={n.id}
n={n}
t={t}
onRead={() => readMut.mutate(n.id)}
onDismiss={() => dismissMut.mutate(n.id)}
/>
))}
</div>
)}
</div>
);
}
function NotificationRow({
n,
t,
onRead,
onDismiss,
}: {
n: AppNotification;
t: (k: string, o?: any) => string;
onRead: () => void;
onDismiss: () => void;
}) {
// The maintenance producer ships the affected videos in `data.videos`; list a few titles.
const videos: { id: string; title: string | null }[] = Array.isArray(n.data?.videos)
? n.data!.videos
: [];
// Known notification types are rendered from i18n (so they're trilingual) using the typed
// payload; the server-stored title/body are an English fallback for any unknown type.
const isMaintenance = n.type === "maintenance" && typeof n.data?.count === "number";
const title = isMaintenance ? t("inbox.maintenance.title") : n.title;
const body = isMaintenance
? t("inbox.maintenance.body", { count: n.data!.count })
: n.body;
return (
<div
className={`glass rounded-xl p-3.5 flex items-start gap-3 transition ${
n.read ? "opacity-70" : ""
}`}
>
{!n.read && <span className="mt-1.5 w-2 h-2 rounded-full bg-accent shrink-0" aria-hidden />}
<div className="flex-1 min-w-0">
<div className="flex items-baseline gap-2">
<span className="font-medium text-sm">{title}</span>
<span className="text-[11px] text-muted shrink-0">
{relativeTime(n.created_at, t)}
</span>
</div>
{body && <div className="text-sm text-muted mt-0.5">{body}</div>}
{videos.length > 0 && (
<ul className="mt-2 text-xs text-muted list-disc pl-4 space-y-0.5">
{videos.slice(0, 8).map((v) => (
<li key={v.id} className="truncate">
{v.title || v.id}
</li>
))}
{videos.length > 8 && (
<li className="list-none text-muted/70">
{t("inbox.andMore", { count: videos.length - 8 })}
</li>
)}
</ul>
)}
</div>
<div className="flex items-center gap-1 shrink-0">
{!n.read && (
<button
onClick={onRead}
title={t("inbox.markRead")}
aria-label={t("inbox.markRead")}
className="p-1.5 rounded-lg text-muted hover:text-fg hover:bg-card transition"
>
<Check className="w-4 h-4" />
</button>
)}
<button
onClick={onDismiss}
title={t("inbox.dismiss")}
aria-label={t("inbox.dismiss")}
className="p-1.5 rounded-lg text-muted hover:text-fg hover:bg-card transition"
>
<X className="w-4 h-4" />
</button>
</div>
</div>
);
}

View file

@ -0,0 +1,16 @@
{
"navLabel": "Benachrichtigungen",
"title": "Benachrichtigungen",
"subtitle": "Neuigkeiten aus deiner Bibliothek und vom System.",
"empty": "Alles erledigt.",
"markAllRead": "Alle als gelesen markieren",
"clearAll": "Alle löschen",
"markRead": "Als gelesen markieren",
"dismiss": "Verwerfen",
"andMore": "und {{count}} weitere",
"maintenance": {
"title": "Videos entfernt",
"body_one": "{{count}} gespeichertes oder in einer Playlist befindliches Video wurde entfernt, weil es auf YouTube nicht mehr verfügbar ist.",
"body_other": "{{count}} gespeicherte oder in Playlists befindliche Videos wurden entfernt, weil sie auf YouTube nicht mehr verfügbar sind."
}
}

View file

@ -0,0 +1,16 @@
{
"navLabel": "Notifications",
"title": "Notifications",
"subtitle": "Updates from your library and the system.",
"empty": "You're all caught up.",
"markAllRead": "Mark all read",
"clearAll": "Clear all",
"markRead": "Mark read",
"dismiss": "Dismiss",
"andMore": "and {{count}} more",
"maintenance": {
"title": "Videos removed",
"body_one": "{{count}} saved or playlisted video was removed because it's no longer available on YouTube.",
"body_other": "{{count}} saved or playlisted videos were removed because they're no longer available on YouTube."
}
}

View file

@ -0,0 +1,16 @@
{
"navLabel": "Értesítések",
"title": "Értesítések",
"subtitle": "Frissítések a könyvtáradból és a rendszertől.",
"empty": "Nincs új értesítés.",
"markAllRead": "Összes olvasott",
"clearAll": "Összes törlése",
"markRead": "Olvasottnak jelöl",
"dismiss": "Elvetés",
"andMore": "és még {{count}}",
"maintenance": {
"title": "Videók eltávolítva",
"body_one": "{{count}} mentett vagy lejátszási listás videó eltávolítva, mert már nem elérhető a YouTube-on.",
"body_other": "{{count}} mentett vagy lejátszási listás videó eltávolítva, mert már nem elérhetők a YouTube-on."
}
}

View file

@ -356,6 +356,19 @@ export interface Account {
active: boolean;
}
// A durable, server-backed notification (the inbox center). Distinct from the client-side
// transient toast/bell, which lives only in localStorage.
export interface AppNotification {
id: number;
type: string;
title: string;
body: string | null;
data: Record<string, any> | null;
read: boolean;
dismissed: boolean;
created_at: string | null;
}
export const api = {
me: (): Promise<Me> => req("/api/me"),
accounts: (): Promise<Account[]> => req("/api/me/accounts"),
@ -478,6 +491,19 @@ export const api = {
addInvite: (email: string) =>
req("/api/admin/invites", { method: "POST", body: JSON.stringify({ email }) }),
// --- notification inbox (durable, server-backed) ---
notifications: (includeDismissed = false): Promise<{ items: AppNotification[]; total: number }> =>
req(`/api/me/notifications?include_dismissed=${includeDismissed}`),
notificationUnreadCount: (): Promise<{ count: number }> =>
req("/api/me/notifications/unread_count"),
markNotificationRead: (id: number) =>
req(`/api/me/notifications/${id}/read`, { method: "POST" }),
markAllNotificationsRead: () =>
req("/api/me/notifications/read_all", { method: "POST" }),
dismissNotification: (id: number) =>
req(`/api/me/notifications/${id}/dismiss`, { method: "POST" }),
clearNotifications: () => req("/api/me/notifications/clear", { method: "POST" }),
// --- user tags ---
createTag: (t: { name: string; color?: string; category?: string }) =>
req("/api/tags", { method: "POST", body: JSON.stringify(t) }),

View file

@ -78,17 +78,29 @@ export function hasFilterParams(params: URLSearchParams): boolean {
return KEYS.some((k) => params.has(k));
}
export type Page = "feed" | "channels" | "stats" | "playlists" | "settings" | "scheduler";
// The single source of truth for valid page ids; `Page` and the runtime validator both
// derive from it, so adding a page is a one-line change (no parallel allowlists to keep in
// sync). "feed" is the default/fallback.
export const PAGES = [
"feed",
"channels",
"stats",
"playlists",
"settings",
"scheduler",
"notifications",
] as const;
export type Page = (typeof PAGES)[number];
/** Narrow an arbitrary string to a known Page (else null). */
export function isPage(p: string | null | undefined): p is Page {
return !!p && (PAGES as readonly string[]).includes(p);
}
export function readPage(): Page {
const p = new URLSearchParams(window.location.search).get("page");
return p === "channels" ||
p === "stats" ||
p === "playlists" ||
p === "settings" ||
p === "scheduler"
? p
: "feed";
return isPage(p) ? p : "feed";
}
/** Build a shareable absolute URL that reproduces the current filters (+ page). Used by the