import { createHash } from "node:crypto"; import { mkdir, mkdtemp, rm, writeFile } from "node:fs/promises"; import { tmpdir } from "node:os"; import path from "node:path"; import sharp from "sharp"; import { afterAll, beforeAll, beforeEach, describe, expect, it } from "vitest"; import { teamSideRows } from "../src/archive/directory.js"; import { galleryAssignments } from "../src/archive/gallery.js"; import { canonicalTeam, describeFolder, directorySides, exhibitionName, galleryRoot, isExhibition, isInitials, isTeam, knownVersus, lisbonDay, parseFolder, pickFixture, teamLabel, teamMatcher, type FixtureCandidate } from "../src/archive/match.js"; import { CloudClient, parseMultistatus } from "../src/archive/nextcloud.js"; import { ArchiveService, localDirs } from "../src/archive/service.js"; import { FaceService } from "../src/faces/service.js"; import type { FaceAnalysis, FaceEngine } from "../src/faces/process.js"; import { execFileSync } from "node:child_process"; import { SecretBox } from "../src/delivery/secrets.js"; import { IngestService } from "../src/ingest/service.js"; import { MemoryBroadcaster } from "../src/realtime.js"; import { LocalStorage, UrlSigner } from "../src/storage/storage.js"; import { bearer, createTestApp, login, resetDb, seedUser, type TestContext } from "./helpers.js"; const KEY = Buffer.alloc(32, 7).toString("base64"); const quiet = { info: () => {}, warn: () => {} }; describe("archive folder names", () => { it("reads FPA folders: season, competition code, day and teams", () => { expect(parseFolder("/FPA/Fotos/2025_2026/Competições Nacionais/PO01/20250913 - SCP x ABC")).toMatchObject({ home: "SCP", away: "ABC", day: "2025-09-13", season: "20252026", competition: "PO01", round: null, }); expect(parseFolder("/FPA/Fotos/2025_2026/Competições Nacionais/PO09A/20251102 - Madeira SAD x Colégio de Gaia")?.competition).toBe("PO09A"); }); it("reads Liga bwin folders whose teams are written as one code", () => { expect(parseFolder("/LPbwin - 22-23/JORNADA 11/CPACxRAFC")).toMatchObject({ home: "CPAC", away: "RAFC", day: null, season: "20222023", competition: "ligaportugalbetclic", round: "11", }); expect(parseFolder("/LPbwin - 22-23/JORNADA 1/1.GVFCxPSC")).toMatchObject({ home: "GVFC", away: "PSC", round: "1", competition: "ligaportugalbetclic" }); const t = (name: string, abbreviation: string) => ({ name, abbreviation, slug: name.toLowerCase() }); const fixture: FixtureCandidate = { id: "cpac", startsAt: new Date("2022-10-29T19:30:00Z"), season: "20222023", round: "11", competition: { externalId: "ligaportugalbetclic" }, homeTeam: t("Casa Pia AC", "CPAC"), awayTeam: t("Rio Ave FC", "RAFC"), }; expect(pickFixture(parseFolder("/LPbwin - 22-23/JORNADA 11/CPACxRAFC")!, [fixture], new Date("2026-10-19T00:00:00Z"))?.id).toBe("cpac"); }); it("reads a slash between two clubs, in any archive, and leaves a season slash alone", () => { expect(parseFolder("/FPA/Fotos/2025_2026/Competições Nacionais/PO09/20250913 - ALMADA AC / EXT. GIL EANES")).toMatchObject({ home: "ALMADA AC", away: "EXT. GIL EANES", day: "2025-09-13", season: "20252026", competition: "PO09", }); expect(parseFolder("/Liga/04.11.23 ALMADA AC / EXT. GIL EANES")).toMatchObject({ home: "ALMADA AC", away: "EXT. GIL EANES", day: "2023-11-04" }); expect(directorySides("ALMADA AC / EXT. GIL EANES")).toEqual(["ALMADA AC", "EXT. GIL EANES"]); expect(parseFolder("/x/20250913 - 2025/2026")).toBeNull(); expect(parseFolder("/x/20250913 - Final / Video")).toBeNull(); expect(directorySides("Sporting CP")).toEqual(["Sporting CP"]); // A sponsor after the slash is the same club, not the away team. "Avanca / Bioria" was Avanca. expect(parseFolder("/Liga/04.11.23 Avanca / Bioria")).toMatchObject({ home: "Avanca / Bioria", away: "", single: true, day: "2023-11-04" }); expect(parseFolder("/FPA/Fotos/2024_2025/PO01/20240913 - Avanca / Bioria")).toBeNull(); expect(parseFolder("/Liga/04.11.23 Sporting CP / Betclic")).toMatchObject({ home: "Sporting CP / Betclic", away: "", single: true }); const clubs = [ { name: "Avanca", abbreviation: null, slug: "avanca" }, { name: "SL Benfica", abbreviation: "SLB", slug: "benfica" }, { name: "FC Porto", abbreviation: "FCP", slug: "porto" }, { name: "Sporting CP", abbreviation: "SCP", slug: "sporting-cp" }, ]; expect(canonicalTeam("Avanca / Bioria", clubs)).toBe("Avanca"); expect(canonicalTeam("Bioria / Avanca", clubs)).toBe("Avanca"); expect(canonicalTeam("Sporting CP / Betclic", clubs)).toBe("Sporting CP"); expect(canonicalTeam("ALMADA AC / EXT. GIL EANES", clubs)).toBe("ALMADA AC / EXT. GIL EANES"); expect(knownVersus("Avanca / Bioria", clubs)).toBeNull(); expect(knownVersus("Benfica / Porto", clubs)).toEqual({ home: "SL Benfica", away: "FC Porto" }); const match = teamMatcher(clubs); expect(directorySides("Avanca / Bioria", (n) => match.knownName(n))).toEqual(["Avanca / Bioria"]); expect(directorySides("Benfica / Porto", (n) => match.knownName(n))).toEqual(["Benfica", "Porto"]); for (const name of ["Avanca / Bioria", "Bioria / Avanca", "Sporting CP / Betclic", "Benfica / Porto", "ALMADA AC / EXT. GIL EANES"]) expect(match(name)).toBe(canonicalTeam(name, clubs)); expect( teamSideRows([{ id: "e1", home: "SCP", away: "Benfica" }], match, new Map([["benfica", "SL Benfica"]])), ).toEqual([ { eventId: "e1", raw: "SCP", name: "Sporting CP" }, { eventId: "e1", raw: "Benfica", name: "SL Benfica" }, ]); }); it("reads Liga folders: competition and season from the top, matchday, numbered games", () => { expect(parseFolder("/LPBetclic 26-27/Jornada 5/03. Sporting CP x SC Braga")).toMatchObject({ home: "Sporting CP", away: "SC Braga", day: null, season: "20262027", competition: "ligaportugalbetclic", round: "5", }); }); it("finds the game above a photographer's folder, and Liga rounds and seasons written their way", () => { expect(parseFolder("/LPBetclic 26-27/Jornada 5/03. Sporting CP x SC Braga/Peter Spark")).toMatchObject({ home: "Sporting CP", away: "SC Braga", round: "5", season: "20262027" }); const t = (name: string) => ({ name, abbreviation: null, slug: name }); const fixture: FixtureCandidate = { id: "x", startsAt: new Date("2026-09-20T18:00:00Z"), season: "2026/2027", round: "Jornada 5", competition: { externalId: "ligaportugalbetclic" }, homeTeam: t("Sporting CP"), awayTeam: t("SC Braga") }; expect(pickFixture(parseFolder("/LPBetclic 26-27/Jornada 5/03. Sporting CP x SC Braga/Selecionadas")!, [fixture])?.id).toBe("x"); expect(pickFixture(parseFolder("/LPBetclic 26-27/Jornada 6/03. Sporting CP x SC Braga")!, [fixture])).toBeNull(); }); it("never takes a game from a season or month alone, nor a reserve or youth side for the first team", () => { const t = (name: string) => ({ name, abbreviation: null, slug: name }); const senior: FixtureCandidate = { id: "s", startsAt: new Date("2026-10-09T19:15:00Z"), season: "20262027", round: "Jornada 8", competition: { externalId: "ligaportugalbetclic" }, homeTeam: t("SC Braga"), awayTeam: t("Sporting CP") }; expect(pickFixture(parseFolder("/2026_2027/Braga x Sporting")!, [senior])).toBeNull(); expect(pickFixture(parseFolder("/2026_2027/09.10.2026 Braga x Sporting")!, [senior])?.id).toBe("s"); expect(pickFixture(parseFolder("/2026_2027/09.10.2026 Braga B x Sporting B")!, [senior])).toBeNull(); expect(pickFixture(parseFolder("/Sub-23/09.10.2026 Braga x Sporting")!, [senior])).toBeNull(); }); it("never dates photos on a day still to come: future games are not candidates, and years read the right way", () => { const t = (name: string) => ({ name, abbreviation: null, slug: name }); const now = new Date("2026-10-15T12:00:00Z"); const later: FixtureCandidate = { id: "f", startsAt: new Date("2027-01-10T15:00:00Z"), season: "20262027", round: "Jornada 17", competition: { externalId: "ligaportugalmeusuper" }, homeTeam: t("FC Porto B"), awayTeam: t("SL Benfica B") }; expect(pickFixture(parseFolder("/LP2 26-27/Jornada 17/FC Porto B x SL Benfica B")!, [later], now)).toBeNull(); const played = { ...later, id: "p", startsAt: new Date("2026-01-10T15:00:00Z"), season: "20252026" }; expect(pickFixture(parseFolder("/LP2/10.01.2026 FC Porto B x SL Benfica B")!, [later, played], now)?.id).toBe("p"); // "23.09.28": the 28th of September 2023 (the 23rd of September 2028 has not come yet). expect(parseFolder("/Liga/23.09.28 Estrela Amadora x Braga")).toMatchObject({ day: "2023-09-28", home: "Estrela Amadora", away: "Braga" }); expect(parseFolder("/Liga/04.11.23 Mafra x Leixoes")).toMatchObject({ day: "2023-11-04" }); expect(parseFolder("/x/20991010 - SCP x ABC")).toMatchObject({ day: null }); }); it("reads the Liga cloud's own namings: dashes, month and year, day.month.year, one club", () => { expect(parseFolder("/LP2 23-24/02. CD Feirense - U Leiria")).toMatchObject({ home: "CD Feirense", away: "U Leiria", single: false }); expect(parseFolder("/Mafra/04.11.2023 Mafra va Leixoes")).toMatchObject({ home: "Mafra", away: "Leixoes", day: "2023-11-04", season: "20232024" }); expect(parseFolder("/Mafra/01.2024 NACIONAL")).toMatchObject({ home: "NACIONAL", away: "", single: true, month: "2024-01", season: "20232024" }); expect(parseFolder("/x/02.23 SC Covilha")).toMatchObject({ home: "SC Covilha", month: "2023-02", season: "20222023", single: true }); const t = (name: string) => ({ name, abbreviation: null, slug: name }); const f = (id: string, day: string, home: string, away: string): FixtureCandidate => ({ id, startsAt: new Date(`${day}T15:00:00Z`), season: "20232024", round: null, competition: { externalId: "ligaportugalmeusuper" }, homeTeam: t(home), awayTeam: t(away) }); const jan = [f("a", "2024-01-07", "CD Mafra", "CD Nacional"), f("b", "2024-01-14", "CD Tondela", "CD Mafra"), f("c", "2024-01-21", "CD Nacional", "Leixões SC")]; // The club's folder names the other side. expect(pickFixture(parseFolder("/Mafra/01.2024 NACIONAL")!, jan)?.id).toBe("a"); // Without it, Nacional played twice that month: not sure, so no game. expect(pickFixture(parseFolder("/Outros/01.2024 NACIONAL")!, jan)).toBeNull(); expect(pickFixture(parseFolder("/Outros/01.2024 Tondela")!, jan)?.id).toBe("b"); }); it("leaves folders that are not games", () => { expect(parseFolder("/FPA/Fotos/2025_2026/Eventos/Gala 20250614")).toBeNull(); expect(parseFolder("/FPA/Fotos/2025_2026")).toBeNull(); // A day's happening, not a club; an event's parts, not two teams. expect(parseFolder("/FPA/Fotos/2024_2025/Seleções Nacionais/Seleção Nacional A Masculina/20241105 - Treino")).toBeNull(); expect(parseFolder("/FPA/Fotos/2024_2025/Eventos/Festa do Andebol 2025 - Externo/Dia 2")).toBeNull(); expect(parseFolder("/FPA/Fotos/2024_2025/Taça Portugal/20250607 - Final - Video")).toBeNull(); }); it("puts a game's parts with the game, and reads the FPA's ways of naming", () => { const game = "/FPA/Fotos/2024_2025/Supertaça Kempa 2024/20240824 - ABC x SCP"; for (const part of ["1P", "2P", "Aquecimento", "7M"]) { expect(describeFolder(`${game}/${part}`)).toMatchObject({ occasion: game, section: part }); expect(parseFolder(`${game}/${part}`)).toMatchObject({ home: "ABC", away: "SCP", day: "2024-08-24" }); } const final = "/FPA/Fotos/2025_2026/Competições Nacionais/PO20/20260607 - SLB x SCP"; expect(describeFolder(`${final}/02 - Primeira Parte`)).toMatchObject({ occasion: final, section: "Primeira Parte" }); expect(describeFolder(`${final}/05 - Cerimónia`).occasion).toBe(final); expect(describeFolder("/FPA/Fotos/2024_2025/Taça Portugal/20250607 - Final/Analog/05510").occasion).toBe("/FPA/Fotos/2024_2025/Taça Portugal/20250607 - Final"); // Competition codes written every way; matchdays in the name. expect(parseFolder("/FPA/Fotos/2024_2025/PO01_2024_25/20241209 SLB x SCP")).toMatchObject({ competition: "PO01", home: "SLB", away: "SCP" }); expect(parseFolder("/FPA/Fotos/2026_2027/Competições Nacionais/PO09 - Campeonato Betclic F/20260830 - ABC x SPS")?.competition).toBe("PO09"); expect(parseFolder("/FPA/Fotos/2018_2019/PO-09/J12 - GAIA x ALA")).toMatchObject({ competition: "PO09", round: "12", home: "GAIA", away: "ALA" }); expect(parseFolder("/FPA/Fotos/2019_2020/Andebol 1/20190830 - 1ª J - FCG x VFC")).toMatchObject({ competition: "PO01", round: "1", home: "FCG", away: "VFC" }); expect(parseFolder("/FPA/Fotos/2015_2016/Taça de Portugal/20160403 - SCP x SLB - Final")).toMatchObject({ home: "SCP", away: "SLB" }); }); it("names national teams by country, and keeps club initials that look like codes", () => { expect(parseFolder("/FPA/Fotos/2024_2025/Seleções Nacionais/Seleção Nacional A Masculina/IHF World Championship 2025/20250122 - SWE x POR")).toMatchObject({ home: "Suécia", away: "Portugal" }); expect(parseFolder("/FPA/Fotos/2025_2026/Seleções Nacionais/SNAF/Women's EHF Euro 2026 Qualifiers/20260409 - POR x MNE/1P")).toMatchObject({ home: "Portugal", away: "Montenegro" }); expect(parseFolder("/FPA/Fotos/2024_2025/Seleções Nacionais/Seleção Nacional A Feminina/Women's EHF Euro 2024/20241128 - Spain x Portugal")).toMatchObject({ home: "Espanha", away: "Portugal" }); expect(parseFolder("/FPA/Fotos/2025_2026/Seleções Nacionais/M18/Torneio Tiby/_TEAM PORTUGAL_/PHOTOS MATCH/POR_FRA/M4 - ICONSPORT")).toMatchObject({ home: "Portugal", away: "França" }); // Marítimo and Belenenses, not Morocco and Belgium. expect(parseFolder("/FPA/Fotos/2024_2025/PO01_2024_25/20241218 BEL x MAD")).toMatchObject({ home: "BEL", away: "MAD" }); expect(parseFolder("/FPA/Fotos/2024_2025/PO01_2024_25/20250524 - MAR x SCP")).toMatchObject({ home: "MAR", away: "SCP" }); }); it("reads a photo session's folders as the athletes in it", () => { const session = "/FPA/Fotos/2024_2025/Seleções Nacionais/Seleção Nacional A Feminina/20241118 - Sessão"; expect(describeFolder(`${session}/7 - Bebiana Sabino`)).toMatchObject({ occasion: session, title: "Seleção Nacional A Feminina · Sessão", section: "Bebiana Sabino", people: [{ name: "Bebiana Sabino", number: "7" }], }); expect(describeFolder(`${session}/tec - Renata Pereira`).people).toEqual([{ name: "Renata Pereira", number: null }]); expect(describeFolder(`${session}/misc`)).toMatchObject({ occasion: session, people: [] }); const studio = "/FPA/Fotos/2024_2025/Seleções Nacionais/Seleção Nacional A Masculina/202412 - Estágio Rio Maior/20241229 - Estudio"; expect(describeFolder(`${studio}/Diogo Rema`)).toMatchObject({ occasion: studio, people: [{ name: "Diogo Rema", number: null }] }); expect(describeFolder("/FPA/Fotos/2025_2026/Seleções Nacionais/SNAM/20260103 - Sessão Alternativo/Team Orange + 1/Ana Teixeira").people).toEqual([{ name: "Ana Teixeira", number: null }]); expect(describeFolder("/FPA/Fotos/2023/Sessão/Alexandre Cavalcanti, Manuel Gaspar").people).toEqual([]); expect(describeFolder("/FPA/Fotos/2025_2026/Seleções Nacionais/SNAF/20260306 - Sessao/Alexandre Cavalcanti, Manuel Gaspar").people.map((p) => p.name)).toEqual(["Alexandre Cavalcanti", "Manuel Gaspar"]); // Clubs in an undated session are not people; nor are the groups. expect(describeFolder("/FPA/Fotos/2020_2021/Sessão de Fotos/SL Benfica").people).toEqual([]); expect(describeFolder("/FPA/Fotos/2020_2021/Sessão de Fotos/Águas Santas Milaneza").people).toEqual([]); expect(describeFolder(`${session.replace("20241118 - Sessão", "20260306 - Sessao")}/Grupos`).people).toEqual([]); }); it("puts a game's parts and a session's athletes in one gallery", () => { const game = "/FPA/Fotos/2023_2024/Supertaça Masculina 2023/20231217 - SLB x SCP"; for (const part of ["1P", "2P", "Aquecimento", "Cerimónia", "1 - Pre-Match", "2 - 1st Half", "WARM UP", "GAME", "FLASH", "P1"]) { expect(galleryRoot(`${game}/${part}`)).toBe(game); expect(galleryRoot(`${game}/${part}/selecionadas`)).toBe(game); } const session = "/FPA/Fotos/2023_2024/Seleções Nacionais/Seleção Nacional A Feminina/20231008 - Sessao SNAF"; expect(galleryRoot(`${session}/7 - Bebiana Sabino`)).toBe(session); expect(galleryRoot(`${session}/Equipa Técnica/Ana Teixeira`)).toBe(session); expect(galleryRoot("/FPA/Fotos/2024_2025/Seleções Nacionais/Seleção Nacional A Masculina/202412 - Estágio Rio Maior/20241229 - Estudio/Diogo Rema")).toBe( "/FPA/Fotos/2024_2025/Seleções Nacionais/Seleção Nacional A Masculina/202412 - Estágio Rio Maior/20241229 - Estudio", ); // A game filed inside another folder stays its own gallery. const nest = "/FPA/Fotos/2023_2024/Eventos/20240608 - Colégio Gaia x Vermoim"; expect(galleryRoot(`${nest}/20240509 - Portugal x Bosnia`)).toBe(`${nest}/20240509 - Portugal x Bosnia`); expect(galleryRoot("/LPBetclic - 24-25/Jornada 7/4. SLB x GVFC/3. CPAC x VSC")).toBe("/LPBetclic - 24-25/Jornada 7/4. SLB x GVFC/3. CPAC x VSC"); // A shelf that is not two clubs does not swallow the days under it, nor does a final without two clubs. expect(galleryRoot("/FPA/Fotos/2022_2023/PBHT - EXT/Etapa 1 - Nazaré/Dia 1")).toBe("/FPA/Fotos/2022_2023/PBHT - EXT/Etapa 1 - Nazaré/Dia 1"); expect(galleryRoot("/FPA/Fotos/2018_2019/Andebol de Praia/20180727 - Fase Final/DIA 1")).toBe("/FPA/Fotos/2018_2019/Andebol de Praia/20180727 - Fase Final/DIA 1"); // The same game copied under another name, when that copy is itself a game, stays separate. expect(galleryRoot("/LPBetclic 25-26/Jornada 22/6. CD Nacional x FC Porto/15.02.2026 NACIONAL X FC PORTO")).toBe( "/LPBetclic 25-26/Jornada 22/6. CD Nacional x FC Porto/15.02.2026 NACIONAL X FC PORTO", ); // The duplicate mirror is not a session just because the shelf says "sessão". const mirror = "/FPA/Fotos/SESSÃO ESTÚDIO SNAF (2020 a 2022) - Equipamento Select/2023_2024/Supertaça Masculina 2023/20231217 - SLB x SCP"; expect(galleryRoot(`${mirror}/1P`)).toBe(mirror); const gameId = "game"; const partId = "part"; const nestedId = "nested"; const assigned = galleryAssignments([ { id: gameId, path: game }, { id: partId, path: `${game}/1P` }, { id: nestedId, path: `${nest}/20240509 - Portugal x Bosnia` }, ]); expect(assigned.get(partId)).toBe(gameId); expect(assigned.get(gameId)).toBe(gameId); expect(assigned.get(nestedId)).toBe(nestedId); }); it("names what is not a game after the folders above when its own name says little", () => { expect(describeFolder("/FPA/Fotos/2025_2026/Eventos/Encontro Nacional sub-14 - Externo/Dia 2/Cerimónia")).toMatchObject({ occasion: "/FPA/Fotos/2025_2026/Eventos/Encontro Nacional sub-14 - Externo/Dia 2", title: "Encontro Nacional sub-14 - Externo · Dia 2", section: "Cerimónia", }); expect(describeFolder("/FPA/Fotos/2025_2026/Supertaça Kempa 2025/Feminina/1P").title).toBe("Supertaça Kempa 2025 · Feminina"); expect(describeFolder("/FPA/Fotos/2025_2026/Eventos/20260308 - Seminário Dia da Mulher").title).toBe("Seminário Dia da Mulher"); }); it("knows teams by abbreviation, name and close names", () => { const scp = { name: "Sporting CP", abbreviation: "SCP", slug: "sporting-cp" }; expect(isTeam("SCP", scp)).toBe(true); expect(isTeam("Sporting", scp)).toBe(true); expect(isTeam("SLB", scp)).toBe(false); }); it("knows clubs by their initials, as the FPA folders name them", () => { expect(isInitials("SCP", "Sporting Clube de Portugal")).toBe(true); expect(isInitials("SLB", "Sport Lisboa e Benfica")).toBe(true); expect(isInitials("AAAS", "Associação Atlética de Águas Santas")).toBe(true); expect(isInitials("FCP", "FC Porto")).toBe(true); expect(isInitials("SCP", "Sport Lisboa e Benfica")).toBe(false); expect(isTeam("ABC", { name: "ABC de Braga / Uminho", abbreviation: null, slug: "abc-braga" })).toBe(true); expect(isTeam("SLB", { name: "Sport Lisboa e Benfica", abbreviation: null, slug: "benfica" })).toBe(true); expect(isTeam("SLB", { name: "Sporting Clube de Portugal", abbreviation: null, slug: "sporting" })).toBe(false); // The program writes the federation code. "AAAS" is not the initials of the sponsor name. const aguas = { name: "Águas Santas Milaneza", abbreviation: null, slug: "aguas-santas-milaneza" }; const sporting = { name: "Sporting CP", abbreviation: null, slug: "sporting-cp" }; expect(isTeam("AAAS", aguas)).toBe(true); expect(isTeam("SCP", sporting)).toBe(true); expect(isTeam("AAAS", { name: "AA Águas Santas 'B'", abbreviation: null, slug: "aa-aguas-santas-b" })).toBe(false); const today: FixtureCandidate = { id: "hoje", startsAt: new Date("2026-10-18T13:00:00Z"), season: "20262027", round: null, competition: { externalId: "PO01" }, homeTeam: aguas, awayTeam: sporting, }; expect(pickFixture(parseFolder("/FPA/Fotos/2026_2027/Competições Nacionais/PO01 - Campeonato Betclic/20261018 - AAAS x SCP")!, [today])?.id).toBe("hoje"); }); it("takes a game only when both sides are recognised, never with one guessed", () => { const t = (name: string) => ({ name, abbreviation: null, slug: name }); const f = (id: string, home: string, away: string): FixtureCandidate => ({ id, startsAt: new Date("2026-10-03T17:00:00Z"), season: "20262027", round: null, competition: { externalId: "PO01" }, homeTeam: t(home), awayTeam: t(away) }); const fixtures = [f("a", "Sporting Clube de Portugal", "Marítimo Madeira Andebol SAD"), f("b", "Sport Lisboa e Benfica", "FC Gaia")]; expect(pickFixture(parseFolder("/2026_2027/Competições Nacionais/PO01/20261003 - SCP x Marítimo")!, fixtures)?.id).toBe("a"); expect(pickFixture(parseFolder("/2026_2027/Competições Nacionais/PO01/20261003 - SCP x SLB")!, fixtures)).toBeNull(); expect(pickFixture(parseFolder("/2026_2027/Competições Nacionais/PO01/20261003 - SCP x Desconhecido")!, fixtures)).toBeNull(); }); it("never matches a legends' tournament or a charity game to a championship, nor a first team to its B side", () => { const t = (name: string) => ({ name, abbreviation: null, slug: name }); const f = (id: string, day: string, home: string, away: string, season = "20252026"): FixtureCandidate => ({ id, startsAt: new Date(`${day}T17:00:00Z`), season, round: "2", competition: { externalId: "ligaportugalmeusuper" }, homeTeam: t(home), awayTeam: t(away) }); const legends = parseFolder("/Liga Portugal Legends 2025-26/Dia 2/8. SL Benfica x SCU Torreense")!; expect(isExhibition(legends)).toBe(true); expect(exhibitionName(legends)).toBe("Liga Portugal Legends 2025-26"); expect(pickFixture({ ...legends, day: "2026-03-10" }, [f("a", "2026-03-10", "SL Benfica", "SCU Torreense")])).toBeNull(); expect(isTeam("SL Benfica", t("SL Benfica B"))).toBe(false); expect(isTeam("Benfica B", t("SL Benfica B"))).toBe(true); const game = parseFolder("/2025_2026/Liga/20260310 - SL Benfica x SCU Torreense")!; expect(pickFixture(game, [f("b", "2026-03-10", "SL Benfica B", "SCU Torreense")])).toBeNull(); }); it("names teams without the date before them, and as the known team when one fits", () => { expect(teamLabel("01.23 Leixoes SC")).toBe("Leixoes SC"); expect(teamLabel("02_ESTORIL PRAIA")).toBe("ESTORIL PRAIA"); expect(teamLabel("10 (copiar).22 CD Tondela")).toBe("CD Tondela"); expect(teamLabel("1 Gil Vicente")).toBe("Gil Vicente"); expect(teamLabel("Sporting CP B")).toBe("Sporting CP B"); const known = [ { name: "Sporting CP", abbreviation: "SCP", slug: "sporting-cp" }, { name: "U. Leiria", abbreviation: "UDL", slug: "u-leiria" }, { name: "SL Benfica B", abbreviation: "SLB B", slug: "benfica-b" }, ]; expect(canonicalTeam("01 SCP", known)).toBe("Sporting CP"); expect(canonicalTeam("06_SPORTING CP", known)).toBe("Sporting CP"); expect(canonicalTeam("02.2024 Benfica B", known)).toBe("SL Benfica B"); expect(canonicalTeam("09.2023 Leiria", known)).toBe("U. Leiria"); // The prepared matcher (many names, same teams) answers the same. const match = teamMatcher(known); for (const name of ["01 SCP", "06_SPORTING CP", "02.2024 Benfica B", "09.2023 Leiria", "Benfica", "UDL", "SLB B", "FC Porto", "", "12"]) expect(match(name)).toBe(canonicalTeam(name, known)); }); it("picks the one fixture with those teams on that day", () => { const team = (name: string, abbreviation: string) => ({ name, abbreviation, slug: name.toLowerCase().replace(/ /g, "-") }); const fx = (id: string, day: string, home: ReturnType, away: ReturnType, round: string | null = null): FixtureCandidate => ({ id, startsAt: new Date(`${day}T18:00:00Z`), season: "20252026", round, competition: { externalId: "PO01" }, homeTeam: home, awayTeam: away, }); const scp = team("Sporting CP", "SCP"); const abc = team("ABC de Braga", "ABC"); const slb = team("SL Benfica", "SLB"); const fixtures = [fx("a", "2025-09-13", scp, abc), fx("b", "2025-09-13", slb, abc), fx("c", "2026-02-01", abc, scp)]; expect(pickFixture(parseFolder("/2025_2026/PO01/20250913 - SCP x ABC")!, fixtures)?.id).toBe("a"); expect(pickFixture(parseFolder("/2025_2026/PO01/20260201 - ABC x SCP")!, fixtures)?.id).toBe("c"); expect(pickFixture(parseFolder("/2025_2026/PO01/20250914 - SCP x SLB")!, fixtures)).toBeNull(); }); }); describe("WebDAV listing", () => { it("parses a Nextcloud multistatus (ids, etags, sizes, folders, escaped names)", () => { const xml = ` /nc/remote.php/dav/files/peter/FPA/Fotos/ "abc"1099HTTP/1.1 200 OK HTTP/1.1 404 Not Found /nc/remote.php/dav/files/peter/FPA/Fotos/Competi%c3%a7%c3%b5es%20Nacionais/ "def"11HTTP/1.1 200 OK /nc/remote.php/dav/files/peter/FPA/Fotos/A%20%26%20B.jpg "f1"1234image/jpeg12HTTP/1.1 200 OK `; const entries = parseMultistatus(xml, "/nc/remote.php/dav/files/peter"); expect(entries).toEqual([ expect.objectContaining({ path: "/FPA/Fotos", fileId: "10", etag: "abc", isDir: true }), expect.objectContaining({ path: "/FPA/Fotos/Competições Nacionais", name: "Competições Nacionais", fileId: "11", isDir: true }), expect.objectContaining({ path: "/FPA/Fotos/A & B.jpg", fileId: "12", size: 1234, isDir: false, contentType: "image/jpeg" }), ]); }); }); describe("CloudClient retries transient failures", () => { const whoami = (url: URL) => (url.pathname.endsWith("/ocs/v2.php/cloud/user") ? Response.json({ ocs: { data: { id: "peter" } } }) : null); it("retries a 423/503 blip on a download and succeeds, instead of failing on the first try", async () => { let calls = 0; const fetchImpl: typeof fetch = async (input) => { const url = new URL(String(input)); const who = whoami(url); if (who) return who; calls++; return calls <= 2 ? new Response(null, { status: 503 }) : new Response(new Uint8Array(Buffer.from("hello")), { status: 200 }); }; const client = new CloudClient({ baseUrl: "https://cloud.test", username: "peter", password: "pw" }, fetchImpl); const dir = await mkdtemp(path.join(tmpdir(), "pr-retry-test-")); try { await client.download("/a.jpg", path.join(dir, "out.jpg")); expect(calls).toBe(3); } finally { await rm(dir, { recursive: true, force: true }); } }); it("gives up after exhausting retries and throws a transient NextcloudError", async () => { const fetchImpl: typeof fetch = async (input) => { const url = new URL(String(input)); return whoami(url) ?? new Response(null, { status: 503 }); }; const client = new CloudClient({ baseUrl: "https://cloud.test", username: "peter", password: "pw" }, fetchImpl); const dir = await mkdtemp(path.join(tmpdir(), "pr-retry-test-")); try { await expect(client.download("/a.jpg", path.join(dir, "out.jpg"))).rejects.toMatchObject({ status: 503 }); } finally { await rm(dir, { recursive: true, force: true }); } }); it("retries a 503 blip on a PROPFIND (BIT-31498) and succeeds, instead of failing the whole walk", async () => { const multistatus = ` /remote.php/dav/files/peter/FPA/Fotos/ "abc"10HTTP/1.1 200 OK `; let calls = 0; const fetchImpl: typeof fetch = async (input) => { const url = new URL(String(input)); const who = whoami(url); if (who) return who; calls++; return calls <= 2 ? new Response(null, { status: 503 }) : new Response(multistatus, { status: 207 }); }; const client = new CloudClient({ baseUrl: "https://cloud.test", username: "peter", password: "pw" }, fetchImpl); const { self } = await client.list("/FPA/Fotos"); expect(self.fileId).toBe("10"); expect(calls).toBe(3); }); }); interface Node { id: string; data?: Buffer; } /** A Nextcloud with a file tree (ids, etags that change up the tree), login flow v2 and shares. */ class FakeCloud { nodes = new Map([["/", { id: "1" }]]); private next = 100; authorised = false; propfinds: string[] = []; user = "peter"; password = "app-pass-123"; /** Who authorises the next login flow, and the other accounts (viewers) with what is shared with them. */ loginAs = "peter"; viewers = new Map(); revoked: string[] = []; idOf(p: string) { return this.nodes.get(p)!.id; } add(file: string, data?: Buffer) { const parts = file.split("/").filter(Boolean); let cur = ""; for (let i = 0; i < parts.length; i++) { cur += "/" + parts[i]; const last = i === parts.length - 1; if (!this.nodes.has(cur)) this.nodes.set(cur, { id: String(this.next++), ...(last && data ? { data } : {}) }); else if (last && data) this.nodes.get(cur)!.data = data; } } remove(file: string) { for (const k of [...this.nodes.keys()]) if (k === file || k.startsWith(file + "/")) this.nodes.delete(k); } private etag(p: string): string { const n = this.nodes.get(p)!; if (n.data) return createHash("md5").update(n.data).digest("hex"); const kids = this.children(p).map((c) => c + ":" + this.etag(c)); return createHash("md5").update(kids.join("|")).digest("hex"); } private children(p: string): string[] { const prefix = p === "/" ? "/" : p + "/"; return [...this.nodes.keys()].filter((k) => k !== p && k.startsWith(prefix) && !k.slice(prefix.length).includes("/")); } private entry(p: string): string { const n = this.nodes.get(p)!; const href = `/remote.php/dav/files/${this.user}${p.split("/").map(encodeURIComponent).join("/")}${n.data ? "" : "/"}`; return `${href}"${this.etag(p)}"${ n.data ? `${n.data.length}` : "" }${n.id}HTTP/1.1 200 OK`; } fetch: typeof fetch = async (input, init) => { const url = new URL(String(input)); const method = init?.method ?? "GET"; if (url.pathname === "/index.php/login/v2" && method === "POST") { return Response.json({ poll: { token: "tok", endpoint: "https://cloud.test/login/v2/poll" }, login: "https://cloud.test/login/v2/flow/xyz" }); } if (url.pathname === "/login/v2/poll") { if (!this.authorised) return new Response(null, { status: 404 }); const viewer = this.viewers.get(this.loginAs); return Response.json({ server: "https://cloud.test", loginName: this.loginAs, appPassword: viewer?.password ?? this.password }); } const auth = new Headers(init?.headers).get("authorization"); const who = [[this.user, this.password] as const, ...[...this.viewers].map(([u, v]) => [u, v.password] as const)].find( ([u, pw]) => auth === "Basic " + Buffer.from(`${u}:${pw}`).toString("base64"), )?.[0]; if (!who) return new Response(null, { status: 401 }); if (url.pathname === "/ocs/v2.php/cloud/user") return Response.json({ ocs: { data: { id: who, "display-name": who.toUpperCase() } } }); if (url.pathname === "/ocs/v2.php/apps/files_sharing/api/v1/shares") { const v = this.viewers.get(who); return Response.json({ ocs: { data: (v?.shared ?? []).map((id) => ({ item_source: Number(id), share_type: 1, permissions: v?.edit?.includes(id) ? 31 : 1 })) } }); } if (url.pathname === "/ocs/v2.php/core/apppassword" && method === "DELETE") { this.revoked.push(who); return Response.json({}); } if (who !== this.user) return new Response(null, { status: 404 }); const dav = /^\/remote\.php\/dav\/files\/[^/]+(\/.*)?$/.exec(url.pathname); if (dav) { const p = decodeURIComponent(dav[1] ?? "/").replace(/(.)\/$/, "$1") || "/"; const n = this.nodes.get(p); if (!n) return new Response(null, { status: 404 }); if (method === "PROPFIND") { this.propfinds.push(p); const kids = n.data ? [] : this.children(p); return new Response(`${[p, ...kids].map((k) => this.entry(k)).join("")}`, { status: 207 }); } if (method === "GET" && n.data) return new Response(new Uint8Array(n.data), { status: 200, headers: { "content-type": "image/jpeg" } }); } return new Response(null, { status: 404 }); }; } const jpeg = (seed: number) => sharp({ create: { width: 3000, height: 2000, channels: 3, background: { r: seed % 255, g: (seed * 7) % 255, b: 90 } } }) .jpeg() .toBuffer(); describe("archive from a Nextcloud", () => { let ctx: TestContext; let cloud: FakeCloud; let storageRoot: string; let token: string; let orgId: string; let ownerId: string; let worker: ArchiveService; const fetchProxy: typeof fetch = (input, init) => cloud.fetch(input, init); beforeAll(async () => { storageRoot = await mkdtemp(path.join(tmpdir(), "pr-archive-test-")); ctx = await createTestApp({ DELIVERY_SECRET_KEY: KEY, STORAGE_ROOT: storageRoot }, undefined, fetchProxy); }); afterAll(async () => { await ctx.app.close(); await ctx.db.$disconnect(); await rm(storageRoot, { recursive: true, force: true }); }); beforeEach(async () => { await resetDb(ctx.db); cloud = new FakeCloud(); const { user, org } = await seedUser(ctx.db, "peter@test.pt", { org: "bitreport", role: "OWNER" }); orgId = org!.id; ownerId = user.id; token = (await login(ctx.app, "peter@test.pt")).body.accessToken; const storage = new LocalStorage(storageRoot); const ingest = new IngestService({ db: ctx.db, storage, signer: new UrlSigner("s".repeat(40), 3600), broadcaster: new MemoryBroadcaster(), ingestRoot: path.join(storageRoot, "ingest"), log: quiet }); worker = new ArchiveService({ db: ctx.db, secrets: new SecretBox(KEY), log: quiet, ingest, fetchImpl: fetchProxy }); const comp = await ctx.db.sportsCompetition.create({ data: { provider: "FPA", externalId: "PO01", sport: "andebol", name: "Andebol 1", season: "20252026" } }); const scp = await ctx.db.sportsTeam.create({ data: { provider: "FPA", externalId: "1", sport: "andebol", name: "Sporting CP", abbreviation: "SCP", slug: "sporting-cp" } }); const abc = await ctx.db.sportsTeam.create({ data: { provider: "FPA", externalId: "2", sport: "andebol", name: "ABC de Braga", abbreviation: "ABC", slug: "abc-de-braga" } }); await ctx.db.sportsFixture.create({ data: { competitionId: comp.id, season: "20252026", externalId: "g1", homeTeamId: scp.id, awayTeamId: abc.id, startsAt: new Date("2025-09-13T18:00:00Z") } }); await ctx.db.sportsFixture.create({ data: { competitionId: comp.id, season: "20252026", externalId: "g2", homeTeamId: abc.id, awayTeamId: scp.id, startsAt: new Date("2026-02-01T18:00:00Z") } }); const game = "/FPA/Fotos/2025_2026/Competições Nacionais/PO01/20250913 - SCP x ABC"; cloud.add(`${game}/PS_0001.jpg`, await jpeg(1)); cloud.add(`${game}/PS_0002.jpg`, await jpeg(2)); cloud.add(`${game}/notes.txt`, Buffer.from("x")); cloud.add("/FPA/Fotos/2025_2026/Eventos/Gala 20250614/G_0001.jpg", await jpeg(3)); cloud.add("/Outros/nao.jpg", await jpeg(4)); }); const connect = async () => { const res = await ctx.app.inject({ method: "POST", url: `/v1/orgs/${orgId}/cloud-sources`, headers: bearer(token), payload: { name: "Cloud FPA", baseUrl: "https://cloud.test/", rootPath: "/FPA/Fotos/" } }); expect(res.statusCode).toBe(201); return res.json() as { id: string; status: string; loginUrl: string; rootPath: string }; }; it("connects with the login flow, indexes the galleries into their games, and serves originals from the cloud", async () => { const source = await connect(); expect(source).toMatchObject({ status: "LOGIN", loginUrl: "https://cloud.test/login/v2/flow/xyz", rootPath: "/FPA/Fotos" }); // Not authorised yet: still waiting. let res = await ctx.app.inject({ method: "GET", url: `/v1/cloud-sources/${source.id}`, headers: bearer(token) }); expect(res.json()).toMatchObject({ status: "LOGIN", account: null }); cloud.authorised = true; res = await ctx.app.inject({ method: "GET", url: `/v1/cloud-sources/${source.id}`, headers: bearer(token) }); expect(res.json()).toMatchObject({ status: "READY", account: "peter", loginUrl: null }); const stored = await ctx.db.cloudSource.findUniqueOrThrow({ where: { id: source.id } }); expect(stored.secretEnc).not.toContain("app-pass"); expect(await worker.scanDue()).toBe(1); const folders = await ctx.db.cloudFolder.findMany({ where: { photoCount: { gt: 0 } }, include: { event: true }, orderBy: { path: "asc" } }); expect(folders.map((f) => [f.path.split("/").pop(), f.photoCount, f.matchedBy])).toEqual([ ["20250913 - SCP x ABC", 2, "FIXTURE"], ["Gala 20250614", 1, "FOLDER"], ]); const gameEvent = folders[0]!.event!; expect(gameEvent).toMatchObject({ home: "Sporting CP", away: "ABC de Braga", competitionCode: "PO01", sport: "andebol" }); expect(gameEvent.archivedAt).not.toBeNull(); expect(folders[1]!.event).toMatchObject({ home: "Gala 20250614", away: "" }); expect(folders[1]!.event!.startsAt.toISOString()).toBe("2025-06-14T12:00:00.000Z"); // Index everything queued. for (let ids = await worker.claim(10); ids.length; ids = await worker.claim(10)) for (const id of ids) await worker.index(id); const files = await ctx.db.cloudFile.findMany({ include: { photo: true } }); expect(files).toHaveLength(3); expect(files.every((f) => f.status === "DONE" && f.photo?.source === "CLOUD" && !f.photo.originalStored)).toBe(true); const photo = files.find((f) => f.path.endsWith("PS_0001.jpg"))!.photo!; expect(photo).toMatchObject({ eventId: gameEvent.id, width: 3000, height: 2000, status: "READY", uploaderId: ownerId }); // The source's progress. res = await ctx.app.inject({ method: "GET", url: `/v1/orgs/${orgId}/cloud-sources`, headers: bearer(token) }); expect(res.json().sources[0].counts).toMatchObject({ done: 3, pending: 0, galleries: 2, games: 1, unmatched: 1 }); // The full original, read from the cloud. res = await ctx.app.inject({ method: "GET", url: `/v1/photos/${photo.id}/original`, headers: bearer(token) }); expect(res.statusCode).toBe(200); expect(createHash("sha256").update(res.rawPayload).digest("hex")).toBe(photo.sha256); // Nothing changed: the walk stops at the root. cloud.propfinds = []; await worker.scan(source.id); expect(cloud.propfinds).toEqual(["/FPA/Fotos"]); // A new photo and a removed one: only the changed branch is read again. cloud.propfinds = []; cloud.add("/FPA/Fotos/2025_2026/Competições Nacionais/PO01/20250913 - SCP x ABC/PS_0003.jpg", await jpeg(5)); cloud.remove("/FPA/Fotos/2025_2026/Competições Nacionais/PO01/20250913 - SCP x ABC/PS_0002.jpg"); const stats = await worker.scan(source.id); expect(stats.queued).toBe(1); expect(cloud.propfinds).not.toContain("/FPA/Fotos/2025_2026/Eventos"); expect(await ctx.db.cloudFile.count()).toBe(3); expect(await ctx.db.cloudFile.count({ where: { status: "PENDING" } })).toBe(1); }); it("resumes a walk cut short by a restart, reading only what it had not finished", async () => { const source = await connect(); cloud.authorised = true; await ctx.app.inject({ method: "GET", url: `/v1/cloud-sources/${source.id}`, headers: bearer(token) }); await worker.scan(source.id); // As a deploy leaves it: still "walking", one branch not read to the end, no next walk planned. const gala = await ctx.db.cloudFolder.findFirstOrThrow({ where: { path: { endsWith: "Gala 20250614" } } }); await ctx.db.cloudFile.deleteMany({ where: { folderId: gala.id } }); for (let f: typeof gala | null = gala; f; f = f.parentId ? await ctx.db.cloudFolder.findUnique({ where: { id: f.parentId } }) : null) { await ctx.db.cloudFolder.update({ where: { id: f.id }, data: { etag: null } }); } await ctx.db.cloudSource.update({ where: { id: source.id }, data: { status: "SCANNING", lastScanAt: null, nextScanAt: new Date(Date.now() + 86_400_000) } }); expect(await worker.scanDue()).toBe(0); await worker.requeueStale(); cloud.propfinds = []; expect(await worker.scanDue()).toBe(1); expect(cloud.propfinds).not.toContain("/FPA/Fotos/2025_2026/Competições Nacionais"); expect(await ctx.db.cloudFile.count({ where: { folderId: gala.id } })).toBe(1); const after = await ctx.db.cloudSource.findUniqueOrThrow({ where: { id: source.id } }); expect(after.status).toBe("READY"); expect(after.lastScanAt).not.toBeNull(); }); it("requeues a photo instead of failing it when a download blip outlasts the cloud client's own retries (BIT-31505)", async () => { const source = await connect(); cloud.authorised = true; await ctx.app.inject({ method: "GET", url: `/v1/cloud-sources/${source.id}`, headers: bearer(token) }); await worker.scan(source.id); const [id] = await worker.claim(1); const claimed = await ctx.db.cloudFile.findUniqueOrThrow({ where: { id } }); expect(claimed).toMatchObject({ status: "WORKING", attempts: 1 }); // Nextcloud stays unavailable for longer than CloudClient.call's own retry budget (BIT-31491): the GET for // this file keeps answering 503 past the last retry, so download() gives up and throws. const realFetch = cloud.fetch; const name = claimed.path.split("/").pop()!; cloud.fetch = async (input, init) => { if ((init?.method ?? "GET") === "GET" && new URL(String(input)).pathname.endsWith(name)) return new Response(null, { status: 503 }); return realFetch(input, init); }; await worker.index(id); cloud.fetch = realFetch; // Given back to the walk, not failed outright, and the claim's attempt is given back with it: a cloud blip // never counts toward the permanent-failure limit the way a real decoding/matching error would. const requeued = await ctx.db.cloudFile.findUniqueOrThrow({ where: { id } }); expect(requeued).toMatchObject({ status: "PENDING", attempts: 0 }); expect(requeued.error).toContain("503"); const [again] = await worker.claim(1); expect(again).toBe(id); await worker.index(again); expect(await ctx.db.cloudFile.findUniqueOrThrow({ where: { id } })).toMatchObject({ status: "DONE" }); }); it("logs a download blip at info, not warn, so a free retry never reaches the error hub as a new error (BIT-31513)", async () => { const source = await connect(); cloud.authorised = true; await ctx.app.inject({ method: "GET", url: `/v1/cloud-sources/${source.id}`, headers: bearer(token) }); const calls: { level: "info" | "warn"; msg: string }[] = []; const spy = { info: (_obj: unknown, msg: string) => calls.push({ level: "info", msg }), warn: (_obj: unknown, msg: string) => calls.push({ level: "warn", msg }), }; const storage = new LocalStorage(storageRoot); const ingest = new IngestService({ db: ctx.db, storage, signer: new UrlSigner("s".repeat(40), 3600), broadcaster: new MemoryBroadcaster(), ingestRoot: path.join(storageRoot, "ingest"), log: quiet }); const spied = new ArchiveService({ db: ctx.db, secrets: new SecretBox(KEY), log: spy, ingest, fetchImpl: fetchProxy }); await spied.scan(source.id); const [id] = await spied.claim(1); const claimed = await ctx.db.cloudFile.findUniqueOrThrow({ where: { id } }); const realFetch = cloud.fetch; const name = claimed.path.split("/").pop()!; cloud.fetch = async (input, init) => { if ((init?.method ?? "GET") === "GET" && new URL(String(input)).pathname.endsWith(name)) return new Response(null, { status: 503 }); return realFetch(input, init); }; await spied.index(id); cloud.fetch = realFetch; // Same recoverable blip as BIT-31505: a free retry, not an error to page on, so logHooks (reporter.ts) must // never see it as a "warn" carrying an err (it would otherwise reach errors.bitreport.pt and reopen the Loop). expect(calls).toContainEqual({ level: "info", msg: "archive: image download blipped, requeued for a free retry" }); expect(calls.some((c) => c.level === "warn")).toBe(false); }); it("puts a game's halves in one event with the clubs' names, and names a session's athletes on their photos", async () => { const game = "/FPA/Fotos/2024_2025/Supertaça Kempa 2024/20240824 - SCP x ABC"; cloud.add(`${game}/1P/H_0001.jpg`, await jpeg(6)); cloud.add(`${game}/2P/H_0002.jpg`, await jpeg(7)); const session = "/FPA/Fotos/2025_2026/Seleções Nacionais/SNAF/20260306 - Sessao"; cloud.add(`${session}/7 - Bebiana Sabino/S_0001.jpg`, await jpeg(8)); cloud.add(`${session}/8 - Constança Sequeira/S_0002.jpg`, await jpeg(9)); const source = await connect(); cloud.authorised = true; await ctx.app.inject({ method: "GET", url: `/v1/cloud-sources/${source.id}`, headers: bearer(token) }); await worker.scan(source.id); for (let ids = await worker.claim(10); ids.length; ids = await worker.claim(10)) for (const id of ids) await worker.index(id); const folder = (p: string) => ctx.db.cloudFolder.findFirstOrThrow({ where: { path: p }, include: { event: true } }); const [h1, h2] = await Promise.all([folder(`${game}/1P`), folder(`${game}/2P`)]); expect(h1.eventId).toBe(h2.eventId); expect(h1).toMatchObject({ matchedBy: "NAME", event: { home: "Sporting CP", away: "ABC de Braga", homeShort: "SCP", awayShort: "ABC" } }); expect(lisbonDay(h1.event!.startsAt)).toBe("2024-08-24"); const [s1, s2] = await Promise.all([folder(`${session}/7 - Bebiana Sabino`), folder(`${session}/8 - Constança Sequeira`)]); expect(s1.eventId).toBe(s2.eventId); expect(s1).toMatchObject({ matchedBy: "FOLDER", event: { home: "SNAF · Sessao", away: "" } }); const photo = await ctx.db.photo.findFirstOrThrow({ where: { originalName: "S_0001.jpg" } }); expect(photo.players).toEqual(["Bebiana Sabino"]); // Galleries made before this was understood (one event per half, named "1P") are put right by the next walk. const stray = await ctx.db.event.create({ data: { organizationId: orgId, home: "2P", away: "", startsAt: new Date(), ingestFrom: new Date(), ingestUntil: new Date(), iptcTemplate: {}, createdById: ownerId, archivedAt: new Date() } }); await worker.setFolderEvent(h2.id, { eventId: stray.id }, "FOLDER"); await ctx.db.photo.update({ where: { id: photo.id }, data: { players: [] } }); await worker.rematch(source.id); expect((await folder(`${game}/2P`)).eventId).toBe(h1.eventId); expect(await ctx.db.event.findUnique({ where: { id: stray.id } })).toBeNull(); expect((await ctx.db.photo.findUniqueOrThrow({ where: { id: photo.id } })).players).toEqual(["Bebiana Sabino"]); // Nothing to change the time after. expect(await worker.rematch(source.id)).toBe(0); }); it("moves a gallery to the game chosen by hand, with its photos", async () => { const source = await connect(); cloud.authorised = true; await ctx.app.inject({ method: "GET", url: `/v1/cloud-sources/${source.id}`, headers: bearer(token) }); await worker.scan(source.id); for (const id of await worker.claim(10)) await worker.index(id); let res = await ctx.app.inject({ method: "GET", url: `/v1/cloud-sources/${source.id}/folders?state=unmatched`, headers: bearer(token) }); const folders = res.json().folders as { id: string; path: string; indexed: number; event: { id: string } }[]; expect(folders).toEqual([expect.objectContaining({ path: "/2025_2026/Eventos/Gala 20250614", indexed: 1, matchedBy: "FOLDER" })]); const oldEvent = folders[0]!.event.id; const fixture = await ctx.db.sportsFixture.findFirstOrThrow({ where: { externalId: "g2" } }); res = await ctx.app.inject({ method: "PUT", url: `/v1/cloud-folders/${folders[0]!.id}/event`, headers: bearer(token), payload: { fixtureId: fixture.id } }); expect(res.statusCode).toBe(200); expect(res.json()).toMatchObject({ matchedBy: "MANUAL", event: { fixtureId: fixture.id } }); const photo = await ctx.db.photo.findFirstOrThrow({ where: { originalName: "G_0001.jpg" } }); expect(photo.eventId).toBe(res.json().event.id); // The folder's own event, now empty, is gone. expect(await ctx.db.event.findUnique({ where: { id: oldEvent } })).toBeNull(); }); it("never drops an event a match lands on while its own cleanup still thinks it is empty (BIT-31531)", async () => { const source = await connect(); cloud.authorised = true; await ctx.app.inject({ method: "GET", url: `/v1/cloud-sources/${source.id}`, headers: bearer(token) }); await worker.scan(source.id); for (const id of await worker.claim(10)) await worker.index(id); const gameFolder = await ctx.db.cloudFolder.findFirstOrThrow({ where: { path: { endsWith: "20250913 - SCP x ABC" } } }); const galaFolder = await ctx.db.cloudFolder.findFirstOrThrow({ where: { path: { endsWith: "Gala 20250614" } } }); const gameEventId = gameFolder.eventId!; const galaEventId = galaFolder.eventId!; // galaFolder is galaEventId's only folder, so moving it onto the game's event makes galaEventId empty and // triggers dropIfEmpty(galaEventId) at the end of the move. Hold that cleanup open right at its delete — as if // another match had just made it look empty a moment ago — while a second move lands gameFolder (and its // photos) on galaEventId. Before BIT-31531 dropIfEmpty read "empty" and deleted on that stale read regardless // of what arrived after; the fix folds the check into the delete's own WHERE, so it must see the new tenant. let releaseDelete!: () => void; const heldOpen = new Promise((resolve) => (releaseDelete = resolve)); let reachedDelete!: () => void; const deleteReached = new Promise((resolve) => (reachedDelete = resolve)); const gated = ctx.db.$extends({ query: { event: { async deleteMany({ args, query }) { if (args.where?.id === galaEventId) { reachedDelete(); await heldOpen; } return query(args); }, }, }, }); const slowWorker = new ArchiveService({ db: gated as unknown as TestContext["db"], secrets: new SecretBox(KEY), log: quiet, fetchImpl: fetchProxy }); const held = slowWorker.setFolderEvent(galaFolder.id, { eventId: gameEventId }); await deleteReached; await worker.setFolderEvent(gameFolder.id, { eventId: galaEventId }); releaseDelete(); await held; const gameAfter = await ctx.db.cloudFolder.findUniqueOrThrow({ where: { id: gameFolder.id } }); expect(gameAfter.eventId).toBe(galaEventId); expect(await ctx.db.event.findUnique({ where: { id: galaEventId } })).not.toBeNull(); const gamePhotos = await ctx.db.photo.findMany({ where: { originalName: { in: ["PS_0001.jpg", "PS_0002.jpg"] } } }); expect(gamePhotos.every((p) => p.eventId === galaEventId)).toBe(true); }); it("asks again when the cloud revokes the app password", async () => { const source = await connect(); cloud.authorised = true; await ctx.app.inject({ method: "GET", url: `/v1/cloud-sources/${source.id}`, headers: bearer(token) }); cloud.password = "changed"; await worker.scan(source.id); const res = await ctx.app.inject({ method: "GET", url: `/v1/cloud-sources/${source.id}`, headers: bearer(token) }); expect(res.json()).toMatchObject({ status: "LOGIN", lastError: "login_revoked" }); }); it("shows outside viewers only the galleries shared with them on the cloud", async () => { const source = await connect(); cloud.authorised = true; await ctx.app.inject({ method: "GET", url: `/v1/cloud-sources/${source.id}`, headers: bearer(token) }); await worker.scan(source.id); for (const id of await worker.claim(10)) await worker.index(id); cloud.authorised = false; // A club account: the PO01 folder is shared with its group. cloud.viewers.set("abc", { password: "abc-pass", shared: [cloud.idOf("/FPA/Fotos/2025_2026/Competições Nacionais/PO01")] }); cloud.viewers.set("ninguem", { password: "n-pass", shared: [] }); const signIn = async (who: string, remember?: boolean) => { cloud.loginAs = who; cloud.authorised = false; let res = await ctx.app.inject({ method: "GET", url: `/v1/archive/${source.id}` }); expect(res.json()).toMatchObject({ name: "Cloud FPA", cloud: "cloud.test" }); res = await ctx.app.inject({ method: "POST", url: `/v1/archive/${source.id}/login` }); const { state, loginUrl } = res.json() as { state: string; loginUrl: string }; expect(loginUrl).toContain("cloud.test"); res = await ctx.app.inject({ method: "POST", url: "/v1/archive/login/poll", payload: { state } }); expect(res.statusCode).toBe(202); cloud.authorised = true; res = await ctx.app.inject({ method: "POST", url: "/v1/archive/login/poll", payload: { state, ...(remember === false && { remember }) } }); expect(res.statusCode).toBe(200); return res.json() as { token: string; viewer: { name: string; all: boolean } }; }; const galleries = async (t: string) => { const res = await ctx.app.inject({ method: "GET", url: `/v1/archive/${source.id}/galleries`, headers: { authorization: `Archive ${t}` } }); expect(res.statusCode).toBe(200); return (res.json() as { galleries: { id: string; title: string; cover: string | null }[] }).galleries; }; const club = await signIn("abc"); expect(club.viewer).toEqual({ name: "ABC", all: false, folders: 1 }); // Kept signed in (the default): the app password stays, to read the shares again later. expect(cloud.revoked).not.toContain("abc"); const seen = await galleries(club.token); expect(seen.map((g) => g.title)).toEqual(["Sporting CP x ABC de Braga"]); expect(seen[0]!.cover).toMatch(/^\/v1\/files\/photos\//); let res = await ctx.app.inject({ method: "GET", url: `/v1/archive/galleries/${seen[0]!.id}`, headers: { authorization: `Archive ${club.token}` } }); expect(res.json().photos).toHaveLength(2); // The gala is not shared with the club. const gala = await ctx.db.cloudFolder.findFirstOrThrow({ where: { path: { endsWith: "Gala 20250614" } } }); res = await ctx.app.inject({ method: "GET", url: `/v1/archive/galleries/${gala.id}`, headers: { authorization: `Archive ${club.token}` } }); expect(res.statusCode).toBe(404); // Not kept signed in: the app password is used once and revoked. const nobody = await signIn("ninguem", false); expect(cloud.revoked).toContain("ninguem"); expect(await galleries(nobody.token)).toEqual([]); // The account that indexes the archive sees all of it. const owner = await signIn("peter"); expect(owner.viewer.all).toBe(true); expect((await galleries(owner.token)).length).toBe(2); // Filters: what each gallery is, its season, the order. const list = async (qs: string) => { const r = await ctx.app.inject({ method: "GET", url: `/v1/archive/${source.id}/galleries?${qs}`, headers: { authorization: `Archive ${owner.token}` } }); expect(r.statusCode).toBe(200); return r.json() as { total: number; seasons?: string[]; galleries: { title: string; kind: string; season: string | null }[] }; }; const games = await list("kind=game"); expect(games.galleries.map((g) => g.title)).toEqual(["Sporting CP x ABC de Braga"]); expect((await list("kind=event")).galleries.map((g) => g.kind)).toEqual(["event"]); const all = await list("sort=az"); expect(all.seasons).toContain("2024/25"); expect((await list("season=2024/25")).galleries.every((g) => g.season === "2024/25")).toBe(true); expect((await list("season=1999/00")).galleries).toEqual([]); // A forged or foreign token is refused. res = await ctx.app.inject({ method: "GET", url: `/v1/archive/${source.id}/galleries`, headers: { authorization: `Archive ${club.token.slice(0, -2)}xx` } }); expect(res.statusCode).toBe(401); // A share taken away on the cloud is gone here at the next reading of the shares. const club2 = await signIn("abc"); expect((await galleries(club2.token)).length).toBe(1); cloud.viewers.get("abc")!.shared = []; await ctx.db.archiveGrant.updateMany({ data: { checkedAt: new Date(Date.now() - 15 * 60_000) } }); expect(await galleries(club2.token)).toEqual([]); // Its app password refused by the cloud (revoked there): signed out. cloud.viewers.get("abc")!.password = "changed"; await ctx.db.archiveGrant.updateMany({ data: { checkedAt: new Date(Date.now() - 15 * 60_000) } }); res = await ctx.app.inject({ method: "GET", url: `/v1/archive/${source.id}/galleries`, headers: { authorization: `Archive ${club2.token}` } }); expect(res.statusCode).toBe(401); // Signing out revokes the kept app password and ends the session. res = await ctx.app.inject({ method: "POST", url: "/v1/archive/logout", headers: { authorization: `Archive ${owner.token}` } }); expect(res.statusCode).toBe(204); expect(cloud.revoked).toContain("peter"); res = await ctx.app.inject({ method: "GET", url: `/v1/archive/${source.id}/galleries`, headers: { authorization: `Archive ${owner.token}` } }); expect(res.statusCode).toBe(401); }); it("finds people by face within what each viewer may see", async () => { const source = await connect(); cloud.authorised = true; await ctx.app.inject({ method: "GET", url: `/v1/cloud-sources/${source.id}`, headers: bearer(token) }); await worker.scan(source.id); for (const id of await worker.claim(10)) await worker.index(id); // Faces as the face worker leaves them: the game's player named, a look-alike unnamed at the gala, someone else. const unit = (v: number[]) => { const n = Math.hypot(...v); return v.map((x) => x / n); }; const martimVec = unit([1, 0.1, 0, 0]); const lookAlike = unit([1, 0.15, 0.05, 0]); const other = unit([0, 0, 1, 0]); const photo = (name: string) => ctx.db.photo.findFirstOrThrow({ where: { originalName: name } }); const [p1, p2, gala] = await Promise.all([photo("PS_0001.jpg"), photo("PS_0002.jpg"), photo("G_0001.jpg")]); const martim = await ctx.db.person.create({ data: { organizationId: orgId, name: "Martim Costa", club: "Sporting CP", number: "21", centroid: martimVec, model: "auraface-v1" } }); const group = (eventId: string, centroid: number[], personId: string | null) => ctx.db.faceGroup.create({ data: { organizationId: orgId, eventId, centroid, model: "auraface-v1", size: 1, personId } }); const face = (photoId: string, groupId: string, embedding: number[]) => ctx.db.face.create({ data: { organizationId: orgId, photoId, groupId, x0: 0.4, y0: 0.2, x1: 0.5, y1: 0.35, score: 0.9, sharpness: 120, embedding, model: "auraface-v1" } }); const g1 = await group(p1.eventId!, martimVec, martim.id); const f1 = await face(p1.id, g1.id, martimVec); await face(p2.id, g1.id, martimVec); const g2 = await group(gala.eventId!, lookAlike, null); await face(gala.id, g2.id, lookAlike); const g3 = await group(p2.eventId!, other, null); await face(p2.id, g3.id, other); cloud.authorised = false; cloud.viewers.set("abc", { password: "abc-pass", shared: [cloud.idOf("/FPA/Fotos/2025_2026/Competições Nacionais/PO01")] }); const signIn = async (who: string) => { cloud.loginAs = who; cloud.authorised = false; const { state } = (await ctx.app.inject({ method: "POST", url: `/v1/archive/${source.id}/login` })).json() as { state: string }; cloud.authorised = true; return ((await ctx.app.inject({ method: "POST", url: "/v1/archive/login/poll", payload: { state } })).json() as { token: string }).token; }; const get = (t: string, url: string) => ctx.app.inject({ method: "GET", url, headers: { authorization: `Archive ${t}` } }); const owner = await signIn("peter"); let res = await get(owner, `/v1/archive/${source.id}/people`); expect(res.json()).toMatchObject({ people: [{ name: "Martim Costa", club: "Sporting CP", photos: 2, face: { box: expect.any(Object) } }], clubs: expect.arrayContaining([expect.objectContaining({ name: "Sporting CP", people: 1, kind: "club" })]), }); // "Juntar nomes": ABC de Braga counted as Sporting CP (a test pairing), then apart again. const merge = (url: string, payload: unknown) => ctx.app.inject({ method: "POST", url: `/v1/archive/${source.id}/clubs/${url}`, headers: { authorization: `Archive ${owner}` }, payload }); expect((await merge("merge", { into: "Sporting CP", names: ["ABC de Braga", "Sporting CP"] })).json()).toMatchObject({ merged: 1 }); let clubs = (await get(owner, `/v1/archive/${source.id}/people`)).json().clubs as { name: string; also?: string[] }[]; expect(clubs.find((c) => c.name === "Sporting CP")?.also).toEqual(["ABC de Braga"]); expect(clubs.some((c) => c.name === "ABC de Braga")).toBe(false); expect((await get(owner, `/v1/archive/${source.id}/people?club=${encodeURIComponent("ABC de Braga")}`)).json().people).toHaveLength(1); expect((await merge("unmerge", { name: "abc de braga" })).json()).toMatchObject({ removed: 1 }); clubs = (await get(owner, `/v1/archive/${source.id}/people`)).json().clubs; expect(clubs.some((c) => c.name === "ABC de Braga")).toBe(true); // Martim: his two named photos, and the gala photo with a face like his. res = await get(owner, `/v1/archive/${source.id}/people/${martim.id}`); const body = res.json() as { counts: Record; photos: { id: string; level: string; gallery: { title: string } }[] }; expect(body.counts).toEqual({ confirmed: 2, probable: 0, similar: 1 }); expect(body.photos.find((p) => p.id === gala.id)).toMatchObject({ level: "similar" }); res = await get(owner, `/v1/archive/${source.id}/people/${martim.id}?level=confirmed`); expect(res.json().photos).toHaveLength(2); // From a face in a photo: the same. res = await get(owner, `/v1/archive/${source.id}/faces/${f1.id}/similar`); expect(res.json()).toMatchObject({ person: { name: "Martim Costa" } }); expect((res.json().photos as { id: string; level: string }[]).map((p) => [p.id, p.level]).sort()).toEqual( [[p1.id, "confirmed"], [p2.id, "confirmed"], [gala.id, "similar"]].sort(), ); // The gallery says where the faces are. const folder = await ctx.db.cloudFolder.findFirstOrThrow({ where: { path: { endsWith: "SCP x ABC" } } }); res = await get(owner, `/v1/archive/galleries/${folder.id}?limit=1`); expect(res.json().photos).toHaveLength(1); expect(res.json().total).toBe(2); expect(res.json().photos[0].faces).toBeUndefined(); expect(res.json().people).toEqual([expect.objectContaining({ name: "Martim Costa", count: 2 })]); expect(res.json().roster).toEqual([expect.objectContaining({ name: "Martim Costa", here: 2, inGame: 2 })]); res = await get(owner, `/v1/archive/photos/${p2.id}`); expect((res.json().faces as { person: { name: string } | null }[]).map((f) => f.person?.name ?? null).sort()).toEqual(["Martim Costa", null].sort()); // The club sees the game but not the gala: no look-alike from there, and not that photo. const club = await signIn("abc"); res = await get(club, `/v1/archive/photos/${gala.id}`); expect(res.statusCode).toBe(404); res = await get(club, `/v1/archive/${source.id}/people/${martim.id}`); expect(res.json().counts).toEqual({ confirmed: 2, probable: 0, similar: 0 }); res = await get(club, `/v1/archive/${source.id}/faces/${f1.id}/similar`); expect(res.json().photos).toHaveLength(2); }); it("lets those who edit on the cloud review faces, and only there", async () => { const source = await connect(); cloud.authorised = true; await ctx.app.inject({ method: "GET", url: `/v1/cloud-sources/${source.id}`, headers: bearer(token) }); await worker.scan(source.id); for (const id of await worker.claim(10)) await worker.index(id); const unit = (v: number[]) => { const n = Math.hypot(...v); return v.map((x) => x / n); }; const martimVec = unit([1, 0.1, 0, 0]); const photo = (name: string) => ctx.db.photo.findFirstOrThrow({ where: { originalName: name } }); const [p1, p2, gala] = await Promise.all([photo("PS_0001.jpg"), photo("PS_0002.jpg"), photo("G_0001.jpg")]); const martim = await ctx.db.person.create({ data: { organizationId: orgId, name: "Martim Costa", club: "Sporting CP", number: "21", centroid: martimVec, model: "auraface-v1" } }); const group = (eventId: string, suggested: string | null) => ctx.db.faceGroup.create({ data: { organizationId: orgId, eventId, centroid: unit([0, 1, 0, 0]), model: "auraface-v1", size: 1, suggestedPersonId: suggested, suggestionScore: suggested ? 0.8 : null } }); const face = (photoId: string, groupId: string) => ctx.db.face.create({ data: { organizationId: orgId, photoId, groupId, x0: 0.4, y0: 0.2, x1: 0.5, y1: 0.35, score: 0.9, sharpness: 120, embedding: unit([0, 1, 0, 0]), model: "auraface-v1" } }); const g1 = await group(p1.eventId!, martim.id); await face(p1.id, g1.id); const g2 = await group(p2.eventId!, martim.id); await face(p2.id, g2.id); const gGala = await group(gala.eventId!, martim.id); await face(gala.id, gGala.id); // A club editor (PO01 shared with edit rights) and a club reader (the same folder, read only). const po01 = cloud.idOf("/FPA/Fotos/2025_2026/Competições Nacionais/PO01"); cloud.viewers.set("abc", { password: "abc-pass", shared: [po01], edit: [po01] }); cloud.viewers.set("leitor", { password: "l-pass", shared: [po01] }); const signIn = async (who: string) => { cloud.loginAs = who; cloud.authorised = false; const { state } = (await ctx.app.inject({ method: "POST", url: `/v1/archive/${source.id}/login` })).json() as { state: string }; cloud.authorised = true; return ((await ctx.app.inject({ method: "POST", url: "/v1/archive/login/poll", payload: { state } })).json() as { token: string }).token; }; const as = (t: string) => ({ authorization: `Archive ${t}` }); const editor = await signIn("abc"); const reader = await signIn("leitor"); const owner = await signIn("peter"); let res = await ctx.app.inject({ method: "GET", url: `/v1/archive/${source.id}/me`, headers: as(editor) }); expect(res.json()).toMatchObject({ canReview: true, canManagePeople: false, pending: 2 }); res = await ctx.app.inject({ method: "GET", url: `/v1/archive/${source.id}/me`, headers: as(reader) }); expect(res.json()).toMatchObject({ canReview: false, canManagePeople: false }); res = await ctx.app.inject({ method: "GET", url: `/v1/archive/${source.id}/me`, headers: as(owner) }); expect(res.json()).toMatchObject({ canReview: true, canManagePeople: true, pending: 3 }); // The editor sees the game's suggestions, not the gala's; the reader none. res = await ctx.app.inject({ method: "GET", url: `/v1/archive/${source.id}/review`, headers: as(editor) }); const review = res.json() as { counts: Record; groups: { id: string; suggested: { name: string } | null; faces: unknown[] }[] }; expect(review.groups.map((g) => g.id).sort()).toEqual([g1.id, g2.id].sort()); expect(review.groups[0]!.suggested?.name).toBe("Martim Costa"); expect(review.groups[0]!.faces).toHaveLength(1); expect(review.counts.suggested).toBe(2); res = await ctx.app.inject({ method: "GET", url: `/v1/archive/${source.id}/review`, headers: as(reader) }); expect(res.statusCode).toBe(403); // The gallery tells the editor how many faces wait, per photo, and how sure each suggestion is; not the reader. const gallery = await ctx.db.cloudFile.findFirstOrThrow({ where: { photoId: p1.id }, select: { folder: { select: { id: true, galleryFolderId: true } } } }); const gid = gallery.folder.galleryFolderId ?? gallery.folder.id; res = await ctx.app.inject({ method: "GET", url: `/v1/archive/galleries/${gid}`, headers: as(editor) }); const waiting = res.json() as { pending?: number; photos: { id: string; pending?: number }[] }; expect(waiting.pending).toBeGreaterThanOrEqual(1); expect(waiting.photos.find((p) => p.id === p1.id)?.pending).toBe(1); res = await ctx.app.inject({ method: "GET", url: `/v1/archive/galleries/${gid}`, headers: as(reader) }); expect((res.json() as { pending?: number }).pending).toBeUndefined(); // Âmbito: one gallery's faces only (not the gala's), with its name. res = await ctx.app.inject({ method: "GET", url: `/v1/archive/${source.id}/review?gallery=${gid}`, headers: as(owner) }); const scoped = res.json() as { gallery: { id: string; title: string } | null; counts: Record }; expect(scoped.gallery?.id).toBe(gid); expect(scoped.counts.suggested).toBe(2); // "Juntar nomes" is for those who edit everything. res = await ctx.app.inject({ method: "POST", url: `/v1/archive/${source.id}/clubs/merge`, headers: as(editor), payload: { into: "Sporting CP", names: ["Sporting"] } }); expect(res.statusCode).toBe(403); res = await ctx.app.inject({ method: "GET", url: `/v1/archive/photos/${p1.id}`, headers: as(editor) }); expect((res.json() as { faces: { score: number | null }[] }).faces[0]!.score).toBeCloseTo(0.8, 2); const act = (t: string, groupId: string, payload: Record) => ctx.app.inject({ method: "POST", url: `/v1/archive/${source.id}/review/groups/${groupId}`, headers: as(t), payload }); // Confirm: the photo gets the name. res = await act(editor, g1.id, { action: "confirm" }); expect(res.json()).toMatchObject({ personId: martim.id, ignored: false }); expect((await ctx.db.photo.findUniqueOrThrow({ where: { id: p1.id } })).players).toContain("Martim Costa"); // "Não é": never suggested as him again. res = await act(editor, g2.id, { action: "reject" }); expect(res.json()).toMatchObject({ suggestedPersonId: null }); expect(await ctx.db.faceGroupRejection.count({ where: { groupId: g2.id, personId: martim.id } })).toBe(1); // False positive, and undo. res = await act(editor, g2.id, { action: "ignore" }); expect(res.json()).toMatchObject({ ignored: true }); res = await act(editor, g2.id, { action: "undo" }); expect(res.json()).toMatchObject({ ignored: false }); // Not in their folders, or read only: refused. expect((await act(editor, gGala.id, { action: "confirm" })).statusCode).toBe(403); expect((await act(reader, g1.id, { action: "undo" })).statusCode).toBe(403); // Downloads at web size for anyone who sees the photos; the cloud's links only for those who edit there. const game = await ctx.db.cloudFolder.findFirstOrThrow({ where: { path: { endsWith: "20250913 - SCP x ABC" } } }); const seen = async (t: string) => (await ctx.app.inject({ method: "GET", url: `/v1/archive/galleries/${game.id}`, headers: as(t) })).json() as { cloudUrl: string | null; photos: { cloudUrl?: string }[] }; expect((await seen(reader)).cloudUrl).toBeNull(); expect((await seen(reader)).photos[0]!.cloudUrl).toBeUndefined(); expect((await seen(editor)).cloudUrl).toMatch(/^https:\/\/cloud\.test\/f\//); const ask = (t: string, payload: Record) => ctx.app.inject({ method: "POST", url: `/v1/archive/${source.id}/downloads`, headers: as(t), payload }); res = await ask(reader, { photoIds: [p1.id] }); const one = res.json() as { url: string; photos: number }; expect(one.photos).toBe(1); res = await ctx.app.inject({ method: "GET", url: one.url }); expect(res.statusCode).toBe(200); expect(res.headers["content-type"]).toBe("image/jpeg"); expect(res.headers["content-disposition"]).toContain('filename="PS_0001.jpg"'); const meta = await sharp(res.rawPayload).metadata(); expect(Math.max(meta.width!, meta.height!)).toBeLessThanOrEqual(2048); expect((await ask(reader, { photoIds: [gala.id] })).statusCode).toBe(404); res = await ask(reader, { folderId: game.id }); expect(res.json()).toMatchObject({ photos: 2 }); res = await ctx.app.inject({ method: "GET", url: (res.json() as { url: string }).url }); expect(res.headers["content-type"]).toBe("application/zip"); expect(res.rawPayload.subarray(0, 2).toString()).toBe("PK"); expect((await ctx.app.inject({ method: "GET", url: one.url.slice(0, -3) + "abc" })).statusCode).toBe(404); // A person as a whole: only the account that edits everything. const off = (t: string, payload: Record) => ctx.app.inject({ method: "POST", url: `/v1/archive/${source.id}/people/${martim.id}/recognition`, headers: as(t), payload }); expect((await off(editor, { enabled: false })).statusCode).toBe(403); res = await off(owner, { enabled: false, removeConfirmed: true }); expect(res.json()).toMatchObject({ enabled: false, confirmed: 1 }); const after = await ctx.db.person.findUniqueOrThrow({ where: { id: martim.id } }); expect(after.recognitionOffAt).not.toBeNull(); expect(after.centroid).toEqual([]); expect((await ctx.db.faceGroup.findUniqueOrThrow({ where: { id: g1.id } })).personId).toBeNull(); expect((await ctx.db.faceGroup.findUniqueOrThrow({ where: { id: gGala.id } })).suggestedPersonId).toBeNull(); expect((await ctx.db.photo.findUniqueOrThrow({ where: { id: p1.id } })).players).not.toContain("Martim Costa"); res = await ctx.app.inject({ method: "GET", url: `/v1/archive/${source.id}/people/${martim.id}/history`, headers: as(owner) }); expect(res.json()).toMatchObject({ recognitionOff: { by: "PETER" }, canManage: true }); expect(res.json()).toMatchObject({ references: expect.any(Array), confirmedGroups: expect.any(Number), rejected: expect.any(Number) }); expect(res.json().rejected).toBeGreaterThan(0); expect((res.json().actions as { action: string }[]).map((a) => a.action)).toEqual(expect.arrayContaining(["confirm", "reject", "recognition_off_all"])); }); it("waits for disk space before indexing, and says how much the archive needs", async () => { const source = await connect(); cloud.authorised = true; await ctx.app.inject({ method: "GET", url: `/v1/cloud-sources/${source.id}`, headers: bearer(token) }); await worker.scan(source.id); const res = await ctx.app.inject({ method: "GET", url: `/v1/orgs/${orgId}/cloud-sources`, headers: bearer(token) }); expect(res.json().storage).toMatchObject({ free: expect.any(Number), total: expect.any(Number), needed: 3 * 1.6e6 }); const full = new ArchiveService({ db: ctx.db, secrets: new SecretBox(KEY), log: quiet, fetchImpl: fetchProxy, storageRoot: storageRoot, minFreeBytes: Number.MAX_SAFE_INTEGER }); expect(await full.claim(10)).toEqual([]); expect((await worker.claim(10)).length).toBe(3); }); it("reads the files from disk when the cloud is mounted here, and downloads the ones that are not", async () => { expect(localDirs(" https://cloud.test/FPA/Fotos/=/mnt/nc/peter/files/FPA/Fotos/ , nada, https://x.pt=/d")).toEqual([ { baseUrl: "https://cloud.test", prefix: "/FPA/Fotos", dir: "/mnt/nc/peter/files/FPA/Fotos" }, { baseUrl: "https://x.pt", prefix: "", dir: "/d" }, ]); const source = await connect(); cloud.authorised = true; await ctx.app.inject({ method: "GET", url: `/v1/cloud-sources/${source.id}`, headers: bearer(token) }); await worker.scan(source.id); const game = "/FPA/Fotos/2025_2026/Competições Nacionais/PO01/20250913 - SCP x ABC"; const mount = path.join(storageRoot, "mount"); await mkdir(path.join(mount, "2025_2026/Competições Nacionais/PO01/20250913 - SCP x ABC"), { recursive: true }); for (const name of ["PS_0001.jpg", "PS_0002.jpg"]) { const node = cloud.nodes.get(`${game}/${name}`)!; await writeFile(path.join(mount, "2025_2026/Competições Nacionais/PO01/20250913 - SCP x ABC", name), node.data!); // What the cloud would send now is broken: only the copy on disk can make the photo. node.data = Buffer.alloc(node.data!.length, 1); } const storage = new LocalStorage(storageRoot); const ingest = new IngestService({ db: ctx.db, storage, signer: new UrlSigner("s".repeat(40), 3600), broadcaster: new MemoryBroadcaster(), ingestRoot: path.join(storageRoot, "ingest"), log: quiet }); const mounted = new ArchiveService({ db: ctx.db, secrets: new SecretBox(KEY), log: quiet, ingest, fetchImpl: fetchProxy, localDirs: localDirs(`https://cloud.test/FPA/Fotos=${mount}`) }); for (const id of await mounted.claim(10)) await mounted.index(id); const files = await ctx.db.cloudFile.findMany({ include: { photo: true } }); // The gala photo is not on the mount: downloaded as usual. expect(files.map((f) => [f.path.split("/").pop(), f.status, f.photo?.width]).sort()).toEqual([ ["G_0001.jpg", "DONE", 3000], ["PS_0001.jpg", "DONE", 3000], ["PS_0002.jpg", "DONE", 3000], ]); await rm(mount, { recursive: true, force: true }); }); it("never adds to a live event: the same game gets an archive event of its own, and folders put there before leave", async () => { const source = await connect(); cloud.authorised = true; await ctx.app.inject({ method: "GET", url: `/v1/cloud-sources/${source.id}`, headers: bearer(token) }); // The game photographed live: an event of the library linked to the official game. const fixture = await ctx.db.sportsFixture.findFirstOrThrow({ where: { externalId: "g1" } }); const live = await ctx.db.event.create({ data: { organizationId: orgId, home: "Sporting CP", away: "ABC de Braga", startsAt: fixture.startsAt, ingestFrom: fixture.startsAt, ingestUntil: fixture.startsAt, iptcTemplate: {}, createdById: ownerId, fixtureId: fixture.id } }); await worker.scan(source.id); for (let ids = await worker.claim(10); ids.length; ids = await worker.claim(10)) for (const id of ids) await worker.index(id); const folder = await ctx.db.cloudFolder.findFirstOrThrow({ where: { path: { endsWith: "SCP x ABC" } }, include: { event: true } }); expect(folder.matchedBy).toBe("FIXTURE"); expect(folder.eventId).not.toBe(live.id); expect(folder.event!.archivedAt).not.toBeNull(); expect(await ctx.db.photo.count({ where: { eventId: live.id } })).toBe(0); // What an earlier version did: the folder and its photos in the live event. Taken back out. const photos = (await ctx.db.cloudFile.findMany({ where: { folderId: folder.id } })).map((f) => f.photoId!); await ctx.db.cloudFolder.update({ where: { id: folder.id }, data: { eventId: live.id } }); await ctx.db.photo.updateMany({ where: { id: { in: photos } }, data: { eventId: live.id } }); expect(await worker.leaveLiveEvents()).toBe(1); expect(await ctx.db.photo.count({ where: { eventId: live.id } })).toBe(0); expect((await ctx.db.cloudFolder.findUniqueOrThrow({ where: { id: folder.id } })).eventId).toBe(folder.eventId); }); it("takes a folder off the official game when its photos were taken on another day", async () => { const game = "/FPA/Fotos/2025_2026/Competições Nacionais/PO01/20250913 - SCP x ABC"; const taken = await sharp({ create: { width: 3000, height: 2000, channels: 3, background: "#456" } }).jpeg().withExif({ IFD2: { DateTimeOriginal: "2025:11:02 18:00:00" } }).toBuffer(); cloud.add(`${game}/PS_0003.jpg`, taken); const source = await connect(); cloud.authorised = true; await ctx.app.inject({ method: "GET", url: `/v1/cloud-sources/${source.id}`, headers: bearer(token) }); await worker.scan(source.id); for (let ids = await worker.claim(10); ids.length; ids = await worker.claim(10)) for (const id of ids) await worker.index(id); const folder = await ctx.db.cloudFolder.findFirstOrThrow({ where: { path: game }, include: { event: true } }); expect(folder).toMatchObject({ matchedBy: "NAME", fixtureRejected: true }); expect(folder.event!.fixtureId).toBeNull(); // Every photo of the folder went with it (none left in the official game's event). const files = await ctx.db.cloudFile.findMany({ where: { folderId: folder.id }, include: { photo: true } }); expect(files.every((f) => f.status === "DONE" && f.photo?.eventId === folder.eventId)).toBe(true); expect(await ctx.db.event.count({ where: { fixtureId: { not: null } } })).toBe(0); }); it("takes every gallery off a game still to come at once, whatever rule matched it", async () => { const game = "/FPA/Fotos/2025_2026/Competições Nacionais/PO01/20250913 - SCP x ABC"; cloud.add(`${game}/PS_0004.jpg`, await sharp({ create: { width: 600, height: 400, channels: 3, background: "#456" } }).jpeg().toBuffer()); const source = await connect(); cloud.authorised = true; await ctx.app.inject({ method: "GET", url: `/v1/cloud-sources/${source.id}`, headers: bearer(token) }); await worker.scan(source.id); for (let ids = await worker.claim(10); ids.length; ids = await worker.claim(10)) for (const id of ids) await worker.index(id); // As an older rule left it: on an official game of next year. const folder = await ctx.db.cloudFolder.findFirstOrThrow({ where: { path: game } }); const fixture = await ctx.db.sportsFixture.findFirstOrThrow({ where: { externalId: "g1" } }); await ctx.db.sportsFixture.update({ where: { id: fixture.id }, data: { startsAt: new Date("2027-02-28T15:00:00Z") } }); await ctx.db.event.update({ where: { id: folder.eventId! }, data: { startsAt: new Date("2027-02-28T15:00:00Z"), fixtureId: fixture.id } }); await ctx.db.cloudFolder.update({ where: { id: folder.id }, data: { matchedBy: "FIXTURE" } }); expect(await worker.takeOffFutureGames()).toBe(1); const after = await ctx.db.cloudFolder.findUniqueOrThrow({ where: { id: folder.id }, include: { event: true } }); expect(after.matchedBy).not.toBe("FIXTURE"); expect(after.event!.startsAt.getTime()).toBeLessThan(Date.now() + 6 * 3600_000); }); it("an editor checks the official games again on demand and sees what changed: a legends' game leaves the championship's", async () => { const game = "/FPA/Fotos/Liga Portugal Legends 2025-26/Dia 2/8. SL Benfica x SCU Torreense"; cloud.add(`${game}/LEG_0001.jpg`, await sharp({ create: { width: 600, height: 400, channels: 3, background: "#456" } }).jpeg().toBuffer()); const source = await connect(); cloud.authorised = true; await ctx.app.inject({ method: "GET", url: `/v1/cloud-sources/${source.id}`, headers: bearer(token) }); await worker.scan(source.id); for (let ids = await worker.claim(10); ids.length; ids = await worker.claim(10)) for (const id of ids) await worker.index(id); // As an older rule left it: on another game of the championship (its day already past). const folder = await ctx.db.cloudFolder.findFirstOrThrow({ where: { path: game } }); const fixture = await ctx.db.sportsFixture.findFirstOrThrow({ where: { externalId: "g1" } }); await ctx.db.event.update({ where: { id: folder.eventId! }, data: { startsAt: fixture.startsAt, fixtureId: fixture.id } }); await ctx.db.cloudFolder.update({ where: { id: folder.id }, data: { matchedBy: "FIXTURE" } }); const res = await ctx.app.inject({ method: "POST", url: `/v1/cloud-sources/${source.id}/rematch`, headers: bearer(token) }); expect(res.statusCode).toBe(200); expect(res.json()).toMatchObject({ errors: [] }); expect(res.json().changes).toContainEqual({ path: "/Liga Portugal Legends 2025-26/Dia 2/8. SL Benfica x SCU Torreense", from: "FIXTURE", to: "NAME" }); const after = await ctx.db.cloudFolder.findUniqueOrThrow({ where: { id: folder.id }, include: { event: true } }); expect(after.event).toMatchObject({ fixtureId: null, competition: "Liga Portugal Legends 2025-26" }); }); it("dates a gallery by its photos when its name has no day, and takes it off a game of another day", async () => { const game = "/FPA/Fotos/2025_2026/Competições Nacionais/PO01/SCP x ABC"; for (const [i, at] of ["2025:07:10 18:00:00", "2025:07:10 18:30:00", "2025:07:10 19:10:00", "2025:07:11 01:00:00"].entries()) { cloud.add(`${game}/X_${i}.jpg`, await sharp({ create: { width: 900, height: 600, channels: 3, background: { r: 10 * i, g: 80, b: 120 } } }).jpeg().withExif({ IFD2: { DateTimeOriginal: at } }).toBuffer()); } const source = await connect(); cloud.authorised = true; await ctx.app.inject({ method: "GET", url: `/v1/cloud-sources/${source.id}`, headers: bearer(token) }); await worker.scan(source.id); for (let ids = await worker.claim(20); ids.length; ids = await worker.claim(20)) for (const id of ids) await worker.index(id); const folder = await ctx.db.cloudFolder.findFirstOrThrow({ where: { path: game } }); expect(await worker.captureDay(folder.id)).toBe("2025-07-10"); // What an earlier version did: the folder put in the official SCP x ABC of September (another day). const fixture = await ctx.db.sportsFixture.findFirstOrThrow({ where: { externalId: "g1" } }); await worker.setFolderEvent(folder.id, { fixtureId: fixture.id }, "FIXTURE"); expect(await worker.rematch(source.id)).toBeGreaterThan(0); const fixed = await ctx.db.cloudFolder.findUniqueOrThrow({ where: { id: folder.id }, include: { event: true } }); expect(fixed).toMatchObject({ matchedBy: "NAME", fixtureRejected: true }); expect(fixed.event!.fixtureId).toBeNull(); expect(lisbonDay(fixed.event!.startsAt)).toBe("2025-07-10"); // Its photos went with it. const photos = await ctx.db.cloudFile.findMany({ where: { folderId: folder.id }, include: { photo: true } }); expect(photos.every((f) => f.photo?.eventId === fixed.eventId)).toBe(true); }); it("gives the archive's site its owner's look, which can be changed", async () => { const source = await connect(); cloud.authorised = true; let res = await ctx.app.inject({ method: "GET", url: `/v1/cloud-sources/${source.id}`, headers: bearer(token) }); expect(res.json()).toMatchObject({ look: "fpa" }); expect((await ctx.app.inject({ method: "GET", url: `/v1/archive/${source.id}` })).json()).toMatchObject({ look: "fpa", name: "Cloud FPA" }); res = await ctx.app.inject({ method: "PATCH", url: `/v1/cloud-sources/${source.id}`, headers: bearer(token), payload: { look: "liga" } }); expect(res.json()).toMatchObject({ look: "liga" }); res = await ctx.app.inject({ method: "PATCH", url: `/v1/cloud-sources/${source.id}`, headers: bearer(token), payload: { look: null } }); expect(res.json()).toMatchObject({ look: null }); expect((await ctx.app.inject({ method: "PATCH", url: `/v1/cloud-sources/${source.id}`, headers: bearer(token), payload: { look: "benfica" } })).statusCode).toBe(400); }); it("serves an archive at an address of its own, one archive per address", async () => { const source = await connect(); cloud.authorised = true; await ctx.app.inject({ method: "GET", url: `/v1/cloud-sources/${source.id}`, headers: bearer(token) }); const patch = (hostname: unknown) => ctx.app.inject({ method: "PATCH", url: `/v1/cloud-sources/${source.id}`, headers: bearer(token), payload: { hostname } }); let res = await patch("https://Arquivo.LigaPortugal.pt/"); expect(res.json()).toMatchObject({ hostname: "arquivo.ligaportugal.pt" }); expect((await ctx.app.inject({ method: "GET", url: "/v1/archive/host?host=arquivo.ligaportugal.pt" })).json()).toEqual({ id: source.id }); // The proxy asks before a certificate: only an archive's address gets one. expect((await ctx.app.inject({ method: "GET", url: "/v1/archive/host?domain=arquivo.ligaportugal.pt" })).statusCode).toBe(200); expect((await ctx.app.inject({ method: "GET", url: "/v1/archive/host?domain=other.example.pt" })).statusCode).toBe(404); expect((await ctx.app.inject({ method: "GET", url: `/v1/archive/${source.id}` })).json()).toMatchObject({ hostname: "arquivo.ligaportugal.pt" }); expect((await patch("not a host")).statusCode).toBe(400); // A public site's domain is taken. await ctx.db.site.create({ data: { organizationId: orgId, domain: "fotos.example.pt", name: "Fotos" } }); expect((await patch("fotos.example.pt")).statusCode).toBe(409); res = await patch(""); expect(res.json()).toMatchObject({ hostname: null }); expect((await ctx.app.inject({ method: "GET", url: "/v1/archive/host?host=arquivo.ligaportugal.pt" })).statusCode).toBe(404); }); it("shares the worker between clouds: a big newer archive does not starve another", async () => { const source = await connect(); cloud.authorised = true; await ctx.app.inject({ method: "GET", url: `/v1/cloud-sources/${source.id}`, headers: bearer(token) }); await worker.scan(source.id); const folder = await ctx.db.cloudFolder.findFirstOrThrow({ where: { sourceId: source.id, eventId: { not: null } } }); // Another cloud with a much bigger backlog, all in a later game. const other = await ctx.db.cloudSource.create({ data: { organizationId: orgId, name: "Liga", baseUrl: "https://liga.test", rootPath: "/", status: "READY" } }); const ev = await ctx.db.event.findUniqueOrThrow({ where: { id: folder.eventId! } }); const later = await ctx.db.event.create({ data: { organizationId: orgId, home: "SLB", away: "FCP", startsAt: new Date(ev.startsAt.getTime() + 365 * 864e5), ingestFrom: new Date(), ingestUntil: new Date(), iptcTemplate: {} } }); const f2 = await ctx.db.cloudFolder.create({ data: { sourceId: other.id, fileId: "f2", path: "/Liga/SLB x FCP", photoCount: 40, eventId: later.id, matchedBy: "FIXTURE" } }); await ctx.db.cloudFile.createMany({ data: Array.from({ length: 40 }, (_, i) => ({ sourceId: other.id, folderId: f2.id, fileId: `x${i}`, path: `/Liga/SLB x FCP/${i}.jpg` })) }); const ids = await worker.claim(10); expect(ids).toHaveLength(10); const bySource = await ctx.db.cloudFile.groupBy({ by: ["sourceId"], where: { id: { in: ids } }, _count: true }); expect(Object.fromEntries(bySource.map((r) => [r.sourceId, r._count]))).toEqual({ [source.id]: 3, [other.id]: 7 }); }); it("reads teams from the stored directory and hides games the viewer cannot see", async () => { const source = await connect(); cloud.authorised = true; await ctx.app.inject({ method: "GET", url: `/v1/cloud-sources/${source.id}`, headers: bearer(token) }); await worker.scan(source.id); cloud.authorised = false; cloud.viewers.set("peter", { password: "peter-pass", shared: [cloud.idOf("/FPA/Fotos")] }); cloud.viewers.set("ninguem", { password: "n-pass", shared: [] }); const signIn = async (who: string) => { cloud.loginAs = who; cloud.authorised = false; const { state } = (await ctx.app.inject({ method: "POST", url: `/v1/archive/${source.id}/login` })).json() as { state: string }; cloud.authorised = true; return ((await ctx.app.inject({ method: "POST", url: "/v1/archive/login/poll", payload: { state } })).json() as { token: string }).token; }; const get = (t: string, url: string) => ctx.app.inject({ method: "GET", url, headers: { authorization: `Archive ${t}` } }); const owner = await signIn("peter"); expect((await get(owner, `/v1/archive/${source.id}/directory`)).json()).toEqual({ teams: [], ready: false }); expect(await worker.rebuildDirectory(source.id)).toBeGreaterThan(0); expect((await get(owner, `/v1/archive/${source.id}/directory`)).json()).toEqual({ ready: true, teams: [ { name: "ABC de Braga", galleries: 1 }, { name: "Sporting CP", galleries: 1 }, ], }); const none = await signIn("ninguem"); expect((await get(none, `/v1/archive/${source.id}/directory`)).json()).toEqual({ ready: true, teams: [] }); await ctx.db.archiveClubAlias.create({ data: { sourceId: source.id, aliasKey: "abc de braga", alias: "ABC de Braga", name: "Sporting CP" } }); await worker.markDirectoryDirty(source.id); expect(await worker.rebuildDue()).toBe(true); expect((await get(owner, `/v1/archive/${source.id}/directory`)).json()).toEqual({ ready: true, teams: [{ name: "Sporting CP", galleries: 1 }] }); expect(await worker.rebuildDue()).toBe(false); const games = await get(owner, `/v1/archive/${source.id}/galleries?team=${encodeURIComponent("Sporting CP")}`); expect(games.statusCode).toBe(200); const titles = (games.json() as { galleries: { title: string }[] }).galleries.map((g) => g.title); expect(titles.some((title) => title.includes("Sporting CP"))).toBe(true); expect(titles.some((title) => title.includes("Gala"))).toBe(false); }); it.skipIf(!hasFfmpeg)("keeps videos in their galleries: a web copy made once, shown and played only where the cloud shares them", async () => { const game = "/FPA/Fotos/2025_2026/Competições Nacionais/PO01/20250913 - SCP x ABC"; const clips = "/FPA/Fotos/2025_2026/Eventos/Apresentacao 20250901"; cloud.add(`${game}/Golo 1.mp4`, mp4(1280, 720)); cloud.add(`${clips}/Plantel.mov`, mp4(720, 1280)); const source = await connect(); cloud.authorised = true; await ctx.app.inject({ method: "GET", url: `/v1/cloud-sources/${source.id}`, headers: bearer(token) }); const storage = new LocalStorage(storageRoot); const videoWorker = new ArchiveService({ db: ctx.db, secrets: new SecretBox(KEY), log: quiet, fetchImpl: fetchProxy, storage, videoTools: { ffmpeg: "ffmpeg", ffprobe: "ffprobe" } }); await videoWorker.scan(source.id); // A folder of videos only is a gallery too, with its event. const gameFolder = await ctx.db.cloudFolder.findFirstOrThrow({ where: { path: game } }); const clipsFolder = await ctx.db.cloudFolder.findFirstOrThrow({ where: { path: clips } }); expect(gameFolder).toMatchObject({ photoCount: 2, videoCount: 1, matchedBy: "FIXTURE" }); expect(clipsFolder).toMatchObject({ photoCount: 0, videoCount: 1, matchedBy: "FOLDER" }); expect(clipsFolder.eventId).not.toBeNull(); for (const id of await worker.claim(10)) await worker.index(id); const ids = await videoWorker.claimVideos(5); expect(ids).toHaveLength(2); for (const id of ids) await videoWorker.indexVideo(id); const videos = await ctx.db.cloudVideo.findMany({ orderBy: { path: "asc" } }); expect(videos.map((v) => [v.path.split("/").pop(), v.status, v.width, v.height])).toEqual([ ["Golo 1.mp4", "DONE", 1280, 720], ["Plantel.mov", "DONE", 720, 1280], ]); const golo = videos[0]!; expect(golo.durationMs).toBeGreaterThan(1500); expect(await storage.exists(`${golo.storageKey}/web.mp4`)).toBe(true); // Nothing left to make. expect(await videoWorker.claimVideos(5)).toEqual([]); let res = await ctx.app.inject({ method: "GET", url: `/v1/orgs/${orgId}/cloud-sources`, headers: bearer(token) }); expect(res.json().sources[0].counts).toMatchObject({ videos: 2, videosPending: 0, galleries: 3 }); // A club sees the game's video, not the other gallery's. cloud.authorised = false; cloud.viewers.set("abc", { password: "abc-pass", shared: [cloud.idOf("/FPA/Fotos/2025_2026/Competições Nacionais/PO01")] }); const signIn = async (who: string) => { cloud.loginAs = who; cloud.authorised = false; const { state } = (await ctx.app.inject({ method: "POST", url: `/v1/archive/${source.id}/login` })).json() as { state: string }; cloud.authorised = true; return ((await ctx.app.inject({ method: "POST", url: "/v1/archive/login/poll", payload: { state } })).json() as { token: string }).token; }; const as = (t: string) => ({ authorization: `Archive ${t}` }); const club = await signIn("abc"); res = await ctx.app.inject({ method: "GET", url: `/v1/archive/${source.id}/galleries`, headers: as(club) }); expect(res.json().galleries).toEqual([expect.objectContaining({ id: gameFolder.id, photoCount: 2, videoCount: 1 })]); res = await ctx.app.inject({ method: "GET", url: `/v1/archive/galleries/${gameFolder.id}`, headers: as(club) }); const page = res.json() as { photos: unknown[]; videoTotal: number; videos: { id: string; name: string; src: string; poster: string; thumb: string; download: string; cloudUrl?: string; width: number }[] }; expect(page.photos).toHaveLength(2); expect(page.videoTotal).toBe(1); expect(page.videos).toEqual([expect.objectContaining({ name: "Golo 1.mp4", width: 1280 })]); const v = page.videos[0]!; // Viewers who only see the folder are not sent to the cloud. expect(v.cloudUrl).toBeUndefined(); res = await ctx.app.inject({ method: "GET", url: `/v1/archive/galleries/${clipsFolder.id}`, headers: as(club) }); expect(res.statusCode).toBe(404); // The web copy plays from any point: ranges answered, the whole file otherwise. res = await ctx.app.inject({ method: "GET", url: v.src, headers: { range: "bytes=0-99" } }); expect(res.statusCode).toBe(206); expect(res.headers["content-type"]).toBe("video/mp4"); expect(res.headers["content-range"]).toMatch(/^bytes 0-99\/\d+$/); expect(res.rawPayload.length).toBe(100); const whole = Number(String(res.headers["content-range"]).split("/")[1]); res = await ctx.app.inject({ method: "GET", url: v.src }); expect(res.statusCode).toBe(200); expect(res.rawPayload.length).toBe(whole); expect(res.headers["accept-ranges"]).toBe("bytes"); res = await ctx.app.inject({ method: "GET", url: v.src, headers: { range: `bytes=${whole}-` } }); expect(res.statusCode).toBe(416); res = await ctx.app.inject({ method: "GET", url: v.download }); expect(res.headers["content-disposition"]).toContain('filename="Golo 1.mp4"'); res = await ctx.app.inject({ method: "GET", url: v.poster }); expect(res.headers["content-type"]).toBe("image/jpeg"); // A link altered, or one file's signature on another, opens nothing. expect((await ctx.app.inject({ method: "GET", url: v.src.replace(/sig=[^&]+/, "sig=AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA") })).statusCode).toBe(404); expect((await ctx.app.inject({ method: "GET", url: v.src.replace("/web?", "/download?") })).statusCode).toBe(404); // The indexing account sees both, the videos-only gallery with its video's frame as cover, and the original's link. const owner = await signIn("peter"); res = await ctx.app.inject({ method: "GET", url: `/v1/archive/${source.id}/galleries`, headers: as(owner) }); const clipsCard = (res.json().galleries as { id: string; cover: string | null; photoCount: number; videoCount: number }[]).find((g) => g.id === clipsFolder.id)!; expect(clipsCard).toMatchObject({ photoCount: 0, videoCount: 1 }); expect(clipsCard.cover).toMatch(/^\/v1\/files\/videos\/[^/]+\/thumb\?/); res = await ctx.app.inject({ method: "GET", url: `/v1/archive/galleries/${gameFolder.id}`, headers: as(owner) }); expect(res.json().videos[0].cloudUrl).toBe(`https://cloud.test/f/${cloud.idOf(`${game}/Golo 1.mp4`)}`); // Gone from the cloud: gone here, its files too. const key = golo.storageKey!; cloud.remove(`${game}/Golo 1.mp4`); await videoWorker.scan(source.id); expect(await ctx.db.cloudVideo.count({ where: { folderId: gameFolder.id } })).toBe(0); expect(await storage.exists(`${key}/web.mp4`)).toBe(false); expect((await ctx.db.cloudFolder.findUniqueOrThrow({ where: { id: gameFolder.id } })).videoCount).toBe(0); // Without ffmpeg a video waits with the reason, and "Analisar agora" tries it again. cloud.add(`${clips}/Treino.mp4`, mp4(640, 360)); const noTools = new ArchiveService({ db: ctx.db, secrets: new SecretBox(KEY), log: quiet, fetchImpl: fetchProxy, storage, videoTools: { ffmpeg: "no-ffmpeg-here", ffprobe: "no-ffprobe-here" } }); await noTools.scan(source.id); for (const id of await noTools.claimVideos(5)) await noTools.indexVideo(id); expect(await ctx.db.cloudVideo.findFirstOrThrow({ where: { path: { endsWith: "Treino.mp4" } } })).toMatchObject({ status: "FAILED", error: "ffprobe_missing" }); await ctx.app.inject({ method: "POST", url: `/v1/cloud-sources/${source.id}/scan`, headers: bearer(token) }); expect((await ctx.db.cloudVideo.findFirstOrThrow({ where: { path: { endsWith: "Treino.mp4" } } })).status).toBe("PENDING"); }, 60_000); it.skipIf(!hasFfmpeg)("finds faces in videos the photos' way: same groups, same suggestions, reviewed and named, and shown with when", async () => { const game = "/FPA/Fotos/2025_2026/Competições Nacionais/PO01/20250913 - SCP x ABC"; cloud.add(`${game}/Golo 1.mp4`, mp4(640, 360)); await ctx.db.organization.update({ where: { id: orgId }, data: { biometricsEnabled: true, biometricsLegalBasis: "teste" } }); const source = await connect(); cloud.authorised = true; await ctx.app.inject({ method: "GET", url: `/v1/cloud-sources/${source.id}`, headers: bearer(token) }); const storage = new LocalStorage(storageRoot); const videoWorker = new ArchiveService({ db: ctx.db, secrets: new SecretBox(KEY), log: quiet, fetchImpl: fetchProxy, storage, videoTools: { ffmpeg: "ffmpeg", ffprobe: "ffprobe" } }); await videoWorker.scan(source.id); for (const id of await worker.claim(10)) await worker.index(id); for (const id of await videoWorker.claimVideos(5)) await videoWorker.indexVideo(id); const video = await ctx.db.cloudVideo.findFirstOrThrow(); expect(video).toMatchObject({ status: "DONE", facesStatus: "PENDING" }); const facesCount = async () => (await ctx.app.inject({ method: "GET", url: `/v1/orgs/${orgId}/cloud-sources`, headers: bearer(token) })).json().sources[0].counts; expect(await facesCount()).toMatchObject({ videoFacesPending: 1, videoFacesDone: 0 }); // Rita in the photos and the first second of the video; someone else from 0.8 s on, in the video only. const rita = unitVec(1); const other = unitVec(2); const at = (x: number, emb: number[]) => ({ x0: x, y0: 0.2, x1: x + 0.12, y1: 0.4, score: 0.95, sharpness: 120, landmarks: [] as [number, number][], embedding: emb }); const engine: FaceEngine = { model: "auraface-v1", async analyse(file: string): Promise { const frame = /frame_(\d+)\.jpg$/.exec(file); if (!frame) return { width: 2048, height: 1365, faces: [at(0.4, rita)] }; const i = Number(frame[1]); return { width: 640, height: 360, faces: [...(i <= 6 ? [at(0.1, rita)] : []), ...(i >= 5 ? [at(0.6, other)] : [])] }; }, async close() {}, }; const faces = new FaceService({ db: ctx.db, storage, broadcaster: new MemoryBroadcaster(), log: quiet, engine, videoTools: { ffmpeg: "ffmpeg", ffprobe: "ffprobe" }, videoFps: 5 }); await ctx.db.person.create({ data: { organizationId: orgId, name: "Rita Sousa", centroid: rita, model: "auraface-v1", faceCount: 5 } }); await ctx.db.photo.updateMany({ data: { facesStatus: "PENDING" } }); for (let ids = await faces.claim(10); ids.length; ids = await faces.claim(10)) for (const id of ids) await faces.process(id); expect(await faces.claimVideos(1)).toEqual([video.id]); await faces.processVideo(video.id); // Two appearances, each with when it is on screen and its frame; Rita's joins the group of her photos' faces. const appearances = await ctx.db.videoFace.findMany({ where: { videoId: video.id }, orderBy: { startMs: "asc" } }); expect(appearances.map((a) => [a.startMs, a.endMs, a.frames])).toEqual([ [0, 1000, 6], [800, 1800, 6], ]); expect(await storage.exists(appearances[0]!.frameKey)).toBe(true); const photoFace = await ctx.db.face.findFirstOrThrow({ where: { photo: { originalName: "PS_0001.jpg" } } }); expect(appearances[0]!.groupId).toBe(photoFace.groupId); expect(appearances[1]!.groupId).not.toBe(photoFace.groupId); const ritaGroup = await ctx.db.faceGroup.findUniqueOrThrow({ where: { id: photoFace.groupId! }, include: { suggested: true } }); expect(ritaGroup.suggested?.name).toBe("Rita Sousa"); expect((await ctx.db.cloudVideo.findUniqueOrThrow({ where: { id: video.id } })).facesStatus).toBe("DONE"); expect(await facesCount()).toMatchObject({ videoFacesPending: 0, videoFacesDone: 1, videoFacesFailed: 0 }); // An editor of the game's folder reviews it: the card carries the video's frame, and confirming names both. const po01 = cloud.idOf("/FPA/Fotos/2025_2026/Competições Nacionais/PO01"); cloud.viewers.set("abc", { password: "abc-pass", shared: [po01], edit: [po01] }); cloud.authorised = false; cloud.loginAs = "abc"; const { state } = (await ctx.app.inject({ method: "POST", url: `/v1/archive/${source.id}/login` })).json() as { state: string }; cloud.authorised = true; const club = ((await ctx.app.inject({ method: "POST", url: "/v1/archive/login/poll", payload: { state } })).json() as { token: string }).token; const as = { authorization: `Archive ${club}` }; let res = await ctx.app.inject({ method: "GET", url: `/v1/archive/${source.id}/review?status=suggested`, headers: as }); const card = (res.json().groups as { id: string; photos: number; videos: number; faces: { src: string; video?: { id: string; atMs: number } }[] }[]).find((g) => g.id === ritaGroup.id)!; expect(card).toMatchObject({ photos: 2, videos: 1 }); const frame = card.faces.find((f) => f.video)!; expect(frame.video).toMatchObject({ id: video.id }); res = await ctx.app.inject({ method: "GET", url: frame.src }); expect([res.statusCode, res.headers["content-type"]]).toEqual([200, "image/jpeg"]); expect((await ctx.app.inject({ method: "GET", url: frame.src.replace(/sig=[^&]+/, "sig=AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA") })).statusCode).toBe(404); // Before: probable in the gallery's video. After confirming: named, with when. const gameFolder = await ctx.db.cloudFolder.findFirstOrThrow({ where: { path: game } }); const peopleOfVideo = async () => ((await ctx.app.inject({ method: "GET", url: `/v1/archive/galleries/${gameFolder.id}`, headers: as })).json().videos[0].people as { name: string; level: string; startMs: number; moments: unknown[] }[]); expect(await peopleOfVideo()).toEqual([expect.objectContaining({ name: "Rita Sousa", level: "probable", startMs: 0 })]); res = await ctx.app.inject({ method: "POST", url: `/v1/archive/${source.id}/review/groups/${ritaGroup.id}`, headers: as, payload: { action: "confirm" } }); expect(res.statusCode).toBe(200); expect(await peopleOfVideo()).toEqual([{ id: ritaGroup.suggestedPersonId, name: "Rita Sousa", level: "confirmed", startMs: 0, moments: [{ startMs: 0, endMs: 1000 }] }]); // Her page lists the video, with its frame and the moments to jump to. res = await ctx.app.inject({ method: "GET", url: `/v1/archive/${source.id}/people/${ritaGroup.suggestedPersonId}`, headers: as }); expect(res.json().videos).toEqual([expect.objectContaining({ id: video.id, name: "Golo 1.mp4", level: "confirmed", moments: [{ startMs: 0, endMs: 1000 }], gallery: expect.objectContaining({ id: gameFolder.id }) })]); // A viewer without edit rights cannot act on a group that has the video. cloud.viewers.set("ler", { password: "ler-pass", shared: [po01] }); cloud.authorised = false; cloud.loginAs = "ler"; const s2 = ((await ctx.app.inject({ method: "POST", url: `/v1/archive/${source.id}/login` })).json() as { state: string }).state; cloud.authorised = true; const reader = ((await ctx.app.inject({ method: "POST", url: "/v1/archive/login/poll", payload: { state: s2 } })).json() as { token: string }).token; const otherGroup = appearances[1]!.groupId!; res = await ctx.app.inject({ method: "POST", url: `/v1/archive/${source.id}/review/groups/${otherGroup}`, headers: { authorization: `Archive ${reader}` }, payload: { action: "ignore" } }); expect(res.statusCode).toBe(403); // The folder moved to another event: its video's faces are looked for again there, never left in the old groups. const fixture = await ctx.db.sportsFixture.findFirstOrThrow({ where: { externalId: "g2" } }); await videoWorker.setFolderEvent(gameFolder.id, { fixtureId: fixture.id }); expect(await ctx.db.videoFace.count({ where: { videoId: video.id } })).toBe(0); expect((await ctx.db.cloudVideo.findUniqueOrThrow({ where: { id: video.id } })).facesStatus).toBe("PENDING"); expect(await storage.exists(appearances[0]!.frameKey)).toBe(false); }, 90_000); it.skipIf(!hasFfmpeg)("reads a long video a minute at a time: one face on screen throughout is one appearance", async () => { const game = "/FPA/Fotos/2025_2026/Competições Nacionais/PO01/20250913 - SCP x ABC"; cloud.add(`${game}/Jogo.mp4`, execFileSync("ffmpeg", ["-hide_banner", "-loglevel", "error", "-f", "lavfi", "-i", "testsrc=size=160x90:rate=5:duration=65", "-c:v", "mpeg4", "-f", "mp4", "-movflags", "frag_keyframe+empty_moov", "pipe:1"], { maxBuffer: 64 * 1024 * 1024 })); await ctx.db.organization.update({ where: { id: orgId }, data: { biometricsEnabled: true, biometricsLegalBasis: "teste" } }); const source = await connect(); cloud.authorised = true; await ctx.app.inject({ method: "GET", url: `/v1/cloud-sources/${source.id}`, headers: bearer(token) }); const storage = new LocalStorage(storageRoot); const videoWorker = new ArchiveService({ db: ctx.db, secrets: new SecretBox(KEY), log: quiet, fetchImpl: fetchProxy, storage, videoTools: { ffmpeg: "ffmpeg", ffprobe: "ffprobe" } }); await videoWorker.scan(source.id); for (const id of await videoWorker.claimVideos(5)) await videoWorker.indexVideo(id); const video = await ctx.db.cloudVideo.findFirstOrThrow(); const someone = unitVec(7); let analysed = 0; const engine: FaceEngine = { model: "auraface-v1", async analyse(): Promise { analysed++; return { width: 160, height: 90, faces: [{ x0: 0.4, y0: 0.2, x1: 0.55, y1: 0.5, score: 0.9, sharpness: 100, landmarks: [], embedding: someone }] }; }, async close() {}, }; const faces = new FaceService({ db: ctx.db, storage, broadcaster: new MemoryBroadcaster(), log: quiet, engine, videoTools: { ffmpeg: "ffmpeg", ffprobe: "ffprobe" }, videoFps: 2 }); expect(await faces.claimVideos(1)).toEqual([video.id]); await faces.processVideo(video.id); expect(analysed).toBeGreaterThanOrEqual(128); const appearances = await ctx.db.videoFace.findMany({ where: { videoId: video.id } }); expect(appearances).toHaveLength(1); expect(appearances[0]!.startMs).toBe(0); expect(appearances[0]!.endMs).toBeGreaterThan(64_000); expect(appearances[0]!.frames).toBe(analysed); }, 120_000); it.skipIf(!hasFfmpeg)("never keeps a stale video result: asked again meanwhile, it is dropped; a stopping worker puts it back", async () => { const game = "/FPA/Fotos/2025_2026/Competições Nacionais/PO01/20250913 - SCP x ABC"; cloud.add(`${game}/Golo 1.mp4`, mp4(640, 360)); await ctx.db.organization.update({ where: { id: orgId }, data: { biometricsEnabled: true, biometricsLegalBasis: "teste" } }); const source = await connect(); cloud.authorised = true; await ctx.app.inject({ method: "GET", url: `/v1/cloud-sources/${source.id}`, headers: bearer(token) }); const storage = new LocalStorage(storageRoot); const videoWorker = new ArchiveService({ db: ctx.db, secrets: new SecretBox(KEY), log: quiet, fetchImpl: fetchProxy, storage, videoTools: { ffmpeg: "ffmpeg", ffprobe: "ffprobe" } }); await videoWorker.scan(source.id); for (const id of await videoWorker.claimVideos(5)) await videoWorker.indexVideo(id); const video = await ctx.db.cloudVideo.findFirstOrThrow(); const someone = unitVec(9); let onFirst: (() => Promise) | null = null; const engine: FaceEngine = { model: "auraface-v1", async analyse(): Promise { const hook = onFirst; onFirst = null; if (hook) await hook(); return { width: 640, height: 360, faces: [{ x0: 0.4, y0: 0.2, x1: 0.55, y1: 0.5, score: 0.9, sharpness: 100, landmarks: [], embedding: someone }] }; }, async close() {}, }; const faces = new FaceService({ db: ctx.db, storage, broadcaster: new MemoryBroadcaster(), log: quiet, engine, videoTools: { ffmpeg: "ffmpeg", ffprobe: "ffprobe" }, videoFps: 5 }); // Asked again while being read (its folder moved, its copy made again): this run writes nothing. expect(await faces.claimVideos(1)).toEqual([video.id]); onFirst = async () => void (await ctx.db.cloudVideo.update({ where: { id: video.id }, data: { facesStatus: "PENDING" } })); await faces.processVideo(video.id); expect(await ctx.db.videoFace.count()).toBe(0); expect((await ctx.db.cloudVideo.findUniqueOrThrow({ where: { id: video.id } })).facesStatus).toBe("PENDING"); // The next run is the one that counts. expect(await faces.claimVideos(1)).toEqual([video.id]); await faces.processVideo(video.id); expect(await ctx.db.videoFace.count()).toBe(1); expect((await ctx.db.cloudVideo.findUniqueOrThrow({ where: { id: video.id } })).facesStatus).toBe("DONE"); // A worker stopping mid-video (a deploy) puts it back in the queue, its earlier faces untouched. await ctx.db.cloudVideo.update({ where: { id: video.id }, data: { facesStatus: "PENDING" } }); expect(await faces.claimVideos(1)).toEqual([video.id]); onFirst = async () => faces.stopVideos(); await faces.processVideo(video.id); expect((await ctx.db.cloudVideo.findUniqueOrThrow({ where: { id: video.id } })).facesStatus).toBe("PENDING"); expect(await ctx.db.videoFace.count()).toBe(1); // Left RUNNING by a worker that is gone, and failed ones after a while: back in the queue. await ctx.db.$executeRaw`UPDATE cloud_videos SET faces_status = 'RUNNING', updated_at = now() - interval '2 hours'`; expect(await faces.requeueVideos()).toBe(1); expect((await ctx.db.cloudVideo.findUniqueOrThrow({ where: { id: video.id } })).facesStatus).toBe("PENDING"); }, 90_000); }); const hasFfmpeg = (() => { try { execFileSync("ffmpeg", ["-version"], { stdio: "ignore" }); return true; } catch { return false; } })(); /** A two-second test clip (picture and sound) of that size. */ function mp4(width: number, height: number): Buffer { return execFileSync("ffmpeg", [ "-hide_banner", "-loglevel", "error", "-f", "lavfi", "-i", `testsrc=size=${width}x${height}:rate=10:duration=2`, "-f", "lavfi", "-i", "sine=frequency=440:duration=2", "-c:v", "mpeg4", "-c:a", "aac", "-shortest", "-f", "mp4", "-movflags", "frag_keyframe+empty_moov", "pipe:1", ], { maxBuffer: 64 * 1024 * 1024 }); } /** A unit vector of the embedder's length, different for each seed. */ function unitVec(seed: number): number[] { const v = Array.from({ length: 512 }, (_, i) => Math.sin(seed * 977 + i * 13.37)); const n = Math.hypot(...v); return v.map((x) => x / n); }