Files
silo-server/internal/audiobooks/abs/progress.go
T
9b111649f3 perf+fix(audiobooks): detail page, browse, sessions & scanner (#169)
* perf(catalog): fix audiobook detail N+1 + slow people facets

Audiobook detail pages were slow in proportion to track count (up to 433
files/book). Root causes, found by EXPLAIN ANALYZE on the live DB:

- effectiveAudioSelection ran 3-4 user-store queries (profile, audio pref,
  library pref) per file inside buildPlaybackInfo's loop, though the results
  are invariant across a request. Introduce a request-scoped audioPrefResolver
  that memoizes the store lookups (library prefs keyed by folder); a 400-file
  audiobook now issues each query once instead of per file. Selection logic is
  unchanged (audioPreference returns a copy so the original-language sentinel
  is still resolved per file).
- buildAudiobookExtension ran its four independent related-content queries
  serially; run them concurrently so latency is the slowest, not the sum.
- author/narrator browse facets did a full people-table scan; add a
  (kind, content_id, person_id) index so the facet resolves from an index-only
  scan of just that kind's credits (~112ms -> ~49ms on the live library).

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>

* perf(catalog): cache audiobook author/narrator group browse

The Authors/Narrators audiobook pages were slow on cold load and slow again
after a hard refresh (fast only while the React Query client cache was warm).

Root cause (EXPLAIN ANALYZE on live, 31K-audiobook library): the grouped
browse query is ~234ms/page, there are ~13K distinct authors, and the client
pages through the entire list on every load (sequential 500-row requests). With
no server-side cache each of the ~20 pages re-ran the full aggregation
(COUNT(*) OVER() forces it), so a cold load was ~20x234ms. The client's 60s
staleTime was the only thing making a warm revisit fast; a refresh wiped it.

Fix: AudiobookGroupsCache caches the full sorted group list per (library,
group_by, sort, viewer) for 60s (matching the client staleTime, so no extra
staleness) and serves every page as an in-memory slice — one aggregation per
window instead of one per page, and a refresh is a cache hit. Also raise the
client page size 500->2000 so fewer sequential round-trips are needed now that
a larger page is a cheap slice.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>

* perf(settings): throttle per-request device last_seen upserts

Device-setting reads (HandleGetDeviceSetting, HandleGetEffectiveSettings,
HandleGetEffectiveSubtitleAppearance) each registered the request's device — an
INSERT ... ON CONFLICT upsert of last_seen_at on a single per-device row. A page
that fetches many settings fired hundreds of these concurrently; they serialized
on that row's lock (observed 100-237ms each, ~250 per page load in the slow
query log), taxing every settings fetch.

Throttle device registration to one upsert per (profile, device) per 5 minutes
via an in-process TTL cache, marking the device seen before the upsert so a
concurrent burst collapses to a single write. last_seen_at stays fresh to within
the window. Reads no longer issue a contended write on the hot path.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>

* perf+fix(audiobooks): probe-repair, resume position, cache storm, groups reveal, hot-row + stats index

From the full audiobook code review (EXPLAIN + slow-query trace on live):

- #1 (P0, detail-page killer): NeedsCriticalProbeRepair required video codec/
  resolution/tracks, which audio-only files never have, so PlaybackProbeEnsurer
  re-ran ffprobe per file on every detail/watch load (up to N serial spawns for
  an N-track book) and never converged. Gate video-field checks on the file
  actually having a video stream. TDD.
- #3 (P0): abs session-sync rewound the resume cursor — UpdateProgressPosition
  did an unconditional SET with no monotonic guard, ignored its error, and
  no-op'd when no row existed (first-listen resume lost). Now a finish-preserving
  GREATEST upsert; caller logs failures.
- #4 (P0 perf): progress reports fired every ~10s invalidated all of
  catalogKeys.all → refetched every active browse/detail query incl the 13k
  audiobook group lists. Scope invalidation to the reported item's detail.
- #6 (P1 perf): Authors/Narrators page rendered all ~13k groups + cover images
  at once (main-thread freeze). Incremental reveal: render a capped window, grow
  on scroll via IntersectionObserver.
