Benachrichtigungen: Handle bei Antworten, neu auch Reposts
Bei Antworten steht statt "Jemand" der Handle. Damit er nach einer Umbenennung stimmt, speichert die Benachrichtigung nur die uid (actor) und den Auszug; den Text setzt der Abruf zusammen. Die Tabelle war noch nirgends ausgerollt, daher direkt in neuer Form statt per ALTER. Neu ist der Repost eines eigenen Beitrags (kind bump), in derselben Transaktion wie der Bump. Wer repostet, wird nicht gespeichert, die Meldung sagt daher "Jemand". Eigene Reposts lösen nichts aus. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
@@ -22,6 +22,7 @@
|
||||
<li>Beiträge und Chats: Anzeigename und @handle stehen zweizeilig neben dem Profilbild</li>
|
||||
<li>Beiträge und Chats: Das Datum steht jetzt rechts in der Kopfzeile</li>
|
||||
<li>Neu: Benachrichtigungen. Antwortet jemand auf deinen Beitrag, zählt die Glocke in der Navigation mit; ein Klick auf die Meldung führt zur Antwort</li>
|
||||
<li>Benachrichtigungen nennen jetzt den Handle der Antwortenden und melden auch, wenn jemand deinen Beitrag repostet</li>
|
||||
</ul>
|
||||
<h3>07.11.2026</h3>
|
||||
<ul>
|
||||
|
||||
@@ -8,7 +8,7 @@ import { useMe } from "./auth";
|
||||
|
||||
export type Notification = {
|
||||
id: number;
|
||||
kind: "reply";
|
||||
kind: "reply" | "bump";
|
||||
message: string;
|
||||
// Interner Pfad, etwa /e/123.
|
||||
link: string;
|
||||
|
||||
@@ -161,16 +161,20 @@ 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>).
|
||||
-- pid ist der auslösende Beitrag: wird er gelöscht oder bearbeitet, zieht die
|
||||
-- Benachrichtigungen an uid. kind: reply (Antwort auf einen eigenen Beitrag)
|
||||
-- oder bump (eigener Beitrag repostet). actor: wer geantwortet hat, 0 =
|
||||
-- unbekannt (Reposts werden niemandem zugeordnet). excerpt: Anfang des
|
||||
-- zitierten Beitrags; den Text setzt erst der Abruf zusammen, damit er den
|
||||
-- aktuellen Handle zeigt. link ist ein interner Pfad (/e/<pid>), pid der
|
||||
-- zitierte Beitrag: wird er bearbeitet oder gelöscht, 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,
|
||||
actor BIGINT NOT NULL DEFAULT 0,
|
||||
excerpt TEXT NOT NULL DEFAULT '',
|
||||
link TEXT NOT NULL,
|
||||
pid BIGINT NOT NULL DEFAULT 0,
|
||||
created_at BIGINT NOT NULL,
|
||||
|
||||
@@ -166,15 +166,15 @@ 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)
|
||||
// Die Benachrichtigung über die Antwort zitiert sie: der Auszug soll keinen
|
||||
// Text zeigen, den der Autor inzwischen geändert hat.
|
||||
// Benachrichtigungen zitieren den Beitrag: 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)
|
||||
`UPDATE notification SET excerpt = $1 WHERE pid = $2`, excerpt(content), e.PID)
|
||||
return err
|
||||
}); err != nil {
|
||||
return apperr.Internal(err)
|
||||
|
||||
@@ -14,8 +14,8 @@ import (
|
||||
const (
|
||||
// maxNotifications begrenzt die Liste auf die jüngsten Einträge.
|
||||
maxNotifications = 50
|
||||
// snippetRunes: so viel vom Beitrag steht in der Benachrichtigung.
|
||||
snippetRunes = 50
|
||||
// excerptRunes: so viel vom Beitrag steht in der Benachrichtigung.
|
||||
excerptRunes = 50
|
||||
)
|
||||
|
||||
// notificationJSON ist eine Benachrichtigung in der Liste. Seen meldet den
|
||||
@@ -30,29 +30,63 @@ type notificationJSON struct {
|
||||
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 == "" {
|
||||
// excerpt ist der Anfang eines Beitrags für die Benachrichtigung, Leerraum
|
||||
// zusammengefasst.
|
||||
func excerpt(content string) string {
|
||||
e := strings.Join(strings.Fields(content), " ")
|
||||
if short := runes.Truncate(e, excerptRunes); short != e {
|
||||
e = strings.TrimSpace(short) + "…"
|
||||
}
|
||||
return e
|
||||
}
|
||||
|
||||
// notificationMessage setzt den Text zusammen. actor ist der Handle dessen,
|
||||
// der geantwortet hat; leer (Reposts, unbekannt) heißt "Jemand".
|
||||
func notificationMessage(kind, actor, excerpt string) string {
|
||||
who := "Jemand"
|
||||
if actor != "" {
|
||||
who = "@" + actor
|
||||
}
|
||||
msg := who + " hat deinen Beitrag repostet."
|
||||
if kind == "reply" {
|
||||
msg = who + " hat auf deinen Beitrag geantwortet."
|
||||
}
|
||||
if excerpt != "" {
|
||||
msg += " (" + excerpt + ")"
|
||||
}
|
||||
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.
|
||||
// (uid 0). Zitiert wird die Antwort. Läuft in der Transaktion, die sie 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 {
|
||||
`INSERT INTO notification (uid, kind, actor, excerpt, link, pid, created_at)
|
||||
SELECT uid, 'reply', $1, $2, $3, $4, $5 FROM entry
|
||||
WHERE pid = $6 AND uid <> 0 AND uid <> $1`,
|
||||
in.uid, excerpt(in.content), fmt.Sprintf("/e/%d", pid), pid, in.created, in.replyTo); err != nil {
|
||||
return fmt.Errorf("benachrichtigung anlegen: %w", err)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// notifyBump benachrichtigt den Autor über einen Repost seines Beitrags pid,
|
||||
// außer er hat ihn selbst repostet. Wer repostet, wird nicht gespeichert.
|
||||
func notifyBump(ctx context.Context, tx *sql.Tx, pid, bumper, now int64) error {
|
||||
var author int64
|
||||
var content string
|
||||
if err := tx.QueryRowContext(ctx,
|
||||
`SELECT uid, content FROM entry WHERE pid = $1`, pid).Scan(&author, &content); err != nil {
|
||||
return fmt.Errorf("beitrag lesen: %w", err)
|
||||
}
|
||||
if author == 0 || author == bumper {
|
||||
return nil
|
||||
}
|
||||
if _, err := tx.ExecContext(ctx,
|
||||
`INSERT INTO notification (uid, kind, excerpt, link, pid, created_at)
|
||||
VALUES ($1, 'bump', $2, $3, $4, $5)`,
|
||||
author, excerpt(content), fmt.Sprintf("/e/%d", pid), pid, now); err != nil {
|
||||
return fmt.Errorf("benachrichtigung anlegen: %w", err)
|
||||
}
|
||||
return nil
|
||||
@@ -63,8 +97,9 @@ func notifyReply(ctx context.Context, tx *sql.Tx, in newEntry, pid int64) error
|
||||
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)
|
||||
`SELECT n.id, n.kind, COALESCE(a.handle, ''), n.excerpt, n.link, n.created_at, n.seen_at > 0
|
||||
FROM notification n LEFT JOIN account a ON a.uid = n.actor AND n.actor <> 0
|
||||
WHERE n.uid = $1 ORDER BY n.id DESC LIMIT $2`, uid, maxNotifications)
|
||||
if err != nil {
|
||||
return apperr.Internal(err)
|
||||
}
|
||||
@@ -72,9 +107,11 @@ func (s *Server) handleNotifications(w http.ResponseWriter, r *http.Request) err
|
||||
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 {
|
||||
var actor, excerpt string
|
||||
if err := rows.Scan(&n.ID, &n.Kind, &actor, &excerpt, &n.Link, &n.CreatedAt, &n.Seen); err != nil {
|
||||
return apperr.Internal(err)
|
||||
}
|
||||
n.Message = notificationMessage(n.Kind, actor, excerpt)
|
||||
list = append(list, n)
|
||||
}
|
||||
if err := rows.Err(); err != nil {
|
||||
|
||||
@@ -47,7 +47,7 @@ func TestNotifyReply(t *testing.T) {
|
||||
t.Fatalf("liste: %+v", list)
|
||||
}
|
||||
n := list.Notifications[0]
|
||||
wantMsg := "Jemand hat auf deinen Beitrag geantwortet. (" + strings.TrimSpace(long[:50]) + "…)"
|
||||
wantMsg := "@bob 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)
|
||||
}
|
||||
@@ -60,13 +60,16 @@ func TestNotifyReply(t *testing.T) {
|
||||
t.Error("zweiter Abruf: nicht als gesehen markiert")
|
||||
}
|
||||
|
||||
// Bearbeiten zieht den Auszug nach, Löschen nimmt die Benachrichtigung mit.
|
||||
// Bearbeiten zieht den Auszug nach, ein neuer Handle erscheint sofort,
|
||||
// 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()
|
||||
resp = postForm(t, bob, srv.URL+"/api/user/handle", url.Values{"handle": {"robert"}})
|
||||
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)
|
||||
if got := list.Notifications[0].Message; got != "@robert hat auf deinen Beitrag geantwortet. (neu)" {
|
||||
t.Errorf("nach Bearbeiten und Umbenennen: %q", got)
|
||||
}
|
||||
resp = postForm(t, bob, fmt.Sprintf("%s/api/entry/%d/delete", srv.URL, answer), nil)
|
||||
resp.Body.Close()
|
||||
@@ -76,6 +79,37 @@ func TestNotifyReply(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestNotifyBump(t *testing.T) {
|
||||
t.Parallel()
|
||||
srv := newTestServer(t)
|
||||
alice := registerAndLogin(t, srv, "alice")
|
||||
bob := registerAndLogin(t, srv, "bob")
|
||||
mine := createEntry(t, alice, srv, post("mein erster\nbeitrag"))
|
||||
own := createEntry(t, alice, srv, post("selbst repostet"))
|
||||
|
||||
for _, b := range []struct {
|
||||
c *http.Client
|
||||
pid int64
|
||||
}{{bob, mine}, {alice, own}} {
|
||||
resp := postForm(t, b.c, fmt.Sprintf("%s/api/entry/%d/bump", srv.URL, b.pid), nil)
|
||||
resp.Body.Close()
|
||||
if resp.StatusCode != http.StatusOK {
|
||||
t.Fatalf("bump %d: status %d", b.pid, resp.StatusCode)
|
||||
}
|
||||
}
|
||||
var list notificationList
|
||||
getAs(t, alice, srv.URL+"/api/notifications", &list)
|
||||
if len(list.Notifications) != 1 {
|
||||
t.Fatalf("liste: %+v", list.Notifications)
|
||||
}
|
||||
n := list.Notifications[0]
|
||||
// Wer repostet, wird nicht gespeichert: "Jemand", auch wenn es bob war.
|
||||
if n.Kind != "bump" || n.Link != fmt.Sprintf("/e/%d", mine) ||
|
||||
n.Message != "Jemand hat deinen Beitrag repostet. (mein erster beitrag)" {
|
||||
t.Errorf("benachrichtigung: %+v", n)
|
||||
}
|
||||
}
|
||||
|
||||
func TestNotificationsNeedLogin(t *testing.T) {
|
||||
t.Parallel()
|
||||
srv := newTestServer(t)
|
||||
|
||||
@@ -278,7 +278,7 @@ func deleteAccount(ctx context.Context, tx *sql.Tx, uid int64) error {
|
||||
`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)`,
|
||||
`DELETE FROM notification WHERE uid = $1 OR actor = $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`,
|
||||
} {
|
||||
|
||||
@@ -2,11 +2,13 @@ package httpapi
|
||||
|
||||
import (
|
||||
"context"
|
||||
"database/sql"
|
||||
"net/http"
|
||||
"strconv"
|
||||
"time"
|
||||
|
||||
"kver/internal/apperr"
|
||||
"kver/internal/database"
|
||||
)
|
||||
|
||||
// tally ist der Abstimmungsstand eines Beitrags; selected ist die eigene
|
||||
@@ -111,11 +113,21 @@ func (s *Server) handleBump(w http.ResponseWriter, r *http.Request) error {
|
||||
// Bedingung sitzt direkt im UPDATE (statt Read-then-Write), damit zwei
|
||||
// gleichzeitige Bumps den Cooldown nicht umgehen können.
|
||||
now := s.Now().Unix()
|
||||
res, err := s.DB.ExecContext(r.Context(),
|
||||
var bumped bool
|
||||
if err := database.InTx(r.Context(), s.DB, func(tx *sql.Tx) error {
|
||||
res, err := tx.ExecContext(r.Context(),
|
||||
`UPDATE entry SET last_activity = $1, bump_count = bump_count + 1, last_bump = $1
|
||||
WHERE pid = $2 AND deleted = 0 AND last_bump + bump_count * $3 <= $1`,
|
||||
now, pid, bumpStep)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if n, _ := res.RowsAffected(); n == 0 {
|
||||
return nil
|
||||
}
|
||||
bumped = true
|
||||
return notifyBump(r.Context(), tx, pid, currentUID(r), now)
|
||||
}); err != nil {
|
||||
return apperr.Internal(err)
|
||||
}
|
||||
var bumpCount, lastBump, deleted int64
|
||||
@@ -124,7 +136,7 @@ func (s *Server) handleBump(w http.ResponseWriter, r *http.Request) error {
|
||||
Scan(&bumpCount, &lastBump, &deleted); err != nil || deleted != 0 {
|
||||
return errEntryNotFound
|
||||
}
|
||||
if n, _ := res.RowsAffected(); n == 0 {
|
||||
if !bumped {
|
||||
writeBumpCooldown(w, max(lastBump+bumpCount*bumpStep-now, 0), bumpCount)
|
||||
return nil
|
||||
}
|
||||
|
||||
+12
-4
@@ -206,10 +206,18 @@ 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
|
||||
Zwei Arten (`kind`):
|
||||
|
||||
- `reply`: jemand hat auf einen eigenen Beitrag geantwortet (nicht bei
|
||||
Antworten an sich selbst), etwa „@bob hat auf deinen Beitrag geantwortet.
|
||||
(Anfang der Antwort…)“; `link` führt zur Antwort. Der Handle ist der
|
||||
aktuelle, auch nach einer Umbenennung.
|
||||
- `bump`: jemand hat einen eigenen Beitrag repostet (nicht beim eigenen
|
||||
Repost): „Jemand hat deinen Beitrag repostet. (Anfang des Beitrags…)“.
|
||||
Wer repostet, speichert der Server nicht.
|
||||
|
||||
Der Auszug umfasst die ersten 50 Zeichen. Wird der zitierte Beitrag
|
||||
bearbeitet, zieht er nach; wird er gelöscht (auch mit dem Konto), verschwindet
|
||||
die Benachrichtigung.
|
||||
|
||||
| Methode | Pfad | Auth | Request | Erfolg |
|
||||
|
||||
Reference in New Issue
Block a user