diff --git a/frontend/src/Nav.tsx b/frontend/src/Nav.tsx index 8e595d7..32579dc 100644 --- a/frontend/src/Nav.tsx +++ b/frontend/src/Nav.tsx @@ -4,13 +4,14 @@ import { Bell, ChartColumn, House, Info, LogOut, MessageSquare, Search, Settings import { api } from "./api"; import { useAuthChanged, useMe } from "./auth"; import { useUnread } from "./chats"; +import { useUnreadNotifications } from "./notifications"; import { lockKeyring } from "./keyring"; type Target = { title: string; icon?: ReactNode; to: string; end?: boolean; badge?: number }; // Bereiche, die es noch nicht gibt: Route und Platzhalter-Seite bestehen, // in der Navigation sind sie bis dahin ausgeblendet. -const unfinished = new Set(["/notifications"]); +const unfinished = new Set(); export const isReady = (to: string) => !unfinished.has(to); @@ -21,10 +22,11 @@ function useMainTargets(): Target[] { const me = useMe().data; const profile = me ? `/u/${encodeURIComponent(me.handle)}` : "/me"; const unread = useUnread(); + const unseen = useUnreadNotifications(); const targets: Target[] = [ { title: "Feed", icon: , to: "/", end: true }, { title: "Suche", icon: , to: "/search" }, - { title: "Benachrichtigungen", icon: , to: "/notifications" }, + { title: "Benachrichtigungen", icon: , to: "/notifications", badge: unseen }, { title: "Chats", icon: , to: "/chats", badge: unread }, { title: "Profil", icon: , to: profile }, ]; diff --git a/frontend/src/docs/info.html b/frontend/src/docs/info.html index 9685bcf..127a130 100644 --- a/frontend/src/docs/info.html +++ b/frontend/src/docs/info.html @@ -21,6 +21,7 @@
  • Helles Design: Hintergrund in warmem Off-White statt reinem Weiß, angenehmer zu lesen
  • Beiträge und Chats: Anzeigename und @handle stehen zweizeilig neben dem Profilbild
  • Beiträge und Chats: Das Datum steht jetzt rechts in der Kopfzeile
  • +
  • Neu: Benachrichtigungen. Antwortet jemand auf deinen Beitrag, zählt die Glocke in der Navigation mit; ein Klick auf die Meldung führt zur Antwort
  • 07.11.2026

      diff --git a/frontend/src/main.tsx b/frontend/src/main.tsx index a663815..55f48d4 100644 --- a/frontend/src/main.tsx +++ b/frontend/src/main.tsx @@ -9,7 +9,8 @@ import { EntryPage } from "./pages/EntryPage"; import { UserPage } from "./pages/UserPage"; import { StatsPage } from "./pages/StatsPage"; import { ResetPage } from "./pages/ResetPage"; -import { MePage, Placeholder } from "./pages/Placeholder"; +import { MePage } from "./pages/Placeholder"; +import { NotificationsPage } from "./pages/NotificationsPage"; import { DocPage } from "./pages/DocPage"; import { SettingsPage } from "./pages/SettingsPage"; import { KeysPage } from "./pages/KeysPage"; @@ -46,7 +47,7 @@ const router = createBrowserRouter([ { path: "/reset", element: }, { path: "/me", element: }, { path: "/search", element: }, - { path: "/notifications", element: }, + { path: "/notifications", element: }, { path: "/chats", element: }, { path: "/chats/:handle", element: }, { path: "/settings", element: }, diff --git a/frontend/src/notifications.ts b/frontend/src/notifications.ts new file mode 100644 index 0000000..e5e77e7 --- /dev/null +++ b/frontend/src/notifications.ts @@ -0,0 +1,48 @@ +import { useQuery, useQueryClient } from "@tanstack/react-query"; +import { api } from "./api"; +import { useMe } from "./auth"; + +// Benachrichtigungen (notes/api.md): der Zähler am Glocken-Icon fragt +// angemeldet alle 30 Sekunden nach; die Liste markiert beim Abruf alles als +// gesehen, danach steht der Zähler sofort auf 0. + +export type Notification = { + id: number; + kind: "reply"; + message: string; + // Interner Pfad, etwa /e/123. + link: string; + created_at: number; + // Stand vor dem Abruf: false = neu. + seen: boolean; +}; + +const pollUnread = 30_000; + +export function useUnreadNotifications() { + const me = useMe().data; + return ( + useQuery({ + queryKey: ["notifications", "unread"], + queryFn: async () => (await api.get<{ unread: number }>("/notifications/unread")).unread, + enabled: !!me, + refetchInterval: pollUnread, + }).data ?? 0 + ); +} + +export function useNotifications() { + const me = useMe().data; + const qc = useQueryClient(); + return useQuery({ + queryKey: ["notifications", "list"], + queryFn: async () => { + const list = (await api.get<{ notifications: Notification[] }>("/notifications")).notifications; + qc.setQueryData(["notifications", "unread"], 0); + return list; + }, + enabled: !!me, + // Jeder Besuch der Seite gilt als Ansehen. + staleTime: 0, + }); +} diff --git a/frontend/src/pages/NotificationsPage.tsx b/frontend/src/pages/NotificationsPage.tsx new file mode 100644 index 0000000..7355456 --- /dev/null +++ b/frontend/src/pages/NotificationsPage.tsx @@ -0,0 +1,38 @@ +import { Link } from "react-router"; +import { errMsg } from "../api"; +import { useMe } from "../auth"; +import { AuthBox } from "../components/AuthBox"; +import { formatTime } from "../format"; +import { useNotifications } from "../notifications"; + +// NotificationsPage listet die jüngsten Benachrichtigungen; ein Klick führt +// zum Beitrag. Was beim Öffnen noch ungesehen war, steht fett. +export function NotificationsPage() { + const me = useMe(); + return ( + <> +
      +

      Benachrichtigungen

      + {me.data && } +
      + {me.isSuccess && !me.data && } + + ); +} + +function NotificationList() { + const list = useNotifications(); + if (list.isError) return

      {errMsg(list.error, "Benachrichtigungen konnten nicht geladen werden.")}

      ; + if (list.data?.length === 0) return

      Noch keine Benachrichtigungen.

      ; + return ( +
        + {list.data?.map((n) => ( +
      • + {n.seen ? n.message : {n.message}} +
        + {formatTime(n.created_at)} +
      • + ))} +
      + ); +} diff --git a/frontend/src/pages/Placeholder.tsx b/frontend/src/pages/Placeholder.tsx index a11aec0..bbc6ea6 100644 --- a/frontend/src/pages/Placeholder.tsx +++ b/frontend/src/pages/Placeholder.tsx @@ -2,8 +2,8 @@ import { Navigate } from "react-router"; import { useMe } from "../auth"; import { AuthBox } from "../components/AuthBox"; -// Placeholder steht für Bereiche, die noch eigene Projekte sind -// (Benachrichtigungen). +// Placeholder steht für Bereiche, die noch eigene Projekte sind (siehe +// unfinished in Nav.tsx). export function Placeholder({ title }: { title: string }) { return (
      diff --git a/internal/database/schema.sql b/internal/database/schema.sql index 3b5dfe0..17b60d4 100644 --- a/internal/database/schema.sql +++ b/internal/database/schema.sql @@ -161,6 +161,24 @@ CREATE INDEX IF NOT EXISTS idx_message_pair ON message(sender, recipient, id); CREATE INDEX IF NOT EXISTS idx_message_recipient ON message(recipient, id); CREATE INDEX IF NOT EXISTS idx_message_created ON message(created_at); +-- Benachrichtigungen an uid, etwa "Jemand hat auf deinen Beitrag geantwortet". +-- kind: reply; message ist fertiger Text, link ein interner Pfad (/e/). +-- pid ist der auslösende Beitrag: wird er gelöscht oder bearbeitet, zieht die +-- Benachrichtigung mit (internal/httpapi/notifications.go). seen_at = 0: +-- ungesehen. +CREATE TABLE IF NOT EXISTS notification ( + id BIGINT GENERATED ALWAYS AS IDENTITY PRIMARY KEY, + uid BIGINT NOT NULL, + kind TEXT NOT NULL, + message TEXT NOT NULL, + link TEXT NOT NULL, + pid BIGINT NOT NULL DEFAULT 0, + created_at BIGINT NOT NULL, + seen_at BIGINT NOT NULL DEFAULT 0 +); +CREATE INDEX IF NOT EXISTS idx_notification_uid ON notification(uid, id); +CREATE INDEX IF NOT EXISTS idx_notification_pid ON notification(pid); + -- Indizes für die häufigen Zugriffspfade; ohne sie werden Feed (ORDER BY -- last_activity), Thread (WHERE reply_to) und Vote-Zähler (WHERE pid) mit -- wachsender Tabelle zu Full-Table-Scans. handle/session.value/vote(uid,pid) diff --git a/internal/httpapi/entry_write.go b/internal/httpapi/entry_write.go index 5cb6541..ea97d09 100644 --- a/internal/httpapi/entry_write.go +++ b/internal/httpapi/entry_write.go @@ -91,7 +91,8 @@ func (s *Server) readNewEntry(r *http.Request) (newEntry, error) { } // insertEntry speichert den Beitrag und liefert seine pid. Eine Antwort hebt -// reply_count und last_activity aller Vorfahren mit an. +// reply_count und last_activity aller Vorfahren mit an und benachrichtigt den +// Autor des Elternbeitrags. func (s *Server) insertEntry(ctx context.Context, in newEntry) (int64, error) { var pid int64 err := database.InTx(ctx, s.DB, func(tx *sql.Tx) error { @@ -102,7 +103,10 @@ func (s *Server) insertEntry(ctx context.Context, in newEntry) (int64, error) { if in.replyTo == 0 { return nil } - return bumpAncestors(ctx, tx, in.replyTo, in.created) + if err := bumpAncestors(ctx, tx, in.replyTo, in.created); err != nil { + return err + } + return notifyReply(ctx, tx, in, pid) }) return pid, err } @@ -162,8 +166,17 @@ func (s *Server) handleEditEntry(w http.ResponseWriter, r *http.Request) error { return apperr.Invalid("entry.empty", "Inhalt darf nicht leer sein.").At("content") } linkURL := linkpreview.Key(content) - if _, err := s.DB.ExecContext(r.Context(), - `UPDATE entry SET content = $1, link_url = $2 WHERE pid = $3`, content, linkURL, e.PID); err != nil { + // Die Benachrichtigung über die Antwort zitiert sie: der Auszug soll keinen + // Text zeigen, den der Autor inzwischen geändert hat. + if err := database.InTx(r.Context(), s.DB, func(tx *sql.Tx) error { + if _, err := tx.ExecContext(r.Context(), + `UPDATE entry SET content = $1, link_url = $2 WHERE pid = $3`, content, linkURL, e.PID); err != nil { + return err + } + _, err := tx.ExecContext(r.Context(), + `UPDATE notification SET message = $1 WHERE pid = $2 AND kind = 'reply'`, replyMessage(content), e.PID) + return err + }); err != nil { return apperr.Internal(err) } s.Previews.Request(r.Context(), linkURL) @@ -197,9 +210,16 @@ func (s *Server) handleDeleteEntry(w http.ResponseWriter, r *http.Request) error if err != nil { return err } - if _, err := s.DB.ExecContext(r.Context(), - `UPDATE entry SET deleted = 1, content = '', filepath = '', link_url = '', uid = 0 WHERE pid = $1`, - e.PID); err != nil { + // Mit dem Beitrag verschwindet auch die Benachrichtigung, die ihn zitiert. + if err := database.InTx(r.Context(), s.DB, func(tx *sql.Tx) error { + if _, err := tx.ExecContext(r.Context(), + `UPDATE entry SET deleted = 1, content = '', filepath = '', link_url = '', uid = 0 WHERE pid = $1`, + e.PID); err != nil { + return err + } + _, err := tx.ExecContext(r.Context(), `DELETE FROM notification WHERE pid = $1`, e.PID) + return err + }); err != nil { return apperr.Internal(err) } s.removeMedia(e.Filepath) diff --git a/internal/httpapi/notifications.go b/internal/httpapi/notifications.go new file mode 100644 index 0000000..a902a6a --- /dev/null +++ b/internal/httpapi/notifications.go @@ -0,0 +1,106 @@ +package httpapi + +import ( + "context" + "database/sql" + "fmt" + "net/http" + "strings" + + "kver/internal/apperr" + "kver/internal/runes" +) + +const ( + // maxNotifications begrenzt die Liste auf die jüngsten Einträge. + maxNotifications = 50 + // snippetRunes: so viel vom Beitrag steht in der Benachrichtigung. + snippetRunes = 50 +) + +// notificationJSON ist eine Benachrichtigung in der Liste. Seen meldet den +// Stand vor dem Abruf: so sieht die Liste, was neu war, obwohl der Abruf +// selbst alles als gesehen markiert. +type notificationJSON struct { + ID int64 `json:"id"` + Kind string `json:"kind"` + Message string `json:"message"` + Link string `json:"link"` + CreatedAt int64 `json:"created_at"` + Seen bool `json:"seen"` +} + +// replyMessage ist der Text der Benachrichtigung über eine Antwort, mit den +// ersten Zeichen der Antwort (Leerraum zusammengefasst). +func replyMessage(content string) string { + const msg = "Jemand hat auf deinen Beitrag geantwortet." + snippet := strings.Join(strings.Fields(content), " ") + if snippet == "" { + return msg + } + if short := runes.Truncate(snippet, snippetRunes); short != snippet { + snippet = strings.TrimSpace(short) + "…" + } + return msg + " (" + snippet + ")" +} + +// notifyReply benachrichtigt den Autor des Elternbeitrags über die Antwort +// pid, nicht aber bei Antworten auf sich selbst oder auf gelöschte Beiträge +// (uid 0). Läuft in der Transaktion, die die Antwort anlegt. +func notifyReply(ctx context.Context, tx *sql.Tx, in newEntry, pid int64) error { + if _, err := tx.ExecContext(ctx, + `INSERT INTO notification (uid, kind, message, link, pid, created_at) + SELECT uid, 'reply', $1, $2, $3, $4 FROM entry + WHERE pid = $5 AND uid <> 0 AND uid <> $6`, + replyMessage(in.content), fmt.Sprintf("/e/%d", pid), pid, in.created, in.replyTo, in.uid); err != nil { + return fmt.Errorf("benachrichtigung anlegen: %w", err) + } + return nil +} + +// handleNotifications liefert die jüngsten Benachrichtigungen, neueste +// zuerst, und markiert die gelieferten als gesehen. +func (s *Server) handleNotifications(w http.ResponseWriter, r *http.Request) error { + ctx, uid := r.Context(), currentUID(r) + rows, err := s.DB.QueryContext(ctx, + `SELECT id, kind, message, link, created_at, seen_at > 0 FROM notification + WHERE uid = $1 ORDER BY id DESC LIMIT $2`, uid, maxNotifications) + if err != nil { + return apperr.Internal(err) + } + defer rows.Close() + list := []notificationJSON{} + for rows.Next() { + var n notificationJSON + if err := rows.Scan(&n.ID, &n.Kind, &n.Message, &n.Link, &n.CreatedAt, &n.Seen); err != nil { + return apperr.Internal(err) + } + list = append(list, n) + } + if err := rows.Err(); err != nil { + return apperr.Internal(err) + } + // Nur bis zur jüngsten gelieferten: was während des Abrufs neu kam, hat + // noch niemand gesehen. + if len(list) > 0 { + if _, err := s.DB.ExecContext(ctx, + `UPDATE notification SET seen_at = $1 WHERE uid = $2 AND seen_at = 0 AND id <= $3`, + s.Now().Unix(), uid, list[0].ID); err != nil { + return apperr.Internal(err) + } + } + writeJSON(w, http.StatusOK, map[string]any{"notifications": list}) + return nil +} + +// handleNotificationsUnread zählt die ungesehenen Benachrichtigungen (für den +// Zähler am Icon). +func (s *Server) handleNotificationsUnread(w http.ResponseWriter, r *http.Request) error { + var n int64 + if err := s.DB.QueryRowContext(r.Context(), + `SELECT COUNT(*) FROM notification WHERE uid = $1 AND seen_at = 0`, currentUID(r)).Scan(&n); err != nil { + return apperr.Internal(err) + } + writeJSON(w, http.StatusOK, map[string]int64{"unread": n}) + return nil +} diff --git a/internal/httpapi/notifications_test.go b/internal/httpapi/notifications_test.go new file mode 100644 index 0000000..c779c38 --- /dev/null +++ b/internal/httpapi/notifications_test.go @@ -0,0 +1,85 @@ +package httpapi + +import ( + "fmt" + "net/http" + "net/url" + "strings" + "testing" +) + +type notificationList struct { + Notifications []notificationJSON `json:"notifications"` +} + +func unreadNotifications(t *testing.T, c *http.Client, srv *testServer) int { + t.Helper() + var out struct { + Unread int `json:"unread"` + } + if code := getAs(t, c, srv.URL+"/api/notifications/unread", &out); code != http.StatusOK { + t.Fatalf("/notifications/unread: status %d", code) + } + return out.Unread +} + +func TestNotifyReply(t *testing.T) { + t.Parallel() + srv := newTestServer(t) + alice := registerAndLogin(t, srv, "alice") + bob := registerAndLogin(t, srv, "bob") + + root := createEntry(t, alice, srv, post("frage")) + createEntry(t, alice, srv, reply(root, "nachtrag")) // an sich selbst: nichts + long := strings.Repeat("wort ", 20) + answer := createEntry(t, bob, srv, reply(root, long)) + + if n := unreadNotifications(t, alice, srv); n != 1 { + t.Fatalf("alice ungesehen: %d, erwartet 1", n) + } + if n := unreadNotifications(t, bob, srv); n != 0 { + t.Errorf("bob ungesehen: %d, erwartet 0", n) + } + + var list notificationList + getAs(t, alice, srv.URL+"/api/notifications", &list) + if len(list.Notifications) != 1 { + t.Fatalf("liste: %+v", list) + } + n := list.Notifications[0] + wantMsg := "Jemand hat auf deinen Beitrag geantwortet. (" + strings.TrimSpace(long[:50]) + "…)" + if n.Kind != "reply" || n.Link != fmt.Sprintf("/e/%d", answer) || n.Seen || n.Message != wantMsg { + t.Errorf("benachrichtigung: %+v", n) + } + // Das Ansehen der Liste markiert alles als gesehen. + if c := unreadNotifications(t, alice, srv); c != 0 { + t.Errorf("nach dem Ansehen ungesehen: %d", c) + } + getAs(t, alice, srv.URL+"/api/notifications", &list) + if !list.Notifications[0].Seen { + t.Error("zweiter Abruf: nicht als gesehen markiert") + } + + // Bearbeiten zieht den Auszug nach, Löschen nimmt die Benachrichtigung mit. + editURL := fmt.Sprintf("%s/api/entry/%d/edit", srv.URL, answer) + resp := postForm(t, bob, editURL, url.Values{"content": {"neu"}}) + resp.Body.Close() + getAs(t, alice, srv.URL+"/api/notifications", &list) + if got := list.Notifications[0].Message; got != "Jemand hat auf deinen Beitrag geantwortet. (neu)" { + t.Errorf("nach dem Bearbeiten: %q", got) + } + resp = postForm(t, bob, fmt.Sprintf("%s/api/entry/%d/delete", srv.URL, answer), nil) + resp.Body.Close() + getAs(t, alice, srv.URL+"/api/notifications", &list) + if len(list.Notifications) != 0 { + t.Errorf("nach dem Löschen: %+v", list.Notifications) + } +} + +func TestNotificationsNeedLogin(t *testing.T) { + t.Parallel() + srv := newTestServer(t) + if code := getAny(t, srv.URL+"/api/notifications/unread", &struct{}{}); code != http.StatusUnauthorized { + t.Errorf("ohne Login: status %d, erwartet 401", code) + } +} diff --git a/internal/httpapi/server.go b/internal/httpapi/server.go index 0d33444..63da7fc 100644 --- a/internal/httpapi/server.go +++ b/internal/httpapi/server.go @@ -128,6 +128,8 @@ func (s *Server) apiRoutes(r chi.Router) { // Schlüssel (notes/schluessel.md); die Änderungen gedrosselt. r.Get("/user/keys/secret", s.api(s.handleKeySecrets)) // Direktnachrichten (notes/chats.md); Senden gedrosselt gegen Spam. + r.Get("/notifications", s.api(s.handleNotifications)) + r.Get("/notifications/unread", s.api(s.handleNotificationsUnread)) r.Get("/chats", s.api(s.handleChats)) r.Get("/chats/{handle}", s.api(s.handleChat)) r.With(s.limitByIP(60, time.Minute)).Post("/chats/{handle}", s.api(s.handleSendMessage)) diff --git a/internal/httpapi/users.go b/internal/httpapi/users.go index ef39943..0dd8939 100644 --- a/internal/httpapi/users.go +++ b/internal/httpapi/users.go @@ -277,6 +277,8 @@ func deleteAccount(ctx context.Context, tx *sql.Tx, uid int64) error { `DELETE FROM vote WHERE uid = $1`, `DELETE FROM account_key WHERE uid = $1`, `DELETE FROM message WHERE sender = $1 OR recipient = $1`, + // Vor dem UPDATE auf entry: danach stehen die Beiträge auf uid 0. + `DELETE FROM notification WHERE uid = $1 OR pid IN (SELECT pid FROM entry WHERE uid = $1)`, `UPDATE entry SET deleted = 1, content = '', filepath = '', link_url = '', uid = 0 WHERE uid = $1`, `DELETE FROM account WHERE uid = $1`, } { diff --git a/notes/api.md b/notes/api.md index e9820e4..2aa5d06 100644 --- a/notes/api.md +++ b/notes/api.md @@ -204,6 +204,19 @@ sie stündlich. Senden ist gedrosselt (60/min pro IP). --- +## Benachrichtigungen + +Bisher nur `kind: "reply"`: jemand hat auf einen eigenen Beitrag geantwortet +(nicht bei Antworten an sich selbst). `message` ist fertiger Text mit den +ersten 50 Zeichen der Antwort, `link` der interne Pfad zur Antwort. Wird die +Antwort bearbeitet, zieht der Auszug nach; wird sie gelöscht, verschwindet +die Benachrichtigung. + +| Methode | Pfad | Auth | Request | Erfolg | +|---|---|---|---|---| +| GET | `/api/notifications` | ✓ | – | `200 {"notifications":[{"id","kind","message","link","created_at","seen"}]}`, die 50 jüngsten, neueste zuerst; `seen` ist der Stand vor dem Abruf, der Abruf markiert alle gelieferten als gesehen | +| GET | `/api/notifications/unread` | ✓ | – | `200 {"unread"}`: Zahl der ungesehenen | + ## Statistik | Methode | Pfad | Erfolg |