SPB Git

Repository Public

studio-captions.test.ts 9.7 KB 132 lines typescript

1import { describe, expect, it } from "vitest";2import { langLabel, normaliseLang, toTranscript, validateCaptions } from "@/server/captions";3import { contentMismatch, extOf, safeFilename, sniff } from "@/server/magic";45const vtt = (...cues: [string, string, string][]) => `WEBVTT\n\n${cues.map(([a, b, t], i) => `${i + 1}\n${a} --> ${b}\n${t}\n`).join("\n")}`;67describe("WebVTT validation", () => {8  it("accepts a clean file and reports its cues", () => {9    const r = validateCaptions(vtt(["00:00:00.000", "00:00:04.000", "Bonjour."], ["00:00:04.000", "00:00:08.500", "Bienvenue dans le cours."]), { videoDuration: 9 });10    expect(r).toMatchObject({ ok: true, cues: 2, duration: 8.5, errors: [], warnings: [] });11    expect(r.preview[1]).toEqual({ start: 4, end: 8.5, text: "Bienvenue dans le cours." });12  });1314  it("accepts the short mm:ss.mmm form, cue settings, NOTE and STYLE blocks, a BOM and CRLF line ends", () => {15    const r = validateCaptions("\ufeffWEBVTT - titre\r\n\r\nNOTE commentaire\r\n\r\nSTYLE\r\n::cue { color: white }\r\n\r\n00:01.000 --> 00:03.000 line:90% align:center\r\n<v Prof>Avec des <i>balises</i>.\r\n");16    expect(r.ok).toBe(true);17    expect(r.preview[0]!.text).toBe("Avec des balises."); // markup is stripped from what is stored and indexed18  });1920  it.each([21    ["no header", "00:00:00.000 --> 00:00:02.000\nSans en-tête.\n", /en-tête WEBVTT/],22    ["comma as decimal separator (SRT)", vtt(["00:00:00,000", "00:00:02,000", "Format SRT."]), /mal formé/],23    ["end before start", vtt(["00:00:05.000", "00:00:03.000", "À l'envers."]), /fin avant le début/],24    ["zero-length cue", vtt(["00:00:05.000", "00:00:05.000", "Instantané."]), /fin avant le début/],25    ["negative time", "WEBVTT\n\n-00:00:01.000 --> 00:00:02.000\nNégatif.\n", /temps négatif/],26    ["overlap", vtt(["00:00:00.000", "00:00:04.000", "Un."], ["00:00:03.000", "00:00:06.000", "Deux."]), /chevauchement/],27    ["out of order", vtt(["00:00:10.000", "00:00:12.000", "Tard."], ["00:00:01.000", "00:00:02.000", "Tôt."]), /désordre/],28    ["empty cue", "WEBVTT\n\n00:00:00.000 --> 00:00:02.000\n\n\n00:00:02.000 --> 00:00:03.000\nSuite.\n", /sans repère|vide/],29    ["minutes above 59", vtt(["00:75:00.000", "00:76:00.000", "Minutes impossibles."]), /mal formé/],30    ["cue after the end of the video", vtt(["00:00:00.000", "00:00:02.000", "Début."], ["00:05:00.000", "00:05:02.000", "Bien après."]), /après la fin de la vidéo/],31    ["no cue at all", "WEBVTT\n\nNOTE rien\n", /aucune réplique/],32    ["binary content", "WEBVTT\n\n00:00:00.000 --> 00:00:01.000\nx\0y\n", /octets nuls/],33  ])("refuses: %s", (_name, source, pattern) => {34    const r = validateCaptions(source, { videoDuration: 60 });35    expect(r.ok).toBe(false);36    expect(r.errors.join(" | ")).toMatch(pattern);37  });3839  it("warns, without refusing, about reading speed, very long cues and partial coverage", () => {40    const r = validateCaptions(vtt(["00:00:00.000", "00:00:01.000", "Une réplique beaucoup trop longue pour être lue en une seule seconde par quiconque."], ["00:00:02.000", "00:00:30.000", "Une réplique affichée très longtemps."]), { videoDuration: 600 });41    expect(r.ok).toBe(true);42    expect(r.warnings.join(" | ")).toMatch(/caractères par seconde/);43    expect(r.warnings.join(" | ")).toMatch(/très longue/);44    expect(r.warnings.join(" | ")).toMatch(/ne couvrent que 5 %/);45  });4647  it("caps the size of what it will read", () => {48    expect(validateCaptions(`WEBVTT\n\n${"x".repeat(5_000_001)}`).errors[0]).toMatch(/trop volumineux/);49  });50});5152describe("language tags", () => {53  it("normalises BCP 47 tags and refuses anything else", () => {54    expect(normaliseLang("fr-ca")).toBe("fr-CA");55    expect(normaliseLang("FR_CA")).toBe("fr-CA");56    expect(normaliseLang("en")).toBe("en");57    expect(normaliseLang("zh-hant-tw")).toBe("zh-Hant-TW");58    for (const bad of ["", "français", "fr-", "f", "fr-CA-x-y-z", "../fr", "fr CA", "<script>"]) expect(normaliseLang(bad), bad).toBeNull();59    expect(langLabel("fr-CA")).toMatch(/^Français/);60    expect(langLabel("en")).toBe("Anglais");61  });62});6364describe("transcript import", () => {65  it("turns WebVTT cues into searchable segments, one per cue", () => {66    const { transcript, errors } = toTranscript(vtt(["00:00:00.000", "00:00:04.000", "Premier."], ["00:00:04.000", "00:00:08.000", "Second."]), "vtt", "fr-CA");67    expect(errors).toEqual([]);68    expect(transcript).toEqual({ lang: "fr-CA", segments: [{ start: 0, end: 4, text: "Premier." }, { start: 4, end: 8, text: "Second." }] });69  });70  it("accepts JSON as { lang, segments } or as a bare array, and cleans the text", () => {71    expect(toTranscript(JSON.stringify({ lang: "en", segments: [{ start: 0, end: 2, text: "  Hello \n world " }] }), "json", "fr-CA").transcript).toEqual({ lang: "en", segments: [{ start: 0, end: 2, text: "Hello world" }] });72    expect(toTranscript(JSON.stringify([{ start: 1, end: 2, text: "Un" }]), "json", "fr-CA").transcript.lang).toBe("fr-CA");73  });74  it("refuses malformed input instead of guessing", () => {75    expect(toTranscript("{pas du json", "json", "fr").errors).toEqual(["JSON invalide"]);76    expect(toTranscript(JSON.stringify({ segments: [{ start: 0, end: 1 }] }), "json", "fr").errors[0]).toMatch(/format inattendu/);77    expect(toTranscript(JSON.stringify([{ start: 5, end: 6, text: "b" }, { start: 1, end: 2, text: "a" }]), "json", "fr").errors.join()).toMatch(/désordre/);78    expect(toTranscript("WEBVTT\n\n00:00:05.000 --> 00:00:01.000\nx\n", "vtt", "fr").errors.length).toBeGreaterThan(0);79  });80});8182describe("file-type detection by content", () => {83  const mp4 = Buffer.concat([Buffer.from([0, 0, 0, 0x20]), Buffer.from("ftypisom"), Buffer.alloc(40)]), mov = Buffer.concat([Buffer.from([0, 0, 0, 0x14]), Buffer.from("ftypqt  "), Buffer.alloc(40)]);84  const webm = Buffer.concat([Buffer.from([0x1a, 0x45, 0xdf, 0xa3, 0x9f, 0x42, 0x82, 0x84]), Buffer.from("webm"), Buffer.alloc(40)]), mkv = Buffer.concat([Buffer.from([0x1a, 0x45, 0xdf, 0xa3, 0x9f, 0x42, 0x82, 0x88]), Buffer.from("matroska"), Buffer.alloc(40)]);85  const elf = Buffer.concat([Buffer.from([0x7f, 0x45, 0x4c, 0x46, 2, 1, 1, 0]), Buffer.alloc(60)]), exe = Buffer.concat([Buffer.from("MZ\x90\0\x03\0\0\0"), Buffer.alloc(60)]), macho = Buffer.concat([Buffer.from([0xcf, 0xfa, 0xed, 0xfe, 7, 0, 0, 1]), Buffer.alloc(60)]);8687  it("recognises what it accepts from its first bytes", () => {88    expect([sniff(mp4), sniff(mov), sniff(webm), sniff(mkv)]).toEqual(["mp4", "mov", "webm", "mkv"]);89    expect(sniff(Buffer.from("%PDF-1.7\n…"))).toBe("pdf");90    expect(sniff(Buffer.from("PK\x03\x04…"))).toBe("zip");91    expect(sniff(Buffer.from([0x1f, 0x8b, 8, 0]))).toBe("gzip");92    expect(sniff(Buffer.from([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a]))).toBe("png");93    expect(sniff(Buffer.from([0xff, 0xd8, 0xff, 0xe0]))).toBe("jpeg");94    expect(sniff(Buffer.from("WEBVTT\n\n00:00.000 --> 00:01.000\nx"))).toBe("vtt");95    expect(sniff(Buffer.from("# Titre\n\nTexte accentué : été, façade, œuvre."))).toBe("text");96    expect(sniff(Buffer.from("texte coupé au milieu d'un caractère é").subarray(0, -1))).toBe("text");97    for (const b of [elf, exe, macho, Buffer.alloc(0), Buffer.from([0xff, 0xfe, 0x00, 0x41])]) expect(sniff(b)).toBe("unknown");98  });99100  it("refuses a file whose content does not match its extension, whatever it is called", () => {101    expect(contentMismatch("master", "cours.mp4", mp4)).toBeNull();102    expect(contentMismatch("master", "iphone.mov", mov)).toBeNull();103    expect(contentMismatch("master", "ecran.webm", webm)).toBeNull();104    expect(contentMismatch("master", "page.mp4", Buffer.from("<html><script>alert(1)</script></html>"))).toMatch(/ne correspond pas/);105    expect(contentMismatch("master", "programme.mp4", elf)).toMatch(/ne correspond pas/);106    expect(contentMismatch("master", "archive.mov", Buffer.from("PK\x03\x04"))).toMatch(/ne correspond pas/);107    expect(contentMismatch("master", "video.avi", mp4)).toMatch(/non accepté/);108    expect(contentMismatch("resource", "diapos.pdf", Buffer.from("%PDF-1.4"))).toBeNull();109    expect(contentMismatch("resource", "diapos.pdf", exe)).toMatch(/ne correspond pas/);110    expect(contentMismatch("resource", "donnees.csv", Buffer.from("a,b\n1,2\n"))).toBeNull();111    expect(contentMismatch("resource", "donnees.csv", macho)).toMatch(/ne correspond pas/);112    expect(contentMismatch("resource", "labo.zip", Buffer.from("%PDF-1.4"))).toMatch(/ne correspond pas/);113    expect(contentMismatch("resource", "outil.sh", Buffer.from("#!/bin/sh\nrm -rf /"))).toMatch(/non accepté/);114    expect(contentMismatch("resource", "page.html", Buffer.from("<html>"))).toMatch(/non accepté/);115    expect(contentMismatch("resource", "image.svg", Buffer.from("<svg onload=x>"))).toMatch(/non accepté/);116    expect(contentMismatch("captions", "st.vtt", Buffer.from("WEBVTT\n"))).toBeNull();117    expect(contentMismatch("captions", "st.vtt", Buffer.from("1\n00:00:00,000 --> 00:00:01,000\nSRT"))).toMatch(/ne correspond pas/);118    expect(contentMismatch("archive", "depot.tar.gz", Buffer.from([0x1f, 0x8b, 8, 0]))).toBeNull();119    expect(contentMismatch("archive", "depot.zip", Buffer.from([0x1f, 0x8b, 8, 0]))).toMatch(/ne correspond pas/);120  });121122  it("reduces any file name to a harmless base name", () => {123    expect(safeFilename("../../../etc/passwd.pdf")).toBe("passwd.pdf");124    expect(safeFilename("C:\\Users\\x\\Séance 1 — diapositives (v2).PDF")).toBe("Seance-1-diapositives-v2.pdf");125    expect(safeFilename("depot du cours.tar.gz")).toBe("depot-du-cours.tar.gz");126    expect(safeFilename(".htaccess")).toBe("fichier.htaccess");127    expect(safeFilename("\0\0.mp4")).toBe("fichier.mp4");128    expect(safeFilename(`${"a".repeat(300)}.pdf`).length).toBeLessThanOrEqual(84);129    expect(extOf("A.TAR.GZ")).toBe("tar.gz");130  });131});132
Files main
Menu

Theme