diff --git a/apps/api/src/delivery/transports.ts b/apps/api/src/delivery/transports.ts index 7976365..cfefa06 100644 --- a/apps/api/src/delivery/transports.ts +++ b/apps/api/src/delivery/transports.ts @@ -175,6 +175,7 @@ export class ZerozeroTransport implements Transport { const account = await this.client.login(); const author = meta?.author?.trim() || account.name || "PhotoReport"; const imageId = await this.client.upload(gameId, fileName, data, author); + await this.client.publish(gameId, imageId); return `${gameId}/${imageId}`; }); } diff --git a/apps/api/src/delivery/zerozero.test.ts b/apps/api/src/delivery/zerozero.test.ts index fb93030..f8bd6ae 100644 --- a/apps/api/src/delivery/zerozero.test.ts +++ b/apps/api/src/delivery/zerozero.test.ts @@ -1,6 +1,45 @@ import { describe, expect, it } from "vitest"; +import { TransportError } from "./transports.js"; import { ZerozeroClient } from "./zerozero.js"; +/** + * A desk that is already willing to sign the client in, and answers photo-sync however the test says. + * Login is the real OAuth dance; only the publish routes vary. + */ +function desk(publish: (pathname: string) => Response): typeof fetch { + return async (input, init) => { + const url = new URL(String(input)); + const method = init?.method ?? "GET"; + const cookie = new Headers(init?.headers).get("cookie") ?? ""; + const has = (name: string) => cookie.split(/;\s*/).some((part) => part.startsWith(`${name}=`)); + if (url.hostname === "www.zerozero.pt" && url.pathname === "/oauth.php") { + if (has("zzuser")) { + return new Response(null, { + status: 302, + headers: { location: "https://fotos.zerozero.pt/api/auth/callback?code=c&state=s" }, + }); + } + return new Response("login", { status: 200, headers: { "set-cookie": "PHPSESSID=s; Domain=.zerozero.pt" } }); + } + if (url.hostname === "www.zerozero.pt" && url.pathname === "/ax_login.php" && method === "POST") { + return new Response(JSON.stringify({ status: true }), { headers: { "set-cookie": "zzuser=1; Domain=.zerozero.pt" } }); + } + if (url.pathname === "/api/auth/login") { + return Response.json({ authURL: "https://www.zerozero.pt/oauth.php?response_type=code&state=s" }); + } + if (url.pathname === "/api/auth/callback") { + return new Response(null, { status: 302, headers: { location: "https://fotos.zerozero.pt/", "set-cookie": "desk=ok; Path=/" } }); + } + if (url.pathname === "/api/auth/me") { + if (!has("desk")) return Response.json({ error: "unauthorized" }, { status: 401 }); + return Response.json({ role: "photographer", photographer_name: "Kapta+" }); + } + if (url.pathname === "/") return new Response("desk", { status: 200 }); + if (method === "POST" && url.pathname.startsWith("/api/photo-sync/")) return publish(url.pathname); + return new Response("no", { status: 404 }); + }; +} + describe("zerozero remove", () => { it("never asks the desk to delete a \"synced-\" placeholder (a real image is taken back: test/delivery.test.ts)", async () => { const calls: string[] = []; @@ -14,3 +53,91 @@ describe("zerozero remove", () => { expect(calls).toEqual([]); }); }); + +describe("zerozero publish", () => { + it("publishes the one photo that was just uploaded", async () => { + const calls: string[] = []; + const client = new ZerozeroClient( + { username: "kapta", password: "zz-pass" }, + desk((pathname) => { + calls.push(pathname); + return Response.json({ synced: 1, failed: 0, failures: [] }); + }), + ); + await client.publish("12627743", "img-9"); + expect(calls).toEqual(["/api/photo-sync/img-9"]); + }); + + it("publishes the game when the account cannot publish one photo", async () => { + const calls: string[] = []; + const client = new ZerozeroClient( + { username: "kapta", password: "zz-pass" }, + desk((pathname) => { + calls.push(pathname); + if (pathname.startsWith("/api/photo-sync/match/")) return Response.json({ synced: 1, failed: 0, failures: [] }); + return Response.json({ error: "forbidden" }, { status: 403 }); + }), + ); + await client.publish("12627743", "img-9"); + expect(calls).toEqual(["/api/photo-sync/img-9", "/api/photo-sync/match/12627743"]); + }); + + it("publishes the whole game when the desk has no single-photo publish", async () => { + const calls: string[] = []; + const client = new ZerozeroClient( + { username: "kapta", password: "zz-pass" }, + desk((pathname) => { + calls.push(pathname); + if (pathname === "/api/photo-sync/match/12627743") return Response.json({ synced: 1, failed: 0, failures: [] }); + return new Response("missing", { status: 404 }); + }), + ); + await client.publish("12627743", "img-9"); + expect(calls).toEqual(["/api/photo-sync/img-9", "/api/photo-sync/match/12627743"]); + }); + + it("publishes the game when the desk already had the file and there is no image id", async () => { + const calls: string[] = []; + const client = new ZerozeroClient( + { username: "kapta", password: "zz-pass" }, + desk((pathname) => { + calls.push(pathname); + return Response.json({ synced: 0, failed: 0, failures: [] }); + }), + ); + await client.publish("12627743", "synced-PS_jogo_1.jpg"); + expect(calls).toEqual(["/api/photo-sync/match/12627743"]); + }); + + it("retries when the desk reports that this photo did not publish", async () => { + const client = new ZerozeroClient( + { username: "kapta", password: "zz-pass" }, + desk(() => Response.json({ synced: 0, failed: 1, failures: [{ id: "img-9", error: "desk busy" }] })), + ); + const err = await client.publish("12627743", "img-9").then( + () => null, + (error: unknown) => error, + ); + expect(err).toBeInstanceOf(TransportError); + expect((err as TransportError).message).toBe("zerozero publish: desk busy"); + expect((err as TransportError).transient).toBe(true); + }); + + it("does not retry when neither publish route accepts the account", async () => { + const calls: string[] = []; + const client = new ZerozeroClient( + { username: "kapta", password: "zz-pass" }, + desk((pathname) => { + calls.push(pathname); + return Response.json({ error: "forbidden" }, { status: 403 }); + }), + ); + const err = await client.publish("12627743", "img-9").then( + () => null, + (error: unknown) => error, + ); + expect(err).toBeInstanceOf(TransportError); + expect((err as TransportError).transient).toBe(false); + expect(calls).toEqual(["/api/photo-sync/img-9", "/api/photo-sync/match/12627743"]); + }); +}); diff --git a/apps/api/src/delivery/zerozero.ts b/apps/api/src/delivery/zerozero.ts index 23bd884..8b6d73b 100644 --- a/apps/api/src/delivery/zerozero.ts +++ b/apps/api/src/delivery/zerozero.ts @@ -11,12 +11,16 @@ import { TransportError } from "./transports.js"; * Lisbon time). * - Upload: tus 1.0 at `/api/upload?match_id=`, metadata `match_id`, `artist` (the author shown with the photo) * and the file name. The image's id is the upload's id; `DELETE /api/images/` takes it back. + * - Publish: the upload only lands on the desk. The public game shows it after `POST /api/photo-sync/` + * (the desk's "send now"). When that route is missing, `POST /api/photo-sync/match/` publishes the game. */ export const ZEROZERO_URL = "https://fotos.zerozero.pt"; const LOGIN_SITE = "https://www.zerozero.pt"; const CHUNK = 5 * 1024 * 1024; const TIMEOUT_MS = 60_000; +/** Publishing pushes the file onwards to the public game, which is slower than one tus chunk. */ +const PUBLISH_TIMEOUT_MS = 180_000; export interface ZerozeroGame { id: string; @@ -104,7 +108,7 @@ export class ZerozeroClient { ) {} /** One request with the jar's cookies; redirects followed by hand so every hop's cookies are kept. */ - private async request(url: string, init: RequestInit = {}, hops = 10): Promise<{ res: Response; url: string }> { + private async request(url: string, init: RequestInit = {}, hops = 10, timeoutMs = TIMEOUT_MS): Promise<{ res: Response; url: string }> { let current = url; let options = init; for (let i = 0; i <= hops; i++) { @@ -114,7 +118,7 @@ export class ZerozeroClient { if (!headers.has("user-agent")) headers.set("user-agent", "PhotoReport/2 (delivery)"); let res: Response; try { - res = await this.fetchImpl(current, { ...options, headers, redirect: "manual", signal: AbortSignal.timeout(TIMEOUT_MS) }); + res = await this.fetchImpl(current, { ...options, headers, redirect: "manual", signal: AbortSignal.timeout(timeoutMs) }); } catch (err) { throw new TransportError(`zerozero: ${fetchFailure(err)}`, true); } @@ -263,6 +267,58 @@ export class ZerozeroClient { return new URL(url).pathname.split("/").filter(Boolean).pop()!; } + /** + * Puts an uploaded photo on the public game. The desk keeps it first (`sync_status` pending); without this call + * it never leaves the photographer's page. One photo when the desk allows it, otherwise the whole game. + * `synced-` is not an image id (the desk already had the file), so the game is published. + */ + async publish(gameId: string, imageId: string): Promise { + const placeholder = imageId.startsWith("synced-"); + if (!placeholder) { + const one = await this.postApi(`/photo-sync/${encodeURIComponent(imageId)}`, PUBLISH_TIMEOUT_MS); + // 404/405: this desk has no single-photo publish. 403: this account may still publish the game. + if (one.status !== 404 && one.status !== 405 && one.status !== 403) { + this.assertPublished(one, imageId); + return; + } + } + const match = await this.postApi(`/photo-sync/match/${encodeURIComponent(gameId)}`, PUBLISH_TIMEOUT_MS); + const ours = placeholder ? null : imageId; + this.assertPublished(match, ours); + } + + private async postApi(path: string, timeoutMs: number, retry = true): Promise<{ status: number; body: unknown }> { + await this.login(); + const { res } = await this.request(`${this.base}/api${path}`, { method: "POST" }, 10, timeoutMs); + if (res.status === 401 && retry) { + this.account = null; + this.jar.clear(); + return this.postApi(path, timeoutMs, false); + } + const text = await res.text(); + let body: unknown = null; + if (text) { + try { + body = JSON.parse(text) as unknown; + } catch { + body = null; + } + } + return { status: res.status, body }; + } + + private assertPublished(result: { status: number; body: unknown }, imageId: string | null): void { + if (result.status >= 200 && result.status < 300) { + assertSyncBody(result.body, imageId); + return; + } + const detail = errorText(result.body); + const transient = result.status >= 500 || result.status === 429 || result.status === 404; + let message = `zerozero publish: ${result.status}`; + if (detail) message = `${message} ${detail}`; + throw new TransportError(message, transient); + } + /** Takes an uploaded image back. Already gone (or no longer this account's to remove) is not an error. */ async remove(imageId: string): Promise { // "synced-" (from `upload`, when the desk already had the file) is not a real image id: there was @@ -275,6 +331,31 @@ export class ZerozeroClient { } } +function errorText(body: unknown): string | null { + if (!body || typeof body !== "object") return null; + const error = (body as { error?: unknown }).error; + if (typeof error !== "string" || !error) return null; + return error.replace(/\s+/g, " ").slice(0, 180); +} + +function assertSyncBody(body: unknown, imageId: string | null): void { + if (!body || typeof body !== "object") return; + const record = body as { sync_status?: unknown; syncStatus?: unknown; failures?: unknown; error?: unknown }; + const status = record.sync_status ?? record.syncStatus; + if (status === "failed") { + const message = typeof record.error === "string" && record.error ? record.error : "the desk could not publish the photo"; + throw new TransportError(`zerozero publish: ${message}`, true); + } + if (!imageId || !Array.isArray(record.failures)) return; + for (const failure of record.failures) { + if (!failure || typeof failure !== "object") continue; + const row = failure as { id?: unknown; error?: unknown }; + if (row.id !== imageId) continue; + const message = typeof row.error === "string" && row.error ? row.error : "the desk could not publish the photo"; + throw new TransportError(`zerozero publish: ${message}`, true); + } +} + function toGame(r: Record | null | undefined): ZerozeroGame | null { if (!r) return null; const s = (v: unknown) => (typeof v === "string" || typeof v === "number" ? String(v) : null); diff --git a/apps/api/test/delivery.test.ts b/apps/api/test/delivery.test.ts index 599bd26..3eb0c97 100644 --- a/apps/api/test/delivery.test.ts +++ b/apps/api/test/delivery.test.ts @@ -75,6 +75,8 @@ class FakeNextcloud { class FakeZerozero { logins = 0; removed: string[] = []; + /** Paths of POST /api/photo-sync/… after each upload (the public game, not only the desk). */ + syncs: string[] = []; uploads = new Map; data: Buffer; length: number }>(); password = "zz-pass"; @@ -129,6 +131,10 @@ class FakeZerozero { this.uploads.set(id, { gameId: url.searchParams.get("match_id")!, meta, data: Buffer.alloc(0), length: Number(h.get("upload-length")) }); return new Response(null, { status: 201, headers: { location: `/upload/${id}` } }); } + if (method === "POST" && url.pathname.startsWith("/api/photo-sync/")) { + this.syncs.push(url.pathname); + return Response.json({ synced: 1, failed: 0, failures: [] }); + } const gone = /^\/api\/images\/(.+)$/.exec(url.pathname); if (gone && method === "DELETE") { this.removed.push(gone[1]!); @@ -622,6 +628,8 @@ describe("delivery", () => { expect(first.meta).toMatchObject({ match_id: "12627747", artist: "Peter Spark / Kapta+", filename: "PS_SC Torreense x Sunderland_1.jpg", filetype: "image/jpeg" }); expect(first.data.length).toBe(first.length); expect((await sharp(first.data).metadata()).width).toBe(3000); + // The desk upload is not the public game: each photo is published there before the delivery is done. + expect(zz.syncs).toEqual(["/api/photo-sync/img-1", "/api/photo-sync/img-2"]); // Signed in once for the whole batch. expect(zz.logins).toBe(1); @@ -644,6 +652,7 @@ describe("delivery", () => { expect(zz.removed).toEqual([itemA.remotePath!.split("/")[1]]); // Same name ({n} kept), shown once in the game. expect(zz.uploads.get(resent.remotePath!.split("/")[1]!)!.meta.filename).toBe(zz.uploads.get(itemA.remotePath!.split("/")[1]!)!.meta.filename); + expect(zz.syncs.at(-1)).toBe(`/api/photo-sync/${resent.remotePath!.split("/")[1]}`); expect(await delivery.queueEdited()).toBe(0); // A reject that bypassed the library PATCH (flag flipped in the DB) is still taken back on the next sweep. diff --git a/docs/ARCHITECTURE.md b/docs/ARCHITECTURE.md index 8188760..e61d090 100644 --- a/docs/ARCHITECTURE.md +++ b/docs/ARCHITECTURE.md @@ -474,9 +474,12 @@ The same queue also delivers to SFTP, FTP/FTPS and Dropbox (`delivery/transports - **ZeroZero** (`fotos.zerozero.pt`, `delivery/zerozero.ts`): the photographer's zerozero.pt account. The server signs in through zerozero.pt's OAuth (`/api/auth/login` → `oauth.php` → `ax_login.php` → `/api/auth/callback`, cookies kept in a small jar), and uploads with tus to `/api/upload?match_id=` with the file name and the - author (`artist`: the photographer's name from the IPTC creator). The "folder" is the game: chosen for the - event by pasting the game's link (kept in `events.zerozero_game_id`), or found among the desk's upcoming games - by both teams and kick-off within 3 hours. The delivered item's remote path is `/` + author (`artist`: the photographer's name from the IPTC creator). The upload only reaches the photographer's + desk. The public game shows the photo after publish: `POST /api/photo-sync/`, or + `POST /api/photo-sync/match/` when the desk has no single-image publish (the same call as + "Sincronizar com zerozero"). A delivery is done only after that call succeeds. The "folder" is the game: + chosen for the event by pasting the game's link (kept in `events.zerozero_game_id`), or found among the desk's + upcoming games by both teams and kick-off within 3 hours. The delivered item's remote path is `/` (`DELETE /api/images/` takes it back). Each target also has Photo Mechanic's uploader output options: fit-in-box size, JPEG quality, output