Files
silo-server/internal/notifications/preferences_repo.go
QuickandClaude Fable 5 b091f0c6c1 feat(notifications): in-app inbox, realtime, webhooks, web push + shared SMTP core
Implements the notification system foundation and all v1 delivery channels
that need no external infrastructure (specs 00/01/04/05 in
docs/superpowers/plans/notifications/):

Foundation (spec 01):
- episode_availability seeding + per-library seed markers: "newly available"
  means newly released to this server, so back-catalog imports and first
  scans never flood (verified on dev: 1.13M episodes seeded silently)
- release_events -> profile_series_interest fanout worker with settling
  delay, per-series burst caps, FOR UPDATE SKIP LOCKED multi-node claims,
  and a guarded last-notified cursor
- interest index maintained via a userstore provider decorator so every
  favorites/watchlist/progress mutation path (REST, jellycompat, imports,
  playback) feeds it; progress writes only recompute on state transitions
- durable per-profile inbox + read state, forward-sync cursor API,
  websocket channel with short-lived single-use handshake tickets
- web UI: sidebar badge, inbox page, toasts, per-profile preferences
- startup/daily tasks: availability seeding, interest rebuild, retention

Outbound webhooks (spec 04):
- Discord embeds (text-only per the v1 privacy contract) and generic
  JSON signed Stripe-style with per-webhook secrets
- HTTPS-only + private-destination guard enforced at registration and at
  connect time (DNS-rebinding mitigation); URLs/secrets encrypted at rest
- durable per-target outbox enqueued in the fanout transaction, lease-based
  claims, 24h exponential retry, 3x-consecutive-4xx auto-disable with an
  in-app notice (loop-guarded)

Web push (spec 05):
- VAPID keypair self-provisioned at startup (single atomic JSON setting,
  private half encrypted at rest) — no third-party accounts needed
- payloads E2E-encrypted (RFC 8291); 404/410 treated as unsubscribe
- service worker + subscribe flow in Settings -> Notifications

Shared SMTP core (internal/mail):
- feature-agnostic mail.Sender over live email.* settings, STARTTLS or
  implicit TLS, encrypted password, admin Email settings page with
  synchronous test send; no consumer yet by design (digest is v1.5)

APNs/FCM (specs 02/03) are deferred to v2; the capability endpoint reports
them unavailable so clients render truthfully.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-06-11 14:55:46 -04:00

99 lines
3.4 KiB
Go

package notifications
import (
"context"
"errors"
"fmt"
"github.com/jackc/pgx/v5"
"github.com/jackc/pgx/v5/pgxpool"
)
// PreferencesRepository owns notification_preferences.
type PreferencesRepository struct {
pool *pgxpool.Pool
}
// NewPreferencesRepository creates a PreferencesRepository.
func NewPreferencesRepository(pool *pgxpool.Pool) *PreferencesRepository {
return &PreferencesRepository{pool: pool}
}
// Get returns the profile's preferences, defaulting missing rows to
// all-enabled.
func (r *PreferencesRepository) Get(ctx context.Context, profileID string) (Preferences, error) {
prefs := DefaultPreferences(profileID)
err := r.pool.QueryRow(ctx, `
SELECT enabled, notify_favorites, notify_watchlist, notify_continue_watching, notify_next_up, updated_at
FROM notification_preferences
WHERE profile_id = $1`,
profileID,
).Scan(&prefs.Enabled, &prefs.NotifyFavorites, &prefs.NotifyWatchlist,
&prefs.NotifyContinueWatching, &prefs.NotifyNextUp, &prefs.UpdatedAt)
if errors.Is(err, pgx.ErrNoRows) {
return prefs, nil
}
if err != nil {
return prefs, fmt.Errorf("get notification preferences: %w", err)
}
return prefs, nil
}
// GetMany returns preferences for the given profiles, defaulting missing rows
// to all-enabled. Used by the fanout worker.
func (r *PreferencesRepository) GetMany(ctx context.Context, tx pgx.Tx, profileIDs []string) (map[string]Preferences, error) {
out := make(map[string]Preferences, len(profileIDs))
for _, profileID := range profileIDs {
out[profileID] = DefaultPreferences(profileID)
}
if len(profileIDs) == 0 {
return out, nil
}
rows, err := tx.Query(ctx, `
SELECT profile_id, enabled, notify_favorites, notify_watchlist, notify_continue_watching, notify_next_up, updated_at
FROM notification_preferences
WHERE profile_id = ANY($1)`,
profileIDs)
if err != nil {
return nil, fmt.Errorf("get notification preferences batch: %w", err)
}
defer rows.Close()
for rows.Next() {
var prefs Preferences
if err := rows.Scan(&prefs.ProfileID, &prefs.Enabled, &prefs.NotifyFavorites,
&prefs.NotifyWatchlist, &prefs.NotifyContinueWatching, &prefs.NotifyNextUp, &prefs.UpdatedAt); err != nil {
return nil, fmt.Errorf("scan notification preferences: %w", err)
}
out[prefs.ProfileID] = prefs
}
return out, rows.Err()
}
// Upsert writes the profile's preferences. Idempotent.
func (r *PreferencesRepository) Upsert(ctx context.Context, prefs Preferences) error {
_, err := r.pool.Exec(ctx, `
INSERT INTO notification_preferences
(profile_id, enabled, notify_favorites, notify_watchlist, notify_continue_watching, notify_next_up, updated_at)
VALUES ($1, $2, $3, $4, $5, $6, now())
ON CONFLICT (profile_id) DO UPDATE SET
enabled = EXCLUDED.enabled,
notify_favorites = EXCLUDED.notify_favorites,
notify_watchlist = EXCLUDED.notify_watchlist,
notify_continue_watching = EXCLUDED.notify_continue_watching,
notify_next_up = EXCLUDED.notify_next_up,
updated_at = now()`,
prefs.ProfileID, prefs.Enabled, prefs.NotifyFavorites,
prefs.NotifyWatchlist, prefs.NotifyContinueWatching, prefs.NotifyNextUp)
if err != nil {
return fmt.Errorf("upsert notification preferences: %w", err)
}
return nil
}
// DeleteForProfile removes a deleted profile's preference row.
func (r *PreferencesRepository) DeleteForProfile(ctx context.Context, profileID string) error {
_, err := r.pool.Exec(ctx,
`DELETE FROM notification_preferences WHERE profile_id = $1`, profileID)
return err
}