- #10: throttle abs TouchToken last_seen upsert (one per token per 5min) — same
  hot-row contention class as the device fix.
- #8: index abs_playback_sessions (user_id, profile_id, started_at) for the
  listening-stats aggregations.

Deferred (need contract/validation): listening-time idempotency (client delta-vs-
cumulative), scanner deleted-file reconcile, abs session retention job, abs list-
handler batch fetch, scanner-output P2s (need re-backfill).

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>

* perf(audiobooks): batch-fetch abs list/shelf handlers (kill N+1)

handleSimilarItems, handleItemsInProgress, and handleGetMyProgress called
MediaStore.GetAudiobookByID once per row — up to ~500 single fetches (each a
few queries) on app open. Add GetAudiobooksByIDs (one access-scoped fetch +
people/series hydrated once for the whole set) and look results up from the
returned map, preserving order. Underlying primitives (GetByIDsWithAccess,
hydratePeople/Series) were already batch-capable.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>

* fix(audiobooks): reconcile deleted files on scan + prune session history

#5: ScanAudiobookFolder only ever upserted — deleted/renamed books leaked
media_items/media_files/memberships forever. Mirror the ebook reconcile: collect
seenPaths during the walk, MarkMissing files no longer on disk, then
reconcileLibraryMemberships. Safety mirrors ebooks/video: an inaccessible root
(unmounted source) is skipped entirely, and a walk that saw zero files while the
DB has rows only reconciles after operator cleanup confirmation
(ebookEmptyCleanupAllowed) — so a flapping mount can't wipe the catalog. Soft
mark only; the existing grace-period purge hard-deletes later. Reconcile runs
only on a fully-completed (non-cancelled) scan. (#9 coarse case already handled:
audiobookFolderShouldSkip skips unchanged folders; per-file reuse deferred.)

#8-retention: abs_playback_sessions grew unbounded (one row per play-start, never
deleted) and fed every listening-stats scan. Add an hourly sweep in
SessionCleaner: close abandoned open sessions (no /close, stopped syncing >24h)
and delete closed sessions older than 90 days. Mirrors the recommendation_cache /
missing-files prune pattern.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>

* fix(audiobooks): address max-effort code-review findings

From /code-review max on the pre-PR diff:
- DATA RACE (P0): SessionCleaner.lastABSSessionPrune is read+written by both the
  15s ticker goroutine and the shutdown-path CleanStale call (main.go defers
  Stop() to after that call). Guard the prune-due gate with a mutex. (CleanStale
  was stateless before this branch, so concurrent calls were previously safe.)
- ScanAudiobookFolder hardcoded fullScan=true into the empty-walk cleanup guard,
  but it's also called from ScanSubtree (incremental scans). An empty subtree
  scan would wrongly consume the operator's one-shot empty-cleanup allowance and
  warn. Thread a real fullScan flag (true from ScanFolder, false from the two
  subtree call sites), mirroring the ebook path.
- Revert UpdateProgressPosition to UPDATE-only (drop the INSERT-on-missing):
  keep the monotonic GREATEST + finish guard that fixes the resume rewind, but
  restore the no-op-on-missing contract so a stray sync tick can't resurrect
  just-cleared progress or create a zero-duration continue-listening row.
- Clamp the audiobook-groups handler limit (paging moved into the cache, leaving
  the old 500/page bound stranded); also gofmt the Scanner struct.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>

* fix(audiobooks): address review feedback for scanner and stats

* fix(audiobooks): address review feedback

* fix(audiobooks): retry failed session prune

---------

Co-authored-by: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
Co-authored-by: Quick <31828688+Quick104@users.noreply.github.com>
2026-06-17 09:51:43 -04:00

457 lines
17 KiB
Go

