From de3970560056327ac287b81e12e2a058b77dd85c Mon Sep 17 00:00:00 2001 From: spark Date: Tue, 20 Oct 2026 14:21:02 +0000 Subject: [PATCH 1/2] Show and play archive videos: a web copy made once by ffmpeg, signed and seekable, in the galleries the cloud shares. Videos in gallery folders are walked like photos into cloud_videos (a folder of videos only is a gallery too). The worker makes an H.264/AAC MP4 (short side at most 1080 px, faststart), a poster and a thumbnail; the original stays on the cloud. Viewers get them by signed links with Range support, above the photos, in a player like the large photo; download is the web copy, the original's link only for those who edit on the cloud. Also gives the face review's overlay its own class: it reused .arq-lightbox and broke the large photo's layout. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01SC7s5gwdivkoBXbRGxbnAo --- .../migration.sql | 29 +++ apps/api/prisma/schema.prisma | 39 ++++ apps/api/src/app.ts | 2 +- apps/api/src/archive/routes.ts | 20 +- apps/api/src/archive/service.ts | 137 ++++++++++++- apps/api/src/archive/video.test.ts | 134 +++++++++++++ apps/api/src/archive/video.ts | 188 ++++++++++++++++++ apps/api/src/archive/viewer.ts | 67 ++++++- apps/api/src/config.ts | 5 + apps/api/src/storage/storage.ts | 31 ++- apps/api/src/worker.ts | 4 +- apps/api/test/archive.test.ts | 130 ++++++++++++ apps/site/src/app/arquivo/[id]/Browse.tsx | 6 +- apps/site/src/app/arquivo/[id]/Gallery.tsx | 47 ++++- apps/site/src/app/arquivo/[id]/Review.tsx | 2 +- .../site/src/app/arquivo/[id]/VideoPlayer.tsx | 95 +++++++++ apps/site/src/app/arquivo/[id]/api.ts | 37 ++++ apps/site/src/app/arquivo/[id]/archive.css | 3 +- apps/site/src/app/arquivo/[id]/parts.tsx | 1 + apps/site/src/app/arquivo/[id]/video.css | 104 ++++++++++ docs/DEPLOY.md | 3 +- docs/archive.md | 18 ++ 22 files changed, 1059 insertions(+), 43 deletions(-) create mode 100644 apps/api/prisma/migrations/20261020120000_archive_videos/migration.sql create mode 100644 apps/api/src/archive/video.test.ts create mode 100644 apps/api/src/archive/video.ts create mode 100644 apps/site/src/app/arquivo/[id]/VideoPlayer.tsx create mode 100644 apps/site/src/app/arquivo/[id]/video.css diff --git a/apps/api/prisma/migrations/20261020120000_archive_videos/migration.sql b/apps/api/prisma/migrations/20261020120000_archive_videos/migration.sql new file mode 100644 index 0000000..767d6d8 --- /dev/null +++ b/apps/api/prisma/migrations/20261020120000_archive_videos/migration.sql @@ -0,0 +1,29 @@ +-- Videos in the archive: a web copy and a poster are kept, the original stays on the cloud. +ALTER TABLE "cloud_folders" ADD COLUMN "video_count" INTEGER NOT NULL DEFAULT 0; + +CREATE TABLE "cloud_videos" ( + "id" UUID NOT NULL, + "source_id" UUID NOT NULL, + "folder_id" UUID NOT NULL, + "file_id" TEXT NOT NULL, + "path" TEXT NOT NULL, + "etag" TEXT, + "size" BIGINT, + "status" TEXT NOT NULL DEFAULT 'PENDING', + "attempts" INTEGER NOT NULL DEFAULT 0, + "error" TEXT, + "duration_ms" INTEGER, + "width" INTEGER, + "height" INTEGER, + "captured_at" TIMESTAMP(3), + "storage_key" TEXT, + "web_bytes" BIGINT, + "created_at" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP, + "updated_at" TIMESTAMP(3) NOT NULL, + CONSTRAINT "cloud_videos_pkey" PRIMARY KEY ("id") +); +CREATE UNIQUE INDEX "cloud_videos_source_id_file_id_key" ON "cloud_videos"("source_id", "file_id"); +CREATE INDEX "cloud_videos_status_source_id_idx" ON "cloud_videos"("status", "source_id"); +CREATE INDEX "cloud_videos_folder_id_status_path_idx" ON "cloud_videos"("folder_id", "status", "path"); +ALTER TABLE "cloud_videos" ADD CONSTRAINT "cloud_videos_source_id_fkey" FOREIGN KEY ("source_id") REFERENCES "cloud_sources"("id") ON DELETE CASCADE ON UPDATE CASCADE; +ALTER TABLE "cloud_videos" ADD CONSTRAINT "cloud_videos_folder_id_fkey" FOREIGN KEY ("folder_id") REFERENCES "cloud_folders"("id") ON DELETE CASCADE ON UPDATE CASCADE; diff --git a/apps/api/prisma/schema.prisma b/apps/api/prisma/schema.prisma index 76af1d5..39af583 100644 --- a/apps/api/prisma/schema.prisma +++ b/apps/api/prisma/schema.prisma @@ -1638,6 +1638,7 @@ model CloudSource { organization Organization @relation(fields: [organizationId], references: [id], onDelete: Cascade) folders CloudFolder[] files CloudFile[] + videos CloudVideo[] grants ArchiveGrant[] faceActions ArchiveFaceAction[] @@ -1657,6 +1658,8 @@ model CloudFolder { parentId String? @map("parent_id") @db.Uuid /// Images directly inside. photoCount Int @default(0) @map("photo_count") + /// Videos directly inside (a gallery can hold photos, videos or both). + videoCount Int @default(0) @map("video_count") eventId String? @map("event_id") @db.Uuid /// How the event was found: FIXTURE (the official game), NAME (from the folder name), MANUAL, or null. matchedBy String? @map("matched_by") @@ -1668,6 +1671,7 @@ model CloudFolder { source CloudSource @relation(fields: [sourceId], references: [id], onDelete: Cascade) event Event? @relation(fields: [eventId], references: [id], onDelete: SetNull) files CloudFile[] + videos CloudVideo[] grants ArchiveGrantFolder[] @@unique([sourceId, fileId]) @@ -1705,6 +1709,41 @@ model CloudFile { @@map("cloud_files") } +/// A video in an archive folder. The original stays on the cloud; the archive keeps a web copy (H.264 MP4, at most +/// 1080p, faststart), a poster and a thumbnail under `storageKey` (a folder: web.mp4, poster.jpg, thumb.jpg). +model CloudVideo { + id String @id @default(uuid()) @db.Uuid + sourceId String @map("source_id") @db.Uuid + folderId String @map("folder_id") @db.Uuid + fileId String @map("file_id") + path String + etag String? + size BigInt? + /// PENDING (to make its web copy), WORKING, DONE, FAILED. + status String @default("PENDING") + attempts Int @default(0) + error String? + durationMs Int? @map("duration_ms") + width Int? + height Int? + /// The camera's time, when the file says it. + capturedAt DateTime? @map("captured_at") + /// Folder of its files in storage ("/videos/"), set once made. + storageKey String? @map("storage_key") + /// Size of the web copy. + webBytes BigInt? @map("web_bytes") + createdAt DateTime @default(now()) @map("created_at") + updatedAt DateTime @updatedAt @map("updated_at") + + source CloudSource @relation(fields: [sourceId], references: [id], onDelete: Cascade) + folder CloudFolder @relation(fields: [folderId], references: [id], onDelete: Cascade) + + @@unique([sourceId, fileId]) + @@index([status, sourceId]) + @@index([folderId, status, path]) + @@map("cloud_videos") +} + /// What one viewer may see, written when they sign in. Later pages read this row; they do not call the cloud again. /// Shares stay as they were at sign-in until the session ends. model ArchiveGrant { diff --git a/apps/api/src/app.ts b/apps/api/src/app.ts index 34bcb16..2000239 100644 --- a/apps/api/src/app.ts +++ b/apps/api/src/app.ts @@ -111,7 +111,7 @@ export async function buildApp({ config, db, realtime, fetchImpl, reporter: give const secrets = config.DELIVERY_SECRET_KEY ? new SecretBox(config.DELIVERY_SECRET_KEY) : undefined; const sports = new SportsService({ db, storage, log: app.log, fetch: fetchImpl ?? fetch }); // Archive clouds: the API connects them, matches galleries and streams originals; the worker walks and indexes. - const archive = new ArchiveService({ db, secrets, log: app.log, syncSquads: (id) => sports.syncEventSquads(id), ligaSeason: (season) => sports.importLigaSeason(season), storageRoot: config.STORAGE_ROOT, minFreeBytes: config.ARCHIVE_MIN_FREE_GB * 1e9, ...(fetchImpl && { fetchImpl }) }); + const archive = new ArchiveService({ db, secrets, log: app.log, syncSquads: (id) => sports.syncEventSquads(id), ligaSeason: (season) => sports.importLigaSeason(season), storageRoot: config.STORAGE_ROOT, minFreeBytes: config.ARCHIVE_MIN_FREE_GB * 1e9, storage, ...(fetchImpl && { fetchImpl }) }); const delivery = new DeliveryService({ db, storage, secrets, broadcaster, log: app.log, originals: archive, ...(fetchImpl && { fetchImpl }) }); registerErrorHandler(app); diff --git a/apps/api/src/archive/routes.ts b/apps/api/src/archive/routes.ts index 4ce4d9b..264934f 100644 --- a/apps/api/src/archive/routes.ts +++ b/apps/api/src/archive/routes.ts @@ -7,7 +7,7 @@ import type { Db } from "../db.js"; import { NextcloudError } from "../delivery/nextcloud.js"; import type { CloudSource } from "../generated/prisma/client.js"; import { AppError, badRequest, conflict, notFound } from "../lib/errors.js"; -import { ARCHIVE_LOOKS, ArchiveRejected, BYTES_PER_PHOTO, diskSpace, normalisePath, type ArchiveService, type RematchReport } from "./service.js"; +import { ARCHIVE_LOOKS, ArchiveRejected, BYTES_PER_PHOTO, diskSpace, GALLERY, normalisePath, type ArchiveService, type RematchReport } from "./service.js"; const OrgParams = z.object({ orgId: z.uuid() }); const SourceParams = z.object({ sourceId: z.uuid() }); @@ -60,11 +60,18 @@ export async function registerArchiveRoutes(app: FastifyInstance, deps: { db: Db const counts = async (sourceIds: string[]) => { if (!sourceIds.length) return new Map>(); const files = await db.cloudFile.groupBy({ by: ["sourceId", "status"], where: { sourceId: { in: sourceIds } }, _count: { _all: true } }); - const folders = await db.cloudFolder.groupBy({ by: ["sourceId", "matchedBy"], where: { sourceId: { in: sourceIds }, photoCount: { gt: 0 } }, _count: { _all: true } }); + const folders = await db.cloudFolder.groupBy({ by: ["sourceId", "matchedBy"], where: { sourceId: { in: sourceIds }, ...GALLERY }, _count: { _all: true } }); + const videos = await db.cloudVideo.groupBy({ by: ["sourceId", "status"], where: { sourceId: { in: sourceIds } }, _count: { _all: true } }); // The pace: images indexed in the last 15 minutes, per hour. const recent = await db.cloudFile.groupBy({ by: ["sourceId"], where: { sourceId: { in: sourceIds }, status: "DONE", updatedAt: { gte: new Date(Date.now() - 15 * 60_000) } }, _count: { _all: true } }); const out = new Map>(); - const get = (id: string) => out.get(id) ?? out.set(id, { pending: 0, done: 0, failed: 0, galleries: 0, games: 0, named: 0, unmatched: 0, perHour: 0 }).get(id)!; + const get = (id: string) => out.get(id) ?? out.set(id, { pending: 0, done: 0, failed: 0, galleries: 0, games: 0, named: 0, unmatched: 0, perHour: 0, videos: 0, videosPending: 0, videosFailed: 0 }).get(id)!; + for (const v of videos) { + const c = get(v.sourceId); + if (v.status === "DONE") c.videos! += v._count._all; + else if (v.status === "FAILED") c.videosFailed! += v._count._all; + else c.videosPending! += v._count._all; + } for (const r of recent) get(r.sourceId).perHour = r._count._all * 4; for (const f of files) { const c = get(f.sourceId); @@ -95,7 +102,7 @@ export async function registerArchiveRoutes(app: FastifyInstance, deps: { db: Db nextScanAt: s.nextScanAt, lastError: s.lastError, loginUrl: loginUrl ?? archive.pendingLoginUrl(s), - counts: { pending: 0, done: 0, failed: 0, galleries: 0, games: 0, named: 0, unmatched: 0, perHour: 0, ...c }, + counts: { pending: 0, done: 0, failed: 0, galleries: 0, games: 0, named: 0, unmatched: 0, perHour: 0, videos: 0, videosPending: 0, videosFailed: 0, ...c }, }); const loadSource = async (req: Parameters[1], sourceId: string, role: "EDITOR" | "ADMIN") => { @@ -176,6 +183,8 @@ export async function registerArchiveRoutes(app: FastifyInstance, deps: { db: Db const { sourceId } = SourceParams.parse(req.params); await loadSource(req, sourceId, "EDITOR"); await db.cloudFile.updateMany({ where: { sourceId, status: "FAILED" }, data: { status: "PENDING", attempts: 0 } }); + // Videos too (one that waited for ffmpeg is made once it is installed). + await db.cloudVideo.updateMany({ where: { sourceId, status: "FAILED" }, data: { status: "PENDING", attempts: 0 } }); const source = await db.cloudSource.update({ where: { id: sourceId }, data: { nextScanAt: new Date() } }); return serialize(source, (await counts([source.id])).get(source.id)); }); @@ -216,7 +225,7 @@ export async function registerArchiveRoutes(app: FastifyInstance, deps: { db: Db const folders = await db.cloudFolder.findMany({ where: { sourceId, - photoCount: { gt: 0 }, + AND: [GALLERY], ...(query.state === "games" && { matchedBy: { in: ["FIXTURE", "MANUAL"] } }), ...(query.state === "unmatched" && { OR: [{ matchedBy: { in: ["NAME", "FOLDER"] } }, { matchedBy: null }] }), ...(query.state === "named" && { matchedBy: "NAME" }), @@ -237,6 +246,7 @@ export async function registerArchiveRoutes(app: FastifyInstance, deps: { db: Db id: f.id, path: f.path.startsWith(root) ? f.path.slice(root.length) || "/" : f.path, photoCount: f.photoCount, + videoCount: f.videoCount, indexed: indexed.get(f.id) ?? 0, matchedBy: f.matchedBy, event: f.event ? { id: f.event.id, name: eventName(f.event), startsAt: f.event.startsAt, competition: f.event.competition, fixtureId: f.event.fixtureId } : null, diff --git a/apps/api/src/archive/service.ts b/apps/api/src/archive/service.ts index f23d86f..2e054ab 100644 --- a/apps/api/src/archive/service.ts +++ b/apps/api/src/archive/service.ts @@ -1,7 +1,7 @@ import { readCameraInfo } from "../ingest/exif.js"; import { createHash } from "node:crypto"; import { createReadStream } from "node:fs"; -import { mkdtemp, rm, stat, statfs } from "node:fs/promises"; +import { mkdir, mkdtemp, readdir, rm, stat, statfs } from "node:fs/promises"; import { tmpdir } from "node:os"; import path from "node:path"; import { NEWSROOM_TEMPLATE, GENERAL_TEMPLATE } from "@photoreport/metadata"; @@ -13,7 +13,9 @@ import type { CloudFolder, CloudSource } from "../generated/prisma/client.js"; import type { IngestLogger, IngestService } from "../ingest/service.js"; import { ingestWindow } from "../library/events.js"; import { waitUntil } from "../lib/idle.js"; +import type { LocalStorage } from "../storage/storage.js"; import { CloudClient, cleanBase, pollLogin, startLogin, type CloudEntry } from "./nextcloud.js"; +import { makeWebCopy, VIDEO, VideoToolMissing, type VideoTools } from "./video.js"; import { canonicalTeam, competitionLabel, describeFolder, exhibitionName, type FolderGame, isExhibition, isInitials, isTeamName, lisbonDay, parseFolder, pastOrToday, pickFixture, seasonOf } from "./match.js"; export const IMAGE = /\.(jpe?g)$/i; @@ -62,6 +64,10 @@ export interface ArchiveDeps { cpuSlots?: number; /** Clouds' folders mounted on this machine (read from disk, not downloaded): see `localDirs`. */ localDirs?: LocalDir[]; + /** Where videos' web copies are kept (the worker makes them; anyone dropping a video removes its files). */ + storage?: LocalStorage; + /** ffmpeg and ffprobe, for videos' web copies. */ + videoTools?: VideoTools; } /** The looks an archive's site can have (its owner's colours and type); none is PhotoReport's own. */ @@ -246,6 +252,8 @@ export class ArchiveService { async disconnect(sourceId: string): Promise { const source = await this.deps.db.cloudSource.findUniqueOrThrow({ where: { id: sourceId } }); if (source.secretEnc) await this.client(source).revoke(); + // Videos' web copies are the archive's own: they go with it. + await this.dropVideoFiles(await this.deps.db.cloudVideo.findMany({ where: { sourceId }, select: { storageKey: true } })); // The photos stay in the library (their events too); only the link to the cloud goes. await this.deps.db.cloudSource.delete({ where: { id: sourceId } }); } @@ -317,6 +325,7 @@ export class ArchiveService { const dirs = children.filter((c) => c.isDir); const images = children.filter((c) => !c.isDir && IMAGE.test(c.name)); + const videos = children.filter((c) => !c.isDir && VIDEO.test(c.name)); // Images: new ones queued, changed ones queued again, moved ones follow. const existing = await db.cloudFile.findMany({ where: { sourceId: source.id, fileId: { in: images.map((i) => i.fileId) } } }); @@ -335,11 +344,33 @@ export class ArchiveService { } await db.cloudFile.deleteMany({ where: { folderId: folder.id, fileId: { notIn: images.map((i) => i.fileId) } } }); - // Sub-folders gone from the cloud go from here too (and their images). - await db.cloudFolder.deleteMany({ where: { sourceId: source.id, parentId: folder.id, fileId: { notIn: dirs.map((d) => d.fileId) } } }); + // Videos the same way: new and changed ones get their web copy made (again), moved ones follow. + const knownVideos = await db.cloudVideo.findMany({ where: { sourceId: source.id, fileId: { in: videos.map((v) => v.fileId) } } }); + const videoById = new Map(knownVideos.map((v) => [v.fileId, v])); + for (const vid of videos) { + const v = videoById.get(vid.fileId); + const size = vid.size === null ? null : BigInt(vid.size); + if (!v) { + await db.cloudVideo.create({ data: { sourceId: source.id, folderId: folder.id, fileId: vid.fileId, path: vid.path, etag: vid.etag, size } }); + stats.queued++; + } else if (v.etag !== vid.etag) { + await db.cloudVideo.update({ where: { id: v.id }, data: { folderId: folder.id, path: vid.path, etag: vid.etag, size, status: "PENDING", attempts: 0, error: null } }); + stats.queued++; + } else if (v.path !== vid.path || v.folderId !== folder.id) { + await db.cloudVideo.update({ where: { id: v.id }, data: { folderId: folder.id, path: vid.path } }); + } + } + const goneVideos = { folderId: folder.id, fileId: { notIn: videos.map((v) => v.fileId) } }; + await this.dropVideoFiles(await db.cloudVideo.findMany({ where: goneVideos, select: { storageKey: true } })); + await db.cloudVideo.deleteMany({ where: goneVideos }); - folder = await db.cloudFolder.update({ where: { id: folder.id }, data: { photoCount: images.length } }); - if (images.length && !folder.eventId && !folder.matchedBy) await this.matchFolder(source, folder, self); + // Sub-folders gone from the cloud go from here too (and their images and videos). + const goneDirs = { sourceId: source.id, parentId: folder.id, fileId: { notIn: dirs.map((d) => d.fileId) } }; + await this.dropVideoFiles(await db.cloudVideo.findMany({ where: { folder: goneDirs }, select: { storageKey: true } })); + await db.cloudFolder.deleteMany({ where: goneDirs }); + + folder = await db.cloudFolder.update({ where: { id: folder.id }, data: { photoCount: images.length, videoCount: videos.length } }); + if ((images.length || videos.length) && !folder.eventId && !folder.matchedBy) await this.matchFolder(source, folder, self); for (const d of dirs.sort((a, b) => b.name.localeCompare(a.name))) await this.walk(source, client, d.path, folder, stats, full, d); // Marked read only when everything below is: a walk cut short reads the rest next time. @@ -453,7 +484,7 @@ export class ArchiveService { async takeOffFutureGames(now = new Date()): Promise { const { db, log } = this.deps; const folders = await db.cloudFolder.findMany({ - where: { photoCount: { gt: 0 }, OR: [{ matchedBy: null }, { matchedBy: { not: "MANUAL" } }], event: { startsAt: { gt: new Date(now.getTime() + 6 * 3600_000) } } }, + where: { AND: [GALLERY, { OR: [{ matchedBy: null }, { matchedBy: { not: "MANUAL" } }] }], event: { startsAt: { gt: new Date(now.getTime() + 6 * 3600_000) } } }, include: { source: true }, }); let moved = 0; @@ -480,9 +511,8 @@ export class ArchiveService { const folders = await db.cloudFolder.findMany({ where: { sourceId, - photoCount: { gt: 0 }, + AND: [GALLERY, ...(part === "rest" ? [{ OR: [{ matchedBy: null }, { matchedBy: { not: "FIXTURE" as const } }] }] : [])], ...(part === "fixtures" && { matchedBy: "FIXTURE" }), - ...(part === "rest" && { OR: [{ matchedBy: null }, { matchedBy: { not: "FIXTURE" } }] }), }, }); let moved = 0; @@ -835,6 +865,7 @@ export class ArchiveService { const { db, log } = this.deps; const walks = await db.cloudSource.updateMany({ where: { status: "SCANNING" }, data: { status: "READY", nextScanAt: new Date() } }); if (walks.count) log.info({ count: walks.count }, "archive: resuming interrupted walks"); + await db.cloudVideo.updateMany({ where: { status: "WORKING" }, data: { status: "PENDING" } }); return db.cloudFile.updateMany({ where: { status: "WORKING" }, data: { status: "PENDING" } }).then((r) => r.count); } @@ -975,6 +1006,78 @@ export class ArchiveService { } } + // --- videos ---------------------------------------------------------------------------------------------------- + + /** Videos waiting for their web copy, newest season first (like the photos), then by game and name. */ + async claimVideos(limit: number): Promise { + if (limit <= 0 || !this.deps.storage || !this.deps.videoTools) return []; + if (await this.diskLow()) return []; + const rows = await this.deps.db.$queryRaw<{ id: string }[]>` + UPDATE cloud_videos SET status = 'WORKING', attempts = attempts + 1, updated_at = now() + WHERE id IN ( + SELECT v.id FROM cloud_videos v + JOIN cloud_sources s ON s.id = v.source_id AND s.status IN ('READY', 'SCANNING') + JOIN cloud_folders d ON d.id = v.folder_id + LEFT JOIN events e ON e.id = d.event_id + WHERE v.status = 'PENDING' + ORDER BY coalesce(substring(v.path from '(20[0-9]{2})[_-]20[0-9]{2}'), '20' || substring(v.path from '([0-9]{2})[_-][0-9]{2}(/|$| )')) DESC NULLS LAST, + e.starts_at DESC NULLS LAST, v.path + LIMIT ${limit} + FOR UPDATE OF v SKIP LOCKED + ) + RETURNING id`; + return rows.map((r) => r.id); + } + + /** + * One video: read from the cloud (or its mount), its web copy, poster and thumbnail made with ffmpeg and kept in + * storage. The original never leaves the cloud. Without ffmpeg on this machine the video waits (FAILED with the + * reason; "Analisar agora" tries again once it is installed). + */ + async indexVideo(videoId: string): Promise { + const { db, log } = this.deps; + const { storage, videoTools } = this.deps; + if (!storage || !videoTools) throw new Error("videos need storage and ffmpeg"); + const video = await db.cloudVideo.findUniqueOrThrow({ where: { id: videoId }, include: { source: true } }); + const dir = await mkdtemp(path.join(tmpdir(), "pr-archive-video-")); + try { + let original = await this.localFile(video.source.baseUrl, video.path, video.size); + if (!original) { + original = path.join(dir, `original${path.posix.extname(video.path).toLowerCase()}`); + await this.client(video.source).download(video.path, original); + } + const out = path.join(dir, "out"); + await mkdir(out); + const made = await this.cpu.run(() => makeWebCopy(videoTools, original, out)); + const key = storage.videoKey(video.source.organizationId, video.id); + // The new files take the place of an older copy (a changed video). + await rm(storage.resolve(key), { recursive: true, force: true }); + for (const name of await readdir(out)) if (name !== "frame.jpg") await storage.adopt(path.join(out, name), `${key}/${name}`); + await db.cloudVideo.update({ + where: { id: videoId }, + data: { status: "DONE", error: null, storageKey: key, durationMs: made.durationMs, width: made.width, height: made.height, capturedAt: made.capturedAt, webBytes: BigInt(made.webBytes) }, + }); + } catch (err) { + const message = (err as Error).message; + const transient = err instanceof NextcloudError && err.transient; + const gone = err instanceof NextcloudError && err.status === 404; + const missing = err instanceof VideoToolMissing; + const retry = !gone && !missing && (transient || video.attempts < MAX_ATTEMPTS); + await db.cloudVideo.update({ where: { id: videoId }, data: { status: retry ? "PENDING" : "FAILED", error: message, ...(transient && { attempts: { decrement: 1 } }) } }); + if (gone) await db.cloudFolder.update({ where: { id: video.folderId }, data: { etag: null } }); + log.warn({ err, videoId, path: video.path }, "archive: video not indexed"); + } finally { + await rm(dir, { recursive: true, force: true }); + } + } + + /** A video's files in storage, when it is dropped (gone from the cloud, the cloud disconnected). */ + private async dropVideoFiles(videos: { storageKey: string | null }[]): Promise { + const storage = this.deps.storage; + if (!storage) return; + for (const v of videos) if (v.storageKey) await rm(storage.resolve(v.storageKey), { recursive: true, force: true }).catch(() => undefined); + } + // --- originals ------------------------------------------------------------------------------------------------- private async cloudFileOf(photoId: string) { @@ -1035,6 +1138,9 @@ export class ArchiveService { } } +/** A gallery folder: one with photos, videos, or both. */ +export const GALLERY = { OR: [{ photoCount: { gt: 0 } }, { videoCount: { gt: 0 } }] }; + /** "/FPA/Fotos/" → "/FPA/Fotos". */ export const normalisePath = (p: string) => "/" + p.trim().replace(/\\/g, "/").replace(/^\/+|\/+$/g, ""); @@ -1055,6 +1161,7 @@ const BURST_BACKLOG = 500; export class ArchiveWorker { private inFlight = 0; + private videosInFlight = 0; private timer: NodeJS.Timeout | undefined; private stopped = false; private scanning = false; @@ -1069,6 +1176,8 @@ export class ArchiveWorker { intervalMs: number; log: IngestLogger; pressure?: { allow(full: number, burst?: boolean): number }; + /** Videos made at once (each ffmpeg uses several cores). 0: none on this worker. */ + videos?: number; }, ) {} @@ -1113,6 +1222,14 @@ export class ArchiveWorker { this.inFlight--; }); } + // Videos beside the photos, a few at a time: they are few, and each one is long work. + const videoIds = await this.service.claimVideos((this.opts.videos ?? 1) - this.videosInFlight); + for (const id of videoIds) { + this.videosInFlight++; + void this.service.indexVideo(id).finally(() => { + this.videosInFlight--; + }); + } } catch (err) { this.opts.log.warn({ err }, "archive: poll failed"); } @@ -1140,7 +1257,7 @@ export class ArchiveWorker { async stop(timeoutMs = 25_000): Promise { this.stopped = true; if (this.timer) clearTimeout(this.timer); - const drained = await waitUntil(() => !this.ticking && !this.scanning && this.inFlight === 0, { timeoutMs }); - if (!drained) this.opts.log.warn({ inFlight: this.inFlight, scanning: this.scanning }, "archive: stop timed out with work still running"); + const drained = await waitUntil(() => !this.ticking && !this.scanning && this.inFlight === 0 && this.videosInFlight === 0, { timeoutMs }); + if (!drained) this.opts.log.warn({ inFlight: this.inFlight, videos: this.videosInFlight, scanning: this.scanning }, "archive: stop timed out with work still running"); } } diff --git a/apps/api/src/archive/video.test.ts b/apps/api/src/archive/video.test.ts new file mode 100644 index 0000000..b48cde7 --- /dev/null +++ b/apps/api/src/archive/video.test.ts @@ -0,0 +1,134 @@ +import { execFileSync } from "node:child_process"; +import { mkdtemp, rm, stat } from "node:fs/promises"; +import { tmpdir } from "node:os"; +import path from "node:path"; +import { afterAll, beforeAll, describe, expect, it } from "vitest"; +import { UrlSigner } from "../storage/storage.js"; +import { makeWebCopy, parseRange, posterAt, readProbe, VIDEO, VideoToolMissing, webCopyArgs, probe } from "./video.js"; + +describe("archive videos", () => { + it("knows a video by its name", () => { + for (const name of ["Golo 1.MP4", "a.mov", "clip.m4v", "00001.MTS", "x.mkv", "y.webm"]) expect(VIDEO.test(name)).toBe(true); + for (const name of ["foto.jpg", "notes.txt", "mp4", "video.mp4.part"]) expect(VIDEO.test(name)).toBe(false); + }); + + it("answers the ranges a player asks for", () => { + expect(parseRange(undefined, 1000)).toBeNull(); + expect(parseRange("bytes=0-", 1000)).toEqual({ start: 0, end: 999 }); + expect(parseRange("bytes=0-1", 1000)).toEqual({ start: 0, end: 1 }); + expect(parseRange("bytes=500-2000", 1000)).toEqual({ start: 500, end: 999 }); + expect(parseRange("bytes=-100", 1000)).toEqual({ start: 900, end: 999 }); + expect(parseRange("bytes=-5000", 1000)).toEqual({ start: 0, end: 999 }); + expect(parseRange("bytes=1000-", 1000)).toBe("bad"); + expect(parseRange("bytes=9-3", 1000)).toBe("bad"); + expect(parseRange("bytes=-", 1000)).toBe("bad"); + expect(parseRange("items=0-1", 1000)).toBe("bad"); + // Several at once: the whole file instead. + expect(parseRange("bytes=0-1,5-9", 1000)).toBeNull(); + }); + + it("reads length, size, sound and the camera's time", () => { + const info = readProbe({ + format: { duration: "12.480000", tags: { creation_time: "2025-09-13T18:42:10.000000Z" } }, + streams: [ + { codec_type: "video", width: 1920, height: 1080 }, + { codec_type: "audio" }, + ], + }); + expect(info).toEqual({ durationMs: 12480, width: 1920, height: 1080, capturedAt: new Date("2025-09-13T18:42:10.000Z"), hasAudio: true }); + // A camera that never had its clock set. + expect(readProbe({ format: { tags: { creation_time: "1970-01-01T00:00:00Z" } }, streams: [{ codec_type: "video" }] }).capturedAt).toBeNull(); + expect(readProbe({ streams: [] })).toMatchObject({ durationMs: null, width: null, hasAudio: false }); + }); + + it("makes an H.264 web copy that starts at once, with or without sound", () => { + const withSound = webCopyArgs("in.mov", "out.mp4", { audio: true }); + expect(withSound).toEqual(expect.arrayContaining(["libx264", "+faststart", "aac", "0:a:0"])); + expect(withSound.at(-1)).toBe("out.mp4"); + const silent = webCopyArgs("in.mov", "out.mp4", { audio: false }); + expect(silent).toContain("-an"); + expect(silent).not.toContain("0:a:0"); + }); + + it("takes the poster a second in, sooner in a short clip", () => { + expect(posterAt(null)).toBe(0); + expect(posterAt(60_000)).toBe(1); + expect(posterAt(4_000)).toBe(0.4); + }); + + it("signs a video's links apart from the photos'", () => { + let now = 1_800_000_000_000; + const signer = new UrlSigner("x".repeat(40), 3600, () => now); + const url = new URL(signer.videoUrl("6c0b1b55-6d1f-4c2a-9f0e-0f5a3c1b2d3e", "web"), "http://h"); + const exp = Number(url.searchParams.get("exp")); + const sig = url.searchParams.get("sig")!; + expect(url.pathname).toBe("/v1/files/videos/6c0b1b55-6d1f-4c2a-9f0e-0f5a3c1b2d3e/web"); + expect(signer.verifyVideo("6c0b1b55-6d1f-4c2a-9f0e-0f5a3c1b2d3e", "web", exp, sig)).toBe(true); + // Another file of the same video, another video, or a photo: not with this signature. + expect(signer.verifyVideo("6c0b1b55-6d1f-4c2a-9f0e-0f5a3c1b2d3e", "download", exp, sig)).toBe(false); + expect(signer.verifyVideo("00000000-6d1f-4c2a-9f0e-0f5a3c1b2d3e", "web", exp, sig)).toBe(false); + expect(signer.verify("6c0b1b55-6d1f-4c2a-9f0e-0f5a3c1b2d3e", "preview", exp, sig)).toBe(false); + now += 3 * 3600_000; + expect(signer.verifyVideo("6c0b1b55-6d1f-4c2a-9f0e-0f5a3c1b2d3e", "web", exp, sig)).toBe(false); + }); + + it("says when ffmpeg is not installed", async () => { + await expect(probe({ ffmpeg: "ffmpeg-not-here", ffprobe: "ffprobe-not-here" }, "x.mp4")).rejects.toBeInstanceOf(VideoToolMissing); + }); +}); + +const hasFfmpeg = (() => { + try { + execFileSync("ffmpeg", ["-version"], { stdio: "ignore" }); + execFileSync("ffprobe", ["-version"], { stdio: "ignore" }); + return true; + } catch { + return false; + } +})(); + +describe.skipIf(!hasFfmpeg)("archive videos with ffmpeg", () => { + const tools = { ffmpeg: "ffmpeg", ffprobe: "ffprobe" }; + let dir: string; + beforeAll(async () => { + dir = await mkdtemp(path.join(tmpdir(), "pr-video-test-")); + }); + afterAll(async () => { + await rm(dir, { recursive: true, force: true }); + }); + + const clip = (name: string, size: string, audio: boolean) => { + const file = path.join(dir, name); + execFileSync("ffmpeg", [ + "-hide_banner", "-loglevel", "error", "-y", + "-f", "lavfi", "-i", `testsrc=size=${size}:rate=10:duration=2`, + ...(audio ? ["-f", "lavfi", "-i", "sine=frequency=440:duration=2"] : []), + "-c:v", "mpeg4", ...(audio ? ["-c:a", "aac", "-shortest"] : []), + "-metadata", "creation_time=2025-09-13T18:42:10Z", + file, + ]); + return file; + }; + + it("brings a big landscape video down to 1080p, with sound, poster and thumbnail", async () => { + const out = path.join(dir, "landscape"); + await import("node:fs/promises").then((fs) => fs.mkdir(out)); + const made = await makeWebCopy(tools, clip("big.mov", "2560x1440", true), out); + expect(made).toMatchObject({ width: 1920, height: 1080, hasAudio: true }); + expect(made.durationMs).toBeGreaterThan(1500); + expect(made.capturedAt?.toISOString()).toBe("2025-09-13T18:42:10.000Z"); + expect(made.webBytes).toBe((await stat(path.join(out, "web.mp4"))).size); + for (const f of ["poster.jpg", "thumb.jpg"]) expect((await stat(path.join(out, f))).size).toBeGreaterThan(0); + }, 60_000); + + it("keeps a phone's portrait video upright and a small one as it is", async () => { + const portrait = path.join(dir, "portrait"); + const small = path.join(dir, "small"); + await import("node:fs/promises").then(async (fs) => { + await fs.mkdir(portrait); + await fs.mkdir(small); + }); + expect(await makeWebCopy(tools, clip("tall.mp4", "1440x2560", false), portrait)).toMatchObject({ width: 1080, height: 1920, hasAudio: false }); + expect(await makeWebCopy(tools, clip("small.mp4", "640x360", false), small)).toMatchObject({ width: 640, height: 360 }); + }, 60_000); +}); diff --git a/apps/api/src/archive/video.ts b/apps/api/src/archive/video.ts new file mode 100644 index 0000000..be35d8c --- /dev/null +++ b/apps/api/src/archive/video.ts @@ -0,0 +1,188 @@ +import { spawn } from "node:child_process"; +import { createReadStream } from "node:fs"; +import { stat } from "node:fs/promises"; +import path from "node:path"; +import type { FastifyReply } from "fastify"; +import sharp from "sharp"; + +/** + * Videos in the archive (docs/archive.md, "Vídeos"). The original stays on the cloud; the archive keeps a web copy + * every browser plays (H.264 + AAC in MP4, the short side at most 1080 px, faststart so it starts before it has + * all arrived), a poster for the large view and a thumbnail for the grid. Made with ffmpeg on the worker. + */ +export const VIDEO = /\.(mp4|m4v|mov|mts|m2ts|mkv|avi|webm)$/i; + +/** The files of a video's web copy, inside its storage folder. */ +export const VIDEO_FILES = { web: "web.mp4", poster: "poster.jpg", thumb: "thumb.jpg" } as const; +export type VideoVariant = keyof typeof VIDEO_FILES | "download"; +export const VIDEO_VARIANTS = ["web", "poster", "thumb", "download"] as const satisfies readonly VideoVariant[]; + +/** Long side of the poster (the large view before play) and of the grid's thumbnail. */ +const POSTER_SIZE = 1280; +const THUMB_SIZE = 480; +/** The short side of the web copy: 1080p for a landscape video, 1080 wide for a phone's portrait one. */ +export const WEB_SHORT_SIDE = 1080; + +export class VideoToolMissing extends Error { + constructor(tool: string) { + super(`${tool}_missing`); + } +} + +export interface VideoTools { + ffmpeg: string; + ffprobe: string; +} + +export interface VideoInfo { + durationMs: number | null; + width: number | null; + height: number | null; + capturedAt: Date | null; + hasAudio: boolean; +} + +/** ffmpeg's arguments for the web copy (tested on their own). */ +export function webCopyArgs(input: string, output: string, opts: { audio: boolean }): string[] { + // Scales down only: the short side to WEB_SHORT_SIDE at most, the other to keep the shape (even, as H.264 needs). + // ffmpeg turns a phone's rotated video upright on the way (autorotate), so width and height are as shown. + const s = WEB_SHORT_SIDE; + const scale = `scale=w='if(gte(iw,ih),-2,min(${s},iw))':h='if(gte(iw,ih),min(${s},ih),-2)'`; + return [ + "-hide_banner", + "-nostdin", + "-loglevel", + "error", + "-y", + "-i", + input, + "-map", + "0:v:0", + ...(opts.audio ? ["-map", "0:a:0"] : []), + "-vf", + `${scale},format=yuv420p`, + "-c:v", + "libx264", + "-preset", + "veryfast", + "-crf", + "23", + "-profile:v", + "high", + ...(opts.audio ? ["-c:a", "aac", "-b:a", "128k", "-ac", "2"] : ["-an"]), + "-movflags", + "+faststart", + "-max_muxing_queue_size", + "1024", + output, + ]; +} + +/** Where to take the poster from: a second in, or a tenth of a short clip. */ +export function posterAt(durationMs: number | null): number { + if (!durationMs || durationMs <= 0) return 0; + return Math.min(1, durationMs / 10000); +} + +function run(bin: string, args: string[], tool: string): Promise { + return new Promise((resolve, reject) => { + const child = spawn(bin, args, { stdio: ["ignore", "pipe", "pipe"] }); + let out = ""; + let err = ""; + child.stdout.on("data", (d: Buffer) => (out += d.toString())); + child.stderr.on("data", (d: Buffer) => { + // Only the end matters (ffmpeg says why it stopped last). + err = (err + d.toString()).slice(-4000); + }); + child.on("error", (e: NodeJS.ErrnoException) => reject(e.code === "ENOENT" ? new VideoToolMissing(tool) : e)); + child.on("close", (code) => (code === 0 ? resolve(out) : reject(new Error(`${tool} exited ${code}: ${err.trim().split("\n").slice(-3).join(" | ")}`)))); + }); +} + +interface ProbeJson { + format?: { duration?: string; tags?: Record }; + streams?: { codec_type?: string; width?: number; height?: number; duration?: string; tags?: Record }[]; +} + +/** What ffprobe says of a file: length, size as stored, the camera's time, whether it has sound. */ +export async function probe(tools: VideoTools, file: string): Promise { + const json = JSON.parse(await run(tools.ffprobe, ["-v", "error", "-print_format", "json", "-show_format", "-show_streams", file], "ffprobe")) as ProbeJson; + return readProbe(json); +} + +export function readProbe(json: ProbeJson): VideoInfo { + const streams = json.streams ?? []; + const video = streams.find((s) => s.codec_type === "video"); + const seconds = Number(json.format?.duration ?? video?.duration); + const tags = { ...(video?.tags ?? {}), ...(json.format?.tags ?? {}) }; + // Apple's own tag keeps the time zone; creation_time is UTC. A camera that never had its clock set says 1970 or 1904. + const raw = tags["com.apple.quicktime.creationdate"] ?? tags.creation_time ?? null; + const when = raw ? new Date(raw) : null; + const capturedAt = when && !Number.isNaN(when.getTime()) && when.getUTCFullYear() >= 2000 && when.getTime() < Date.now() + 86_400_000 ? when : null; + return { + durationMs: Number.isFinite(seconds) && seconds > 0 ? Math.round(seconds * 1000) : null, + width: video?.width ?? null, + height: video?.height ?? null, + capturedAt, + hasAudio: streams.some((s) => s.codec_type === "audio"), + }; +} + +/** + * The web copy, poster and thumbnail of `input`, written into `dir`. What it answers is read from the copy (its + * size is the one shown, upright), with the original's camera time. + */ +export async function makeWebCopy(tools: VideoTools, input: string, dir: string): Promise { + const original = await probe(tools, input); + const web = path.join(dir, VIDEO_FILES.web); + await run(tools.ffmpeg, webCopyArgs(input, web, { audio: original.hasAudio }), "ffmpeg"); + const copy = await probe(tools, web); + const frame = path.join(dir, "frame.jpg"); + // The most typical frame among the first ones after the start (thumbnail filter), not a black first frame. + await run(tools.ffmpeg, ["-hide_banner", "-nostdin", "-loglevel", "error", "-y", "-ss", String(posterAt(copy.durationMs)), "-i", web, "-vf", "thumbnail=30", "-frames:v", "1", "-q:v", "2", frame], "ffmpeg"); + await sharp(frame).resize(POSTER_SIZE, POSTER_SIZE, { fit: "inside", withoutEnlargement: true }).jpeg({ quality: 85 }).toFile(path.join(dir, VIDEO_FILES.poster)); + await sharp(frame).resize(THUMB_SIZE, THUMB_SIZE, { fit: "inside", withoutEnlargement: true }).jpeg({ quality: 80 }).toFile(path.join(dir, VIDEO_FILES.thumb)); + return { ...copy, capturedAt: original.capturedAt, webBytes: (await stat(web)).size }; +} + +/** A `Range: bytes=…` header against a file's size: the part to send, `null` for the whole file, `"bad"` when it cannot be met. */ +export function parseRange(header: string | undefined, size: number): { start: number; end: number } | null | "bad" { + if (!header) return null; + const m = /^bytes=(\d*)-(\d*)$/.exec(header.trim()); + // Several ranges at once are not worth it for a player: the whole file. + if (!m) return header.includes(",") ? null : "bad"; + const [, a, b] = m; + if (a === "" && b === "") return "bad"; + let start: number; + let end: number; + if (a === "") { + // The last N bytes. + const n = Number(b); + if (!n) return "bad"; + start = Math.max(0, size - n); + end = size - 1; + } else { + start = Number(a); + end = b === "" ? size - 1 : Math.min(Number(b), size - 1); + } + if (start >= size || start > end) return "bad"; + return { start, end }; +} + +/** + * Sends a file the way video players ask for it: whole, or the part named by `Range` (206), so the player can + * start at once and jump to any moment. + */ +export async function sendFile(reply: FastifyReply, file: string, range: string | undefined, headers: Record): Promise { + const size = (await stat(file)).size; + for (const [k, v] of Object.entries(headers)) reply.header(k, v); + reply.header("accept-ranges", "bytes"); + const part = parseRange(range, size); + if (part === "bad") return reply.code(416).header("content-range", `bytes */${size}`).send(); + if (!part) return reply.header("content-length", String(size)).send(createReadStream(file)); + return reply + .code(206) + .header("content-range", `bytes ${part.start}-${part.end}/${size}`) + .header("content-length", String(part.end - part.start + 1)) + .send(createReadStream(file, { start: part.start, end: part.end })); +} diff --git a/apps/api/src/archive/viewer.ts b/apps/api/src/archive/viewer.ts index cdedd58..52a8966 100644 --- a/apps/api/src/archive/viewer.ts +++ b/apps/api/src/archive/viewer.ts @@ -14,7 +14,8 @@ import type { FaceService } from "../faces/service.js"; import { faceBox, facesOfPhotos, registerArchivePeopleRoutes } from "./people.js"; import { registerArchiveDownloadRoutes } from "./downloads.js"; import { registerArchiveReviewRoutes } from "./review.js"; -import type { ArchiveService } from "./service.js"; +import { GALLERY, type ArchiveService } from "./service.js"; +import { sendFile, VIDEO_FILES, VIDEO_VARIANTS } from "./video.js"; /** * The archive for people outside the organization (the federation, the clubs, the press): they sign in with @@ -79,6 +80,8 @@ export class ViewerTokens { const SourceParams = z.object({ sourceId: z.uuid() }); const FolderParams = z.object({ folderId: z.uuid() }); const PhotoParams = z.object({ photoId: z.uuid() }); +const VideoFileParams = z.object({ videoId: z.uuid(), variant: z.enum(VIDEO_VARIANTS) }); +const VideoFileQuery = z.object({ exp: z.coerce.number().int(), sig: z.string().min(10).max(200) }); const GalleryQuery = z.object({ offset: z.coerce.number().int().min(0).default(0), limit: z.coerce.number().int().min(1).max(60).default(48), @@ -276,7 +279,7 @@ export async function registerArchiveViewerRoutes( const folderWhere = (v: Viewer, visible: string[] | "all") => ({ sourceId: v.s, - photoCount: { gt: 0 }, + AND: [GALLERY], eventId: { not: null }, ...(visible !== "all" && { id: { in: visible } }), }); @@ -469,6 +472,12 @@ export async function registerArchiveViewerRoutes( ? await db.cloudFile.findMany({ where: { folderId: { in: folders.map((f) => f.id) }, status: "DONE", photoId: { not: null } }, distinct: ["folderId"], orderBy: { path: "asc" }, select: { folderId: true, photoId: true } }) : []; const cover = new Map(covers.map((c) => [c.folderId, c.photoId!])); + // A gallery of videos only: its first video's frame. + const videoOnly = folders.filter((f) => !cover.has(f.id) && f.videoCount > 0).map((f) => f.id); + const videoCovers = videoOnly.length + ? await db.cloudVideo.findMany({ where: { folderId: { in: videoOnly }, status: "DONE" }, distinct: ["folderId"], orderBy: { path: "asc" }, select: { folderId: true, id: true } }) + : []; + const videoCover = new Map(videoCovers.map((c) => [c.folderId, c.id])); return { viewer: { name: v.n }, total, @@ -482,8 +491,9 @@ export async function registerArchiveViewerRoutes( competition: f.event?.competition ?? null, startsAt: f.event?.startsAt ?? null, photoCount: f.photoCount, - cover: cover.has(f.id) ? signer.url(cover.get(f.id)!, "thumb") : null, - coverLarge: cover.has(f.id) ? signer.url(cover.get(f.id)!, "preview") : null, + videoCount: f.videoCount, + cover: cover.has(f.id) ? signer.url(cover.get(f.id)!, "thumb") : videoCover.has(f.id) ? signer.videoUrl(videoCover.get(f.id)!, "thumb") : null, + coverLarge: cover.has(f.id) ? signer.url(cover.get(f.id)!, "preview") : videoCover.has(f.id) ? signer.videoUrl(videoCover.get(f.id)!, "poster") : null, })), }; }); @@ -589,6 +599,12 @@ export async function registerArchiveViewerRoutes( ORDER BY p.name` : Promise.resolve([]), ]); + // The gallery's videos come with its first page (they are few); not when it is filtered by a person or a player, + // whose faces and names are only on the photos for now. + const videos = + query.offset === 0 && !query.player && !query.person + ? await db.cloudVideo.findMany({ where: { folderId, status: "DONE", storageKey: { not: null } }, orderBy: { path: "asc" }, take: 200 }) + : []; const facePhotos = await db.photo.findMany({ where: { id: { in: sharpest.map((f) => f.photo_id) } }, select: { id: true, width: true, height: true, renderedSeq: true, developSnapshot: true }, @@ -619,6 +635,20 @@ export async function registerArchiveViewerRoutes( people: named.map((p) => ({ id: p.id, name: p.name, count: Number(p.count), face: faceOf.get(p.id) ?? null })), /** Everyone named in this game, so a gallery can offer them even when this part has only some. */ roster: roster.map((p) => ({ id: p.id, name: p.name, club: p.club, number: p.number, here: Number(p.here), inGame: Number(p.in_game) })), + videoTotal: folder.videoCount, + videos: videos.map((x) => ({ + id: x.id, + name: x.path.split("/").pop(), + durationMs: x.durationMs, + width: x.width, + height: x.height, + capturedAt: x.capturedAt, + thumb: signer.videoUrl(x.id, "thumb"), + poster: signer.videoUrl(x.id, "poster"), + src: signer.videoUrl(x.id, "web"), + download: signer.videoUrl(x.id, "download"), + ...(onCloud && { cloudUrl: `${base}/f/${x.fileId}` }), + })), photos: files.map((f) => ({ id: f.photo!.id, name: f.path.split("/").pop(), @@ -648,6 +678,29 @@ export async function registerArchiveViewerRoutes( return { id: file.photo.id, faces: faces.get(file.photo.id) ?? [] }; }); + /** + * A video's files by signed URL (`