SPB Git

Repository Public

catalog.ts 12.8 KB 166 lines typescript

1import { z } from "zod";2import { all, bumpCatalog, get, getSetting, now, run, tx } from "../db";3import * as cat from "../catalog";4import { probeStream, saveProbe } from "../checker";5import { HttpError, route } from "./core";6import * as T from "../titles";78const bool = (v: string | null) => v === "1" || v === "true";910route("GET", "/health", () => ({ ok: true, channels: cat.index().list.length }), { public: true });1112route("GET", "/channels", (c) => {13  const p = c.url.searchParams;14  const status = p.get("status");15  return cat.search({16    q: p.get("q")?.slice(0, 100) || undefined, country: p.get("country") || undefined, category: p.get("category") || undefined, language: p.get("language") || undefined,17    status: status === "up" || status === "down" || status === "unknown" ? status : undefined, fav: bool(p.get("fav")), list: Number(p.get("list")) || undefined,18    hidden: p.get("hidden") === "only" ? "only" : undefined, guide: bool(p.get("guide")), web: bool(p.get("web")), recent: bool(p.get("recent")),19    sort: p.get("sort") === "recent" ? "recent" : undefined, offset: Number(p.get("offset")) || 0, limit: Number(p.get("limit")) || 60,20  });21});2223route("GET", "/meta", () => {24  const { list } = cat.index(); const sets = cat.userSets();25  const count = (key: (c: cat.Channel) => (string | null)[]) => { const m = new Map<string, number>(); for (const c of list) if (!sets.hidden.has(c.id)) for (const k of key(c)) if (k) m.set(k, (m.get(k) ?? 0) + 1); return m; };26  const cc = count((c) => [c.country]), cg = count((c) => c.categories), cl = count((c) => c.languages);27  return {28    total: list.length,29    countries: all<{ code: string; name: string; flag: string }>("SELECT code, name, flag FROM countries").filter((x) => cc.has(x.code)).map((x) => ({ ...x, count: cc.get(x.code)! })),30    categories: all<{ id: string; name: string }>("SELECT id, name FROM categories").filter((x) => cg.has(x.id)).map((x) => ({ ...x, count: cg.get(x.id)! })),31    languages: all<{ code: string; name: string }>("SELECT code, name FROM languages").filter((x) => cl.has(x.code)).map((x) => ({ ...x, count: cl.get(x.code)! })).sort((a, b) => b.count - a.count),32    lists: cat.lists(),33  };34});3536route("GET", "/home", () => {37  const initial = Number(getSetting("initial_sync_at") ?? 0);38  const fr = (c: cat.Channel) => (c.languages.includes("fra") ? 0 : 1);39  const last = cat.historyChannels(1)[0] ?? null;40  const rows = [41    { key: "continue", title: "Continuer à regarder", items: cat.historyChannels(18), href: null },42    { key: "favorites", title: "Chaînes favorites", items: cat.listChannels(1).slice(0, 24), href: "/favoris" },43    { key: "ca", title: "Chaînes canadiennes", items: cat.row((c) => c.country === "CA", 24, fr), href: "/chaines?country=CA" },44    { key: "fr", title: "Chaînes françaises", items: cat.row((c) => c.country === "FR"), href: "/chaines?country=FR" },45    { key: "news", title: "Informations et actualités", items: cat.row((c) => c.categories.includes("news"), 24, fr), href: "/chaines?category=news" },46    { key: "sports", title: "Sports", items: cat.row((c) => c.categories.includes("sports"), 24, fr), href: "/chaines?category=sports" },47    { key: "entertainment", title: "Divertissement", items: cat.row((c) => c.categories.includes("entertainment"), 24, fr), href: "/chaines?category=entertainment" },48    { key: "music", title: "Musique", items: cat.row((c) => c.categories.includes("music"), 24, fr), href: "/chaines?category=music" },49    { key: "recent", title: "Chaînes récemment ajoutées", items: initial ? cat.search({ recent: true, sort: "recent", limit: 24 }).items : [], href: "/chaines?recent=1" },50  ];51  const ids = [...new Set(rows.flatMap((r) => r.items.map((i) => i.id)))];52  const feature = (t: T.Title) => t.kind === "movie" && !t.short;53  const titleRows = [54    { key: "t-continue", title: "Reprendre un film ou une série", items: T.continueWatching(18), href: "/continuer" },55    { key: "t-list", title: "Ma liste", items: T.favTitles().slice(0, 24), href: "/favoris" },56    { key: "t-films", title: "Films à découvrir", items: T.trow((t) => feature(t) && !!t.poster, 24, "daily", 21), href: "/films" },57    { key: "t-series", title: "Séries", items: T.trow((t) => t.kind === "series", 24), href: "/series" },58    { key: "t-fr", title: "Films francophones", items: T.trow((t) => feature(t) && t.languages.includes("fr"), 24, "daily", 22), href: "/catalogue?kind=movie&language=fr" },59    { key: "t-docs", title: "Documentaires", items: T.trow((t) => t.documentary && !!t.poster, 24, "daily", 23), href: "/documentaires" },60    { key: "t-library", title: "Ma bibliothèque", items: T.trow((t) => t.library, 24, "recent"), href: "/bibliotheque" },61  ].filter((r) => r.items.length > 0);62  // Banner candidates: only titles that have artwork and a real source.63  const featured = T.trow((t) => feature(t) && !!t.backdrop && !!t.year, 6, "daily", 24).map((t) => T.titleDetail(t.id)?.title).filter(Boolean);64  return { last, rows, titleRows, featured, programmes: cat.nowNext(ids), autoResume: getSetting("auto_resume") === "1", synced: !!initial, lastSyncAt: Number(getSetting("last_sync_at") ?? 0) || null };65});6667route("GET", "/channels/:id", (c) => {68  const ch = cat.channelsByIds([c.params[0]])[0] ?? cat.listChannels(1).find((x) => x.id === c.params[0]);69  if (!ch) throw new HttpError(404, "Chaîne introuvable");70  const extra = get<{ website: string | null; network: string | null; alt_names: string }>("SELECT website, network, alt_names FROM channels WHERE id = ?", ch.id);71  return { channel: { ...ch, website: extra?.website ?? null, network: extra?.network ?? null }, streams: cat.channelStreams(ch.id), programmes: cat.nowNext([ch.id])[ch.id] ?? [],72    lists: all<{ list_id: number }>("SELECT list_id FROM list_items WHERE channel_id = ?", ch.id).map((r) => r.list_id) };73});7475// On-demand test of one channel (at most its 6 best streams, one at a time): the same polite probe the monitor uses.76const lastManual = new Map<string, number>();77route("POST", "/channels/:id/check", async (c) => {78  const id = c.params[0];79  if (now() - (lastManual.get(id) ?? 0) < 15_000) throw new HttpError(429, "Test déjà effectué il y a quelques secondes");80  lastManual.set(id, now());81  const rows = all<{ id: number; url: string; referrer: string | null; user_agent: string | null }>("SELECT id, url, referrer, user_agent FROM streams WHERE channel_id = ? LIMIT 6", id);82  for (const s of rows) saveProbe(s.id, await probeStream(s, 8000));83  bumpCatalog(); cat.resetIndex();84  return { streams: cat.channelStreams(id) };85});8687// The player reports what really happened in the browser; it is shown next to the server-side test, never instead of it.88route("POST", "/channels/:id/played", async (c) => {89  const b = await c.body(z.object({ streamId: z.number().int(), ok: z.boolean(), error: z.string().max(300).optional() }));90  run("UPDATE streams SET play_ok = ?, play_at = ?, play_error = ? WHERE id = ? AND channel_id = ?", Number(b.ok), now(), b.error ?? null, b.streamId, c.params[0]);91  if (b.ok) cat.recordWatch(c.params[0]);92});9394route("POST", "/favorites", async (c) => {95  const b = await c.body(z.object({ channelId: z.string().max(200), listId: z.number().int().default(1), on: z.boolean() }));96  if (!cat.setFavorite(b.channelId, b.listId, b.on)) throw new HttpError(404, "Chaîne ou liste introuvable");97});98route("POST", "/hidden", async (c) => { const b = await c.body(z.object({ channelId: z.string().max(200), on: z.boolean() })); cat.setHidden(b.channelId, b.on); });99route("GET", "/lists", () => ({ lists: cat.lists() }));100route("GET", "/lists/:id", (c) => ({ items: cat.listChannels(Number(c.params[0])), programmes: cat.nowNext(cat.listChannels(Number(c.params[0])).map((x) => x.id)) }));101route("POST", "/lists", async (c) => {102  const b = await c.body(z.object({ name: z.string().trim().min(1).max(60) }));103  const pos = get<{ p: number }>("SELECT COALESCE(MAX(position), 0) + 1 p FROM lists")!.p;104  return { id: Number(run("INSERT INTO lists(name, position, created_at) VALUES(?,?,?)", b.name, pos, now()).lastInsertRowid) };105});106route("PATCH", "/lists/:id", async (c) => {107  const id = Number(c.params[0]);108  const b = await c.body(z.object({ name: z.string().trim().min(1).max(60).optional(), order: z.array(z.string().max(200)).max(5000).optional() }));109  if (b.name) run("UPDATE lists SET name = ? WHERE id = ?", b.name, id);110  if (b.order) cat.reorderList(id, b.order);111});112route("DELETE", "/lists/:id", (c) => { const id = Number(c.params[0]); if (id === 1) throw new HttpError(400, "La liste « Favoris » ne peut pas être supprimée"); run("DELETE FROM lists WHERE id = ?", id); });113route("PUT", "/lists", async (c) => { const b = await c.body(z.object({ order: z.array(z.number().int()).max(200) })); tx(() => b.order.forEach((id, i) => run("UPDATE lists SET position = ? WHERE id = ?", i, id))); });114route("GET", "/now", (c) => ({ programmes: cat.nowNext((c.url.searchParams.get("ids") ?? "").split(",").filter(Boolean).slice(0, 80)) }));115route("GET", "/history", () => ({ items: cat.historyChannels(60) }));116route("DELETE", "/history", () => { run("DELETE FROM history"); });117118// Guide: channels that have real programme data (favourites first), in pages, with their programmes in the window.119route("GET", "/guide", (c) => {120  const p = c.url.searchParams;121  const from = Number(p.get("from")) || now() - 3600_000, to = Math.min(Number(p.get("to")) || from + 6 * 3600_000, from + 36 * 3600_000);122  const scope = p.get("scope") ?? "data";123  const withData = cat.channelsWithProgrammes();124  const sets = cat.userSets();125  let list: cat.Channel[];126  if (scope === "fav") list = cat.listChannels(1);127  else {128    const q = cat.search({ q: p.get("q") || undefined, country: p.get("country") || undefined, limit: 200, offset: 0 });129    const allCh = p.get("q") || p.get("country") ? q.items : cat.channelsByIds([...withData]);130    list = allCh.filter((x) => scope === "all" || withData.has(x.id)).sort((a, b) => Number(sets.fav.has(b.id)) - Number(sets.fav.has(a.id)) || a.name.localeCompare(b.name, "fr"));131  }132  const offset = Number(p.get("offset")) || 0, limit = 60;133  const page = list.slice(offset, offset + limit);134  return { total: list.length, channels: page, programmes: cat.programmes(page.map((x) => x.id), from, to), from, to, withData: withData.size, lastEpgAt: Number(getSetting("last_epg_at") ?? 0) || null };135});136137// --- personal M3U playlists (management; the playlists themselves are served by /m3u/<token>.m3u) --------------------------138import * as PL from "../playlists";139import { env } from "../env";140const FilterSchema = z.object({ lists: z.array(z.number().int()).optional(), countries: z.array(z.string()).optional(), categories: z.array(z.string()).optional(), languages: z.array(z.string()).optional(),141  onlyUp: z.boolean().optional(), best: z.boolean().optional(), group: z.enum(["category", "country"]).optional(), max: z.number().int().optional() });142const view = (p: PL.Row) => {143  const filter = PL.cleanFilter(JSON.parse(p.filter)); const entries = PL.buildEntries(filter);144  return { id: p.id, name: p.name, filter, url: `${env.appUrl}/m3u/${p.token}.m3u`, epgUrl: `${env.appUrl}/m3u/${p.token}.xml`, createdAt: p.created_at, lastUsedAt: p.last_used_at, lastUsedBy: p.last_used_by, hits: p.hits,145    channels: new Set(entries.map((e) => e.channel.id)).size, streams: entries.length };146};147route("GET", "/playlists", () => ({ playlists: PL.listPlaylists().map(view) }));148route("POST", "/playlists/preview", async (c) => {149  const f = PL.cleanFilter(await c.body(FilterSchema)); const e = PL.buildEntries(f);150  const groups = new Map<string, number>(); for (const x of e) groups.set(x.group, (groups.get(x.group) ?? 0) + 1);151  return { channels: new Set(e.map((x) => x.channel.id)).size, streams: e.length, groups: [...groups].map(([name, count]) => ({ name, count })).slice(0, 40), sample: e.slice(0, 8).map((x) => x.channel.name) };152});153route("POST", "/playlists", async (c) => {154  const b = await c.body(z.object({ name: z.string().trim().min(1).max(60), filter: FilterSchema }));155  if (PL.listPlaylists().length >= 20) throw new HttpError(400, "20 playlists au maximum");156  return view(PL.createPlaylist(b.name, PL.cleanFilter(b.filter)));157});158route("PATCH", "/playlists/:id", async (c) => {159  const b = await c.body(z.object({ name: z.string().trim().min(1).max(60).optional(), filter: FilterSchema.optional() }));160  if (b.name) run("UPDATE playlists SET name = ? WHERE id = ?", b.name, Number(c.params[0]));161  if (b.filter) run("UPDATE playlists SET filter = ? WHERE id = ?", JSON.stringify(PL.cleanFilter(b.filter)), Number(c.params[0]));162});163// A new address: every device that still uses the old one loses access.164route("POST", "/playlists/:id/rotate", (c) => { run("UPDATE playlists SET token = ?, last_used_at = NULL, last_used_by = NULL, hits = 0 WHERE id = ?", PL.newToken(), Number(c.params[0])); });165route("DELETE", "/playlists/:id", (c) => { run("DELETE FROM playlists WHERE id = ?", Number(c.params[0])); });166
Files main
Menu

Theme