900 lines
31 KiB
Go
900 lines
31 KiB
Go
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"
|
||
|
||
// QuietTimeKey is the app_settings row backing the daily server quiet-time window.
|
||
const QuietTimeKey = "quiet_time"
|
||
|
||
// 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"
|
||
|
||
const RadarrRequestPolicyKey = "radarr_request_policy"
|
||
|
||
const ArrIntegrationPolicyKey = "arr_integration_policy"
|
||
|
||
// ArrIntegrationPolicy lets the operator stop either *arr integration without removing
|
||
// credentials or request policy. Both start enabled for existing households.
|
||
type ArrIntegrationPolicy struct {
|
||
SonarrEnabled bool `json:"sonarrEnabled"`
|
||
RadarrEnabled bool `json:"radarrEnabled"`
|
||
UpdatedAt time.Time `json:"updatedAt"`
|
||
}
|
||
|
||
func DefaultArrIntegrationPolicy() ArrIntegrationPolicy {
|
||
return ArrIntegrationPolicy{SonarrEnabled: true, RadarrEnabled: true}
|
||
}
|
||
|
||
func (s *Store) ArrIntegrationPolicy(ctx context.Context) (ArrIntegrationPolicy, error) {
|
||
var raw []byte
|
||
err := s.pool.QueryRow(ctx, `SELECT value FROM app_settings WHERE key = $1`, ArrIntegrationPolicyKey).Scan(&raw)
|
||
if errors.Is(err, pgx.ErrNoRows) {
|
||
return DefaultArrIntegrationPolicy(), nil
|
||
}
|
||
if err != nil {
|
||
return DefaultArrIntegrationPolicy(), fmt.Errorf("store: read arr integration policy: %w", err)
|
||
}
|
||
var policy ArrIntegrationPolicy
|
||
if err := json.Unmarshal(raw, &policy); err != nil {
|
||
return DefaultArrIntegrationPolicy(), fmt.Errorf("store: decode arr integration policy: %w", err)
|
||
}
|
||
return policy, nil
|
||
}
|
||
|
||
func (s *Store) SetArrIntegrationPolicy(ctx context.Context, policy ArrIntegrationPolicy) 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()`,
|
||
ArrIntegrationPolicyKey, string(raw))
|
||
if err != nil {
|
||
return fmt.Errorf("store: write arr integration policy: %w", err)
|
||
}
|
||
return nil
|
||
}
|
||
|
||
// 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"`
|
||
Placements map[string]HeroPlacementPolicy `json:"placements,omitempty"`
|
||
UpdatedAt time.Time `json:"updatedAt"`
|
||
Schedules []HeroSchedule `json:"schedules"`
|
||
}
|
||
|
||
// HeroPlacementPolicy is one independently resolved spotlight. Keeping the placement as
|
||
// a map key means another section can be added without changing the stored document.
|
||
type HeroPlacementPolicy struct {
|
||
PinnedItemIDs []string `json:"pinnedItemIds"`
|
||
PrimeSubtitle string `json:"primeSubtitle"`
|
||
}
|
||
|
||
// HeroSchedule is resolved by the gateway for every home response. An empty Frequency is
|
||
// the original absolute start/end shape and remains valid. Daily and weekly schedules use
|
||
// the gateway's local clock; a window such as 22:00–02:00 belongs to the day it starts.
|
||
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"`
|
||
Frequency string `json:"frequency,omitempty"`
|
||
StartTime string `json:"startTime,omitempty"`
|
||
EndTime string `json:"endTime,omitempty"`
|
||
Priority int `json:"priority"`
|
||
UserID string `json:"userId,omitempty"`
|
||
Enabled bool `json:"enabled"`
|
||
Placements []string `json:"placements,omitempty"`
|
||
}
|
||
|
||
const (
|
||
HeroPlacementHome = "home"
|
||
HeroPlacementMovies = "movies"
|
||
HeroPlacementTVShows = "tv_shows"
|
||
)
|
||
|
||
func ValidHeroPlacement(value string) bool {
|
||
switch strings.ToLower(strings.TrimSpace(value)) {
|
||
case HeroPlacementHome, HeroPlacementMovies, HeroPlacementTVShows:
|
||
return true
|
||
default:
|
||
return false
|
||
}
|
||
}
|
||
|
||
func normaliseHeroPlacementPolicy(policy HeroPlacementPolicy) HeroPlacementPolicy {
|
||
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.PrimeSubtitle = strings.TrimSpace(policy.PrimeSubtitle)
|
||
if runes := []rune(policy.PrimeSubtitle); len(runes) > 160 {
|
||
policy.PrimeSubtitle = string(runes[:160])
|
||
}
|
||
return policy
|
||
}
|
||
|
||
func (policy HeroPolicy) Placement(name string) HeroPlacementPolicy {
|
||
name = strings.ToLower(strings.TrimSpace(name))
|
||
if placement, ok := policy.Placements[name]; ok {
|
||
return placement
|
||
}
|
||
if name == HeroPlacementHome {
|
||
return HeroPlacementPolicy{PinnedItemIDs: policy.PinnedItemIDs, PrimeSubtitle: policy.PrimeSubtitle}
|
||
}
|
||
return HeroPlacementPolicy{PinnedItemIDs: []string{}}
|
||
}
|
||
|
||
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])
|
||
}
|
||
if policy.Placements == nil {
|
||
policy.Placements = map[string]HeroPlacementPolicy{}
|
||
}
|
||
if _, exists := policy.Placements[HeroPlacementHome]; !exists {
|
||
policy.Placements[HeroPlacementHome] = HeroPlacementPolicy{PinnedItemIDs: policy.PinnedItemIDs, PrimeSubtitle: policy.PrimeSubtitle}
|
||
}
|
||
cleanPlacements := make(map[string]HeroPlacementPolicy, len(policy.Placements))
|
||
for name, placement := range policy.Placements {
|
||
name = strings.ToLower(strings.TrimSpace(name))
|
||
if ValidHeroPlacement(name) {
|
||
cleanPlacements[name] = normaliseHeroPlacementPolicy(placement)
|
||
}
|
||
}
|
||
for _, name := range []string{HeroPlacementHome, HeroPlacementMovies, HeroPlacementTVShows} {
|
||
if _, exists := cleanPlacements[name]; !exists {
|
||
cleanPlacements[name] = HeroPlacementPolicy{PinnedItemIDs: []string{}}
|
||
}
|
||
}
|
||
policy.Placements = cleanPlacements
|
||
home := policy.Placement(HeroPlacementHome)
|
||
policy.PinnedItemIDs, policy.PrimeSubtitle = home.PinnedItemIDs, home.PrimeSubtitle
|
||
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)
|
||
schedule.Frequency = strings.ToLower(strings.TrimSpace(schedule.Frequency))
|
||
if schedule.Frequency == "once" {
|
||
// "once" is explicit in the new console; empty is the compatible legacy form.
|
||
schedule.Frequency = ""
|
||
}
|
||
recurring := schedule.Frequency == "daily" || schedule.Frequency == "weekly"
|
||
if schedule.ID == "" || schedule.ItemID == "" || seenSchedules[schedule.ID] ||
|
||
(!recurring && !schedule.EndAt.After(schedule.StartAt)) {
|
||
continue
|
||
}
|
||
if recurring {
|
||
schedule.StartTime = normaliseHeroClock(schedule.StartTime)
|
||
schedule.EndTime = normaliseHeroClock(schedule.EndTime)
|
||
if schedule.StartTime == "" || schedule.EndTime == "" || schedule.StartTime == schedule.EndTime {
|
||
continue
|
||
}
|
||
} else {
|
||
schedule.StartTime, schedule.EndTime = "", ""
|
||
}
|
||
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
|
||
if schedule.Frequency == "daily" {
|
||
schedule.Weekdays = []int{}
|
||
}
|
||
placements := make([]string, 0, len(schedule.Placements))
|
||
seenPlacements := map[string]bool{}
|
||
for _, placement := range schedule.Placements {
|
||
placement = strings.ToLower(strings.TrimSpace(placement))
|
||
if ValidHeroPlacement(placement) && !seenPlacements[placement] {
|
||
seenPlacements[placement] = true
|
||
placements = append(placements, placement)
|
||
}
|
||
}
|
||
if len(placements) == 0 {
|
||
placements = []string{HeroPlacementHome}
|
||
}
|
||
schedule.Placements = placements
|
||
cleanSchedules = append(cleanSchedules, schedule)
|
||
}
|
||
policy.Schedules = cleanSchedules
|
||
return policy
|
||
}
|
||
|
||
func normaliseHeroClock(value string) string {
|
||
parsed, err := time.Parse("15:04", strings.TrimSpace(value))
|
||
if err != nil {
|
||
return ""
|
||
}
|
||
return parsed.Format("15:04")
|
||
}
|
||
|
||
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
|
||
}
|
||
|
||
// RadarrRequestPolicy is the movie equivalent of SonarrRequestPolicy. It persists the
|
||
// stable profile id so a renamed or removed profile becomes a safe configuration error.
|
||
type RadarrRequestPolicy struct {
|
||
QualityProfileID int `json:"qualityProfileId"`
|
||
SearchImmediately bool `json:"searchImmediately"`
|
||
UpdatedAt time.Time `json:"updatedAt"`
|
||
}
|
||
|
||
func DefaultRadarrRequestPolicy() RadarrRequestPolicy { return RadarrRequestPolicy{} }
|
||
|
||
func (s *Store) RadarrRequestPolicy(ctx context.Context) (RadarrRequestPolicy, error) {
|
||
var raw []byte
|
||
err := s.pool.QueryRow(ctx, `SELECT value FROM app_settings WHERE key = $1`, RadarrRequestPolicyKey).Scan(&raw)
|
||
if errors.Is(err, pgx.ErrNoRows) {
|
||
return DefaultRadarrRequestPolicy(), nil
|
||
}
|
||
if err != nil {
|
||
return DefaultRadarrRequestPolicy(), fmt.Errorf("store: read Radarr request policy: %w", err)
|
||
}
|
||
var policy RadarrRequestPolicy
|
||
if err := json.Unmarshal(raw, &policy); err != nil {
|
||
return DefaultRadarrRequestPolicy(), fmt.Errorf("store: decode Radarr request policy: %w", err)
|
||
}
|
||
if policy.QualityProfileID < 0 {
|
||
policy.QualityProfileID = 0
|
||
}
|
||
return policy, nil
|
||
}
|
||
|
||
func (s *Store) SetRadarrRequestPolicy(ctx context.Context, policy RadarrRequestPolicy) error {
|
||
if policy.QualityProfileID <= 0 {
|
||
return fmt.Errorf("store: Radarr 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()`,
|
||
RadarrRequestPolicyKey, string(raw))
|
||
if err != nil {
|
||
return fmt.Errorf("store: write Radarr 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
|
||
}
|
||
|
||
// QuietTime is a daily window in the household timezone during which Memby's data plane
|
||
// and background work stand down. The admin control plane and health checks remain live so
|
||
// an operator can change a bad schedule without restarting the container.
|
||
type QuietTime struct {
|
||
Enabled bool `json:"enabled"`
|
||
StartTime string `json:"startTime"`
|
||
EndTime string `json:"endTime"`
|
||
Message string `json:"message"`
|
||
UpdatedAt time.Time `json:"updatedAt"`
|
||
}
|
||
|
||
const DefaultQuietTimeMessage = "Memby is in quiet time. Try again later."
|
||
|
||
func DefaultQuietTime() QuietTime {
|
||
return QuietTime{StartTime: "23:00", EndTime: "07:00", Message: DefaultQuietTimeMessage}
|
||
}
|
||
|
||
// QuietTimeActive reports whether now falls in the configured local-clock window. A
|
||
// window crossing midnight includes late evening and the following morning. Equal or
|
||
// malformed endpoints are treated as inactive; the admin handler refuses both.
|
||
func QuietTimeActive(policy QuietTime, now time.Time, location *time.Location) bool {
|
||
if !policy.Enabled {
|
||
return false
|
||
}
|
||
start, startErr := time.Parse("15:04", policy.StartTime)
|
||
end, endErr := time.Parse("15:04", policy.EndTime)
|
||
if startErr != nil || endErr != nil || policy.StartTime == policy.EndTime {
|
||
return false
|
||
}
|
||
if location == nil {
|
||
location = time.UTC
|
||
}
|
||
local := now.In(location)
|
||
minute := local.Hour()*60 + local.Minute()
|
||
startMinute := start.Hour()*60 + start.Minute()
|
||
endMinute := end.Hour()*60 + end.Minute()
|
||
if startMinute < endMinute {
|
||
return minute >= startMinute && minute < endMinute
|
||
}
|
||
return minute >= startMinute || minute < endMinute
|
||
}
|
||
|
||
func normaliseQuietTime(policy QuietTime) QuietTime {
|
||
defaults := DefaultQuietTime()
|
||
if parsed, err := time.Parse("15:04", strings.TrimSpace(policy.StartTime)); err == nil {
|
||
policy.StartTime = parsed.Format("15:04")
|
||
} else {
|
||
policy.StartTime = defaults.StartTime
|
||
}
|
||
if parsed, err := time.Parse("15:04", strings.TrimSpace(policy.EndTime)); err == nil {
|
||
policy.EndTime = parsed.Format("15:04")
|
||
} else {
|
||
policy.EndTime = defaults.EndTime
|
||
}
|
||
policy.Message = strings.TrimSpace(policy.Message)
|
||
if policy.Message == "" {
|
||
policy.Message = DefaultQuietTimeMessage
|
||
}
|
||
return policy
|
||
}
|
||
|
||
func (s *Store) QuietTime(ctx context.Context) (QuietTime, error) {
|
||
var raw []byte
|
||
err := s.pool.QueryRow(ctx, `SELECT value FROM app_settings WHERE key = $1`, QuietTimeKey).Scan(&raw)
|
||
if errors.Is(err, pgx.ErrNoRows) {
|
||
return DefaultQuietTime(), nil
|
||
}
|
||
if err != nil {
|
||
return DefaultQuietTime(), fmt.Errorf("store: read quiet time: %w", err)
|
||
}
|
||
var policy QuietTime
|
||
if err := json.Unmarshal(raw, &policy); err != nil {
|
||
return DefaultQuietTime(), fmt.Errorf("store: decode quiet time: %w", err)
|
||
}
|
||
return normaliseQuietTime(policy), nil
|
||
}
|
||
|
||
func (s *Store) SetQuietTime(ctx context.Context, policy QuietTime) error {
|
||
policy = normaliseQuietTime(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()`,
|
||
QuietTimeKey, string(raw))
|
||
if err != nil {
|
||
return fmt.Errorf("store: write quiet time: %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
|
||
}
|