package store import ( "context" "encoding/json" "errors" "fmt" "strings" "time" "github.com/jackc/pgx/v5" "github.com/ponzischeme89/memby/server/internal/appupdate" ) // MaintenanceKey is the app_settings row backing maintenance mode. const MaintenanceKey = "maintenance" // RequestPolicyKey controls which Emby users may send titles to Sonarr/Radarr. const RequestPolicyKey = "request_policy" // SonarrRequestPolicyKey is deliberately separate from request access. Access answers who // may ask; this policy answers the safe, household-wide way a TV request is created. const SonarrRequestPolicyKey = "sonarr_request_policy" // PlaybackPolicyKey controls presentation behaviour that should be adjustable without // shipping a new TV build. const PlaybackPolicyKey = "playback_policy" // HeroPolicyKey stores the operator's explicit choices for the launcher hero. const HeroPolicyKey = "hero_policy" // MDBListSettingsKey stores the optional movie-ratings integration. The API key stays // in this server-owned document and is never included in client or admin status payloads. const MDBListSettingsKey = "mdblist_settings" // HeroPolicy stores only Emby ids and the optional prime-card copy. Names and artwork // remain library data, so a metadata correction appears without rewriting operator policy. type HeroPolicy struct { PinnedItemIDs []string `json:"pinnedItemIds"` LegacyPinnedMovieIDs []string `json:"pinnedMovieIds,omitempty"` PrimeSubtitle string `json:"primeSubtitle"` UpdatedAt time.Time `json:"updatedAt"` Schedules []HeroSchedule `json:"schedules"` } // HeroSchedule is resolved by the gateway for every home response. Times are UTC RFC3339; // weekdays use the local calendar day (Sunday=0) and an empty list means every day. type HeroSchedule struct { ID string `json:"id"` ItemID string `json:"itemId"` StartAt time.Time `json:"startAt"` EndAt time.Time `json:"endAt"` Weekdays []int `json:"weekdays,omitempty"` Priority int `json:"priority"` UserID string `json:"userId,omitempty"` Enabled bool `json:"enabled"` } func normalizeHeroPolicy(policy HeroPolicy) HeroPolicy { if len(policy.PinnedItemIDs) == 0 && len(policy.LegacyPinnedMovieIDs) > 0 { policy.PinnedItemIDs = policy.LegacyPinnedMovieIDs } seen := map[string]bool{} ids := make([]string, 0, min(len(policy.PinnedItemIDs), 4)) for _, id := range policy.PinnedItemIDs { id = strings.TrimSpace(id) if id == "" || seen[id] || len(ids) == 4 { continue } seen[id] = true ids = append(ids, id) } policy.PinnedItemIDs = ids policy.LegacyPinnedMovieIDs = nil policy.PrimeSubtitle = strings.TrimSpace(policy.PrimeSubtitle) runes := []rune(policy.PrimeSubtitle) if len(runes) > 160 { policy.PrimeSubtitle = string(runes[:160]) } cleanSchedules := make([]HeroSchedule, 0, len(policy.Schedules)) seenSchedules := map[string]bool{} for _, schedule := range policy.Schedules { schedule.ID, schedule.ItemID, schedule.UserID = strings.TrimSpace(schedule.ID), strings.TrimSpace(schedule.ItemID), strings.TrimSpace(schedule.UserID) if schedule.ID == "" || schedule.ItemID == "" || seenSchedules[schedule.ID] || !schedule.EndAt.After(schedule.StartAt) { continue } seenSchedules[schedule.ID] = true if schedule.Priority < -1000 { schedule.Priority = -1000 } if schedule.Priority > 1000 { schedule.Priority = 1000 } weekdays := make([]int, 0, len(schedule.Weekdays)) seenDays := map[int]bool{} for _, day := range schedule.Weekdays { if day >= 0 && day <= 6 && !seenDays[day] { seenDays[day] = true weekdays = append(weekdays, day) } } schedule.Weekdays = weekdays cleanSchedules = append(cleanSchedules, schedule) } policy.Schedules = cleanSchedules return policy } func (s *Store) HeroPolicy(ctx context.Context) (HeroPolicy, error) { var raw []byte err := s.pool.QueryRow(ctx, `SELECT value FROM app_settings WHERE key = $1`, HeroPolicyKey).Scan(&raw) if errors.Is(err, pgx.ErrNoRows) { return HeroPolicy{PinnedItemIDs: []string{}}, nil } if err != nil { return HeroPolicy{}, fmt.Errorf("store: read hero policy: %w", err) } var policy HeroPolicy if err := json.Unmarshal(raw, &policy); err != nil { return HeroPolicy{}, fmt.Errorf("store: decode hero policy: %w", err) } return normalizeHeroPolicy(policy), nil } func (s *Store) SetHeroPolicy(ctx context.Context, policy HeroPolicy) error { policy = normalizeHeroPolicy(policy) policy.UpdatedAt = time.Now().UTC() raw, err := json.Marshal(policy) if err != nil { return err } _, err = s.pool.Exec(ctx, ` INSERT INTO app_settings (key, value, updated_at) VALUES ($1, $2::jsonb, now()) ON CONFLICT (key) DO UPDATE SET value = EXCLUDED.value, updated_at = now()`, HeroPolicyKey, string(raw)) if err != nil { return fmt.Errorf("store: write hero policy: %w", err) } return nil } var defaultMDBListSources = []string{ "imdb", "tomatoes", "audience", "metacritic", "letterboxd", "rogerebert", "tmdb", "trakt", "mal", "anilist", "anidb", "kitsu", "score", "score_average", } type MDBListSettings struct { Enabled bool `json:"enabled"` APIKey string `json:"apiKey"` Sources []string `json:"sources"` UpdatedAt time.Time `json:"updatedAt"` } func DefaultMDBListSettings() MDBListSettings { return MDBListSettings{Sources: append([]string(nil), defaultMDBListSources...)} } func MDBListSources() []string { return append([]string(nil), defaultMDBListSources...) } func ValidMDBListSource(source string) bool { source = strings.ToLower(strings.TrimSpace(source)) for _, supported := range defaultMDBListSources { if source == supported { return true } } return false } func normalizeMDBListSettings(settings MDBListSettings) MDBListSettings { settings.APIKey = strings.TrimSpace(settings.APIKey) seen := map[string]bool{} sources := make([]string, 0, len(settings.Sources)) for _, source := range settings.Sources { source = strings.ToLower(strings.TrimSpace(source)) if !ValidMDBListSource(source) || seen[source] { continue } seen[source] = true sources = append(sources, source) } if len(sources) == 0 { sources = append(sources, defaultMDBListSources...) } settings.Sources = sources return settings } func (s *Store) MDBListSettings(ctx context.Context) (MDBListSettings, error) { var raw []byte err := s.pool.QueryRow(ctx, `SELECT value FROM app_settings WHERE key = $1`, MDBListSettingsKey).Scan(&raw) if errors.Is(err, pgx.ErrNoRows) { return DefaultMDBListSettings(), nil } if err != nil { return DefaultMDBListSettings(), fmt.Errorf("store: read MDBList settings: %w", err) } var settings MDBListSettings if err := json.Unmarshal(raw, &settings); err != nil { return DefaultMDBListSettings(), fmt.Errorf("store: decode MDBList settings: %w", err) } return normalizeMDBListSettings(settings), nil } func (s *Store) SetMDBListSettings(ctx context.Context, settings MDBListSettings) error { settings = normalizeMDBListSettings(settings) settings.UpdatedAt = time.Now().UTC() raw, err := json.Marshal(settings) if err != nil { return err } _, err = s.pool.Exec(ctx, ` INSERT INTO app_settings (key, value, updated_at) VALUES ($1, $2::jsonb, now()) ON CONFLICT (key) DO UPDATE SET value = EXCLUDED.value, updated_at = now()`, MDBListSettingsKey, string(raw)) if err != nil { return fmt.Errorf("store: write MDBList settings: %w", err) } return nil } // FeaturePolicyKey is the durable operator control plane for optional behaviour. // The catalogue of valid flags lives in the API; the store only persists overrides so // removing or renaming a feature does not strand an unreadable database row. const FeaturePolicyKey = "feature_policy" type FeaturePolicySnapshot struct { Overrides map[string]bool `json:"overrides"` SafeMode bool `json:"safeMode"` Revision int64 `json:"revision"` UpdatedAt time.Time `json:"updatedAt"` } type FeaturePolicy struct { Overrides map[string]bool `json:"overrides"` SafeMode bool `json:"safeMode"` Revision int64 `json:"revision"` UpdatedAt time.Time `json:"updatedAt"` Previous *FeaturePolicySnapshot `json:"previous,omitempty"` } var ErrFeaturePolicyConflict = errors.New("store: feature policy revision conflict") func DefaultFeaturePolicy() FeaturePolicy { return FeaturePolicy{Overrides: map[string]bool{}} } func normalizeFeaturePolicy(policy FeaturePolicy) FeaturePolicy { if policy.Overrides == nil { policy.Overrides = map[string]bool{} } return policy } func (s *Store) FeaturePolicy(ctx context.Context) (FeaturePolicy, error) { var raw []byte err := s.pool.QueryRow(ctx, `SELECT value FROM app_settings WHERE key = $1`, FeaturePolicyKey).Scan(&raw) if errors.Is(err, pgx.ErrNoRows) { return DefaultFeaturePolicy(), nil } if err != nil { return DefaultFeaturePolicy(), fmt.Errorf("store: read feature policy: %w", err) } var policy FeaturePolicy if err := json.Unmarshal(raw, &policy); err != nil { return DefaultFeaturePolicy(), fmt.Errorf("store: decode feature policy: %w", err) } return normalizeFeaturePolicy(policy), nil } // SetFeaturePolicy preserves the prior revision inside the same durable document. This // gives the operator a recovery button without requiring a matching client release. func (s *Store) SetFeaturePolicy( ctx context.Context, next FeaturePolicy, expectedRevision int64, ) (FeaturePolicy, error) { tx, err := s.pool.Begin(ctx) if err != nil { return FeaturePolicy{}, fmt.Errorf("store: begin feature policy write: %w", err) } defer func() { _ = tx.Rollback(ctx) }() if _, err := tx.Exec(ctx, `SELECT pg_advisory_xact_lock(hashtextextended($1, 0))`, FeaturePolicyKey); err != nil { return FeaturePolicy{}, fmt.Errorf("store: lock feature policy: %w", err) } current := DefaultFeaturePolicy() var currentRaw []byte err = tx.QueryRow(ctx, `SELECT value FROM app_settings WHERE key = $1`, FeaturePolicyKey).Scan(¤tRaw) if err == nil { if err := json.Unmarshal(currentRaw, ¤t); err != nil { return FeaturePolicy{}, fmt.Errorf("store: decode current feature policy: %w", err) } current = normalizeFeaturePolicy(current) } else if !errors.Is(err, pgx.ErrNoRows) { return FeaturePolicy{}, fmt.Errorf("store: read current feature policy: %w", err) } if current.Revision != expectedRevision { return FeaturePolicy{}, ErrFeaturePolicyConflict } next = normalizeFeaturePolicy(next) next.Revision = current.Revision + 1 next.UpdatedAt = time.Now().UTC() next.Previous = &FeaturePolicySnapshot{ Overrides: current.Overrides, SafeMode: current.SafeMode, Revision: current.Revision, UpdatedAt: current.UpdatedAt, } raw, err := json.Marshal(next) if err != nil { return FeaturePolicy{}, err } _, err = tx.Exec(ctx, ` INSERT INTO app_settings (key, value, updated_at) VALUES ($1, $2::jsonb, now()) ON CONFLICT (key) DO UPDATE SET value = EXCLUDED.value, updated_at = now()`, FeaturePolicyKey, string(raw)) if err != nil { return FeaturePolicy{}, fmt.Errorf("store: write feature policy: %w", err) } if err := tx.Commit(ctx); err != nil { return FeaturePolicy{}, fmt.Errorf("store: commit feature policy: %w", err) } return next, nil } const DefaultPrerollDurationMs int64 = 6_500 type PlaybackPolicy struct { PrerollEnabled bool `json:"prerollEnabled"` PrerollDurationMs int64 `json:"prerollDurationMs"` UpdatedAt time.Time `json:"updatedAt"` } func DefaultPlaybackPolicy() PlaybackPolicy { return PlaybackPolicy{PrerollEnabled: true, PrerollDurationMs: DefaultPrerollDurationMs} } func normalizePlaybackPolicy(policy PlaybackPolicy) PlaybackPolicy { if policy.PrerollDurationMs == 0 { policy.PrerollDurationMs = DefaultPrerollDurationMs } policy.PrerollDurationMs = max(int64(1_000), min(policy.PrerollDurationMs, int64(30_000))) return policy } func (s *Store) PlaybackPolicy(ctx context.Context) (PlaybackPolicy, error) { var raw []byte err := s.pool.QueryRow(ctx, `SELECT value FROM app_settings WHERE key = $1`, PlaybackPolicyKey).Scan(&raw) if errors.Is(err, pgx.ErrNoRows) { return DefaultPlaybackPolicy(), nil } if err != nil { return DefaultPlaybackPolicy(), fmt.Errorf("store: read playback policy: %w", err) } var policy PlaybackPolicy if err := json.Unmarshal(raw, &policy); err != nil { return DefaultPlaybackPolicy(), fmt.Errorf("store: decode playback policy: %w", err) } return normalizePlaybackPolicy(policy), nil } func (s *Store) SetPlaybackPolicy(ctx context.Context, policy PlaybackPolicy) error { policy = normalizePlaybackPolicy(policy) policy.UpdatedAt = time.Now().UTC() raw, err := json.Marshal(policy) if err != nil { return err } _, err = s.pool.Exec(ctx, ` INSERT INTO app_settings (key, value, updated_at) VALUES ($1, $2::jsonb, now()) ON CONFLICT (key) DO UPDATE SET value = EXCLUDED.value, updated_at = now()`, PlaybackPolicyKey, string(raw)) if err != nil { return fmt.Errorf("store: write playback policy: %w", err) } return nil } type RequestPolicy struct { AllowedUserIDs []string `json:"allowedUserIds"` UpdatedAt time.Time `json:"updatedAt"` } // SonarrRequestPolicy stores Sonarr's stable quality-profile id, never its mutable name. // A zero id means the operator has not selected one yet; the gateway may use only a profile // named 720p as its safe first-run recommendation, never Sonarr's arbitrary default. type SonarrRequestPolicy struct { QualityProfileID int `json:"qualityProfileId"` SearchImmediately bool `json:"searchImmediately"` UpdatedAt time.Time `json:"updatedAt"` } func DefaultSonarrRequestPolicy() SonarrRequestPolicy { return SonarrRequestPolicy{} } func (s *Store) SonarrRequestPolicy(ctx context.Context) (SonarrRequestPolicy, error) { var raw []byte err := s.pool.QueryRow(ctx, `SELECT value FROM app_settings WHERE key = $1`, SonarrRequestPolicyKey).Scan(&raw) if errors.Is(err, pgx.ErrNoRows) { return DefaultSonarrRequestPolicy(), nil } if err != nil { return DefaultSonarrRequestPolicy(), fmt.Errorf("store: read Sonarr request policy: %w", err) } var policy SonarrRequestPolicy if err := json.Unmarshal(raw, &policy); err != nil { return DefaultSonarrRequestPolicy(), fmt.Errorf("store: decode Sonarr request policy: %w", err) } if policy.QualityProfileID < 0 { policy.QualityProfileID = 0 } return policy, nil } func (s *Store) SetSonarrRequestPolicy(ctx context.Context, policy SonarrRequestPolicy) error { if policy.QualityProfileID <= 0 { return fmt.Errorf("store: Sonarr request quality profile is required") } policy.UpdatedAt = time.Now().UTC() raw, err := json.Marshal(policy) if err != nil { return err } _, err = s.pool.Exec(ctx, ` INSERT INTO app_settings (key, value, updated_at) VALUES ($1, $2::jsonb, now()) ON CONFLICT (key) DO UPDATE SET value = EXCLUDED.value, updated_at = now()`, SonarrRequestPolicyKey, string(raw)) if err != nil { return fmt.Errorf("store: write Sonarr request policy: %w", err) } return nil } func (p RequestPolicy) Allows(userID string) bool { for _, allowed := range p.AllowedUserIDs { if allowed == userID { return true } } return false } func (s *Store) RequestPolicy(ctx context.Context) (RequestPolicy, error) { var raw []byte err := s.pool.QueryRow(ctx, `SELECT value FROM app_settings WHERE key = $1`, RequestPolicyKey).Scan(&raw) if errors.Is(err, pgx.ErrNoRows) { return RequestPolicy{AllowedUserIDs: []string{}}, nil } if err != nil { return RequestPolicy{}, fmt.Errorf("store: read request policy: %w", err) } var policy RequestPolicy if err := json.Unmarshal(raw, &policy); err != nil { return RequestPolicy{}, fmt.Errorf("store: decode request policy: %w", err) } if policy.AllowedUserIDs == nil { policy.AllowedUserIDs = []string{} } return policy, nil } func (s *Store) SetRequestPolicy(ctx context.Context, policy RequestPolicy) error { policy.UpdatedAt = time.Now().UTC() raw, err := json.Marshal(policy) if err != nil { return err } _, err = s.pool.Exec(ctx, ` INSERT INTO app_settings (key, value, updated_at) VALUES ($1, $2::jsonb, now()) ON CONFLICT (key) DO UPDATE SET value = EXCLUDED.value, updated_at = now()`, RequestPolicyKey, string(raw)) if err != nil { return fmt.Errorf("store: write request policy: %w", err) } return nil } // Maintenance is the operator switch that takes Memby down independently of Emby. // // Deliberately durable: a restart must not quietly bring the app back up while someone // is still working on it. type Maintenance struct { Enabled bool `json:"enabled"` Message string `json:"message"` UpdatedAt time.Time `json:"updatedAt"` } // DefaultMaintenanceMessage is shown on the TV when the operator did not write one. const DefaultMaintenanceMessage = "Memby is down for maintenance. Try again shortly." func (s *Store) Maintenance(ctx context.Context) (Maintenance, error) { var raw []byte err := s.pool.QueryRow(ctx, `SELECT value FROM app_settings WHERE key = $1`, MaintenanceKey).Scan(&raw) if errors.Is(err, pgx.ErrNoRows) { return Maintenance{}, nil } if err != nil { return Maintenance{}, fmt.Errorf("store: read maintenance: %w", err) } var state Maintenance if err := json.Unmarshal(raw, &state); err != nil { return Maintenance{}, fmt.Errorf("store: decode maintenance: %w", err) } return state, nil } func (s *Store) SetMaintenance(ctx context.Context, state Maintenance) error { state.UpdatedAt = time.Now().UTC() raw, err := json.Marshal(state) if err != nil { return err } _, err = s.pool.Exec(ctx, ` INSERT INTO app_settings (key, value, updated_at) VALUES ($1, $2::jsonb, now()) ON CONFLICT (key) DO UPDATE SET value = EXCLUDED.value, updated_at = now()`, MaintenanceKey, string(raw)) if err != nil { return fmt.Errorf("store: write maintenance: %w", err) } return nil } // UpdatePolicyKey is the app_settings row backing the client update policy. const UpdatePolicyKey = "update_policy" func (s *Store) UpdatePolicy(ctx context.Context) (appupdate.Policy, error) { var raw []byte err := s.pool.QueryRow(ctx, `SELECT value FROM app_settings WHERE key = $1`, UpdatePolicyKey).Scan(&raw) if errors.Is(err, pgx.ErrNoRows) { return appupdate.Policy{}, nil } if err != nil { return appupdate.Policy{}, fmt.Errorf("store: read update policy: %w", err) } var policy appupdate.Policy if err := json.Unmarshal(raw, &policy); err != nil { return appupdate.Policy{}, fmt.Errorf("store: decode update policy: %w", err) } return policy, nil } func (s *Store) SetUpdatePolicy(ctx context.Context, policy appupdate.Policy) error { policy.UpdatedAt = time.Now().UTC() raw, err := json.Marshal(policy) if err != nil { return err } _, err = s.pool.Exec(ctx, ` INSERT INTO app_settings (key, value, updated_at) VALUES ($1, $2::jsonb, now()) ON CONFLICT (key) DO UPDATE SET value = EXCLUDED.value, updated_at = now()`, UpdatePolicyKey, string(raw)) if err != nil { return fmt.Errorf("store: write update policy: %w", err) } return nil } // NewestSession is the fallback credential for the library import: whichever TV signed // in most recently. It means a fresh deployment can import without configuring a // service account, at the cost of the import stopping if that user is ever removed. func (s *Store) NewestSession(ctx context.Context) (Session, error) { var sess Session err := s.pool.QueryRow(ctx, ` SELECT token_hash, emby_user_id, emby_token, username, server_id, device_id, device_name, client_version, client_protocol, client_capabilities, last_seen_at FROM sessions ORDER BY last_seen_at DESC LIMIT 1`). Scan(&sess.TokenHash, &sess.EmbyUserID, &sess.EmbyToken, &sess.Username, &sess.ServerID, &sess.DeviceID, &sess.DeviceName, &sess.ClientVersion, &sess.ClientProtocol, &sess.ClientCapabilities, &sess.LastSeenAt) if errors.Is(err, pgx.ErrNoRows) { return Session{}, ErrNotFound } if err != nil { return Session{}, fmt.Errorf("store: newest session: %w", err) } return sess, nil }