SPB Git

Repository Public

vod.test.ts 9.2 KB 107 lines typescript

1import { describe, expect, it } from "vitest";2import { episodeNumber, iaMatch, mapGenres, pickVideos } from "@/server/vod";3import { parseName, playbackMode, srtToVtt, type Probe } from "@/server/library";45describe("Internet Archive matching", () => {6  const item = (title: string, year?: string) => ({ metadata: { title, year } });7  it("accepts the same work, in any of its titles", () => {8    expect(iaMatch(item("His Girl Friday", "1940"), ["La Dame du vendredi", "His Girl Friday"], 1940)).toBeGreaterThan(1.9);9    expect(iaMatch(item("Le voyage dans la lune"), ["Le Voyage dans la Lune", "A Trip to the Moon"], 1902)).toBeGreaterThan(0);10    expect(iaMatch(item("Nosferatu (1922) Full Movie HD"), ["Nosferatu le vampire", "Nosferatu"], 1922)).toBeGreaterThan(0);11  });12  it("refuses a namesake from another year and an unrelated item", () => {13    expect(iaMatch(item("The Saint's Girl Friday 1953"), ["La Dame du vendredi", "His Girl Friday"], 1940)).toBe(0);14    expect(iaMatch(item("Popeye for President"), ["His Girl Friday"], 1940)).toBe(0);15  });16});1718describe("Internet Archive files", () => {19  it("keeps one browser-playable rendition per work and attaches subtitles", () => {20    const v = pickVideos("x", { files: [21      { name: "film.mpeg", format: "MPEG2", height: "480" }, { name: "film.mp4", format: "h.264", height: "480", length: "5504.57" }, { name: "film_512kb.mp4", format: "512Kb MPEG4", height: "240" },22      { name: "film.ogv", format: "Ogg Video" }, { name: "film.asr.srt", format: "SubRip" }, { name: "film.fr.srt", format: "SubRip" },23    ] });24    expect(v).toHaveLength(1);25    expect(v[0]).toMatchObject({ name: "film.mp4", height: 480, duration: 5505 });26    expect(v[0].url).toBe("https://archive.org/download/x/film.mp4");27    expect(v[0].subtitles.map((s) => s.label)).toEqual(["English (automatique)", "Français"]);28  });29  it("returns nothing when there is no MP4", () => { expect(pickVideos("x", { files: [{ name: "a.avi", format: "DivX" }, { name: "a.ogv", format: "Ogg Video" }] })).toEqual([]); });30});3132describe("naming", () => {33  it("parses episode numbers", () => {34    expect(episodeNumber("Pioneer One - 01x03 - Alone.mp4")).toEqual({ season: 1, episode: 3 });35    expect(episodeNumber("Show.S02E11.720p.mkv")).toEqual({ season: 2, episode: 11 });36    expect(episodeNumber("flash_gordon_ep07_512kb.mp4")).toEqual({ season: 1, episode: 7 });37    expect(episodeNumber("Chapter 4 - Doomed")).toEqual({ season: 1, episode: 4 });38    expect(episodeNumber("no number here")).toBeNull();39  });40  it("recognises films and series from file names", () => {41    expect(parseName("/m/Big Buck Bunny (2008).mp4", "/m")).toEqual({ kind: "movie", title: "Big Buck Bunny", year: 2008 });42    expect(parseName("/m/Sintel.2010.1080p.x265.mkv", "/m")).toEqual({ kind: "movie", title: "Sintel", year: 2010 });43    expect(parseName("/m/Le.Voyage.dans.la.Lune.1902.FRENCH.720p.mkv", "/m")).toMatchObject({ title: "Le Voyage dans la Lune", year: 1902 });44    expect(parseName("/s/Caminandes/Season 1/Caminandes S01E02 Gran Dillama.mp4", "/s/Caminandes/Season 1")).toEqual({ kind: "series", title: "Caminandes", year: null, season: 1, episode: 2, episodeName: "Gran Dillama" });45    expect(parseName("/s/Ma Série (2019)/Saison 2/2x05.mkv", "/s/Ma Série (2019)/Saison 2")).toMatchObject({ kind: "series", title: "Ma Série", year: 2019, season: 2, episode: 5 });46  });47  it("maps Wikidata genre labels", () => { expect(new Set(mapGenres(["cinéma de science-fiction", "film muet", "comédie romantique", "film documentaire"]))).toEqual(new Set(["Science-fiction", "Muet", "Comédie", "Romance", "Documentaire"])); });48});4950describe("playback decision", () => {51  const p = (o: Partial<Probe>): Probe => ({ container: "mp4", duration: 100, size: 1, vcodec: "h264", vtag: "avc1", width: 1920, height: 1080, pixfmt: "yuv420p", acodec: "aac", audio: [], subs: [], ...o });52  it("plays compatible files as they are", () => { expect(playbackMode(p({}))).toBe("direct"); expect(playbackMode(p({ container: "webm", vcodec: "vp9", acodec: "opus" }))).toBe("direct"); });53  it("only changes the container when codecs are fine", () => { expect(playbackMode(p({ container: "mkv" }))).toBe("remux"); expect(playbackMode(p({ acodec: "ac3" }))).toBe("remux"); });54  it("re-encodes what browsers cannot decode", () => { expect(playbackMode(p({ container: "mkv", vcodec: "hevc", pixfmt: "yuv420p10le" }))).toBe("transcode"); expect(playbackMode(p({ pixfmt: "yuv420p10le" }))).toBe("transcode"); expect(playbackMode(p({ container: "avi", vcodec: "mpeg4" }))).toBe("transcode"); });55  it("flags HEVC in MP4 for the browsers that can read it", () => { expect(playbackMode(p({ vcodec: "hevc", vtag: "hvc1" }))).toBe("direct-hevc"); });56  it("converts SRT to WebVTT", () => { expect(srtToVtt("1\n00:00:01,500 --> 00:00:03,000\nBonjour\n")).toBe("WEBVTT\n\n1\n00:00:01.500 --> 00:00:03.000\nBonjour\n"); });57});5859describe("ONF", async () => {60  const { parseEmbed, parseFilm } = await import("@/server/onf");61  const layer = (o: Record<string, string>) => `<script>dataLayer.push({ ${Object.entries(o).map(([k, v]) => `'${k}': ${v.startsWith("{") ? v : `'${v}'`}`).join(", ")} })</script>`;62  it("reads what the embedded player offers", () => {63    const html = layer({ nfb_version_year: "1971", nfb_version_duration: "6268", nfb_work_publishing_status: "Public" }) + `{"source": "https://d3acx5b8mnvbua.cloudfront.net/hls/a/a.m3u8?Policy=x"}`;64    expect(parseEmbed(html)).toEqual({ playable: true, seconds: 6268, year: 1971 });65    expect(parseEmbed(layer({ nfb_version_duration: "120", nfb_work_publishing_status: "Public" })).playable).toBe(false); // no source: nothing to watch66  });67  it("reads the film page: title, synopsis, artwork, real categories", () => {68    const html = `<a><span>Animation</span></a><script type="application/ld+json">{"name": "Mon oncle Antoine", "description": "L&#x27;atmosphère d&#x27;une petite ville", "thumbnailUrl": "https://assets.nfbcdn.ca/t.jpg?w=2048&amp;h=", "image": "https://assets.nfbcdn.ca/j.jpg", "director": [{"name": "Claude Jutra"}]}</script>`69      + layer({ nfb_version_title: "Mon oncle Antoine", nfb_version_year: "1971", nfb_version_duration: "6268", nfb_version_subject: "Famille, Mines", nfb_version_category: "{'en': ['Fiction'], 'fr': ['Fiction', 'Long métrage de fiction']}" });70    const f = parseFilm(html)!;71    expect(f).toMatchObject({ title: "Mon oncle Antoine", year: 1971, seconds: 6268, directors: ["Claude Jutra"], subjects: ["Famille", "Mines"], synopsis: "L'atmosphère d'une petite ville", poster: "https://assets.nfbcdn.ca/j.jpg", backdrop: "https://assets.nfbcdn.ca/t.jpg?w=1280" });72    expect(f.kinds).toEqual(["Fiction", "Long métrage de fiction"]); // the site menu word « Animation » is ignored73  });74});7576describe("personal M3U playlists", async () => {77  const { cleanFilter, renderM3u, renderXmltv, newToken, byToken } = await import("@/server/playlists");78  const { parseM3u } = await import("@/server/m3u");79  const ch = (id: string, name: string) => ({ id, name, country: "CA", categories: ["news"], languages: ["fra"], logo: "https://example.org/l.png", status: "up" as const, streams: 1, web: true, hasGuide: false, firstSeen: 0 });80  it("sanitises filters", () => {81    expect(cleanFilter({ countries: ["CA", "ca", "<x>"], languages: ["fra", "french"], categories: ["news", "NEWS!"], lists: [1, -2, 1.5] as number[], max: 99999 }))82      .toEqual({ lists: [1], countries: ["CA"], categories: ["news"], languages: ["fra"], onlyUp: true, best: true, group: "category", max: 5000 });83  });84  it("writes a playlist our own parser reads back, with player options for streams that need headers", () => {85    const m3u = renderM3u([86      { channel: ch("IciRDI.ca", 'ICI "RDI", info'), group: "Favoris", streamId: 1, url: "https://example.org/rdi.m3u8", referrer: null, userAgent: null, alt: 0 },87      { channel: ch("X.ca", "Chaîne X"), group: "Actualités", streamId: 2, url: "http://example.org/x.m3u8", referrer: "https://site.example/", userAgent: "UA/1.0", alt: 1 },88    ], "https://tv.example/m3u/t.xml");89    expect(m3u.startsWith('#EXTM3U url-tvg="https://tv.example/m3u/t.xml"')).toBe(true);90    const p = parseM3u(m3u);91    expect(p.errors).toEqual([]); expect(p.entries).toHaveLength(2);92    expect(p.entries[0]).toMatchObject({ tvgId: "IciRDI.ca", url: "https://example.org/rdi.m3u8", group: ["Favoris"], logo: "https://example.org/l.png", country: "CA" });93    expect(p.entries[0].name).toBe("ICI 'RDI' info"); // quotes and commas would break the line format94    expect(p.entries[1]).toMatchObject({ referrer: "https://site.example/", userAgent: "UA/1.0", name: "Chaîne X (source 2)" });95  });96  it("produces an empty but valid guide when no programme is known", () => { expect(renderXmltv([])).toContain("<tv generator-info-name=\"SP TV\">"); });97  it("tokens are long, random, and malformed ones are never looked up", () => {98    expect(newToken()).toMatch(/^[A-Za-z0-9_-]{32}$/); expect(newToken()).not.toBe(newToken());99    expect(byToken("short")).toBeUndefined(); expect(byToken("a".repeat(32) + "' OR 1=1")).toBeUndefined();100  });101});102103describe("TMDB enrichment is inert without a key", async () => {104  const { enrichTmdb } = await import("@/server/tmdb");105  it("does nothing and calls nothing", async () => { expect(await enrichTmdb()).toMatchObject({ examined: 0, matched: 0 }); });106});107
Files main
Menu

Theme