Files
memby/server/internal/api/home.go
T

448 lines
14 KiB
Go
Raw Normal View History

package api
import (
2026-07-29 15:26:27 +12:00
"context"
"encoding/json"
"math/rand/v2"
"net/http"
"net/url"
"strconv"
2026-07-29 15:26:27 +12:00
"strings"
"sync"
2026-07-29 15:26:27 +12:00
"time"
2026-07-27 21:06:51 +12:00
"github.com/ponzischeme89/memby/server/internal/appupdate"
"github.com/ponzischeme89/memby/server/internal/cache"
"github.com/ponzischeme89/memby/server/internal/emby"
"github.com/ponzischeme89/memby/server/internal/recommend"
"github.com/ponzischeme89/memby/server/internal/store"
)
// Field sets mirror what each TV row actually renders. Asking Emby for less is the
// single biggest lever on home-screen latency, so keep these tight.
const (
fieldsContinue = "RunTimeTicks,SeriesName,PrimaryImageAspectRatio"
fieldsRow = "ProductionYear,RunTimeTicks,PrimaryImageAspectRatio"
2026-07-29 15:26:27 +12:00
fieldsDetail = "Overview,Genres,MediaStreams,People,ProductionYear,OfficialRating,CommunityRating,RunTimeTicks,PrimaryImageAspectRatio"
fieldsScreensaver = "Overview,Taglines,Genres,ProductionYear,CommunityRating,Studios,OfficialRating,RunTimeTicks"
rowImageTypes = "Backdrop,Primary,Logo"
screensaverImageTypes = "Backdrop,Logo"
)
type homeResponse struct {
// Rows is the home screen as the server wants it drawn: order, titles and kinds all
// decided here, so a new row (a recommendation strip, a seasonal collection) ships
// without touching the TV app. The client renders whatever arrives.
Rows []recommend.Row `json:"rows"`
2026-07-29 15:26:27 +12:00
// The fixed rows are also sent flat. They are what the client caches for an
// instant cold start, and what the direct-to-Emby path still produces.
ContinueWatching []json.RawMessage `json:"continueWatching"`
NextUp []json.RawMessage `json:"nextUp"`
Favorites []json.RawMessage `json:"favorites"`
LatestMovies []json.RawMessage `json:"latestMovies"`
// Partial is true when at least one row failed upstream. The TV shows what arrived
// and flags a refresh error rather than blanking the screen.
Partial bool `json:"partial"`
// Deliberately no update verdict here: this payload is cached per user, and the
// verdict depends on the *client's* version, so a cached body would hand one TV's
// answer to another running a different build. The client asks /v1/update instead.
}
// handleHome answers the entire launcher in one round trip.
func (s *Server) handleHome(w http.ResponseWriter, r *http.Request, sess store.Session) {
ctx := r.Context()
limit := queryInt(r, "limit", 24, 100)
key := cache.UserKey(sess.EmbyUserID, "home:"+itoa(limit))
if raw, err := s.cache.Get(ctx, key); err == nil {
w.Header().Set("X-Memby-Cache", "hit")
writeRaw(w, http.StatusOK, raw)
return
}
cred := credentials(sess)
var (
2026-07-29 15:26:27 +12:00
mu sync.Mutex
failures int
out homeResponse
sonarrRow *recommend.Row
forYouRow *recommend.Row
forYouRowStale bool
wg sync.WaitGroup
)
run := func(dest *[]json.RawMessage, fetch func() (*emby.ItemsResult, error)) {
wg.Add(1)
go func() {
defer wg.Done()
result, err := fetch()
mu.Lock()
defer mu.Unlock()
if err != nil {
failures++
s.log.Warn("home row failed", "error", err)
return
}
*dest = result.Items
}()
}
run(&out.ContinueWatching, func() (*emby.ItemsResult, error) {
2026-07-29 15:26:27 +12:00
return s.emby.ResumeItems(ctx, cred, rowParams(url.Values{
"Recursive": {"true"},
"MediaTypes": {"Video"},
"Limit": {itoa(limit)},
}, fieldsContinue))
})
run(&out.Favorites, func() (*emby.ItemsResult, error) {
return s.emby.Items(ctx, cred, rowParams(url.Values{
"Filters": {"IsFavorite"},
"IncludeItemTypes": {"Movie,Series"},
"Recursive": {"true"},
"SortBy": {"SortName"},
"SortOrder": {"Ascending"},
"Limit": {itoa(limit)},
}, fieldsRow))
})
2026-07-29 15:26:27 +12:00
run(&out.NextUp, func() (*emby.ItemsResult, error) {
return s.emby.NextUp(ctx, cred, rowParams(url.Values{
"Limit": {itoa(limit)},
}, fieldsContinue))
})
run(&out.LatestMovies, func() (*emby.ItemsResult, error) {
return s.emby.Items(ctx, cred, rowParams(url.Values{
"IncludeItemTypes": {"Movie"},
"Recursive": {"true"},
"SortBy": {"DateCreated"},
"SortOrder": {"Descending"},
"Limit": {itoa(limit)},
}, fieldsRow))
})
2026-07-27 21:06:51 +12:00
if s.sonarr != nil && supportsSonarrSchedule(r) {
wg.Add(1)
go func() {
defer wg.Done()
row, err := s.sonarrAiringTodayRow(ctx)
if err != nil {
s.log.Warn("sonarr calendar row failed", "error", err)
return
}
mu.Lock()
sonarrRow = row
mu.Unlock()
}()
}
2026-07-29 15:26:27 +12:00
if s.forYou != nil {
// The prepared pool is one indexed PostgreSQL read. It runs beside the Emby
// calls and deliberately has no live-engine fallback, so Home can never inherit
// Tracearr fan-out or recommendation rebuild latency.
wg.Add(1)
go func() {
defer wg.Done()
location := s.cfg.SonarrLocation
if location == nil {
location = time.UTC
}
window := homeForYouWindowAt(time.Now().In(location))
prepared, hit, stale, err := s.forYou.PreparedRows(ctx, sess, window.Minutes)
if err != nil {
s.log.Warn("prepared Home For You row failed", "user", sess.EmbyUserID, "error", err)
return
}
if !hit || len(prepared) == 0 {
return
}
rowIndex := -1
for i := range prepared {
if prepared[i].ID == "for-you:picks" {
rowIndex = i
break
}
}
if rowIndex < 0 {
return
}
row := prepared[rowIndex]
row.ID = "for-you:home:" + window.ID
row.Title = window.Title
if len(row.Items) > 12 {
row.Items = row.Items[:12]
}
mu.Lock()
forYouRow = &row
forYouRowStale = stale
mu.Unlock()
}()
}
wg.Wait()
if failures == 4 {
writeError(w, http.StatusBadGateway, "could not reach the emby server")
return
}
out.Partial = failures > 0
ensureSlices(&out)
// Recommendations are read from their own long-lived cache. A miss means this
// response ships without them and a rebuild starts in the background — the home
// screen never waits on the engine.
recommendations := s.cachedRecommendations(ctx, sess.EmbyUserID)
if recommendations == nil {
s.refreshRecommendationsInBackground(sess)
}
2026-07-27 21:06:51 +12:00
rows := baseRows(out)
2026-07-29 15:26:27 +12:00
nearContinue := make([]recommend.Row, 0, 2)
if forYouRow != nil {
nearContinue = append(nearContinue, *forYouRow)
if forYouRowStale {
s.forYou.MarkDirty(context.WithoutCancel(ctx), sess)
s.forYou.RefreshAsync(sess, false)
}
}
2026-07-27 21:06:51 +12:00
if sonarrRow != nil {
2026-07-29 15:26:27 +12:00
nearContinue = append(nearContinue, *sonarrRow)
}
if len(nearContinue) > 0 {
// Personalised discovery and today's schedule are most useful immediately
// after Continue Watching, before the broader library collections.
rows = append(rows[:1], append(nearContinue, rows[1:]...)...)
2026-07-27 21:06:51 +12:00
}
out.Rows = append(rows, recommendations...)
body, err := json.Marshal(out)
if err != nil {
s.log.Error("home encode failed", "error", err)
writeError(w, http.StatusInternalServerError, "could not build the home payload")
return
}
// A partial payload is served but never cached: the next request should retry.
if !out.Partial {
if err := s.cache.Set(ctx, key, body, s.cfg.HomeTTL); err != nil {
s.log.Warn("home cache write failed", "error", err)
}
}
w.Header().Set("X-Memby-Cache", "miss")
writeRaw(w, http.StatusOK, body)
}
2026-07-27 21:06:51 +12:00
// Older clients render unknown rows but do not understand MembyPlayable=false, so they
// could try to send a synthetic Sonarr id to Emby. The feature ships with 0.1.54.
func supportsSonarrSchedule(r *http.Request) bool {
version := clientVersion(r)
return version != "" && appupdate.CompareVersions(version, "0.1.54") >= 0
}
// handleScreensaver serves the backdrop pool. The pool is cached and shuffled per
// request, so the Dream still looks random without re-querying Emby every few seconds.
func (s *Server) handleScreensaver(w http.ResponseWriter, r *http.Request, sess store.Session) {
ctx := r.Context()
limit := queryInt(r, "limit", 200, 400)
key := cache.UserKey(sess.EmbyUserID, "screensaver:"+itoa(limit))
var items []json.RawMessage
if raw, err := s.cache.Get(ctx, key); err == nil {
_ = json.Unmarshal(raw, &items)
}
if items == nil {
result, err := s.emby.Items(ctx, credentials(sess), url.Values{
"IncludeItemTypes": {"Movie,Series"},
"Recursive": {"true"},
"Filters": {"HasBackdrop"},
"SortBy": {"Random"},
"Limit": {itoa(limit)},
"Fields": {fieldsScreensaver},
"ImageTypeLimit": {"1"},
"EnableImageTypes": {screensaverImageTypes},
"EnableUserData": {"true"},
})
if err != nil {
s.writeUpstreamError(w, err, "could not load screensaver items")
return
}
items = result.Items
if raw, err := json.Marshal(items); err == nil {
_ = s.cache.Set(ctx, key, raw, s.cfg.ScreensaverTTL)
}
}
shuffled := make([]json.RawMessage, len(items))
copy(shuffled, items)
rand.Shuffle(len(shuffled), func(i, j int) { shuffled[i], shuffled[j] = shuffled[j], shuffled[i] })
writeJSON(w, http.StatusOK, map[string]any{"items": shuffled})
}
func (s *Server) handleSearch(w http.ResponseWriter, r *http.Request, sess store.Session) {
ctx := r.Context()
term := r.URL.Query().Get("q")
if len(term) < 2 {
writeJSON(w, http.StatusOK, map[string]any{"items": []json.RawMessage{}})
return
}
limit := queryInt(r, "limit", 40, 100)
key := cache.UserKey(sess.EmbyUserID, "search:"+itoa(limit)+":"+term)
if raw, err := s.cache.Get(ctx, key); err == nil {
w.Header().Set("X-Memby-Cache", "hit")
writeRaw(w, http.StatusOK, raw)
return
}
// The imported library answers search from Postgres, which is the difference
// between "instant" and "one round trip to Emby per keystroke". An empty result
// falls through to Emby, so search still works before the first import completes.
items, err := s.store.SearchLibrary(ctx, term, limit)
if err != nil {
s.log.Warn("library search failed; falling back to emby", "error", err)
items = nil
}
if len(items) == 0 {
result, err := s.emby.Items(ctx, credentials(sess), rowParams(url.Values{
"SearchTerm": {term},
"IncludeItemTypes": {"Movie,Series,Episode"},
"Recursive": {"true"},
"Limit": {itoa(limit)},
}, fieldsRow))
if err != nil {
s.writeUpstreamError(w, err, "search failed")
return
}
items = result.Items
}
body, err := json.Marshal(map[string]any{"items": nonNil(items)})
if err != nil {
writeError(w, http.StatusInternalServerError, "could not build search results")
return
}
if err := s.cache.Set(ctx, key, body, s.cfg.SearchTTL); err != nil {
s.log.Warn("search cache write failed", "error", err)
}
w.Header().Set("X-Memby-Cache", "miss")
writeRaw(w, http.StatusOK, body)
}
2026-07-29 15:26:27 +12:00
type searchHistoryRequest struct {
Query string `json:"query"`
}
type searchHistoryResponse struct {
Queries []string `json:"queries"`
}
const (
recentSearchDays = 30
recentSearchLimit = 10
)
func (s *Server) handleRecentSearches(w http.ResponseWriter, r *http.Request, sess store.Session) {
if s.store == nil {
writeError(w, http.StatusInternalServerError, "could not load recent searches")
return
}
since := time.Now().Add(-recentSearchDays * 24 * time.Hour)
queries, err := s.store.RecentSearches(
r.Context(),
sess.EmbyUserID,
since,
recentSearchLimit,
)
if err != nil {
writeError(w, http.StatusInternalServerError, "could not load recent searches")
return
}
if queries == nil {
queries = []string{}
}
writeJSON(w, http.StatusOK, searchHistoryResponse{Queries: queries})
}
func (s *Server) handleSearchHistory(w http.ResponseWriter, r *http.Request, sess store.Session) {
var req searchHistoryRequest
if err := json.NewDecoder(http.MaxBytesReader(w, r.Body, 2<<10)).Decode(&req); err != nil {
writeError(w, http.StatusBadRequest, "invalid search history request")
return
}
query := strings.TrimSpace(req.Query)
if len([]rune(query)) < 2 || len([]rune(query)) > 200 {
writeError(w, http.StatusBadRequest, "search query length is invalid")
return
}
if s.store == nil || s.store.RecordSearch(r.Context(), sess.EmbyUserID, query) != nil {
writeError(w, http.StatusInternalServerError, "could not record search")
return
}
w.WriteHeader(http.StatusNoContent)
}
// baseRows describes the three fixed rows.
//
// Titles live here rather than in the app so wording can change server-side. They are
// emitted even when empty: the client draws its own "Nothing in progress" message, and a
// row that vanishes as you watch things is more jarring than an empty one.
func baseRows(h homeResponse) []recommend.Row {
return []recommend.Row{
{ID: "continue", Title: "Continue Watching", Kind: "continue", Items: h.ContinueWatching},
{ID: "next-up", Title: "Next Up", Kind: "nextup", Items: h.NextUp},
{ID: "favorites", Title: "Favourites", Kind: "favorites", Items: h.Favorites},
2026-07-29 15:26:27 +12:00
{ID: "latest-movies", Title: "Recent New Releases", Kind: "latest", Items: h.LatestMovies},
}
}
type homeForYouWindow struct {
ID string
Title string
Minutes int
}
// homeForYouWindowAt keeps Home useful without asking the viewer for a duration.
// These deliberately broad windows suit a household TV: short before lunch, an
// episode-sized pick in the afternoon/late evening, and film headroom at night.
func homeForYouWindowAt(now time.Time) homeForYouWindow {
switch hour := now.Hour(); {
case hour >= 5 && hour < 12:
return homeForYouWindow{ID: "morning", Title: "Quick morning picks for you", Minutes: 30}
case hour >= 12 && hour < 17:
return homeForYouWindow{ID: "afternoon", Title: "An hour for your afternoon", Minutes: 60}
case hour >= 17 && hour < 23:
return homeForYouWindow{ID: "evening", Title: "Tonight's picks for you", Minutes: 120}
default:
return homeForYouWindow{ID: "late-night", Title: "Late-night picks for you", Minutes: 60}
}
}
// rowParams applies the query shape every list endpoint shares.
func rowParams(params url.Values, fields string) url.Values {
params.Set("Fields", fields)
params.Set("ImageTypeLimit", "1")
params.Set("EnableImages", "true")
params.Set("EnableImageTypes", rowImageTypes)
params.Set("EnableTotalRecordCount", "false")
params.Set("EnableUserData", "true")
return params
}
// ensureSlices keeps empty rows as [] rather than null, so kotlinx.serialization can
// decode them into non-null List fields.
func ensureSlices(h *homeResponse) {
h.ContinueWatching = nonNil(h.ContinueWatching)
h.NextUp = nonNil(h.NextUp)
h.Favorites = nonNil(h.Favorites)
h.LatestMovies = nonNil(h.LatestMovies)
}
func nonNil(items []json.RawMessage) []json.RawMessage {
if items == nil {
return []json.RawMessage{}
}
return items
}
func itoa(v int) string { return strconv.Itoa(v) }