SPB Git

Repository Public

vod.spec.ts 14.7 KB 188 lines typescript

1import { expect, test, type Page } from "@playwright/test";23const PASSWORD = process.env.SPTV_PASSWORD ?? "";4test.skip(!PASSWORD, "SPTV_PASSWORD requis");5const canDecode = (name: string) => !name.startsWith("chromium");67async function login(page: Page) {8  await page.goto("/connexion");9  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>;13interface T { id: number; title: string; kind: string; rights: string; source: string; episodes: number; library: boolean }14const advancing = (page: Page, min = 2, timeout = 60_000) => page.waitForFunction((m) => {15  const v = document.querySelector<HTMLVideoElement>("[data-vod] video"); const w = window as unknown as { __t0?: number };16  if (!v || v.paused || v.readyState < 3 || !v.videoWidth) { w.__t0 = undefined; return false; } w.__t0 ??= v.currentTime; return v.currentTime - w.__t0 > m;17}, min, { timeout, polling: 250 }).then(() => true, () => false);18const reset = (page: Page) => page.evaluate(() => { (window as unknown as { __t0?: number }).__t0 = undefined; });1920test("médias et catalogue refusés sans session", async ({ request }) => {21  for (const p of ["/api/titles", "/api/search?q=a", "/api/media/1/file", "/api/media/1/hls/index.m3u8", "/api/media/1/thumb", "/api/media/1/subs/0", "/api/play/1", "/api/admin/library", "/api/admin/vod"])22    expect((await request.get(p)).status(), p).toBe(401);23});2425test("sections Films, Séries, Documentaires : titres réels avec statut des droits", async ({ page }) => {26  await login(page);27  const films = await get<{ total: number; items: T[] }>(page, "/titles?kind=movie&limit=50");28  test.skip(films.total === 0, "catalogue de films pas encore importé");29  expect(films.items.every((t) => ["pd", "cc", "personal", "official"].includes(t.rights))).toBe(true);30  await page.goto("/films");31  await expect(page.getByRole("button", { name: "Regarder" }).first()).toBeVisible();32  await expect(page.getByRole("heading", { level: 2 }).first()).toBeVisible();33  expect(await page.evaluate(() => document.documentElement.scrollWidth - document.documentElement.clientWidth)).toBeLessThanOrEqual(1);34  await page.goto("/series"); await expect(page.locator("main")).toContainText(/Séries|séries/);35  await page.goto("/documentaires"); await expect(page.locator("main")).toContainText(/ocumentaire/);36  // Title page: synopsis block, rights block with its justification and a link to the evidence.37  await page.goto(`/titre/${films.items[0].id}`);38  await expect(page.getByRole("heading", { name: "Source et droits" })).toBeVisible();39  await expect(page.getByRole("link", { name: /Page de la source/ })).toBeVisible();40  await expect(page.getByRole("button", { name: /^(Regarder|Reprendre)/ }).first()).toBeVisible();41});4243test("recherche unifiée : chaînes, films, séries, tolérance aux fautes", async ({ page }) => {44  await login(page);45  const r = await get<{ channels: { total: number }; movies: { total: number }; series: { total: number }; tookMs: number }>(page, "/search?q=news");46  expect(r.channels.total).toBeGreaterThan(10); expect(r.tookMs).toBeLessThan(250);47  const any = await get<{ items: T[] }>(page, "/titles?kind=movie&shorts=exclude&limit=1");48  test.skip(!any.items.length, "catalogue de films pas encore importé");49  const title = any.items[0].title; const typo = title.length > 6 ? title.slice(0, 2) + title[3] + title[2] + title.slice(4) : title;50  const s = await get<{ movies: { items: T[] } }>(page, `/search?q=${encodeURIComponent(typo)}`);51  expect(s.movies.items.map((t) => t.id)).toContain(any.items[0].id);52  await page.goto("/recherche"); await page.getByLabel("Recherche globale").fill("france");53  await expect(page.getByRole("heading", { name: /Chaînes TV/ })).toBeVisible();54  await page.getByRole("tab", { name: "Films" }).click(); await expect(page).toHaveURL(/type=movie/);55});5657test("film : lecture réelle, avance, reprise, liste et marquage", async ({ page }, info) => {58  await login(page);59  const any = await get<{ items: T[] }>(page, "/titles?kind=movie&source=Internet%20Archive&shorts=exclude&limit=3");60  test.skip(!any.items.length, "catalogue de films pas encore importé");61  const t = any.items[0];62  await page.goto(`/titre/${t.id}`);63  const d0 = await get<{ media: { mediaId: number } }>(page, `/titles/${t.id}`);64  await page.evaluate(async (m) => { await fetch("/api/watched", { method: "POST", headers: { "content-type": "application/json" }, body: JSON.stringify({ mediaId: m, watched: false }) }); }, d0.media.mediaId);65  // Ma liste66  await page.reload(); const fav = page.getByRole("button", { name: /Ma liste|Dans ma liste/ }).first();67  if ((await fav.innerText()).includes("Dans")) await fav.click();68  await fav.click(); await expect(fav).toContainText("Dans ma liste");69  expect((await get<{ items: T[] }>(page, "/title-favs")).items.map((x) => x.id)).toContain(t.id);70  await fav.click();71  if (!canDecode(info.project.name)) return; // no H.264 decoder in Playwright's Chromium72  await page.getByRole("button", { name: /^Regarder/ }).first().click(); await reset(page);73  expect(await advancing(page), "le film doit être lu").toBe(true);74  await page.evaluate(() => { document.querySelector<HTMLVideoElement>("[data-vod] video")!.currentTime = 300; }); await reset(page);75  expect(await advancing(page, 1.5), "lecture après avance à 5:00").toBe(true);76  await page.keyboard.press("Escape");77  await expect(page.getByRole("button", { name: /^Reprendre à 5:0/ })).toBeVisible({ timeout: 10_000 });78  const cont = await get<{ titles: (T & { progress: { position: number } })[] }>(page, "/continue");79  expect(cont.titles.find((x) => x.id === t.id)?.progress.position).toBeGreaterThan(295);80  await page.getByRole("button", { name: /^Reprendre/ }).first().click(); await reset(page); await advancing(page, 1);81  expect(await page.evaluate(() => document.querySelector<HTMLVideoElement>("[data-vod] video")!.currentTime)).toBeGreaterThan(295);82  await page.keyboard.press("Escape");83  await page.getByRole("button", { name: "Marquer comme vu" }).click(); await expect(page.getByRole("button", { name: "Vu", exact: true })).toBeVisible();84  await page.getByRole("button", { name: "Vu", exact: true }).click();85});8687test("série : saisons, épisodes, épisode suivant", async ({ page }, info) => {88  await login(page);89  const s = await get<{ items: T[] }>(page, "/titles?kind=series&limit=200");90  test.skip(!s.items.length, "aucune série importée");91  // A series played by SP TV's own player (ARTE series run inside ARTE's embedded player and are covered by engine.spec.ts).92  const own = s.items.filter((x) => x.source !== "ARTE"); test.skip(!own.length, "aucune série lue par le lecteur de SP TV");93  const t = own.find((x) => x.episodes >= 3) ?? own[0];94  const d = await get<{ seasons: { season: number; episodes: { mediaId: number; episode: number }[] }[] }>(page, `/titles/${t.id}`);95  expect(d.seasons.length).toBeGreaterThan(0); expect(d.seasons[0].episodes.length).toBeGreaterThan(1);96  for (const e of d.seasons.flatMap((x) => x.episodes)) await page.evaluate(async (m) => { await fetch("/api/watched", { method: "POST", headers: { "content-type": "application/json" }, body: JSON.stringify({ mediaId: m, watched: false }) }); }, e.mediaId);97  await page.goto(`/titre/${t.id}`);98  await expect(page.getByRole("heading", { name: "Épisodes" })).toBeVisible();99  await expect(page.getByRole("button", { name: /^Lire l'épisode/ })).toHaveCount(d.seasons[0].episodes.length);100  // Marking an episode as watched moves « Regarder » to the next one.101  await page.getByRole("button", { name: `Marquer l'épisode ${d.seasons[0].episodes[0].episode} comme vu` }).click();102  await expect(page.getByRole("button", { name: new RegExp(`^Regarder S${d.seasons[0].season} · É${d.seasons[0].episodes[1].episode}`) })).toBeVisible();103  await page.getByRole("button", { name: `Marquer l'épisode ${d.seasons[0].episodes[0].episode} comme non vu` }).click();104  if (!canDecode(info.project.name)) return;105  await page.getByRole("button", { name: /^Lire l'épisode/ }).first().click(); await reset(page);106  expect(await advancing(page), "l'épisode doit être lu").toBe(true);107  const first = await page.locator("[data-vod] p").first().innerText();108  await page.mouse.move(400, 300); await page.getByRole("button", { name: /^Épisode suivant/ }).click(); await reset(page);109  expect(await advancing(page, 1.5), "l'épisode suivant doit être lu").toBe(true);110  expect(await page.locator("[data-vod] p").first().innerText()).not.toBe(first);111  await page.keyboard.press("Escape");112});113114test("bibliothèque : fichiers servis à la session, conversion et sous-titres", async ({ page, request }, info) => {115  await login(page);116  const lib = await get<{ items: T[] }>(page, "/titles?library=1&limit=50");117  test.skip(!lib.items.length, "aucun fichier dans la bibliothèque");118  const adm = await get<{ dirs: { status: { reachable: boolean } }[]; ffmpeg: boolean }>(page, "/admin/library");119  expect(adm.dirs.length).toBeGreaterThan(0); expect(adm.ffmpeg).toBe(true);120  const film = lib.items.find((x) => x.kind === "movie")!;121  const d = await get<{ media: { mediaId: number; playback: string } }>(page, `/titles/${film.id}`);122  // Range request on the authenticated file route; the same URL without the session cookie is refused.123  const range = await page.evaluate(async (m) => { const r = await fetch(`/api/media/${m}/file`, { headers: { range: "bytes=0-1023" } }); return { status: r.status, len: (await r.arrayBuffer()).byteLength, cr: r.headers.get("content-range") }; }, d.media.mediaId);124  if (d.media.playback === "direct") { expect(range.status).toBe(206); expect(range.len).toBe(1024); }125  expect((await request.get(`/api/media/${d.media.mediaId}/file`)).status()).toBe(401);126  // Path traversal has no handle: media are addressed by number only.127  expect((await page.evaluate(async () => (await fetch("/api/media/..%2F..%2Fetc%2Fpasswd/file")).status))).toBeGreaterThanOrEqual(400);128  expect((await page.evaluate(async (m) => (await fetch(`/api/media/${m}/hls/..%2Fdone`)).status, d.media.mediaId))).toBeGreaterThanOrEqual(400);129  if (!canDecode(info.project.name)) return;130  for (const t of lib.items.filter((x) => x.kind === "movie").slice(0, 3)) {131    await page.goto(`/titre/${t.id}`); await page.getByRole("button", { name: /^(Regarder|Reprendre)/ }).first().click(); await reset(page);132    expect(await advancing(page, 2, 90_000), `lecture de « ${t.title} »`).toBe(true);133    await page.keyboard.press("Escape"); await page.waitForTimeout(400);134  }135});136137test("ONF : film gratuit lu dans le lecteur officiel intégré, lien vers onf.ca", async ({ page }, info) => {138  await login(page);139  const onf = await get<{ total: number; items: T[] }>(page, "/titles?source=ONF&shorts=exclude&limit=5");140  test.skip(!onf.total, "catalogue ONF pas encore importé");141  expect(onf.total).toBeGreaterThan(100); expect(onf.items.every((t) => t.rights === "official")).toBe(true);142  await page.goto(`/titre/${onf.items[0].id}`);143  await expect(page.getByText("Diffusion officielle gratuite").first()).toBeVisible();144  await expect(page.getByRole("link", { name: /Page de la source/ })).toHaveAttribute("href", /^https:\/\/www\.onf\.ca\/film\//);145  await page.getByRole("button", { name: /^Regarder/ }).first().click();146  const frame = page.locator("[data-vod] iframe");147  await expect(frame).toHaveAttribute("src", /^https:\/\/www\.onf\.ca\/film\/[^/]+\/embed\/player\/$/);148  await expect(page.getByRole("link", { name: /Voir sur onf\.ca/ })).toBeVisible();149  if (!info.project.name.startsWith("chromium")) {150    // The official player runs inside the iframe: start it and watch its own clock.151    await page.waitForTimeout(5000);152    const f = page.frames().find((x) => x.url().includes("onf.ca/film/"));153    expect(f, "le lecteur ONF doit être chargé").toBeTruthy();154    await f!.evaluate(() => { document.querySelector<HTMLElement>(".vjs-big-play-button")?.click(); document.querySelector("video")?.play().catch(() => {}); }).catch(() => {});155    const ok = await f!.waitForFunction(() => { const v = document.querySelector("video"); return !!v && !v.paused && v.currentTime > 3; }, null, { timeout: 45_000 }).then(() => true, () => false);156    info.annotations.push({ type: "onf", description: ok ? "film lu dans le lecteur officiel" : "lecteur chargé, lecture non confirmée par le test" });157    console.log(`[${info.project.name}] ONF « ${onf.items[0].title} » : ${ok ? "lu" : "lecteur chargé, lecture non confirmée"}`);158  }159  await page.keyboard.press("Escape");160});161162test("playlist M3U personnelle : adresse à jeton lisible sans session, révocable", async ({ page, request }) => {163  await login(page);164  const post = (path: string, body?: unknown, method = "POST") => page.evaluate(async ([p, b, m]) => { 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, body: await r.json().catch(() => ({})) }; }, [`/api${path}`, body, method] as const);165  const made = await post("/playlists", { name: "Test E2E", filter: { lists: [], countries: ["CA"], languages: ["fra"], onlyUp: true, best: true, group: "category", max: 300 } });166  expect(made.status).toBe(200);167  const pl = made.body as { id: number; url: string; epgUrl: string; channels: number };168  try {169    expect(pl.url).toMatch(/\/m3u\/[A-Za-z0-9_-]{32}\.m3u$/); expect(pl.channels).toBeGreaterThan(3);170    // What a TV app does: a plain GET, no cookie.171    const r = await request.get(pl.url);172    expect(r.status()).toBe(200); expect(r.headers()["content-type"]).toContain("mpegurl");173    const text = await r.text();174    expect(text.startsWith("#EXTM3U")).toBe(true);175    const urls = text.split("\n").filter((l) => /^https?:\/\//.test(l));176    expect(urls.length).toBe(pl.channels); expect((text.match(/#EXTINF/g) ?? []).length).toBe(urls.length);177    expect(text).toContain('tvg-country="CA"'); expect(text).toContain(pl.epgUrl);178    const guide = await request.get(pl.epgUrl); expect(guide.status()).toBe(200); expect(await guide.text()).toContain("<tv ");179    // The management API stays private; a wrong token is a plain 404.180    expect((await request.get("/api/playlists")).status()).toBe(401);181    expect((await request.get(pl.url.replace(/[A-Za-z0-9_-]{32}\.m3u$/, "A".repeat(32) + ".m3u"))).status()).toBe(404);182    // The page shows it; rotating the address cuts the old one.183    await page.goto("/playlists"); await expect(page.getByRole("heading", { name: "Test E2E" })).toBeVisible();184    await post(`/playlists/${pl.id}/rotate`);185    expect((await request.get(pl.url)).status()).toBe(404);186  } finally { await post(`/playlists/${pl.id}`, undefined, "DELETE"); }187});188
Files main
Menu

Theme