The public archive was loading every indexed photo on each click. Pages now come from the database, and Nextcloud is only asked when someone signs in.
887 lines
59 KiB
TypeScript
887 lines
59 KiB
TypeScript
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 { canonicalTeam, describeFolder, exhibitionName, isExhibition, isInitials, isTeam, lisbonDay, parseFolder, pickFixture, teamLabel, type FixtureCandidate } from "../src/archive/match.js";
|
|
import { parseMultistatus } from "../src/archive/nextcloud.js";
|
|
import { ArchiveService, localDirs } from "../src/archive/service.js";
|
|
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 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("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);
|
|
});
|
|
|
|
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");
|
|
});
|
|
|
|
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<typeof team>, away: ReturnType<typeof team>, 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 = `<?xml version="1.0"?>
|
|
<d:multistatus xmlns:d="DAV:" xmlns:oc="http://owncloud.org/ns" xmlns:s="http://sabredav.org/ns">
|
|
<d:response><d:href>/nc/remote.php/dav/files/peter/FPA/Fotos/</d:href>
|
|
<d:propstat><d:prop><d:getetag>"abc"</d:getetag><d:resourcetype><d:collection/></d:resourcetype><oc:fileid>10</oc:fileid><oc:size>99</oc:size></d:prop><d:status>HTTP/1.1 200 OK</d:status></d:propstat>
|
|
<d:propstat><d:prop><d:getcontentlength/></d:prop><d:status>HTTP/1.1 404 Not Found</d:status></d:propstat>
|
|
</d:response>
|
|
<d:response><d:href>/nc/remote.php/dav/files/peter/FPA/Fotos/Competi%c3%a7%c3%b5es%20Nacionais/</d:href>
|
|
<d:propstat><d:prop><d:getetag>"def"</d:getetag><d:resourcetype><d:collection/></d:resourcetype><oc:fileid>11</oc:fileid></d:prop><d:status>HTTP/1.1 200 OK</d:status></d:propstat>
|
|
</d:response>
|
|
<d:response><d:href>/nc/remote.php/dav/files/peter/FPA/Fotos/A%20%26%20B.jpg</d:href>
|
|
<d:propstat><d:prop><d:getetag>"f1"</d:getetag><d:getcontentlength>1234</d:getcontentlength><d:getcontenttype>image/jpeg</d:getcontenttype><d:resourcetype/><oc:fileid>12</oc:fileid></d:prop><d:status>HTTP/1.1 200 OK</d:status></d:propstat>
|
|
</d:response>
|
|
</d:multistatus>`;
|
|
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" }),
|
|
]);
|
|
});
|
|
});
|
|
|
|
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<string, Node>([["/", { 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<string, { password: string; shared: string[] }>();
|
|
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 `<d:response><d:href>${href}</d:href><d:propstat><d:prop><d:getetag>"${this.etag(p)}"</d:getetag>${
|
|
n.data ? `<d:getcontentlength>${n.data.length}</d:getcontentlength><d:resourcetype/>` : "<d:resourcetype><d:collection/></d:resourcetype>"
|
|
}<oc:fileid>${n.id}</oc:fileid></d:prop><d:status>HTTP/1.1 200 OK</d:status></d:propstat></d:response>`;
|
|
}
|
|
|
|
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") {
|
|
return Response.json({ ocs: { data: (this.viewers.get(who)?.shared ?? []).map((id) => ({ item_source: Number(id), share_type: 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(`<?xml version="1.0"?><d:multistatus xmlns:d="DAV:" xmlns:oc="http://owncloud.org/ns">${[p, ...kids].map((k) => this.entry(k)).join("")}</d:multistatus>`, { 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, "[email protected]", { org: "bitreport", role: "OWNER" });
|
|
orgId = org!.id;
|
|
ownerId = user.id;
|
|
token = (await login(ctx.app, "[email protected]")).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("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("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) => {
|
|
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 } });
|
|
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 });
|
|
expect(cloud.revoked).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);
|
|
|
|
const nobody = await signIn("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);
|
|
|
|
// 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);
|
|
});
|
|
|
|
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: [{ name: "Sporting CP", people: 1 }] });
|
|
|
|
// 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<string, number>; 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 })]);
|
|
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("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("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 });
|
|
});
|
|
});
|