package abs
import (
"context"
"encoding/json"
"log/slog"
"net/http"
"time"
"github.com/go-chi/chi/v5"
)
// ---------------------------------------------------------------------------
// Interfaces
// ---------------------------------------------------------------------------
// ProgressStore is the narrow slice of user_watch_progress access the ABS
// handlers need. Implemented by ABSProgressStore in
// internal/audiobooks/abs_progress_store.go.
type ProgressStore interface {
// GetProgress returns the progress row for (userID, profileID, contentID).
// Returns (nil, nil) when no row exists (not an error).
GetProgress(ctx context.Context, userID, profileID, contentID string) (*ProgressRow, error)
// ListProgressForAudiobooks returns all progress rows for (userID, profileID)
// that correspond to audiobooks (media_items.type = 'audiobook').
// Capped at limit rows (most-recently-updated first).
ListProgressForAudiobooks(ctx context.Context, userID, profileID string, limit int) ([]ProgressRow, error)
// UpsertProgress writes a progress row. Fields not set in the body
// (currentTime/duration/isFinished/progress) should be merged by the
// caller before invoking this.
UpsertProgress(ctx context.Context, row ProgressRow) error
// UpdateProgressPosition updates only the position_seconds field for
// (userID, profileID, contentID). Used by session sync to avoid overwriting
// is_finished / progress_pct that the user set explicitly.
UpdateProgressPosition(ctx context.Context, userID, profileID, contentID string, positionSeconds float64) error
// SetHideFromContinue toggles the hide_from_continue flag on a
// progress row. Idempotent — succeeds even when no row matches.
SetHideFromContinue(ctx context.Context, userID, profileID, contentID string, hide bool) error
// DeleteProgress removes the progress row for (userID, profileID, contentID).
// Idempotent — succeeds even when no row matches. Used by the ABS
// "Reset Progress" affordance: DELETE /api/me/progress/{libraryItemId}.
DeleteProgress(ctx context.Context, userID, profileID, contentID string) error
}
// ABSPlaybackSessionStore tracks the active /abs/api/items/{id}/play sessions
// for per-session listening-time accounting (migration 143).
// Implemented by ABSPlaybackSessionStore in
// internal/audiobooks/abs_playback_session_store.go.
type ABSPlaybackSessionStore interface {
// InsertPlaybackSession creates the session row at play-start.
InsertPlaybackSession(ctx context.Context, sess ABSPlaybackSession) error
// GetPlaybackSession fetches a session by its ULID. Returns ErrNotFound
// when absent.
GetPlaybackSession(ctx context.Context, id string) (ABSPlaybackSession, error)
// SyncPlaybackSession updates position + accumulated listening time.
SyncPlaybackSession(ctx context.Context, id string, currentPositionSeconds float64, timeListeningSeconds int) error
// ClosePlaybackSession sets closed_at to now().
ClosePlaybackSession(ctx context.Context, id string) error
// CloseOpenSessionsForPrincipal closes all active sessions for a user
// profile, used when logout revokes that profile's tokens.
CloseOpenSessionsForPrincipal(ctx context.Context, userID, profileID string) error
// AggregateStats returns aggregated listening stats for (user, profile).
AggregateStats(ctx context.Context, userID, profileID string) (Stats, error)
// ListClosedSessions returns paginated closed sessions for (user, profile)
// ordered by started_at DESC. Returns (rows, totalRowCount, error).
ListClosedSessions(ctx context.Context, userID, profileID string, limit, offset int) ([]ABSPlaybackSession, int, error)
}
// Stats is the aggregated /me/listening-stats response shape.
type Stats struct {
TotalTime int // seconds
Items int // distinct content_ids listened to
Days []DayStat // recent days (most-recent first)
DayOfWeek [7]int // index 0 = Sunday
Monthly []MonthStat
}
type DayStat struct {
Date string
Seconds int
}
type MonthStat struct {
Month string
Seconds int
}
// ProgressRow is the in-memory representation of a user_watch_progress row
// as the ABS handlers use it. Intentionally narrow — only the fields the ABS
// wire format cares about.
type ProgressRow struct {
UserID string
ProfileID string
ContentID string
CurrentSeconds float64
DurationSeconds float64
ProgressPct float64
IsFinished bool
UpdatedAt time.Time
}
// ABSPlaybackSession is the in-memory representation of an abs_playback_sessions row.
type ABSPlaybackSession struct {
ID string
UserID string
ProfileID string
ContentID string
MediaFileID *int
TimeListeningSeconds int
CurrentPositionSeconds float64
StartedAt time.Time
LastSyncAt time.Time
ClosedAt *time.Time
}
// ---------------------------------------------------------------------------
// Handlers
// ---------------------------------------------------------------------------
// handleGetMyProgress — GET /abs/api/me/progress
// Lists all progress rows for the caller that belong to audiobooks.
// The ABS mobile client reads this on startup to seed resume positions.
func (h *Handler) handleGetMyProgress(w http.ResponseWriter, r *http.Request) {
a, ok := absAuthFrom(r)
if !ok || a.UserID == "" {
http.Error(w, "unauthorized", http.StatusUnauthorized)
return
}
if h.deps.ProgressStore == nil {
writeJSON(w, http.StatusOK, map[string]any{"mediaProgress": []any{}})
return
}
rows, err := h.deps.ProgressStore.ListProgressForAudiobooks(r.Context(), a.UserID, a.ProfileID, 500)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
access, err := h.accessFilterForAuth(r.Context(), a)
if err != nil {
http.Error(w, "resolve access: "+err.Error(), http.StatusForbidden)
return
}
ids := make([]string, 0, len(rows))
for _, p := range rows {
ids = append(ids, p.ContentID)
}
// One batch fetch acts as the access/existence gate (the item itself isn't
// rendered here), instead of one query per progress row.
byID, err := h.deps.MediaStore.GetAudiobooksByIDs(r.Context(), ids, access)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
out := make([]map[string]any, 0, len(rows))
for _, p := range rows {
if byID[p.ContentID] == nil {
continue
}
out = append(out, progressRowToABS(p))
}
writeJSON(w, http.StatusOK, map[string]any{"mediaProgress": out})
}
// handleGetItemProgress — GET /abs/api/me/progress/{libraryItemId}
// Returns the progress row for one item. 404 when no progress exists.
func (h *Handler) handleGetItemProgress(w http.ResponseWriter, r *http.Request) {
a, ok := absAuthFrom(r)
if !ok || a.UserID == "" {
http.Error(w, "unauthorized", http.StatusUnauthorized)
return
}
contentID := chi.URLParam(r, "libraryItemId")
if h.deps.ProgressStore == nil {
http.Error(w, "progress not found", http.StatusNotFound)
return
}
access, err := h.accessFilterForAuth(r.Context(), a)
if err != nil {
http.Error(w, "resolve access: "+err.Error(), http.StatusForbidden)
return
}
item, err := h.deps.MediaStore.GetAudiobookByID(r.Context(), contentID, access)
if err != nil || item == nil {
http.Error(w, "progress not found", http.StatusNotFound)
return
}
p, err := h.deps.ProgressStore.GetProgress(r.Context(), a.UserID, a.ProfileID, contentID)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
if p == nil {
http.Error(w, "progress not found", http.StatusNotFound)
return
}
writeJSON(w, http.StatusOK, progressRowToABS(*p))
}
// progressBody is the JSON body for POST/PATCH /api/me/progress/{libraryItemId}.
// All fields are optional — only present fields update the row (PATCH semantics).
//
// EbookProgress / EbookLocation are emitted by the ABS clients (AudioBooth's
// BooksService writes them on every page turn). silo's audiobook-first catalog
// doesn't yet persist ebook position; the fields are accepted-and-ignored so
// the client write succeeds and the user isn't shown a sync error. They will
// flow into a dedicated ebook progress column when the ebook scanner lands.
type progressBody struct {
CurrentTime *float64 `json:"currentTime"`
Duration *float64 `json:"duration"`
IsFinished *bool `json:"isFinished"`
Progress *float64 `json:"progress"`
EbookProgress *float64 `json:"ebookProgress"`
EbookLocation *string `json:"ebookLocation"`
}
// handleSetItemProgress — POST /abs/api/me/progress/{libraryItemId}
// UPSERTs the progress row. Merges body fields over any existing row so a
// partial body (only currentTime) doesn't reset duration/isFinished.
//
// This matches sub-plan 3's HandleReportAudiobookProgress in intent but uses
// the ABS wire format and calls ProgressStore directly so the two code paths
// don't need a shared helper — their thresholds/semantics differ enough that
// keeping them separate is cleaner.
func (h *Handler) handleSetItemProgress(w http.ResponseWriter, r *http.Request) {
a, ok := absAuthFrom(r)
if !ok || a.UserID == "" {
http.Error(w, "unauthorized", http.StatusUnauthorized)
return
}
contentID := chi.URLParam(r, "libraryItemId")
var body progressBody
if err := json.NewDecoder(r.Body).Decode(&body); err != nil {
http.Error(w, "invalid body", http.StatusBadRequest)
return
}
if h.deps.ProgressStore == nil {
http.Error(w, "progress store unavailable", http.StatusServiceUnavailable)
return
}
access, err := h.accessFilterForAuth(r.Context(), a)
if err != nil {
http.Error(w, "resolve access: "+err.Error(), http.StatusForbidden)
return
}
item, err := h.deps.MediaStore.GetAudiobookByID(r.Context(), contentID, access)
if err != nil || item == nil {
http.Error(w, "item not found", http.StatusNotFound)
return
}
// Read existing row to merge (PATCH semantics).
var cur ProgressRow
if existing, err := h.deps.ProgressStore.GetProgress(r.Context(), a.UserID, a.ProfileID, contentID); err == nil && existing != nil {
cur = *existing
}
next := ProgressRow{
UserID: a.UserID,
ProfileID: a.ProfileID,
ContentID: contentID,
CurrentSeconds: cur.CurrentSeconds,
DurationSeconds: cur.DurationSeconds,
ProgressPct: cur.ProgressPct,
IsFinished: cur.IsFinished,
UpdatedAt: time.Now(),
}
if body.CurrentTime != nil {
next.CurrentSeconds = *body.CurrentTime
}
if body.Duration != nil {
next.DurationSeconds = *body.Duration
}
if body.Progress != nil {
next.ProgressPct = *body.Progress
}
if body.IsFinished != nil {
next.IsFinished = *body.IsFinished
}
if err := h.deps.ProgressStore.UpsertProgress(r.Context(), next); err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
updated, err := h.deps.ProgressStore.GetProgress(r.Context(), a.UserID, a.ProfileID, contentID)
if err != nil || updated == nil {
// Best-effort: return the in-memory merged row rather than failing.
h.publish(a.UserID, "user_item_progress_updated", map[string]any{"data": progressRowToABS(next)})
writeJSON(w, http.StatusOK, progressRowToABS(next))
return
}
payload := progressRowToABS(*updated)
h.publish(a.UserID, "user_item_progress_updated", map[string]any{"data": payload})
writeJSON(w, http.StatusOK, payload)
}
// syncPayload is the JSON body for PATCH /abs/api/session/{sid}/sync.
type syncPayload struct {
CurrentTime float64 `json:"currentTime"`
// Accept both spellings: real ABS clients send "timeListening"; an older
// silo-plugin draft used "timeListened". UnmarshalJSON merges them.
TimeListening float64 `json:"timeListening"`
TimeListened float64 `json:"timeListened"`
}
// timeDelta returns the accumulated listening time from whichever spelling
// the client used. Both fields are tried; non-zero wins.
func (p syncPayload) timeDelta() float64 {
if p.TimeListening != 0 {
return p.TimeListening
}
return p.TimeListened
}
// handleSessionSync — PATCH /abs/api/session/{sid}/sync
// Heartbeat endpoint the ABS mobile client calls every ~10 s during playback.
// Updates current position in user_watch_progress and accumulates
// time_listening_seconds in abs_playback_sessions.
//
// IDOR guard: the session must belong to the calling user (404 otherwise
// so session existence isn't leaked to other users).
//
// Uses UpdateProgressPosition (not UpsertProgress) to avoid overwriting
// is_finished / progress_pct that the user set explicitly — a sync tick
// that arrives after the user marks a book finished must not un-finish it.
func (h *Handler) handleSessionSync(w http.ResponseWriter, r *http.Request) {
a, ok := absAuthFrom(r)
if !ok {
http.Error(w, "unauthorized", http.StatusUnauthorized)
return
}
sid := chi.URLParam(r, "sid")
var p syncPayload
if err := json.NewDecoder(r.Body).Decode(&p); err != nil {
http.Error(w, "invalid body", http.StatusBadRequest)
return
}
if h.deps.PlaybackSessionStore == nil {
// No session store wired yet — accept the sync but return success
// rather than blocking the player.
writeJSON(w, http.StatusOK, map[string]any{"ok": true})
return
}
// Ownership gate.
sess, err := h.deps.PlaybackSessionStore.GetPlaybackSession(r.Context(), sid)
if err != nil || !sameABSPrincipal(a, sess.UserID, sess.ProfileID) {
http.Error(w, "session not found", http.StatusNotFound)
return
}
access, err := h.accessFilterForAuth(r.Context(), a)
if err != nil {
http.Error(w, "resolve access: "+err.Error(), http.StatusForbidden)
return
}
item, err := h.deps.MediaStore.GetAudiobookByID(r.Context(), sess.ContentID, access)
if err != nil || item == nil {
http.Error(w, "session not found", http.StatusNotFound)
return
}
// Accumulate listening time and update position in abs_playback_sessions.
if err := h.deps.PlaybackSessionStore.SyncPlaybackSession(
r.Context(), sid, p.CurrentTime, int(p.timeDelta()),
); err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
// Update position in user_watch_progress. Must NOT be a full upsert —
// see comment in handleSetItemProgress re: not overwriting is_finished.
if h.deps.ProgressStore != nil {
if err := h.deps.ProgressStore.UpdateProgressPosition(
r.Context(), a.UserID, a.ProfileID, sess.ContentID, p.CurrentTime,
); err != nil {
slog.Warn("abs session sync: update progress position failed",
"session_id", sid, "content_id", sess.ContentID, "error", err)
}
}
// Realtime push to other connected clients.
h.publish(a.UserID, "user_item_progress_updated", map[string]any{
"data": map[string]any{
"libraryItemId": sess.ContentID,
"currentTime": p.CurrentTime,
"sessionId": sid,
},
})
h.publish(a.UserID, "user_session_updated", map[string]any{
"id": sid,
"libraryItemId": sess.ContentID,
"currentTime": p.CurrentTime,
"timeListening": p.timeDelta(),
})
writeJSON(w, http.StatusOK, map[string]any{"ok": true})
}
// handleSessionClose — POST /abs/api/session/{sid}/close
// Finalises a play session. Sets closed_at on the abs_playback_sessions row.
// Only the owning user may close their session (IDOR guard).
func (h *Handler) handleSessionClose(w http.ResponseWriter, r *http.Request) {
a, ok := absAuthFrom(r)
if !ok {
http.Error(w, "unauthorized", http.StatusUnauthorized)
return
}
sid := chi.URLParam(r, "sid")
if h.deps.PlaybackSessionStore == nil {
// No store wired — accept close gracefully.
w.WriteHeader(http.StatusNoContent)
return
}
// Ownership gate.
sess, err := h.deps.PlaybackSessionStore.GetPlaybackSession(r.Context(), sid)
if err != nil || !sameABSPrincipal(a, sess.UserID, sess.ProfileID) {
http.Error(w, "session not found", http.StatusNotFound)
return
}
if err := h.deps.PlaybackSessionStore.ClosePlaybackSession(r.Context(), sid); err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
h.publish(a.UserID, "user_session_closed", map[string]any{
"id": sid,
"libraryItemId": sess.ContentID,
})
w.WriteHeader(http.StatusNoContent)
}
// ---------------------------------------------------------------------------
// Serialisation helpers
// ---------------------------------------------------------------------------
// progressRowToABS shapes a ProgressRow into the ABS /me/progress wire format.
// The `id` field uses the real-ABS convention of "<userID>-<libraryItemId>".
func progressRowToABS(p ProgressRow) map[string]any {
lastMs := p.UpdatedAt.UnixMilli()
out := map[string]any{
"id": p.UserID + "-" + p.ContentID,
"libraryItemId": p.ContentID,
"mediaItemId": p.ContentID,
"currentTime": p.CurrentSeconds,
"duration": p.DurationSeconds,
"isFinished": p.IsFinished,
"progress": p.ProgressPct,
"startedAt": lastMs,
"finishedAt": nil,
"lastUpdate": lastMs,
}
if p.IsFinished {
out["finishedAt"] = lastMs
}
return out
}