Files
Kontrollverlust/internal/httpapi/notifications.go
T
irrlichtandClaude Fable 5.1 b2bb1f176f Aufräumen: Soft-Delete, Benachrichtigungsarten, Antwort-Structs, WebP
Das Soft-Delete-SQL stand zweimal (Beitrag löschen, Konto löschen) und
beide Stellen mussten dieselben Nebentabellen kennen; jetzt macht
softDeleteEntries das für eine WHERE-Bedingung, die Kontolöschung räumt
nur noch ab, was am Nutzer selbst hängt.

Die Benachrichtigungsarten waren an fünf Stellen als Literal im SQL und
im Go-Code; jetzt Konstanten, die als Parameter mitgehen. Antworten auf
Anlegen/Bearbeiten und sessioninfo sind Structs wie der Rest.

media: der Import von x/image/webp registriert den Decoder global, die
Sonderbehandlung in decodeChecked war daher tot und ihr Kommentar falsch
(SaveUpload nahm WebP längst an). Jetzt ein Import mit Kommentar, ein
Pfad für alle Formate.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
2026-11-22 13:12:27 +01:00

156 lines
5.3 KiB
Go

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
// excerptRunes: so viel vom Beitrag steht in der Benachrichtigung.
excerptRunes = 50
)
// Arten von Benachrichtigungen (Spalte notification.kind, Feld kind der API).
const (
kindReply = "reply" // Antwort auf einen eigenen Beitrag
kindMention = "mention" // in einem Beitrag erwähnt
kindBump = "bump" // eigener Beitrag repostet
)
// 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"`
Excerpt string `json:"excerpt"`
Link string `json:"link"`
CreatedAt int64 `json:"created_at"`
Seen bool `json:"seen"`
}
// 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
}
// entryLink ist der interne Pfad zu einem Beitrag, wie ihn eine
// Benachrichtigung trägt.
func entryLink(pid int64) string { return fmt.Sprintf("/e/%d", pid) }
// notificationMessage ist die Zeile, die sagt, was passiert ist. actor ist
// der Handle dessen, der geantwortet hat; leer (Reposts, unbekannt) heißt
// "Jemand". Den Auszug liefert die API getrennt.
func notificationMessage(kind, actor string) string {
who := "Jemand"
if actor != "" {
who = "@" + actor
}
switch kind {
case kindReply:
return who + " hat auf deinen Beitrag geantwortet."
case kindMention:
return who + " hat dich erwähnt."
}
return who + " hat deinen Beitrag repostet."
}
// 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). 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, actor, excerpt, link, pid, created_at)
SELECT uid, $7, $1, $2, $3, $4, $5 FROM entry
WHERE pid = $6 AND uid <> 0 AND uid <> $1`,
in.uid, excerpt(in.content), entryLink(pid), pid, in.created, in.replyTo, kindReply); 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, $6, $2, $3, $4, $5)`,
author, excerpt(content), entryLink(pid), pid, now, kindBump); 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 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)
}
defer rows.Close()
list := []notificationJSON{}
for rows.Next() {
var n notificationJSON
var actor string
if err := rows.Scan(&n.ID, &n.Kind, &actor, &n.Excerpt, &n.Link, &n.CreatedAt, &n.Seen); err != nil {
return apperr.Internal(err)
}
n.Message = notificationMessage(n.Kind, actor)
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
}