Repository Public
1import { expect, test, type Browser, type Page } from "@playwright/test";23// Relay engine, end to end, against a real instance. Playback uses the home channels (files of the owner's library,4// relayed with his declared authorisation): the test never relays a third-party stream.5const PASSWORD = process.env.SPTV_PASSWORD ?? "";6test.skip(!PASSWORD, "SPTV_PASSWORD requis");7const canDecode = (project: string) => !project.startsWith("chromium");8async function login(page: Page) {9 await page.goto("/connexion"); await page.fill('input[name="username"]', process.env.SPTV_USERNAME ?? "sp"); await page.fill('input[name="password"]', PASSWORD);10 await page.click('button[type="submit"]'); await page.waitForURL((u) => u.pathname === "/");11}12const get = <T,>(page: Page, path: string) => page.evaluate(async (p) => (await fetch(p)).json(), `/api${path}`) as Promise<T>;13const send = (page: Page, method: string, path: string, body?: unknown) => page.evaluate(async ([m, p, b]) => { const r = await fetch(p as string, { method: m as string, headers: b ? { "content-type": "application/json" } : undefined, body: b ? JSON.stringify(b) : undefined }); return { status: r.status, data: await r.json().catch(() => ({})) }; }, [method, `/api${path}`, body] as const);14interface Relay { id: string; channel: string; state: string; mode: string | null; clients: number; inKbps: number; ffmpeg: boolean }15interface Admin { engine: { up: boolean; enabled: boolean; version: string | null }; totals: { relays: number; ffmpeg: number; clients: number; cpu: number; rssMb: number }; relays: Relay[]; sessions: { channel: string }[]; sources: { id: number; name: string; kind: string; policy: { allowed: boolean } }[]; limits: { idleSec: number } }16interface Ch { id: string; name: string }17const TOKEN = "A".repeat(43);1819/** A home channel and its stream, or null when the instance has none. */20async function homeChannel(page: Page, nth = 0): Promise<{ name: string; streamId: number } | null> {21 const a = await get<Admin>(page, "/admin/relay");22 const src = a.sources.filter((s) => s.kind === "loop" && s.policy.allowed)[nth]; if (!src) return null;23 const ch = (await get<{ items: Ch[] }>(page, `/channels?q=${encodeURIComponent(src.name)}&limit=5`)).items.find((c) => c.name === src.name); if (!ch) return null;24 const d = await get<{ streams: { id: number; relay: boolean; relayOnly: boolean; url: string }[] }>(page, `/channels/${encodeURIComponent(ch.id)}`);25 expect(d.streams[0]).toMatchObject({ relay: true, relayOnly: true, url: "" });26 return { name: src.name, streamId: d.streams[0].id };27}28async function watch(page: Page, name: string) {29 await page.goto(`/chaines?q=${encodeURIComponent(name)}`);30 await page.getByRole("button", { name: new RegExp(`^${name.replace(/[.*+?^${}()|[\]\\]/g, "\\$&")} — `) }).first().click();31 // Real playback: the clock of the video element moves, with a decoded picture.32 await page.waitForFunction(() => { const v = document.querySelector<HTMLVideoElement>("[data-player] video"); const w = window as unknown as { __t0?: number }; if (!v || v.paused || v.readyState < 3 || !v.videoWidth) { w.__t0 = undefined; return false; } w.__t0 ??= v.currentTime; return v.currentTime - w.__t0 > 3; }, undefined, { timeout: 90_000, polling: 250 });33}34async function second(browser: Browser): Promise<Page> { const ctx = await browser.newContext({ baseURL: test.info().project.use.baseURL }); const p = await ctx.newPage(); await login(p); return p; }3536test("relais : rien n'est accessible sans session ni jeton", async ({ request }) => {37 expect((await request.get("/api/admin/relay")).status()).toBe(401);38 expect((await request.post("/api/relay/open", { data: { streamId: 1 } })).status()).toBeGreaterThanOrEqual(401);39 expect((await request.put("/api/admin/relay/sources/1", { data: { allowed: true, basis: "aucune autorisation réelle", declaration: true } })).status()).toBeGreaterThanOrEqual(401);40 expect((await request.get(`/relay/${TOKEN}/index.m3u8`)).status()).toBe(410);41 expect((await request.get(`/relay/${TOKEN}/timeshift/get.mp4?start=${Date.now() - 30_000}&duration=30`)).status()).toBe(410);42 expect((await request.get("/relay/court/index.m3u8", { maxRedirects: 0 })).status()).toBe(404);43});4445test("relais : état du moteur, sources non autorisées refusées, déclaration exigée", async ({ page }) => {46 await login(page);47 const a = await get<Admin>(page, "/admin/relay");48 expect(a.engine.enabled).toBe(true); expect(a.engine.up, "MediaMTX doit répondre").toBe(true); expect(a.engine.version).toMatch(/^v?\d+\./);49 // A third-party source nobody authorised: no relay, whatever is asked.50 const other = a.sources.find((s) => !s.policy.allowed && s.kind !== "loop")!; expect(other).toBeTruthy();51 const { items } = await get<{ items: Ch[] }>(page, "/channels?status=up&limit=30");52 let refused = 0;53 for (const c of items.slice(0, 8)) {54 const d = await get<{ streams: { id: number; relay: boolean }[] }>(page, `/channels/${encodeURIComponent(c.id)}`);55 const s = d.streams.find((x) => !x.relay); if (!s) continue;56 const r = await send(page, "POST", "/relay/open", { streamId: s.id }); expect(r.status).toBe(403); expect(String(r.data.error)).toMatch(/pas autorisé/); refused++; if (refused >= 2) break;57 }58 expect(refused).toBeGreaterThan(0);59 expect((await send(page, "PUT", `/admin/relay/sources/${other.id}`, { allowed: true, basis: "x" })).status).toBe(400);60 expect((await send(page, "PUT", `/admin/relay/sources/${other.id}`, { allowed: true, basis: "Test : aucune déclaration cochée" })).status).toBe(400);61 expect((await get<Admin>(page, "/admin/relay")).sources.find((s) => s.id === other.id)!.policy.allowed).toBe(false);62 await page.goto("/admin"); await page.getByRole("tab", { name: "Relay Engine" }).click();63 await expect(page.getByRole("heading", { name: /Relay Engine en service/ })).toBeVisible();64 for (const label of ["Flux entrants actifs", "Clients connectés", "Processus de transcodage", "Processeur", "Mémoire", "Temps de lecture (24 h)", "Erreurs (24 h)"]) await expect(page.getByText(label, { exact: true }).first()).toBeVisible();65});6667test("relais : une chaîne et un lecteur, adresse de session temporaire, arrêt automatique", async ({ page, browser, request }, info) => {68 test.skip(!canDecode(info.project.name), "Chromium de Playwright : pas de décodeur H.264");69 await login(page);70 const ch = await homeChannel(page); test.skip(!ch, "aucune chaîne maison sur cette instance");71 await watch(page, ch!.name);72 await expect.poll(async () => (await get<Admin>(page, "/admin/relay")).relays.find((r) => r.channel === ch!.name && r.state === "running")?.inKbps ?? 0, { timeout: 30_000 }).toBeGreaterThan(50);73 const a = await get<Admin>(page, "/admin/relay");74 expect(a.relays.filter((r) => r.channel === ch!.name && r.state === "running")).toHaveLength(1); expect(a.totals.clients).toBeGreaterThanOrEqual(1); expect(a.totals.rssMb).toBeGreaterThan(10);75 // The playback address is a capability bound to the sign-in that opened it: it dies with that sign-in.76 const p2 = await second(browser);77 const o = await send(p2, "POST", "/relay/open", { streamId: ch!.streamId }); expect(o.status).toBe(200);78 const url = String(o.data.url); expect(url).toMatch(/^\/relay\/[A-Za-z0-9_-]{43}\/index\.m3u8$/);79 const m = await request.get(url); expect(m.status()).toBe(200); expect(await m.text()).toContain("#EXTM3U"); expect(await m.text()).not.toMatch(/https?:\/\//);80 await send(p2, "POST", "/auth/logout"); expect((await request.get(url)).status()).toBe(401); expect((await request.get(url)).status()).toBe(410);81 await p2.context().close();82 // Leaving the channel releases the relay after the inactivity delay.83 await page.goto("/admin");84 await expect.poll(async () => (await get<Admin>(page, "/admin/relay")).relays.filter((r) => r.channel === ch!.name && ["starting", "running", "reconnecting"].includes(r.state)).length, { timeout: (a.limits.idleSec + 60) * 1000, intervals: [5000] }).toBe(0);85 expect((await get<Admin>(page, "/admin/relay")).totals.ffmpeg).toBe(0);86});8788test("relais : trois lecteurs sur une chaîne, un seul flux entrant", async ({ page, browser }, info) => {89 test.skip(!canDecode(info.project.name), "Chromium de Playwright : pas de décodeur H.264");90 await login(page);91 const ch = await homeChannel(page); test.skip(!ch, "aucune chaîne maison sur cette instance");92 const p2 = await second(browser), p3 = await second(browser);93 await watch(page, ch!.name); await watch(p2, ch!.name); await watch(p3, ch!.name);94 await expect.poll(async () => (await get<Admin>(page, "/admin/relay")).relays.find((r) => r.channel === ch!.name && r.state === "running")?.clients ?? 0, { timeout: 30_000 }).toBeGreaterThanOrEqual(3);95 const a = await get<Admin>(page, "/admin/relay");96 expect(a.relays.filter((r) => r.channel === ch!.name && r.state === "running")).toHaveLength(1); expect(a.totals.ffmpeg).toBe(1);97 await p2.context().close(); await p3.context().close();98});99100test("relais : plusieurs chaînes simultanées, transcodage, différé", async ({ page, browser }, info) => {101 test.skip(!canDecode(info.project.name), "Chromium de Playwright : pas de décodeur H.264");102 await login(page);103 const a = await homeChannel(page, 0), b = await homeChannel(page, 1); test.skip(!a || !b, "il faut deux chaînes maison");104 const p2 = await second(browser);105 await watch(page, a!.name); await watch(p2, b!.name);106 await expect.poll(async () => (await get<Admin>(page, "/admin/relay")).relays.filter((r) => r.state === "running" && r.inKbps > 0).length, { timeout: 40_000 }).toBeGreaterThanOrEqual(2);107 const st = await get<Admin>(page, "/admin/relay");108 info.annotations.push({ type: "relais", description: st.relays.filter((r) => r.state === "running").map((r) => `${r.channel} : ${r.mode}`).join(" ; ") });109 await p2.context().close();110 // Timeshift: thirty seconds back from the relay's recording, then back to live.111 await page.waitForTimeout(32_000); await page.mouse.move(300, 300);112 await page.evaluate(() => { (window as unknown as { __t0?: number }).__t0 = undefined; });113 await page.getByRole("button", { name: "Revenir 30 secondes en arrière" }).click();114 await page.waitForFunction(() => { const v = document.querySelector<HTMLVideoElement>("[data-player] video"); return !!v && /timeshift\/get\.mp4/.test(v.currentSrc) && !v.paused && v.currentTime > 2 && v.videoWidth > 0; }, undefined, { timeout: 40_000 });115 await page.mouse.move(320, 320); await page.getByRole("button", { name: "Revenir au direct" }).click();116 await page.waitForFunction(() => { const v = document.querySelector<HTMLVideoElement>("[data-player] video"); return !!v && !/timeshift/.test(v.currentSrc) && !v.paused && v.readyState >= 3; }, undefined, { timeout: 60_000 });117});118