Repository Public
1import http from "node:http";2import type { AddressInfo } from "node:net";3import { afterAll, beforeAll, describe, expect, it } from "vitest";4import { bumpCatalog, now, run } from "@/server/db";5import * as cat from "@/server/catalog";6import { ensureBuiltinSources } from "@/server/sync";7import { ingestProgrammes } from "@/server/epg";89// A catalogue of 12 000 generated rows is used ONLY to measure search speed and exercise filters in isolation;10// the real import is verified against IPTV-org in TESTING.md.11beforeAll(() => {12 ensureBuiltinSources();13 const names = ["Ici Radio-Canada Télé", "Ici RDI", "LCN", "TVA Sports", "France 24", "CBC News Network", "TV5 Québec Canada", "Télé-Québec", "BFM TV", "Euronews"];14 const t = now();15 run("BEGIN");16 for (let i = 0; i < 12_000; i++) {17 const name = i < names.length ? names[i] : `Canal ${i} ${["Norte", "Sur", "Este", "Oeste"][i % 4]}`;18 const id = `c${i}`;19 run("INSERT INTO channels(id, name, country, categories, languages, known, first_seen, updated_at) VALUES(?,?,?,?,?,1,?,?)", id, name, i < 8 ? "CA" : i < 10 ? "FR" : "MX", i % 3 ? "general" : "news", i < 10 ? "fra" : "spa", t, t);20 run("INSERT INTO streams(channel_id, source_id, url, first_seen, last_seen, status) VALUES(?,1,?,?,?,?)", id, `https://example.org/${i}.m3u8`, t, t, i % 5 === 0 ? "up" : i % 5 === 1 ? "down" : "unknown");21 }22 run("COMMIT"); bumpCatalog(); cat.resetIndex();23});2425describe("search", () => {26 const names = (q: string, extra: cat.Query = {}) => cat.search({ q, limit: 5, ...extra }).items.map((c) => c.name);27 it("finds exact and prefix matches first", () => { expect(names("lcn")[0]).toBe("LCN"); expect(names("france")[0]).toBe("France 24"); });28 it("ignores accents and case", () => { expect(names("tele quebec")[0]).toBe("Télé-Québec"); expect(names("RADIO CANADA TELE")[0]).toBe("Ici Radio-Canada Télé"); });29 it("tolerates typos and transpositions", () => {30 expect(names("frnace 24")[0]).toBe("France 24");31 expect(names("euronwes")[0]).toBe("Euronews");32 expect(names("radoi canada")[0]).toBe("Ici Radio-Canada Télé");33 expect(names("cbc nwes netwrk")[0]).toBe("CBC News Network");34 });35 it("returns nothing for nonsense", () => { expect(cat.search({ q: "zzzzqqqq" }).total).toBe(0); });36 it("filters by country, category, language and status", () => {37 expect(cat.search({ country: "CA" }).total).toBe(8);38 expect(cat.search({ country: "FR", language: "fra" }).total).toBe(2);39 expect(cat.search({ status: "up" }).total).toBe(2400);40 expect(cat.search({ status: "down", category: "news" }).items.every((c) => c.status === "down" && c.categories.includes("news"))).toBe(true);41 });42 it("paginates", () => { const a = cat.search({ limit: 10 }), b = cat.search({ limit: 10, offset: 10 }); expect(a.items).toHaveLength(10); expect(a.items[0].id).not.toBe(b.items[0].id); });43 it("stays fast on 12 000 channels", () => {44 const t0 = performance.now();45 for (const q of ["frnace", "canal 77 nort", "radio canada", "news", "telequebec"]) cat.search({ q });46 expect((performance.now() - t0) / 5).toBeLessThan(60);47 });48});4950describe("user state", () => {51 it("favourites persist, reorder, and survive a catalogue rebuild", () => {52 cat.setFavorite("c2", 1, true); cat.setFavorite("c4", 1, true); cat.setFavorite("c0", 1, true);53 expect(cat.listChannels(1).map((c) => c.id)).toEqual(["c2", "c4", "c0"]);54 cat.reorderList(1, ["c0", "c2", "c4"]);55 bumpCatalog(); cat.resetIndex();56 expect(cat.listChannels(1).map((c) => c.id)).toEqual(["c0", "c2", "c4"]);57 expect(cat.search({ fav: true }).total).toBe(3);58 cat.setFavorite("c4", 1, false);59 expect(cat.search({ fav: true }).total).toBe(2);60 expect(cat.setFavorite("nope", 1, true)).toBe(false);61 });62 it("a favourite whose streams disappeared stays listed as unavailable", () => {63 run("DELETE FROM streams WHERE channel_id = 'c2'"); run("UPDATE channels SET active = 0 WHERE id = 'c2'"); bumpCatalog(); cat.resetIndex();64 const c = cat.listChannels(1).find((x) => x.id === "c2")!;65 expect(c).toMatchObject({ status: "down", streams: 0 });66 });67 it("hidden channels leave search and rows, and come back", () => {68 cat.setHidden("c1", true);69 expect(cat.search({ q: "ici rdi" }).items.find((c) => c.id === "c1")).toBeUndefined();70 expect(cat.search({ hidden: "only" }).items.map((c) => c.id)).toEqual(["c1"]);71 cat.setHidden("c1", false);72 expect(cat.search({ q: "ici rdi" }).items[0].id).toBe("c1");73 });74 it("history records the last channel", async () => { cat.recordWatch("c5"); await new Promise((r) => setTimeout(r, 5)); cat.recordWatch("c6"); expect(cat.historyChannels(1)[0].id).toBe("c6"); });75 it("programmes: only catalogue channels, now/next in order, nothing invented", () => {76 const t = now();77 const n = ingestProgrammes([78 { channelId: "c0@SD", start: t - 600_000, stop: t + 600_000, title: "En cours", subtitle: null, description: null, category: null },79 { channelId: "c0@SD", start: t + 600_000, stop: t + 1_200_000, title: "Ensuite", subtitle: null, description: null, category: null },80 { channelId: "inconnue.xx", start: t, stop: t + 1000, title: "x", subtitle: null, description: null, category: null },81 ], "test");82 expect([...n.entries()]).toEqual([["c0", 2]]);83 expect(cat.nowNext(["c0", "c3"])).toMatchObject({ c0: [{ title: "En cours" }, { title: "Ensuite" }] });84 expect(cat.nowNext(["c3"]).c3).toBeUndefined();85 });86});8788describe("stream probe", () => {89 let server: http.Server, base: string;90 beforeAll(async () => {91 server = http.createServer((req, res) => {92 const h = { "content-type": "application/vnd.apple.mpegurl", "access-control-allow-origin": "*" };93 if (req.url === "/ok.m3u8") { res.writeHead(200, h); res.end("#EXTM3U\n#EXTINF:6,\nseg0.ts\n"); }94 else if (req.url === "/master.m3u8") { res.writeHead(200, h); res.end("#EXTM3U\n#EXT-X-STREAM-INF:BANDWIDTH=1\nv/broken.m3u8\n"); }95 else if (req.url === "/html.m3u8") { res.writeHead(200, { "content-type": "text/html" }); res.end("<!doctype html><html>parked</html>"); }96 else if (req.url === "/geo.m3u8") { res.writeHead(403); res.end(); }97 else if (req.url === "/slow.m3u8") { /* never answers */ }98 else { res.writeHead(404); res.end(); }99 });100 await new Promise<void>((r) => server.listen(0, "127.0.0.1", r));101 base = `http://127.0.0.1:${(server.address() as AddressInfo).port}`;102 });103 afterAll(() => { server.closeAllConnections(); server.close(); });104 const probe = async (path: string, allow = true) => {105 process.env.SPTV_ALLOW_PRIVATE_HOSTS = allow ? "1" : "0";106 const { probeStream } = await import("@/server/checker");107 try { return await probeStream({ id: 1, url: base + path, referrer: null, user_agent: null }, 1500); } finally { process.env.SPTV_ALLOW_PRIVATE_HOSTS = "0"; }108 };109 it("valid playlist → up, CORS recorded", async () => { expect(await probe("/ok.m3u8")).toMatchObject({ status: "up", httpStatus: 200, cors: true }); });110 it("master playlist with a dead variant → down", async () => { const r = await probe("/master.m3u8"); expect(r.status).toBe("down"); expect(r.error).toMatch(/variante.*404/); });111 it("HTML instead of a playlist → down", async () => { expect((await probe("/html.m3u8")).error).toMatch(/playlist HLS valide/); });112 it("403 → down with an explicit reason", async () => { expect(await probe("/geo.m3u8")).toMatchObject({ status: "down", httpStatus: 403 }); });113 it("404 → down", async () => { expect((await probe("/missing.m3u8")).error).toMatch(/404/); });114 it("timeout → down", async () => { expect((await probe("/slow.m3u8")).error).toMatch(/Délai/); });115 it("private address refused when the guard is active", async () => { expect(await probe("/ok.m3u8", false)).toMatchObject({ status: "down", error: "Adresse privée ou réservée refusée" }); });116});117