SPB Git

Repository Public

studio-media.test.ts 27.4 KB 355 lines typescript

1import { execFileSync } from "node:child_process";2import { createHash, randomBytes } from "node:crypto";3import { existsSync, readFileSync, readdirSync, statSync } from "node:fs";4import { mkdtemp, readFile, rm, writeFile } from "node:fs/promises";5import { tmpdir } from "node:os";6import { join } from "node:path";7import { afterAll, beforeAll, beforeEach, describe, expect, it } from "vitest";8import { getCapsuleData, getCourse } from "@/lib/content";9import { buildView, mediaAllowed } from "@/modules/content-schema";10import { Chapters, Transcript } from "@/modules/content-schema/schema";11import { parseVtt } from "@/modules/learning-engine/vtt";12import { listAudit } from "@/server/audit";13import { createCapsule, getCapsule, getResource, getSessionRow, listResources, putSection, setSessionState, updateCapsule } from "@/server/content";14import { all, get } from "@/server/db";15import { ApiError } from "@/server/http";16import { PermanentJobError, getJob, listJobs } from "@/server/jobs";17import { planPublication, publicManifest, publishSession } from "@/server/publish";18import { DEFAULT_LADDER, configuredLadder, ffmpegStatus, ladderFor, probe } from "@/server/transcode";19import { CHUNK_SIZE, abortUpload, attachCaptions, attachTranscript, completeUpload, getUpload, initUpload, masterFile, putChunk, receivedChunks, saveChapters, sweepUploads, type FinalResult } from "@/server/uploads";20import { runWorker } from "@/server/worker";21import { cleanup, freshStudio } from "./studio-helpers";2223const sha = (b: Buffer | string) => createHash("sha256").update(b).digest("hex");24const pieces = (b: Buffer) => Array.from({ length: Math.max(1, Math.ceil(b.length / CHUNK_SIZE)) }, (_, i) => b.subarray(i * CHUNK_SIZE, (i + 1) * CHUNK_SIZE));25const fingerprint = (b: Buffer) => sha(pieces(b).map(sha).join(""));26const code = async (fn: () => unknown) => { try { await fn(); return "ok"; } catch (e) { return e instanceof ApiError ? e.code : `other:${String(e)}`; } };27/** The whole client side of an upload, as the browser does it. */28async function upload(purpose: string, filename: string, body: Buffer, context: Record<string, unknown>, actor = "ed"): Promise<FinalResult> {29  const init = await initUpload({ purpose, filename, size: body.length, fingerprint: fingerprint(body), context }, actor);30  for (const [n, p] of pieces(body).entries()) if (!init.received.includes(n)) await putChunk(init.upload.id, n, p, sha(p));31  return completeUpload(init.upload.id, actor);32}33const drain = () => runWorker({ drain: true, pollMs: 20, heartbeatMs: 200, timeoutMs: 120_000 });3435const HAS_FFMPEG = (() => { try { execFileSync("ffmpeg", ["-version"], { stdio: "ignore" }); execFileSync("ffprobe", ["-version"], { stdio: "ignore" }); return true; } catch { return false; } })();36let fixtures: string, dir: string, video480: Buffer, videoSilent: Buffer;3738beforeAll(async () => {39  fixtures = await mkdtemp(join(tmpdir(), "atlas-media-fixtures-"));40  if (!HAS_FFMPEG) return;41  // Synthetic sources generated on the spot (never committed): 3 s of test pattern and tone, 854×480; and a silent 320×180 one.42  const ff = (args: string[]) => execFileSync("ffmpeg", ["-hide_banner", "-loglevel", "error", "-y", ...args], { stdio: "ignore" });43  ff(["-f", "lavfi", "-i", "testsrc=size=854x480:rate=25:duration=3", "-f", "lavfi", "-i", "sine=frequency=440:duration=3", "-c:v", "libx264", "-preset", "ultrafast", "-pix_fmt", "yuv420p", "-c:a", "aac", "-shortest", join(fixtures, "480.mp4")]);44  ff(["-f", "lavfi", "-i", "testsrc=size=320x180:rate=25:duration=2", "-c:v", "libx264", "-preset", "ultrafast", "-pix_fmt", "yuv420p", "-an", join(fixtures, "silent.mp4")]);45  video480 = readFileSync(join(fixtures, "480.mp4")); videoSilent = readFileSync(join(fixtures, "silent.mp4"));46});47beforeEach(async () => { dir = await freshStudio(); process.env.ATLAS_X264_PRESET = "ultrafast"; delete process.env.ATLAS_FFMPEG; delete process.env.ATLAS_LADDER; createCapsule("S01", { title: "Capsule d'essai", id: "essai" }, "ed"); });48afterAll(async () => { await cleanup(); await rm(fixtures, { recursive: true, force: true }); });4950describe("rendition ladder", () => {51  it("never upscales: only rungs at or below the source, plus the source's own height when it sits between two rungs", () => {52    const heights = (h: number) => ladderFor(h, DEFAULT_LADDER).map((r) => r.height);53    expect(heights(2160)).toEqual([360, 720, 1080]); // a 4K master is delivered at 1080p at most by default54    expect(heights(1080)).toEqual([360, 720, 1080]);55    expect(heights(720)).toEqual([360, 720]);56    expect(heights(480)).toEqual([360, 480]);57    expect(heights(400)).toEqual([360]);58    expect(heights(360)).toEqual([360]);59    expect(heights(240)).toEqual([240]);60    expect(heights(181)).toEqual([182]); // odd heights are rounded to an even number of lines61    for (const h of [144, 240, 360, 480, 720, 1080, 2160]) expect(Math.max(...heights(h))).toBeLessThanOrEqual(Math.max(h, 2));62    const native = ladderFor(480, DEFAULT_LADDER).find((r) => r.height === 480)!;63    expect(native.videoKbps).toBeGreaterThan(800); expect(native.videoKbps).toBeLessThan(2800);64  });6566  it("reads the ladder from the configuration and reports an invalid one instead of guessing", () => {67    expect(configuredLadder("").ladder).toEqual(DEFAULT_LADDER);68    expect(configuredLadder('[{"height":1080,"videoKbps":4000,"audioKbps":128},{"height":240,"videoKbps":300,"audioKbps":64}]')).toMatchObject({ error: null, ladder: [{ height: 240 }, { height: 1080 }] });69    expect(configuredLadder("pas du json")).toMatchObject({ ladder: DEFAULT_LADDER, error: expect.stringContaining("n'est pas du JSON") });70    expect(configuredLadder('[{"height":99999,"videoKbps":1,"audioKbps":1}]').error).toContain("invalide");71  });72});7374describe("chunked upload", () => {75  const ctx = { sessionId: "S01", capsuleId: "essai" };76  const mp4 = (size: number) => Buffer.concat([Buffer.from([0, 0, 0, 0x20]), Buffer.from("ftypisom"), randomBytes(size - 12)]);7778  it("assembles pieces sent in any order, verifies every checksum, and stores the master under its SHA-256", async () => {79    const body = mp4(CHUNK_SIZE * 2 + 12_345); // three pieces80    const init = await initUpload({ purpose: "master", filename: "Mon cours (final).MP4", size: body.length, fingerprint: fingerprint(body), context: ctx }, "ed");81    expect(init.upload).toMatchObject({ totalChunks: 3, chunkSize: CHUNK_SIZE, filename: "Mon-cours-final.mp4", status: "open" });82    const p = pieces(body);83    await putChunk(init.upload.id, 2, p[2]!, sha(p[2]!));84    await putChunk(init.upload.id, 0, p[0]!, sha(p[0]!));85    expect(await code(() => completeUpload(init.upload.id, "ed"))).toBe("incomplete");86    await putChunk(init.upload.id, 0, p[0]!, sha(p[0]!)); // sending a piece twice is harmless87    await putChunk(init.upload.id, 1, p[1]!, sha(p[1]!));88    expect(receivedChunks(init.upload.id)).toEqual([0, 1, 2]);89    const r = await completeUpload(init.upload.id, "ed");90    expect(r).toMatchObject({ kind: "master", sha256: sha(body), duplicate: false });91    const stored = masterFile(sha(body))!;92    expect(stored.endsWith(`masters/${sha(body)}.mp4`)).toBe(true);93    expect(sha(readFileSync(stored))).toBe(sha(body)); // byte for byte what was sent94    expect(existsSync(join(dir, "uploads", init.upload.id))).toBe(false); // staging is cleaned95    expect(getCapsule("S01", "essai")).toMatchObject({ status: "queued", masterSha: sha(body) });96    expect(listJobs()[0]).toMatchObject({ kind: "transcode", state: "queued", payload: { sessionId: "S01", capsuleId: "essai", masterSha: sha(body) } });97    expect(await completeUpload(init.upload.id, "ed")).toEqual(JSON.parse(JSON.stringify(r))); // completing twice returns the same answer98  });99100  it("refuses a piece that was altered, of the wrong size or out of range — and the upload can go on", async () => {101    const body = mp4(CHUNK_SIZE + 100), p = pieces(body);102    const { upload: up } = await initUpload({ purpose: "master", filename: "a.mp4", size: body.length, fingerprint: fingerprint(body), context: ctx }, "ed");103    const altered = Buffer.from(p[0]!); altered[5000] = altered[5000]! ^ 0xff;104    expect(await code(() => putChunk(up.id, 0, altered, sha(p[0]!)))).toBe("checksum");105    expect(await code(() => putChunk(up.id, 0, p[0]!, null))).toBe("checksum");106    expect(await code(() => putChunk(up.id, 0, p[0]!.subarray(0, 100), sha(p[0]!.subarray(0, 100))))).toBe("bad_chunk");107    expect(await code(() => putChunk(up.id, 2, p[1]!, sha(p[1]!)))).toBe("bad_chunk");108    expect(await code(() => putChunk(up.id, -1, p[1]!, sha(p[1]!)))).toBe("bad_chunk");109    expect(receivedChunks(up.id)).toEqual([]);110    await putChunk(up.id, 0, p[0]!, sha(p[0]!)); await putChunk(up.id, 1, p[1]!, sha(p[1]!));111    expect((await completeUpload(up.id, "ed")).sha256).toBe(sha(body));112  });113114  it("refuses a file whose pieces do not add up to the announced fingerprint, or damaged on the server's disk", async () => {115    const body = mp4(50_000), other = mp4(50_000);116    const a = await initUpload({ purpose: "master", filename: "a.mp4", size: body.length, fingerprint: fingerprint(body), context: ctx }, "ed");117    await putChunk(a.upload.id, 0, other, sha(other)); // a valid piece… of another file118    expect(await code(() => completeUpload(a.upload.id, "ed"))).toBe("checksum");119    expect(getUpload(a.upload.id)).toMatchObject({ status: "failed" });120    expect(await code(() => putChunk(a.upload.id, 0, body, sha(body)))).toBe("closed");121    const b = await initUpload({ purpose: "master", filename: "b.mp4", size: body.length, fingerprint: fingerprint(body), context: ctx }, "ed");122    await putChunk(b.upload.id, 0, body, sha(body));123    await writeFile(join(dir, "uploads", b.upload.id, "000000"), other); // bit rot between reception and assembly124    expect(await code(() => completeUpload(b.upload.id, "ed"))).toBe("checksum");125    expect(masterFile(sha(body))).toBeNull();126    expect(getCapsule("S01", "essai").status).toBe("empty");127  });128129  it("resumes where a transfer stopped, and recognises a file it already stores", async () => {130    const body = mp4(CHUNK_SIZE + 5000), p = pieces(body), input = { purpose: "master", filename: "a.mp4", size: body.length, fingerprint: fingerprint(body), context: ctx };131    const first = await initUpload(input, "ed");132    await putChunk(first.upload.id, 0, p[0]!, sha(p[0]!));133    const again = await initUpload(input, "ed"); // the browser was closed; the same file is offered again134    expect(again).toMatchObject({ resumed: true, received: [0], duplicate: null });135    expect(again.upload.id).toBe(first.upload.id);136    expect((await initUpload(input, "autre-editeur")).resumed).toBe(false); // someone else's unfinished upload is not resumed137    await putChunk(again.upload.id, 1, p[1]!, sha(p[1]!));138    await completeUpload(again.upload.id, "ed");139    const third = await initUpload(input, "ed");140    expect(third.duplicate).toMatchObject({ sha256: sha(body), filename: "a.mp4" }); // told before any byte travels141    await abortUpload(third.upload.id, "ed");142    expect(getUpload(third.upload.id).status).toBe("aborted");143  });144145  it("validates purpose, size, type and destination before anything is sent", async () => {146    const ok = { purpose: "master", filename: "a.mp4", size: 1000, fingerprint: "a".repeat(64), context: ctx };147    expect(await code(() => initUpload({ ...ok, purpose: "virus" }, "ed"))).toBe("invalid");148    expect(await code(() => initUpload({ ...ok, size: 0 }, "ed"))).toBe("invalid");149    expect(await code(() => initUpload({ ...ok, size: 41e9 }, "ed"))).toBe("too_large");150    expect(await code(() => initUpload({ ...ok, filename: "a.exe" }, "ed"))).toBe("bad_type");151    expect(await code(() => initUpload({ ...ok, filename: "a.mp4.sh" }, "ed"))).toBe("bad_type");152    expect(await code(() => initUpload({ ...ok, fingerprint: "court" }, "ed"))).toBe("invalid");153    expect(await code(() => initUpload({ ...ok, context: { sessionId: "S99", capsuleId: "essai" } }, "ed"))).toBe("not_found");154    expect(await code(() => initUpload({ ...ok, context: { sessionId: "S01", capsuleId: "inconnue" } }, "ed"))).toBe("not_found");155    expect(await code(() => initUpload({ ...ok, purpose: "captions", filename: "a.vtt", context: { ...ctx, lang: "klingon!" } }, "ed"))).toBe("bad_lang");156    process.env.ATLAS_QUOTA_GB = "1";157    (globalThis as Record<string, unknown>).__atlasUsage = undefined;158    expect(await code(() => initUpload({ ...ok, size: 2e9 }, "ed"))).toBe("no_space"); // the storage budget would be exceeded159    delete process.env.ATLAS_QUOTA_GB;160    expect(all("SELECT id FROM uploads")).toEqual([]);161  });162163  it("refuses disguised files by their content, and leaves nothing behind", async () => {164    const html = Buffer.from("<!doctype html><script>alert(1)</script>".padEnd(2000, " ")), elf = Buffer.concat([Buffer.from([0x7f, 0x45, 0x4c, 0x46]), randomBytes(2000)]);165    expect(await code(() => upload("master", "cours.mp4", html, ctx))).toBe("bad_content");166    expect(await code(() => upload("master", "cours.mov", elf, ctx))).toBe("bad_content");167    expect(await code(() => upload("resource", "diapos.pdf", elf, { sessionId: "S01", meta: { kind: "slides", title: "Diapos", visibility: "private", download: false, license: null } }))).toBe("bad_content");168    expect(await code(() => upload("captions", "st.vtt", Buffer.from("PK\x03\x04 pas du texte"), { ...ctx, lang: "fr" }))).toBe("bad_content");169    expect(await code(() => upload("archive", "depot.zip", html, {}))).toBe("bad_content");170    expect(readdirSync(join(dir, "uploads"))).toEqual([]);171    expect(existsSync(join(dir, "masters"))).toBe(false);172    expect(listResources("S01")).toEqual([]);173    expect(listAudit({ action: "upload.refused" })).toHaveLength(5);174  });175176  it("clears uploads that were abandoned", async () => {177    const body = mp4(5000);178    const { upload: up } = await initUpload({ purpose: "master", filename: "a.mp4", size: body.length, fingerprint: fingerprint(body), context: ctx }, "ed");179    expect(await sweepUploads()).toBe(0);180    expect(await sweepUploads(-1000)).toBe(1); // everything older than « now + 1 s »181    expect(getUpload(up.id).status).toBe("aborted");182    expect(existsSync(join(dir, "uploads", up.id))).toBe(false);183  });184});185186describe("resources", () => {187  const meta = { kind: "slides", title: "Diapositives", visibility: "private", download: true, license: null };188  it("keeps every version, serves the current one at a stable address, and checks its checksum", async () => {189    const v1 = Buffer.from("%PDF-1.4 première version"), v2 = Buffer.from("%PDF-1.4 deuxième version");190    const a = await upload("resource", "Diapos séance 1.pdf", v1, { sessionId: "S01", meta }) as Extract<FinalResult, { kind: "resource" }>;191    expect(a.resource).toMatchObject({ id: "diapositives", currentVersion: 1 });192    expect(a.resource.versions[0]).toMatchObject({ sha256: sha(v1), bytes: v1.length, mime: "application/pdf", filename: "Diapos-seance-1.pdf" });193    expect(sha(readFileSync(join(dir, "resources", a.resource.versions[0]!.path)))).toBe(sha(v1));194    expect(await code(() => upload("resource", "d.pdf", v1, { sessionId: "S01", resourceId: "diapositives" }))).toBe("duplicate"); // same bytes: not a new version195    await upload("resource", "d2.pdf", v2, { sessionId: "S01", resourceId: "diapositives", note: "Coquille corrigée" });196    const r = getResource("S01", "diapositives");197    expect(r.currentVersion).toBe(2);198    expect(r.versions.map((v) => [v.version, v.sha256, v.note])).toEqual([[2, sha(v2), "Coquille corrigée"], [1, sha(v1), null]]);199    expect(existsSync(join(dir, "resources", r.versions[1]!.path))).toBe(true); // the first version is still on disk200    expect(await code(() => upload("resource", "x.pdf", v2, { sessionId: "S01", resourceId: "inconnue" }))).toBe("not_found");201  });202});203204describe.skipIf(!HAS_FFMPEG)("media pipeline with a real ffmpeg (synthetic video generated in the test)", () => {205  const ctx = { sessionId: "S01", capsuleId: "essai" };206207  it("reports the toolchain as usable here, and says clearly when it is not", async () => {208    expect(await ffmpegStatus(true)).toMatchObject({ ok: true, x264: true, aac: true, message: null });209    process.env.ATLAS_FFMPEG = "/chemin/inexistant/ffmpeg";210    const missing = await ffmpegStatus(true);211    expect(missing).toMatchObject({ ok: false, ffmpeg: null });212    expect(missing.message).toMatch(/ffmpeg est introuvable/);213  });214215  it("validates input with ffprobe: a real video passes, anything else is a permanent refusal", async () => {216    const info = await probe(join(fixtures, "480.mp4"));217    expect(info).toMatchObject({ width: 854, height: 480, fps: 25, videoCodec: "h264", audioCodec: "aac" });218    expect(Math.round(info.duration)).toBe(3);219    expect((await probe(join(fixtures, "silent.mp4"))).audioCodec).toBeNull();220    const fake = join(fixtures, "faux.mp4");221    await writeFile(fake, Buffer.concat([Buffer.from([0, 0, 0, 0x20]), Buffer.from("ftypisom"), randomBytes(5000)])); // right magic bytes, no video inside222    await expect(probe(fake)).rejects.toBeInstanceOf(PermanentJobError);223    await expect(probe(join(fixtures, "480.mp4"), { maxSeconds: 1 })).rejects.toThrow(/la limite est de/);224  });225226  it("upload → queue → worker → HLS renditions, MP4 fallback, poster, thumbnails; master untouched", async () => {227    const result = await upload("master", "essai.mp4", video480, ctx);228    expect(getCapsule("S01", "essai").status).toBe("queued");229    await drain();230    const job = listJobs()[0]!;231    expect(job).toMatchObject({ state: "succeeded", progress: 1, attempts: 1 });232    const c = getCapsule("S01", "essai"), m = c.data.media, root = join(dir, "media");233    expect(c).toMatchObject({ status: "ready", masterSha: sha(video480) });234    expect(c.data.durationSeconds).toBeCloseTo(3, 0);235    expect(c.data.renditions.map((r) => r.height)).toEqual([360, 480]); // 854×480 source: 360p and its own height, no 720p236    expect(c.data.renditions.map((r) => r.width)).toEqual([640, 854]);237    expect(c.data.source).toMatchObject({ width: 854, height: 480, videoCodec: "h264", audioCodec: "aac", filename: "essai.mp4" });238    // The layout the player expects (scripts/make-test-capsule.ts), inside a directory of its own.239    expect(m.hls).toMatch(/^S01\/essai\/r[a-z0-9]+\/master\.m3u8$/);240    const master = await readFile(join(root, m.hls!), "utf8"), base = m.hls!.replace("/master.m3u8", "");241    expect(master).toMatch(/#EXT-X-STREAM-INF:BANDWIDTH=\d+,RESOLUTION=640x360,CODECS="avc1\.[0-9a-f]{6},mp4a\.40\.2"\nv360\/index\.m3u8/);242    expect(master).toMatch(/RESOLUTION=854x480,CODECS="avc1\.[0-9a-f]{6},mp4a\.40\.2"\nv480\/index\.m3u8/);243    expect(master).not.toContain("v720");244    for (const h of [360, 480]) {245      const playlist = await readFile(join(root, base, `v${h}`, "index.m3u8"), "utf8");246      expect(playlist).toContain("#EXT-X-PLAYLIST-TYPE:VOD"); expect(playlist).toContain("#EXT-X-ENDLIST");247      expect(readdirSync(join(root, base, `v${h}`)).filter((f) => f.endsWith(".ts")).length).toBeGreaterThanOrEqual(1);248      expect((await probe(join(root, base, `v${h}`, "seg_00000.ts"))).height).toBe(h);249    }250    const fallback = await probe(join(root, m.mp4!));251    expect(fallback).toMatchObject({ height: 480, videoCodec: "h264", audioCodec: "aac" });252    expect(readFileSync(join(root, m.poster!)).subarray(0, 3)).toEqual(Buffer.from([0xff, 0xd8, 0xff])); // a JPEG253    expect(c.data.thumbs.length).toBeGreaterThanOrEqual(2);254    for (const t of c.data.thumbs) expect(statSync(join(root, t)).size).toBeGreaterThan(200);255    // The master is preserved exactly as uploaded, outside media/.256    expect(sha(readFileSync(masterFile(sha(video480))!))).toBe(sha(video480));257    expect(get<{ probe: string }>("SELECT probe FROM masters WHERE sha256 = ?", sha(video480))!.probe).toContain('"height":480');258    expect(listAudit({ action: "capsule.transcoded" })[0]).toMatchObject({ actor: "worker" });259    expect(existsSync(join(dir, "work", `job-${job.id}-1`))).toBe(false); // scratch space is cleaned260    expect(result.kind).toBe("master");261262    // The same master on a second capsule: recognised, attached without a new upload, encoded into its own directory.263    createCapsule("S01", { title: "Copie", id: "copie" }, "ed");264    const dup = await upload("master", "autre-nom.mp4", video480, { sessionId: "S01", capsuleId: "copie" }) as Extract<FinalResult, { kind: "master" }>;265    expect(dup.duplicate).toBe(true);266    await drain();267    expect(getCapsule("S01", "copie").data.media.hls).not.toBe(m.hls);268    expect(readdirSync(join(dir, "masters"))).toHaveLength(1);269  }, 120_000);270271  it("fails clearly, without retrying, when ffmpeg is missing or the file is not a video", async () => {272    process.env.ATLAS_FFMPEG = "/chemin/inexistant/ffmpeg";273    await upload("master", "essai.mp4", video480, ctx);274    await drain();275    expect(listJobs()[0]).toMatchObject({ state: "failed", attempts: 1 }); // retrying would not install ffmpeg276    expect(listJobs()[0]!.error).toMatch(/ffmpeg est introuvable/);277    expect(getCapsule("S01", "essai").status).toBe("failed");278    delete process.env.ATLAS_FFMPEG;279    createCapsule("S01", { title: "Faux", id: "faux" }, "ed");280    const fake = Buffer.concat([Buffer.from([0, 0, 0, 0x20]), Buffer.from("ftypisom"), randomBytes(20_000)]); // passes the magic-byte check, is not a video281    await upload("master", "faux.mp4", fake, { sessionId: "S01", capsuleId: "faux" });282    await drain();283    const job = listJobs().find((j) => (j.payload as { capsuleId: string }).capsuleId === "faux")!;284    expect(job).toMatchObject({ state: "failed", attempts: 1 });285    expect(job.error).toMatch(/n'est pas une vidéo lisible|Aucune piste vidéo/);286    expect(getCapsule("S01", "faux")).toMatchObject({ status: "failed" });287    expect(getCapsule("S01", "faux").data.media.hls).toBeUndefined();288    expect(existsSync(join(dir, "work")) ? readdirSync(join(dir, "work")).filter((f) => f.startsWith("job-")) : []).toEqual([]);289  }, 60_000);290291  it("captions, transcript and chapters; and a re-encode never rewrites what a publication names", async () => {292    await upload("master", "silencieux.mp4", videoSilent, ctx);293    await drain();294    const first = getCapsule("S01", "essai");295    expect(first.data.renditions.map((r) => r.height)).toEqual([180]); // below the smallest rung: delivered at its own size, not enlarged296    expect(await readFile(join(dir, "media", first.data.media.hls!), "utf8")).toMatch(/CODECS="avc1\.[0-9a-f]{6}"\n/); // silent source: no audio codec announced297298    // Captions: an invalid file is refused and changes nothing; a valid one is stored normalised, under a name of its own.299    const vtt = "WEBVTT\n\n1\n00:00:00.000 --> 00:00:01.000\nPremière <i>réplique</i>.\n\n2\n00:00:01.000 --> 00:00:02.000\nSeconde réplique, avec le mot girouette.\n";300    expect(await code(() => attachCaptions("S01", "essai", vtt.replace("00:00:01.000 --> 00:00:02.000", "00:00:00.500 --> 00:00:02.000"), "fr-CA", {}, "ed"))).toBe("bad_captions");301    expect(await code(() => attachCaptions("S01", "essai", vtt, "pas une langue", {}, "ed"))).toBe("bad_lang");302    expect((await attachCaptions("S01", "essai", "pas du vtt", "fr", { dryRun: true }, "ed")).report.ok).toBe(false); // a dry run reports, never throws303    expect(getCapsule("S01", "essai").data.media.captions).toEqual([]);304    const { capsule, report } = await attachCaptions("S01", "essai", vtt, "fr-ca", {}, "ed");305    expect(report).toMatchObject({ ok: true, cues: 2 });306    const track = capsule.data.media.captions[0]!;307    expect(track).toMatchObject({ lang: "fr-CA", label: "Français canadien" });308    expect(track.path).toMatch(/^S01\/essai\/captions\.fr-CA\.[a-f0-9]{10}\.vtt$/);309    expect(parseVtt(await readFile(join(dir, "media", track.path), "utf8"))).toMatchObject({ errors: [], cues: [{ start: 0, end: 1, text: "Première réplique." }, { start: 1, end: 2 }] });310    // The transcript was derived from the captions since there was none; a JSON one replaces it.311    expect(Transcript.parse(JSON.parse(await readFile(join(dir, "media", capsule.data.media.transcript!), "utf8"))).segments).toHaveLength(2);312    const t = await attachTranscript("S01", "essai", JSON.stringify([{ start: 0, end: 2, text: "Transcription relue, avec le mot girouette." }]), "json", "fr-CA", "ed");313    expect(t.segments).toBe(1);314    expect(await code(() => attachTranscript("S01", "essai", "[]", "json", "fr-CA", "ed"))).toBe("bad_transcript");315    await attachCaptions("S01", "essai", vtt.replace("Première", "First"), "en", {}, "ed");316    expect(getCapsule("S01", "essai").data.media.captions.map((x) => x.lang)).toEqual(["fr-CA", "en"]); // French first317    expect(getCapsule("S01", "essai").data.media.transcript).toBe(t.capsule.data.media.transcript); // a second track does not replace the transcript318319    // Chapters.320    expect(await code(() => saveChapters("S01", "essai", [{ start: 1, title: "Pas à zéro" }], "ed"))).toBe("invalid");321    expect(await code(() => saveChapters("S01", "essai", [{ start: 0, title: "A" }, { start: 99, title: "Après la fin" }], "ed"))).toBe("invalid");322    expect(await code(() => saveChapters("S01", "essai", [{ start: 0, title: "A" }, { start: 1, title: "B" }, { start: 0.5, title: "Désordre" }], "ed"))).toBe("invalid");323    await saveChapters("S01", "essai", [{ start: 0, title: "Début" }, { start: 1, title: "Suite" }], "ed");324    expect(Chapters.parse(JSON.parse(await readFile(join(dir, "media", getCapsule("S01", "essai").data.media.chapters!), "utf8")))).toHaveLength(2);325326    // Publish, then replace the video: the public keeps the files it was given.327    putSection("S01", "quiz", { visibility: "public" }, "ed"); setSessionState("S01", "preview", "ed"); updateCapsule("S01", "essai", { visibility: "public" }, "ed");328    expect(planPublication(getSessionRow("S01")).blockers).toEqual([]);329    publishSession("S01", { confirm: "S01" }, "ed");330    const live = (await getCourse()).sessions.find((s) => s.id === "S01")!.capsules[0]!;331    expect(live.media.hls).toBe(first.data.media.hls);332    expect((await getCapsuleData(live)).transcript!.segments[0]!.text).toContain("girouette");333    expect((await getCapsuleData(live)).chapters).toHaveLength(2);334335    await upload("master", "nouvelle-prise.mp4", video480, ctx);336    await drain();337    const second = getCapsule("S01", "essai");338    expect(second.data.media.hls).not.toBe(first.data.media.hls);339    expect(second.data.renditions.map((r) => r.height)).toEqual([360, 480]);340    expect(second.data.media.captions).toHaveLength(2); // captions, transcript and chapters stay attached to the capsule341    await saveChapters("S01", "essai", [{ start: 0, title: "Nouveau découpage" }], "ed");342    const view = buildView(publicManifest()!, "production"), pub = view.sessions.find((s) => s.id === "S01")!.capsules[0]!;343    expect(pub.media.hls).toBe(first.data.media.hls);                                     // still the first encode344    expect(existsSync(join(dir, "media", first.data.media.hls!))).toBe(true);             // …whose files are still there345    expect((await getCapsuleData(pub)).chapters).toHaveLength(2);                         // …and the chapters it was published with346    expect(mediaAllowed(view, second.data.media.hls!)).toBe(false);                       // the new encode is not reachable347    expect(mediaAllowed(view, second.data.media.mp4!)).toBe(false);348    expect(mediaAllowed(view, getCapsule("S01", "essai").data.media.chapters!)).toBe(false);          // nor are the chapters saved since349    expect(mediaAllowed(view, first.data.media.hls!.replace("master.m3u8", "v180/seg_00000.ts"))).toBe(true);350    publishSession("S01", { confirm: "S01" }, "ed");351    expect((await getCourse()).sessions.find((s) => s.id === "S01")!.capsules[0]!.media.hls).toBe(second.data.media.hls);352    expect(getJob(listJobs()[0]!.id)!.state).toBe("succeeded");353  }, 180_000);354});355
Files main
Menu

Theme