Files
memby/server/internal/store/settings.go
T

491 lines
16 KiB
Go
Raw Normal View History

package store
import (
"context"
"encoding/json"
"errors"
"fmt"
2026-08-03 08:52:55 +12:00
"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"
2026-08-02 22:10:19 +12:00
// RequestPolicyKey controls which Emby users may send titles to Sonarr/Radarr.
const RequestPolicyKey = "request_policy"
2026-08-11 23:41:10 +12:00
// PlaybackPolicyKey controls presentation behaviour that should be adjustable without
2026-08-02 22:10:19 +12:00
// shipping a new TV build.
const PlaybackPolicyKey = "playback_policy"
2026-08-11 23:41:10 +12:00
// HeroPolicyKey stores the operator's explicit choices for the launcher hero.
const HeroPolicyKey = "hero_policy"
2026-08-03 08:52:55 +12:00
// 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"
2026-08-11 23:41:10 +12:00
// 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"`
}
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])
}
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
}
2026-08-03 08:52:55 +12:00
var defaultMDBListSources = []string{
"imdb", "tomatoes", "audience", "metacritic", "letterboxd", "rogerebert",
2026-08-06 22:33:56 +12:00
"tmdb", "trakt", "mal", "anilist", "anidb", "kitsu", "score", "score_average",
2026-08-03 08:52:55 +12:00
}
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
}
2026-08-02 22:10:19 +12:00
// 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(&currentRaw)
if err == nil {
if err := json.Unmarshal(currentRaw, &current); 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"`
}
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, `
2026-07-29 15:26:27 +12:00
SELECT token_hash, emby_user_id, emby_token, username, server_id, device_id,
2026-08-02 22:10:19 +12:00
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,
2026-07-29 15:26:27 +12:00
&sess.ServerID, &sess.DeviceID, &sess.DeviceName, &sess.ClientVersion,
2026-08-02 22:10:19 +12:00
&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
}