SPB Git

Repository Public

titles.ts 18.7 KB 220 lines typescript

1import { all, get, getSetting, now, run } from "./db";2import { normalize, tokenScore } from "./catalog";3import { sign } from "./auth";45export interface Title {6  id: number; kind: "movie" | "series"; title: string; original: string | null; year: number | null; runtime: number | null; genres: string[]; languages: string[]; countries: string[];7  poster: string | null; backdrop: string | null; documentary: boolean; animation: boolean; short: boolean; rights: "pd" | "cc" | "personal" | "official" | "provider"; source: string; library: boolean; addedAt: number;8  episodes: number; fav?: boolean; progress?: { position: number; duration: number | null; completed: boolean; mediaId: number; label?: string } | null;9}10interface Indexed extends Title { norm: string; words: string[]; alt: string[]; people: string; plays: number }1112type G = typeof globalThis & { __sptvTitles?: { version: string; checkedAt: number; list: Indexed[]; byId: Map<number, Indexed> } };1314function build(version: string) {15  // Only titles that really have a playable source are ever listed.16  const rows = all<{ id: number; kind: "movie" | "series"; title: string; original_title: string | null; year: number | null; runtime_sec: number | null; genres: string; languages: string; countries: string; poster: string | null; backdrop: string | null;17    is_documentary: number; is_animation: number; is_short: number; rights_status: "pd" | "cc" | "personal" | "official" | "provider"; source_name: string; origin: string; added_at: number; directors: string; cast_names: string; n: number; thumb: number | null; plays: number | null }>(`18    SELECT t.*, COUNT(m.id) n, MIN(CASE WHEN m.kind = 'file' THEN m.id END) thumb, (SELECT SUM(p.plays) FROM progress p JOIN media pm ON pm.id = p.media_id WHERE pm.title_id = t.id) plays19    FROM titles t JOIN media m ON m.title_id = t.id WHERE t.active = 1 GROUP BY t.id`);20  const list: Indexed[] = rows.map((r) => {21    const norm = normalize(r.title);22    return {23      id: r.id, kind: r.kind, title: r.title, original: r.original_title, year: r.year, runtime: r.runtime_sec, genres: r.genres ? r.genres.split(";") : [], languages: r.languages ? r.languages.split(";") : [], countries: r.countries ? r.countries.split(";") : [],24      poster: r.poster ?? (r.thumb ? `/api/media/${r.thumb}/thumb` : null), backdrop: r.backdrop, documentary: !!r.is_documentary, animation: !!r.is_animation, short: !!r.is_short, rights: r.rights_status, source: r.source_name, library: r.origin === "library",25      addedAt: r.added_at, episodes: r.kind === "series" ? r.n : 0, norm, words: norm.split(" "), alt: r.original_title ? [normalize(r.original_title)] : [], people: normalize(`${r.directors} ${r.cast_names}`), plays: r.plays ?? 0,26    };27  });28  list.sort((a, b) => a.title.localeCompare(b.title, "fr"));29  return { version, checkedAt: now(), list, byId: new Map(list.map((t) => [t.id, t])) };30}31export function tindex() {32  const g = globalThis as G; const cur = g.__sptvTitles;33  if (cur && now() - cur.checkedAt < 3000) return cur;34  const version = getSetting("titles_version") ?? "0";35  if (cur && cur.version === version) { cur.checkedAt = now(); return cur; }36  return (g.__sptvTitles = build(version));37}38export function resetTitles() { (globalThis as G).__sptvTitles = undefined; }3940const favSet = () => new Set(all<{ title_id: number }>("SELECT title_id FROM title_favs").map((r) => r.title_id));41const strip = (t: Indexed, favs: Set<number>): Title => {42  const { norm: _n, words: _w, alt: _a, people: _p, plays: _pl, ...rest } = t; void _n; void _w; void _a; void _p; void _pl;43  return { ...rest, fav: favs.has(t.id) };44};4546export interface TitleQuery {47  q?: string; kind?: "movie" | "series"; genre?: string; yearFrom?: number; yearTo?: number; language?: string; country?: string; source?: string; rights?: string;48  documentary?: boolean; animation?: boolean; library?: boolean; fav?: boolean; shorts?: "only" | "exclude"; sort?: "title" | "recent" | "year" | "popular" | "relevance"; offset?: number; limit?: number;49}50export function searchTitles(query: TitleQuery): { total: number; items: Title[]; tookMs: number } {51  const t0 = performance.now(); const { list } = tindex(); const favs = favSet();52  const toks = query.q ? normalize(query.q).split(" ").filter(Boolean) : [];53  const hits: { t: Indexed; score: number }[] = [];54  for (const t of list) {55    if (query.kind && t.kind !== query.kind) continue;56    if (query.genre && !t.genres.includes(query.genre)) continue;57    if (query.yearFrom && (!t.year || t.year < query.yearFrom)) continue;58    if (query.yearTo && (!t.year || t.year > query.yearTo)) continue;59    if (query.language && !t.languages.includes(query.language)) continue;60    if (query.country && !t.countries.includes(query.country)) continue;61    if (query.source && t.source !== query.source) continue;62    if (query.rights && t.rights !== query.rights) continue;63    if (query.documentary && !t.documentary) continue;64    if (query.animation && !t.animation) continue;65    if (query.library !== undefined && t.library !== query.library) continue;66    if (query.fav && !favs.has(t.id)) continue;67    if (query.shorts === "only" ? !t.short : query.shorts === "exclude" && t.short) continue;68    let score = 0;69    if (toks.length) {70      let ok = true;71      for (const tok of toks) { const s = tokenScore(tok, t) || (t.people.includes(tok) ? 40 : 0); if (!s) { ok = false; break; } score += s; }72      if (!ok) continue;73      score = score / toks.length + (t.norm === toks.join(" ") ? 30 : 0) + (t.short ? 0 : 3);74    }75    hits.push({ t, score });76  }77  const sort = query.sort ?? (toks.length ? "relevance" : "title");78  if (sort === "relevance") hits.sort((a, b) => b.score - a.score || a.t.title.localeCompare(b.t.title, "fr"));79  else if (sort === "recent") hits.sort((a, b) => b.t.addedAt - a.t.addedAt || a.t.title.localeCompare(b.t.title, "fr"));80  else if (sort === "year") hits.sort((a, b) => (b.t.year ?? 0) - (a.t.year ?? 0));81  else if (sort === "popular") hits.sort((a, b) => b.t.plays - a.t.plays || a.t.title.localeCompare(b.t.title, "fr"));82  const offset = Math.max(0, query.offset ?? 0), limit = Math.min(200, Math.max(1, query.limit ?? 60));83  return { total: hits.length, items: hits.slice(offset, offset + limit).map((h) => strip(h.t, favs)), tookMs: Math.round((performance.now() - t0) * 10) / 10 };84}85export const titlesByIds = (ids: number[]) => { const { byId } = tindex(); const favs = favSet(); return ids.map((i) => byId.get(i)).filter((t): t is Indexed => !!t).map((t) => strip(t, favs)); };8687/** Deterministic daily shuffle, so a row is not always the same alphabetical slice but stays stable during the day. */88function daily<T extends { id: number }>(items: T[], salt: number): T[] {89  const day = Math.floor(now() / 86400_000) + salt;90  return [...items].sort((a, b) => ((a.id * 2654435761 + day * 40503) >>> 0) % 9973 - ((b.id * 2654435761 + day * 40503) >>> 0) % 9973);91}92export function trow(filter: (t: Title) => boolean, limit = 24, order: "daily" | "recent" | "popular" = "daily", salt = 0): Title[] {93  const { list } = tindex(); const favs = favSet();94  let items = list.filter(filter);95  // Posters first: a row of grey tiles helps nobody.96  if (order === "recent") items = items.sort((a, b) => b.addedAt - a.addedAt);97  else if (order === "popular") items = items.filter((t) => t.plays > 0).sort((a, b) => b.plays - a.plays);98  else items = daily(items, salt).sort((a, b) => Number(!a.poster) - Number(!b.poster));99  return items.slice(0, limit).map((t) => strip(t, favs));100}101export function facets(kind?: "movie" | "series") {102  const { list } = tindex(); const g = new Map<string, number>(), l = new Map<string, number>(), s = new Map<string, number>(); let minY = 9999, maxY = 0;103  for (const t of list) {104    if (kind && t.kind !== kind) continue;105    for (const x of t.genres) g.set(x, (g.get(x) ?? 0) + 1); for (const x of t.languages) l.set(x, (l.get(x) ?? 0) + 1); s.set(t.source, (s.get(t.source) ?? 0) + 1);106    if (t.year) { minY = Math.min(minY, t.year); maxY = Math.max(maxY, t.year); }107  }108  const top = (m: Map<string, number>) => [...m].sort((a, b) => b[1] - a[1]).map(([id, count]) => ({ id, count }));109  return { genres: top(g), languages: top(l), sources: top(s), years: maxY ? [minY, maxY] : null, total: list.filter((t) => !kind || t.kind === kind).length };110}111112// --- detail, playback, progress -------------------------------------------------------------------------------------113interface MediaRow { id: number; title_id: number; episode_id: number | null; kind: string; url: string | null; path: string | null; container: string | null; vcodec: string | null; acodec: string | null; height: number | null; duration_sec: number | null; playback: string; subtitles: string; audio: string }114const progressOf = (mediaId: number) => get<{ position_sec: number; duration_sec: number | null; completed: number; updated_at: number }>("SELECT position_sec, duration_sec, completed, updated_at FROM progress WHERE media_id = ?", mediaId);115116export function titleDetail(id: number) {117  const t = get<Record<string, string | number | null>>("SELECT * FROM titles WHERE id = ? AND active = 1", id);118  const base = titlesByIds([id])[0];119  if (!t || !base) return null;120  const media = all<MediaRow>("SELECT * FROM media WHERE title_id = ?", id);121  const eps = all<{ id: number; season: number; episode: number; name: string | null; synopsis: string | null; air_date: string | null }>("SELECT * FROM episodes WHERE title_id = ? ORDER BY season, episode", id);122  const one = (m: MediaRow) => { const p = progressOf(m.id); return { mediaId: m.id, duration: m.duration_sec, height: m.height, subtitles: (JSON.parse(m.subtitles) as { label: string }[]).map((s) => s.label), audio: (JSON.parse(m.audio) as { label: string }[]).map((a) => a.label), position: p?.position_sec ?? 0, completed: !!p?.completed, playback: m.playback }; };123  const byEp = new Map(media.filter((m) => m.episode_id).map((m) => [m.episode_id!, m]));124  const seasons = new Map<number, unknown[]>();125  for (const e of eps) { const m = byEp.get(e.id); if (!m) continue; const l = seasons.get(e.season) ?? []; l.push({ id: e.id, season: e.season, episode: e.episode, name: e.name, synopsis: e.synopsis, airDate: e.air_date, ...one(m) }); seasons.set(e.season, l); }126  const film = media.find((m) => !m.episode_id);127  return {128    title: { ...base, synopsis: t.synopsis as string | null, synopsisSource: t.synopsis_source as string | null, directors: String(t.directors || "").split(";").filter(Boolean), cast: String(t.cast_names || "").split(";").filter(Boolean),129      rightsBasis: t.rights_basis as string, rightsUrl: t.rights_url as string | null, sourceUrl: t.source_url as string | null,130      // Set when the poster, the backdrop or the synopsis of this record comes from TMDB (attribution is then displayed).131      tmdb: (t.tmdb_id as string | null) && (String(t.poster ?? "").includes("image.tmdb.org") || String(t.backdrop ?? "").includes("image.tmdb.org") || t.synopsis_source === "TMDB") ? `https://www.themoviedb.org/${t.tmdb_id}` : null },132    media: film ? one(film) : null,133    seasons: [...seasons].sort((a, b) => a[0] - b[0]).map(([season, episodes]) => ({ season, episodes })),134    resume: resumePoint(id),135  };136}137138/** Where « Regarder » should start for a title: the unfinished media, else the first not yet watched, else the beginning. */139export function resumePoint(titleId: number): { mediaId: number; position: number; label: string | null } | null {140  const rows = all<{ id: number; season: number | null; episode: number | null; name: string | null; position_sec: number | null; completed: number | null; updated_at: number | null }>(141    `SELECT m.id, e.season, e.episode, e.name, p.position_sec, p.completed, p.updated_at FROM media m LEFT JOIN episodes e ON e.id = m.episode_id LEFT JOIN progress p ON p.media_id = m.id WHERE m.title_id = ? ORDER BY e.season, e.episode, m.id`, titleId);142  if (!rows.length) return null;143  const label = (r: (typeof rows)[number]) => (r.season !== null ? `S${r.season} · É${r.episode}` : null);144  const last = [...rows].filter((r) => r.updated_at).sort((a, b) => b.updated_at! - a.updated_at!)[0];145  if (last && !last.completed) return { mediaId: last.id, position: last.position_sec ?? 0, label: label(last) };146  const next = last ? rows[rows.indexOf(last) + 1] : null;147  const pick = next ?? rows.find((r) => !r.completed) ?? rows[0];148  return { mediaId: pick.id, position: pick.completed ? 0 : pick.position_sec ?? 0, label: label(pick) };149}150151export function playInfo(mediaId: number) {152  const m = get<MediaRow>("SELECT * FROM media WHERE id = ?", mediaId); if (!m) return null;153  const t = titlesByIds([m.title_id])[0]; if (!t) return null;154  const e = m.episode_id ? get<{ season: number; episode: number; name: string | null }>("SELECT season, episode, name FROM episodes WHERE id = ?", m.episode_id) : null;155  const nextRow = e ? get<{ id: number; season: number; episode: number; name: string | null }>(156    `SELECT m.id, e.season, e.episode, e.name FROM episodes e JOIN media m ON m.episode_id = e.id WHERE e.title_id = ? AND (e.season > ? OR (e.season = ? AND e.episode > ?)) ORDER BY e.season, e.episode LIMIT 1`, m.title_id, e.season, e.season, e.episode) : null;157  const p = progressOf(mediaId);158  const subs = JSON.parse(m.subtitles) as { label: string; lang: string }[]; const audio = JSON.parse(m.audio) as { index: number; label: string; lang: string }[];159  const local = m.kind === "file"; const provider = (m.url ?? "").startsWith("provider://");160  const ticket = provider ? encodeURIComponent(sign(`m:${m.id}`, 12 * 3600)) : "";161  return {162    mediaId, titleId: t.id, title: t.title, kind: t.kind, poster: t.poster, episode: e ? { season: e.season, episode: e.episode, name: e.name } : null,163    // direct: the browser reads the file (remote origin, or our authenticated file route); hls: converted rendition for containers/codecs a browser cannot read.164    // embed: the title is watched inside its publisher's official player (ONF); nothing is extracted from it.165    embed: m.kind === "embed" ? m.url : null, sourceUrl: m.kind === "embed" ? get<{ source_url: string | null }>("SELECT source_url FROM titles WHERE id = ?", m.title_id)?.source_url ?? null : null, sourceName: t.source,166    // provider (your Jellyfin server, an authorised provider): the address is issued by this server as a redirect when playback starts.167    direct: m.kind === "embed" || m.playback === "unsupported" ? null : local ? (m.playback === "remux" || m.playback === "transcode" ? null : `/api/media/${m.id}/file`) : provider ? (m.playback === "direct" ? `/api/provider/media/${m.id}?t=${ticket}` : null) : m.url,168    hls: local ? `/api/media/${m.id}/hls/index.m3u8` : provider && (m.url ?? "").startsWith("provider://jf/") ? `/api/provider/media/${m.id}?hls=1&t=${ticket}` : null, playback: m.playback, container: m.container, external: !local && !provider,169    duration: m.duration_sec, position: p && !p.completed ? p.position_sec : 0,170    subtitles: subs.map((s, i) => ({ label: s.label, lang: s.lang, url: `/api/media/${m.id}/subs/${i}` })), audio,171    next: nextRow ? { mediaId: nextRow.id, label: `S${nextRow.season} · É${nextRow.episode}${nextRow.name ? ` — ${nextRow.name}` : ""}` } : null,172  };173}174175export function saveProgress(mediaId: number, position: number, duration: number | null, completed?: boolean) {176  if (!get("SELECT 1 FROM media WHERE id = ?", mediaId)) return;177  const done = completed ?? (!!duration && duration > 60 && position / duration > 0.93);178  const prev = get<{ updated_at: number }>("SELECT updated_at FROM progress WHERE media_id = ?", mediaId);179  // A new viewing session (more than 30 minutes since the last report) counts as one more play.180  run(`INSERT INTO progress(media_id, position_sec, duration_sec, completed, plays, updated_at) VALUES(?,?,?,?,1,?)181       ON CONFLICT(media_id) DO UPDATE SET position_sec = excluded.position_sec, duration_sec = COALESCE(excluded.duration_sec, duration_sec), completed = excluded.completed,182       plays = plays + ?, updated_at = excluded.updated_at`, mediaId, position, duration, Number(done), now(), prev && now() - prev.updated_at > 30 * 60_000 ? 1 : 0);183}184export function setWatched(mediaId: number, watched: boolean) {185  if (watched) run(`INSERT INTO progress(media_id, position_sec, completed, plays, updated_at) VALUES(?, 0, 1, 1, ?) ON CONFLICT(media_id) DO UPDATE SET completed = 1, updated_at = excluded.updated_at`, mediaId, now());186  else run("DELETE FROM progress WHERE media_id = ?", mediaId);187}188189/** Titles in progress, most recent first: an unfinished film or episode, or the next episode of a series whose last one was finished. */190export function continueWatching(limit = 20): Title[] {191  const ids = all<{ title_id: number }>("SELECT m.title_id, MAX(p.updated_at) u FROM progress p JOIN media m ON m.id = p.media_id GROUP BY m.title_id ORDER BY u DESC LIMIT 60").map((r) => r.title_id);192  const out: Title[] = [];193  for (const t of titlesByIds(ids)) {194    const r = resumePoint(t.id); if (!r) continue;195    const p = progressOf(r.mediaId);196    const allDone = !get("SELECT 1 FROM media m LEFT JOIN progress p ON p.media_id = m.id WHERE m.title_id = ? AND COALESCE(p.completed, 0) = 0", t.id);197    if (allDone) continue;198    // A few seconds watched by curiosity is not « in progress »; the next episode of a started series is.199    const started = !!get("SELECT 1 FROM progress p JOIN media m ON m.id = p.media_id WHERE m.title_id = ? AND (p.completed = 1 OR p.position_sec >= 30)", t.id);200    if (!started) continue;201    const dur = p?.duration_sec ?? get<{ d: number | null }>("SELECT duration_sec d FROM media WHERE id = ?", r.mediaId)?.d ?? null;202    out.push({ ...t, progress: { position: r.position, duration: dur, completed: false, mediaId: r.mediaId, label: r.label ?? undefined } });203    if (out.length >= limit) break;204  }205  return out;206}207export function setTitleFav(titleId: number, on: boolean) {208  if (on) run("INSERT OR IGNORE INTO title_favs(title_id, added_at) VALUES(?, ?)", titleId, now()); else run("DELETE FROM title_favs WHERE title_id = ?", titleId);209}210export const favTitles = () => titlesByIds(all<{ title_id: number }>("SELECT title_id FROM title_favs ORDER BY added_at DESC").map((r) => r.title_id));211212/** Episodes whose own name matches (for the unified search). */213export function searchEpisodes(q: string, limit = 12) {214  const toks = normalize(q).split(" ").filter((t) => t.length > 1); if (!toks.length) return [];215  const { byId } = tindex();216  return all<{ id: number; title_id: number; season: number; episode: number; name: string; media: number }>("SELECT e.id, e.title_id, e.season, e.episode, e.name, m.id media FROM episodes e JOIN media m ON m.episode_id = e.id WHERE e.name IS NOT NULL")217    .filter((e) => byId.has(e.title_id) && toks.every((t) => normalize(e.name).includes(t))).slice(0, limit)218    .map((e) => ({ mediaId: e.media, titleId: e.title_id, series: byId.get(e.title_id)!.title, poster: byId.get(e.title_id)!.poster, season: e.season, episode: e.episode, name: e.name }));219}220
Files main
Menu

Theme