Repository Public
1import fs from "node:fs";2import path from "node:path";3import { Readable } from "node:stream";4import { z } from "zod";5import { all, get, getSetting, log, now, run } from "../db";6import { env } from "../env";7import * as cat from "../catalog";8import * as lib from "../library";9import { fetchText } from "../ssrf";10import * as T from "../titles";11import { HttpError, route, type Ctx } from "./core";1213const bool = (v: string | null) => v === "1" || v === "true";14const num = (v: string | null) => (v && /^\d+$/.test(v) ? Number(v) : undefined);15const feature = (t: T.Title) => t.kind === "movie" && !t.short;1617route("GET", "/titles", (c) => {18 const p = c.url.searchParams; const kind = p.get("kind"); const sort = p.get("sort");19 return T.searchTitles({20 q: p.get("q")?.slice(0, 100) || undefined, kind: kind === "movie" || kind === "series" ? kind : undefined, genre: p.get("genre") || undefined, yearFrom: num(p.get("from")), yearTo: num(p.get("to")),21 language: p.get("language") || undefined, country: p.get("country") || undefined, source: p.get("source") || undefined, rights: p.get("rights") || undefined, documentary: bool(p.get("doc")) || undefined,22 animation: bool(p.get("animation")) || undefined, library: p.get("library") ? bool(p.get("library")) : undefined, fav: bool(p.get("fav")) || undefined,23 shorts: p.get("shorts") === "only" ? "only" : p.get("shorts") === "exclude" ? "exclude" : undefined,24 sort: sort === "recent" || sort === "year" || sort === "popular" || sort === "title" ? sort : undefined, offset: num(p.get("offset")) ?? 0, limit: num(p.get("limit")) ?? 60,25 });26});27route("GET", "/titles/facets", (c) => { const k = c.url.searchParams.get("kind"); return T.facets(k === "movie" || k === "series" ? k : undefined); });28route("GET", "/titles/:id", (c) => { const d = T.titleDetail(Number(c.params[0])); if (!d) throw new HttpError(404, "Titre introuvable"); return d; });29route("GET", "/play/:id", (c) => { const d = T.playInfo(Number(c.params[0])); if (!d) throw new HttpError(404, "Média introuvable"); return d; });30route("POST", "/progress", async (c) => { const b = await c.body(z.object({ mediaId: z.number().int(), position: z.number().min(0).max(1e6), duration: z.number().min(0).max(1e6).nullable().optional(), completed: z.boolean().optional() })); T.saveProgress(b.mediaId, b.position, b.duration ?? null, b.completed); });31route("POST", "/watched", async (c) => { const b = await c.body(z.object({ mediaId: z.number().int(), watched: z.boolean() })); T.setWatched(b.mediaId, b.watched); });32route("POST", "/title-favs", async (c) => { const b = await c.body(z.object({ titleId: z.number().int(), on: z.boolean() })); T.setTitleFav(b.titleId, b.on); });33route("GET", "/title-favs", () => ({ items: T.favTitles() }));34route("GET", "/continue", () => ({ titles: T.continueWatching(40), channels: cat.historyChannels(24) }));3536type Row = { key: string; title: string; items: T.Title[]; href: string | null };37const rows = (list: [string, string, T.Title[], string | null][]): Row[] => list.filter(([, , items]) => items.length > 0).map(([key, title, items, href]) => ({ key, title, items, href }));3839route("GET", "/vod/home", (c) => {40 const section = c.url.searchParams.get("section") ?? "films";41 const g = (genre: string, salt: number) => T.trow((t) => feature(t) && t.genres.includes(genre), 24, "daily", salt);42 let list: Row[];43 if (section === "series") {44 list = rows([45 ["continue", "Continuer à regarder", T.continueWatching(20).filter((t) => t.kind === "series"), null],46 ["all", "Toutes les séries", T.trow((t) => t.kind === "series", 40), "/catalogue?kind=series"],47 ["library", "Dans ma bibliothèque", T.trow((t) => t.kind === "series" && t.library), "/catalogue?kind=series&library=1"],48 ]);49 } else if (section === "docs") {50 list = rows([51 ["recent", "Documentaires récemment ajoutés", T.trow((t) => t.documentary, 24, "recent"), "/catalogue?doc=1&sort=recent"],52 ["long", "Longs métrages documentaires", T.trow((t) => t.documentary && !t.short, 24, "daily", 1), "/catalogue?doc=1&shorts=exclude"],53 ["short", "Courts documentaires", T.trow((t) => t.documentary && t.short, 24, "daily", 2), "/catalogue?doc=1&shorts=only"],54 ["fr", "Documentaires francophones", T.trow((t) => t.documentary && t.languages.includes("fr")), "/catalogue?doc=1&language=fr"],55 ["library", "Dans ma bibliothèque", T.trow((t) => t.documentary && t.library), "/catalogue?doc=1&library=1"],56 ]);57 } else if (section === "library") {58 list = rows([59 ["recent", "Ajouts récents", T.trow((t) => t.library, 24, "recent"), "/catalogue?library=1&sort=recent"],60 ["movies", "Films", T.trow((t) => t.library && t.kind === "movie" && !t.documentary, 40), "/catalogue?library=1&kind=movie"],61 ["series", "Séries", T.trow((t) => t.library && t.kind === "series", 40), "/catalogue?library=1&kind=series"],62 ["docs", "Documentaires", T.trow((t) => t.library && t.documentary, 40), "/catalogue?library=1&doc=1"],63 ]);64 } else {65 list = rows([66 ["continue", "Continuer à regarder", T.continueWatching(20).filter((t) => t.kind === "movie"), null],67 ["recent", "Films récemment ajoutés", T.trow(feature, 24, "recent"), "/catalogue?kind=movie&sort=recent&shorts=exclude"],68 // Real figures only: plays recorded by this application. The row is absent until something has been watched.69 ["popular", "Populaires dans votre bibliothèque", T.trow((t) => t.kind === "movie", 24, "popular"), null],70 ["onf", "Office national du film — longs métrages", T.trow((t) => feature(t) && t.source === "ONF", 24, "daily", 14), "/catalogue?kind=movie&source=ONF&shorts=exclude"],71 ["onf-short", "Office national du film — courts métrages et animation", T.trow((t) => t.source === "ONF" && t.short, 24, "daily", 15), "/catalogue?kind=movie&source=ONF&shorts=only"],72 ["fr", "Films francophones", T.trow((t) => feature(t) && t.languages.includes("fr")), "/catalogue?kind=movie&language=fr"],73 ["docs", "Documentaires", T.trow((t) => t.kind === "movie" && t.documentary, 24, "daily", 3), "/documentaires"],74 ["animation", "Animation", T.trow((t) => t.kind === "movie" && t.animation, 24, "daily", 4), "/catalogue?kind=movie&animation=1"],75 ["sf", "Science-fiction", g("Science-fiction", 5), "/catalogue?kind=movie&genre=Science-fiction"],76 ["action", "Action et aventure", T.trow((t) => feature(t) && (t.genres.includes("Action") || t.genres.includes("Aventure")), 24, "daily", 6), "/catalogue?kind=movie&genre=Aventure"],77 ["comedy", "Comédie", g("Comédie", 7), "/catalogue?kind=movie&genre=Comédie"],78 ["drama", "Drame", g("Drame", 8), "/catalogue?kind=movie&genre=Drame"],79 ["noir", "Policier et film noir", g("Policier", 9), "/catalogue?kind=movie&genre=Policier"],80 ["horror", "Horreur", g("Horreur", 10), "/catalogue?kind=movie&genre=Horreur"],81 ["classics", "Classiques d'avant 1960", T.trow((t) => feature(t) && !!t.year && t.year < 1960, 24, "daily", 11), "/catalogue?kind=movie&to=1959&shorts=exclude"],82 ["pd", "Domaine public", T.trow((t) => feature(t) && t.rights === "pd", 24, "daily", 12), "/catalogue?kind=movie&rights=pd"],83 ["shorts", "Courts métrages", T.trow((t) => t.kind === "movie" && t.short && !t.animation, 24, "daily", 13), "/catalogue?kind=movie&shorts=only"],84 ]);85 }86 // Banner: a title that really has a poster and a source, changing daily.87 const pool = section === "series" ? T.trow((t) => t.kind === "series" && !!t.backdrop, 5) : section === "docs" ? T.trow((t) => t.documentary && !t.short && !!t.backdrop, 5) : section === "library" ? T.trow((t) => t.library, 5, "recent") : T.trow((t) => feature(t) && !!t.backdrop && !!t.year, 5);88 const hero = pool[0] ? T.titleDetail(pool[0].id)?.title ?? null : null;89 return { rows: list, hero, facets: T.facets(section === "series" ? "series" : section === "films" ? "movie" : undefined) };90});9192route("GET", "/search", (c) => {93 const p = c.url.searchParams; const q = (p.get("q") ?? "").slice(0, 100).trim(); const type = p.get("type") ?? "";94 const t0 = performance.now();95 const want = (k: string) => !type || type === k;96 const common = { genre: p.get("genre") || undefined, yearFrom: num(p.get("from")), yearTo: num(p.get("to")), language: p.get("language") || undefined, source: p.get("source") || undefined };97 const filtered = !!(common.genre || common.yearFrom || common.yearTo || common.source);98 const lang3: Record<string, string> = { fr: "fra", en: "eng", es: "spa", de: "deu", it: "ita", pt: "por" };99 const status = p.get("status");100 const channels = want("channel") && !filtered && (q || p.get("country") || common.language || status)101 ? cat.search({ q: q || undefined, country: p.get("country") || undefined, language: common.language ? lang3[common.language] ?? common.language : undefined, status: status === "up" ? "up" : undefined, limit: type ? 60 : 18 }) : { total: 0, items: [] };102 const tq = (extra: T.TitleQuery, limit: number) => (q || filtered || common.language || p.get("country") ? T.searchTitles({ q: q || undefined, ...common, country: p.get("country") || undefined, ...extra, limit }) : { total: 0, items: [] });103 const movies = want("movie") ? tq({ kind: "movie", documentary: undefined }, type ? 60 : 18) : { total: 0, items: [] };104 const series = want("series") ? tq({ kind: "series" }, type ? 60 : 12) : { total: 0, items: [] };105 const docs = type === "doc" ? tq({ documentary: true }, 60) : { total: 0, items: [] };106 const library = type === "library" ? tq({ library: true }, 60) : { total: 0, items: [] };107 const episodes = (want("episode") || want("series")) && q && !filtered ? T.searchEpisodes(q, type === "episode" ? 40 : 10) : [];108 return { q, channels, movies, series, docs, library, episodes, tookMs: Math.round((performance.now() - t0) * 10) / 10, facets: T.facets() };109});110111// --- media: local files, converted renditions, subtitles, thumbnails (authenticated like every other route) ---------------112interface MediaRow { id: number; kind: string; url: string | null; path: string | null; vcodec: string | null; acodec: string | null; playback: string; subtitles: string; title_id: number; height?: number | null }113const TYPES: Record<string, string> = { ".mp4": "video/mp4", ".m4v": "video/mp4", ".mov": "video/quicktime", ".webm": "video/webm", ".mkv": "video/x-matroska", ".ts": "video/mp2t", ".m3u8": "application/vnd.apple.mpegurl", ".jpg": "image/jpeg", ".vtt": "text/vtt; charset=utf-8" };114115/** A media file is served only if it still lies inside its declared, reachable library folder. */116function localMedia(id: number): MediaRow & { path: string } {117 const m = get<MediaRow>("SELECT m.id, m.kind, m.url, m.path, m.vcodec, m.acodec, m.playback, m.subtitles, m.title_id, m.height FROM media m WHERE m.id = ?", id);118 if (!m) throw new HttpError(404, "Média introuvable");119 if (m.kind !== "file" || !m.path) throw new HttpError(400, "Ce média n'est pas un fichier de la bibliothèque");120 const dir = get<{ path: string }>("SELECT d.path FROM library_dirs d JOIN titles t ON t.library_dir = d.id WHERE t.id = ?", m.title_id);121 const chk = dir ? lib.checkDir(dir.path) : null;122 let real: string; try { real = fs.realpathSync(m.path); } catch { throw new HttpError(404, "Fichier absent (dossier non monté ?)"); }123 if (!chk || !chk.ok || !(real === chk.real || real.startsWith(chk.real + path.sep))) throw new HttpError(403, "Fichier hors de la bibliothèque");124 return { ...m, path: real };125}126function sendFile(c: Ctx, file: string, opts: { cache?: string } = {}): Response {127 let st: fs.Stats; try { st = fs.statSync(file); } catch { throw new HttpError(404, "Fichier absent"); }128 const type = TYPES[path.extname(file).toLowerCase()] ?? "application/octet-stream";129 const h: Record<string, string> = { "content-type": type, "accept-ranges": "bytes", "cache-control": opts.cache ?? "private, no-store", "x-content-type-options": "nosniff" };130 const range = /^bytes=(\d*)-(\d*)$/.exec(c.req.headers.get("range") ?? "");131 if (c.req.method === "HEAD") return new Response(null, { status: 200, headers: { ...h, "content-length": String(st.size) } });132 if (range && (range[1] || range[2])) {133 let start = range[1] ? Number(range[1]) : Math.max(0, st.size - Number(range[2])); let end = range[1] && range[2] ? Number(range[2]) : st.size - 1;134 if (start >= st.size) return new Response(null, { status: 416, headers: { "content-range": `bytes */${st.size}` } });135 end = Math.min(end, st.size - 1); start = Math.min(start, end);136 return new Response(Readable.toWeb(fs.createReadStream(file, { start, end })) as ReadableStream, { status: 206, headers: { ...h, "content-range": `bytes ${start}-${end}/${st.size}`, "content-length": String(end - start + 1) } });137 }138 return new Response(Readable.toWeb(fs.createReadStream(file)) as ReadableStream, { status: 200, headers: { ...h, "content-length": String(st.size) } });139}140141route("GET", "/media/:id/file", (c) => sendFile(c, localMedia(Number(c.params[0])).path));142route("GET", "/media/:id/thumb", (c) => sendFile(c, lib.thumbPath(Number(c.params[0])), { cache: "private, max-age=86400" }));143route("GET", "/media/:id/hls/:file", async (c) => {144 const m = localMedia(Number(c.params[0])); const name = c.params[1];145 if (!/^(index\.m3u8|seg\d{5}\.ts)$/.test(name)) throw new HttpError(400, "Fichier invalide");146 const audio = Math.min(16, Number(c.url.searchParams.get("audio")) || 0);147 const job = lib.ensureHls(m, audio);148 if (job.error) throw new HttpError(503, `Conversion impossible : ${job.error}`);149 const file = path.join(job.dir, name);150 if (!(await lib.waitFor(file, job, name === "index.m3u8" ? 30_000 : 45_000))) throw new HttpError(job.error ? 503 : 404, job.error ? `Conversion impossible : ${job.error}` : "Segment pas encore prêt");151 if (name !== "index.m3u8") return sendFile(c, file, { cache: "private, max-age=3600" });152 // Segment URLs keep the chosen audio track; a finished rendition is a plain VOD playlist (seekable everywhere).153 let body = fs.readFileSync(file, "utf8").replace(/^(seg\d{5}\.ts)$/gm, audio ? `$1?audio=${audio}` : "$1");154 if (job.done && !body.includes("#EXT-X-ENDLIST")) body += "#EXT-X-ENDLIST\n";155 return new Response(body, { headers: { "content-type": TYPES[".m3u8"], "cache-control": "no-store" } });156});157route("GET", "/media/:id/subs/:n", async (c) => {158 const m = get<MediaRow>("SELECT id, kind, url, path, vcodec, acodec, playback, subtitles, title_id FROM media WHERE id = ?", Number(c.params[0]));159 const s = m ? (JSON.parse(m.subtitles) as { url?: string; path?: string; stream?: number }[])[Number(c.params[1])] : undefined;160 if (!m || !s) throw new HttpError(404, "Sous-titres introuvables");161 let vtt: string;162 if (s.url) {163 // Remote subtitles are small text files from the same host as the video; fetched server-side only to convert SRT → WebVTT.164 if (!["archive.org", "images-assets.nasa.gov"].includes(new URL(s.url).hostname)) throw new HttpError(400, "Hôte de sous-titres non autorisé");165 vtt = lib.srtToVtt(await fetchText(s.url, 3 * 1024 * 1024, 30_000));166 } else if (s.path) { const real = fs.realpathSync(s.path); if (path.dirname(real) !== path.dirname(localMedia(m.id).path)) throw new HttpError(403, "Fichier hors de la bibliothèque"); vtt = lib.srtToVtt(fs.readFileSync(real, "utf8")); }167 else vtt = await lib.embeddedSubtitle(localMedia(m.id).path, s.stream ?? 0);168 return new Response(vtt, { headers: { "content-type": TYPES[".vtt"], "cache-control": "private, max-age=3600" } });169});170171// --- administration: catalogue and library -----------------------------------------------------------------------------172route("GET", "/admin/vod", () => {173 const n = (sql: string) => get<{ n: number }>(sql)!.n;174 return {175 stats: {176 movies: n("SELECT COUNT(*) n FROM titles t WHERE active = 1 AND kind = 'movie' AND EXISTS(SELECT 1 FROM media m WHERE m.title_id = t.id)"),177 series: n("SELECT COUNT(*) n FROM titles t WHERE active = 1 AND kind = 'series' AND EXISTS(SELECT 1 FROM media m WHERE m.title_id = t.id)"),178 episodes: n("SELECT COUNT(*) n FROM episodes e JOIN titles t ON t.id = e.title_id WHERE t.active = 1"),179 documentaries: n("SELECT COUNT(*) n FROM titles WHERE active = 1 AND is_documentary = 1"), library: n("SELECT COUNT(*) n FROM titles WHERE active = 1 AND origin = 'library'"),180 withSynopsis: n("SELECT COUNT(*) n FROM titles WHERE active = 1 AND synopsis IS NOT NULL"), withPoster: n("SELECT COUNT(*) n FROM titles WHERE active = 1 AND poster IS NOT NULL"),181 withSubtitles: n("SELECT COUNT(DISTINCT title_id) n FROM media WHERE subtitles != '[]'"), inProgress: n("SELECT COUNT(*) n FROM progress WHERE completed = 0"), watched: n("SELECT COUNT(*) n FROM progress WHERE completed = 1"),182 },183 rights: all("SELECT rights_status status, source_name source, COUNT(*) n FROM titles WHERE active = 1 GROUP BY 1, 2 ORDER BY 3 DESC"),184 sources: all("SELECT id, kind, name, ref, as_kind, rights_note, enabled, builtin, last_sync_at, last_status, last_error, title_count FROM vod_sources ORDER BY id"),185 tmdb: !!env.tmdbKey, lastVodAt: Number(getSetting("last_vod_at") ?? 0) || null,186 };187});188route("PATCH", "/admin/vod-sources/:id", async (c) => { const b = await c.body(z.object({ enabled: z.boolean() })); run("UPDATE vod_sources SET enabled = ? WHERE id = ?", Number(b.enabled), Number(c.params[0])); });189190route("GET", "/admin/library", () => {191 let cache = 0; try { for (const d of fs.readdirSync(path.join(env.dataDir, "transcode"))) for (const f of fs.readdirSync(path.join(env.dataDir, "transcode", d))) cache += fs.statSync(path.join(env.dataDir, "transcode", d, f)).size; } catch { /* no cache yet */ }192 return {193 dirs: all<{ id: number; path: string; kind: string; label: string; enabled: number; last_scan_at: number | null; last_status: string | null; last_error: string | null; file_count: number; new_count: number; error_count: number }>("SELECT * FROM library_dirs ORDER BY id")194 .map((d) => ({ ...d, status: lib.dirStatus(d.path), titles: get<{ n: number }>("SELECT COUNT(*) n FROM titles WHERE library_dir = ?", d.id)!.n })),195 roots: lib.libraryRoots().map((r) => ({ path: r, exists: fs.existsSync(r) })), ffmpeg: !!lib.ffmpegPath(), ffprobe: !!lib.ffprobePath(), transcodeCacheBytes: cache,196 playback: all("SELECT playback, COUNT(*) n FROM media WHERE kind = 'file' GROUP BY 1"),197 errors: all("SELECT at, message, meta FROM logs WHERE scope = 'library' AND level IN ('warn','error') ORDER BY id DESC LIMIT 20"),198 lastScanAt: Number(getSetting("last_library_at") ?? 0) || null,199 };200});201route("POST", "/admin/library", async (c) => {202 const b = await c.body(z.object({ path: z.string().min(1).max(1000), kind: z.enum(["movies", "series", "documentaries", "videos"]), label: z.string().trim().min(1).max(60) }));203 const chk = lib.checkDir(b.path); if (!chk.ok) throw new HttpError(400, chk.error);204 if (get("SELECT 1 FROM library_dirs WHERE path = ?", chk.real)) throw new HttpError(409, "Ce dossier est déjà indexé");205 const id = Number(run("INSERT INTO library_dirs(path, kind, label, created_at) VALUES(?,?,?,?)", chk.real, b.kind, b.label, now()).lastInsertRowid);206 log("info", "library", `Dossier ajouté : ${b.label}`);207 return { id };208});209route("DELETE", "/admin/library/:id", (c) => {210 const id = Number(c.params[0]);211 run("DELETE FROM titles WHERE library_dir = ?", id); run("DELETE FROM library_dirs WHERE id = ?", id); // files on disk are never touched212 run("INSERT INTO settings(key, value) VALUES('titles_version', ?) ON CONFLICT(key) DO UPDATE SET value = excluded.value", String(now()));213});214