diff --git a/apps/app/src/i18n.ts b/apps/app/src/i18n.ts index 6daf8ef..6690982 100644 --- a/apps/app/src/i18n.ts +++ b/apps/app/src/i18n.ts @@ -423,6 +423,7 @@ export const t = { }, uploading: (done: number, total: number) => `A enviar ${done} de ${total}`, uploaded: (n: number) => (n === 1 ? "1 foto enviada" : `${n} fotos enviadas`), + sendingOriginals: (n: number) => (n === 1 ? "A enviar 1 original desta máquina" : `A enviar ${n} originais desta máquina`), uploadFailed: (n: number) => `${n} com erro`, dismiss: "Fechar", useEmbeddedTitle: "Usar o Title como jogadores", @@ -605,6 +606,7 @@ export const t = { copied: "Copiado", deliveryErrors: { waiting_for_original: "À espera do original (está no computador do fotógrafo; abre a app PhotoReport nesse computador)", + waiting_for_original_here: "A pedir o original desta máquina…", original_not_here: "O original nunca chegou do computador do fotógrafo", }, deliveryStatus: { QUEUED: "Na fila", RUNNING: "A enviar", WAITING: "À espera do computador", DONE: "Entregue", FAILED: "Falhou", RETRACTED: "Retirada" }, diff --git a/apps/app/src/library/LocalFtp.tsx b/apps/app/src/library/LocalFtp.tsx index ff0fac1..d15d516 100644 --- a/apps/app/src/library/LocalFtp.tsx +++ b/apps/app/src/library/LocalFtp.tsx @@ -62,7 +62,7 @@ const IN_FLIGHT = 6; * Full originals are read through the webview as well. Several at once freeze it, a chunk sits until the access * token expires, and the server answers 401. Two leaves room for the upload to leave. */ -const IN_FLIGHT_ORIGINALS = 2; +const IN_FLIGHT_ORIGINALS = 3; /** * Originals on the wire at once. One waits out each detection and each server reply, so a full card sits in * ingest while the link is idle. This matches the upload queue. The slot stays held until that file has left, diff --git a/apps/app/src/library/TransferBar.tsx b/apps/app/src/library/TransferBar.tsx new file mode 100644 index 0000000..9c71c4f --- /dev/null +++ b/apps/app/src/library/TransferBar.tsx @@ -0,0 +1,53 @@ +import { useSyncExternalStore } from "react"; +import { t } from "../i18n.js"; +import { useIngest } from "./ingest.js"; + +/** + * Thin transfer strip (Photo Mechanic–style): always at the bottom of the workspace while JPEGs or + * originals are leaving this computer — not only on the library page. + */ +export function TransferBar() { + const { uploads, originals } = useIngest(); + const originalFlight = useSyncExternalStore( + (fn) => originals?.subscribe(fn) ?? (() => {}), + () => originals?.inFlight.size ?? 0, + () => 0, + ); + const sending = uploads.items.filter((i) => i.status === "queued" || i.status === "uploading"); + const failed = uploads.items.filter((i) => i.status === "failed"); + const sentCount = uploads.items.filter((i) => i.status === "done" || i.status === "duplicate").length; + const overall = uploads.items.length ? uploads.items.reduce((sum, i) => sum + (i.status === "failed" ? 1 : i.progress), 0) / uploads.items.length : 0; + const busy = sending.length > 0 || originalFlight > 0; + if (!busy && uploads.items.length === 0) return null; + + const label = (() => { + if (sending.length) return t.uploading(sentCount, uploads.items.length); + if (originalFlight > 0) return t.sendingOriginals(originalFlight); + return t.uploaded(sentCount); + })(); + + const pct = sending.length || uploads.items.length ? Math.round(overall * 100) : originalFlight > 0 ? 50 : 100; + + return ( +
+ + {label} + {failed.length > 0 && · {t.uploadFailed(failed.length)}} + {originalFlight > 0 && sending.length > 0 && · {t.sendingOriginals(originalFlight)}} + + + 0 && !sending.length ? "animate-pulse" : ""}`} style={{ width: `${pct}%` }} /> + + {failed.length > 0 && ( + `${f.name}: ${f.error}`).join("\n")}> + {failed[0]?.name}: {failed[0]?.error} + + )} + {!sending.length && uploads.items.length > 0 && ( + + )} +
+ ); +} diff --git a/apps/app/src/library/ingest.tsx b/apps/app/src/library/ingest.tsx index 65eb06e..d145a0a 100644 --- a/apps/app/src/library/ingest.tsx +++ b/apps/app/src/library/ingest.tsx @@ -1,9 +1,9 @@ -import type { LibraryMessage } from "@photoreport/contracts"; import type { PhotoSummary } from "@photoreport/contracts"; -import { createContext, type ReactNode, useCallback, useContext, useEffect, useRef } from "react"; +import { createContext, type ReactNode, useContext, useEffect, useMemo } from "react"; import { useAuth } from "../auth.js"; -import { isDesktop, localOriginal, localOriginalChanged } from "../platform.js"; +import { isDesktop, localOriginal } from "../platform.js"; import { useLocalFtp } from "./LocalFtp.js"; +import { OriginalSender } from "./originals.js"; import { useLibraryLive } from "./realtime.js"; import { useUploadQueue } from "./uploads.js"; import { useOfflineSync } from "../offline/sync.js"; @@ -14,6 +14,8 @@ type Ingest = { localFtp: ReturnType; usb: ReturnType; desktop: boolean; + /** Desktop only: pushes full originals for delivery / 100% zoom, off the JPEG upload queue. */ + originals: OriginalSender | null; }; const IngestContext = createContext(null); @@ -36,89 +38,36 @@ function IngestState({ api, orgId, children }: { api: ReturnType const uploads = useUploadQueue(api, orgId); const localFtp = useLocalFtp(uploads.add, desktop && !!orgId, undefined, orgId); const usb = useUsbCamera(uploads.add, desktop && !!orgId, localFtp.target); + const originals = useMemo(() => (desktop && orgId ? new OriginalSender(api) : null), [api, desktop, orgId]); useOfflineSync(api, orgId); return ( - - {desktop && !!orgId && } + + {desktop && !!orgId && originals && } {desktop && !!orgId && } {children} ); } -/** Several megabytes through IPC. Dozens at once freeze the webview on "A enviar…" and the send never finishes. */ -const ORIGINAL_IPC_MS = 45_000; -/** A few at a time: one is slow, all of them freeze the bar. */ -const MAX_PARALLEL_ORIGINALS = 3; - -function withTimeout(work: Promise, ms: number): Promise { - return new Promise((resolve) => { - let settled = false; - const finish = (value: T | "timeout" | null) => { - if (settled) return; - settled = true; - clearTimeout(timer); - resolve(value); - }; - const timer = setTimeout(() => finish("timeout"), ms); - work.then( - (value) => finish(value), - () => finish(null), - ); - }); -} - /** - * Desktop app: when someone needs the full original of a photo this computer keeps (100% zoom on the web, an export - * made on the server, delivery to ZeroZero), the server asks over the live channel and this sends it. - * Up to three at a time, so the webview stays responsive and the next ask can run. + * Desktop: when delivery (or 100% zoom) needs a full original kept here, send it on its own track — never + * through the JPEG upload queue, so new shots keep leaving and one stuck file does not block the rest. */ -function OriginalResponder({ api, add }: { api: ReturnType["api"]; add: ReturnType["add"] }) { - const sending = useRef(new Set()); - const queue = useRef<{ sha256: string; photoId: string }[]>([]); - const active = useRef(0); - - const pump = useCallback(() => { - while (active.current < MAX_PARALLEL_ORIGINALS) { - const next = queue.current.shift(); - if (!next) return; - active.current += 1; - const release = () => { - sending.current.delete(next.sha256); - active.current -= 1; - pump(); - }; - void (async () => { - const bytes = await withTimeout(localOriginal(next.sha256), ORIGINAL_IPC_MS); - if (bytes && bytes !== "timeout") { - add([new File([bytes], `${next.sha256}.jpg`, { type: "image/jpeg" })], undefined, () => release()); - return; - } - if (bytes !== "timeout") { - // The file is still here but changed since it arrived (Photo Mechanic wrote captions into it): sent as this - // photo's original, which the server checks is the same photo. - try { - const changed = await withTimeout(localOriginalChanged(next.sha256), ORIGINAL_IPC_MS); - if (changed && changed !== "timeout") await api.sendOriginal(next.photoId, new Blob([changed], { type: "image/jpeg" }), `${next.sha256}.jpg`); - } catch { - /* not the same photo, or offline: asked again later */ - } - } - release(); - })(); - } - }, [add, api]); - - const onMessage = useCallback( - (m: LibraryMessage) => { - if (m.type !== "original.requested" || sending.current.has(m.sha256)) return; - sending.current.add(m.sha256); - queue.current.push({ sha256: m.sha256, photoId: m.photoId }); - pump(); - }, - [pump], - ); - useLibraryLive(api, onMessage); +function OriginalResponder({ + api, + orgId, + sender, +}: { + api: ReturnType["api"]; + orgId: string; + sender: OriginalSender; +}) { + useLibraryLive(api, (m) => sender.onMessage(m)); + useEffect(() => { + void sender.flushWaiting(orgId); + const timer = setInterval(() => void sender.flushWaiting(orgId), 45_000); + return () => clearInterval(timer); + }, [sender, orgId]); return null; } diff --git a/apps/app/src/library/originals.test.ts b/apps/app/src/library/originals.test.ts new file mode 100644 index 0000000..ac63cd9 --- /dev/null +++ b/apps/app/src/library/originals.test.ts @@ -0,0 +1,42 @@ +import { describe, expect, it, vi } from "vitest"; +import { OriginalSender } from "./originals.js"; + +describe("OriginalSender", () => { + it("does not put the same sha on the queue twice", () => { + const api = { + sendOriginal: vi.fn(async () => ({ stored: true })), + requestOriginal: vi.fn(async () => ({ stored: false })), + listDeliveries: vi.fn(async () => ({ items: [] })), + }; + const sender = new OriginalSender(api as never); + sender.enqueue({ photoId: "p1", sha256: "abc" }); + sender.enqueue({ photoId: "p1", sha256: "abc" }); + expect(sender.inFlight.size).toBeLessThanOrEqual(1); + }); + + it("asks the server for originals when a delivery is waiting", () => { + const api = { + sendOriginal: vi.fn(async () => ({ stored: true })), + requestOriginal: vi.fn(async () => ({ stored: false })), + listDeliveries: vi.fn(async () => ({ items: [] })), + }; + const sender = new OriginalSender(api as never); + sender.onMessage({ + type: "delivery.updated", + item: { + id: "i1", + targetId: "t1", + photoId: "p1", + eventId: "e1", + sequence: 1, + status: "QUEUED", + attempts: 0, + lastError: "waiting_for_original", + remotePath: null, + byteSize: null, + updatedAt: "", + }, + }); + expect(api.requestOriginal).toHaveBeenCalledWith("p1"); + }); +}); diff --git a/apps/app/src/library/originals.ts b/apps/app/src/library/originals.ts new file mode 100644 index 0000000..7e32d82 --- /dev/null +++ b/apps/app/src/library/originals.ts @@ -0,0 +1,126 @@ +import type { LibraryMessage } from "@photoreport/contracts"; +import type { ApiClient } from "@photoreport/sdk"; +import { localOriginal, localOriginalChanged, prefs } from "../platform.js"; + +/** Several megabytes through IPC. Dozens at once freeze the webview; one slow disk must not kill the rest. */ +const ORIGINAL_IPC_MS = 90_000; + +const PREF_PARALLEL = "originals.parallel"; + +/** How many full originals leave this computer at once (delivery / 100% zoom). Default 4, clamp 2..8. */ +export function originalsParallel(): number { + const n = Number(prefs.get(PREF_PARALLEL)); + if (Number.isFinite(n) && n >= 2 && n <= 8) return Math.floor(n); + return 4; +} + +function withTimeout(work: Promise, ms: number): Promise { + return new Promise((resolve) => { + let settled = false; + const finish = (value: T | "timeout" | null) => { + if (settled) return; + settled = true; + clearTimeout(timer); + resolve(value); + }; + const timer = setTimeout(() => finish("timeout"), ms); + work.then( + (value) => finish(value), + () => finish(null), + ); + }); +} + +export type OriginalNeed = { photoId: string; sha256: string }; + +/** + * Sends originals this computer still has, on their own path (`POST /original`), never through the JPEG + * upload queue. New shots keep uploading in parallel; one stuck original does not block the others. + */ +export class OriginalSender { + private readonly sending = new Set(); + private readonly queue: OriginalNeed[] = []; + private active = 0; + /** photoIds this machine is currently pushing — Destinos shows "a enviar…" instead of "abre a app". */ + readonly inFlight = new Set(); + private readonly listeners = new Set<() => void>(); + + constructor(private readonly api: ApiClient) {} + + subscribe(fn: () => void): () => void { + this.listeners.add(fn); + return () => this.listeners.delete(fn); + } + + private changed(): void { + for (const fn of this.listeners) fn(); + } + + /** From the live channel, or a Destinos row that is waiting for the file on this Mac. */ + enqueue(need: OriginalNeed): void { + if (this.sending.has(need.sha256)) return; + this.sending.add(need.sha256); + this.queue.push(need); + this.pump(); + } + + onMessage(m: LibraryMessage): void { + if (m.type === "original.requested") { + this.enqueue({ photoId: m.photoId, sha256: m.sha256 }); + return; + } + // Delivery is blocked on the original we keep: push it at once (do not wait for the next 60 s ask). + if (m.type === "delivery.updated" && m.item.lastError === "waiting_for_original") { + void this.api.requestOriginal(m.item.photoId).catch(() => {}); + } + } + + /** + * Destinos / start: every queued row still waiting for an original — ask the server (it broadcasts sha256) + * so we send what we have without the photographer clicking Retry. + */ + async flushWaiting(orgId: string): Promise { + try { + const { items } = await this.api.listDeliveries(orgId, { status: "QUEUED" }); + for (const item of items) { + if (item.lastError !== "waiting_for_original") continue; + void this.api.requestOriginal(item.photoId).catch(() => {}); + } + } catch { + /* offline: live channel will ask again */ + } + } + + private pump(): void { + const room = originalsParallel(); + while (this.active < room) { + const next = this.queue.shift(); + if (!next) return; + this.active += 1; + this.inFlight.add(next.photoId); + this.changed(); + void this.sendOne(next).finally(() => { + this.sending.delete(next.sha256); + this.inFlight.delete(next.photoId); + this.active -= 1; + this.changed(); + this.pump(); + }); + } + } + + private async sendOne(need: OriginalNeed): Promise { + const exact = await withTimeout(localOriginal(need.sha256), ORIGINAL_IPC_MS); + let bytes: ArrayBuffer | null = exact && exact !== "timeout" ? exact : null; + if (!bytes) { + const changed = await withTimeout(localOriginalChanged(need.sha256), ORIGINAL_IPC_MS); + bytes = changed && changed !== "timeout" ? changed : null; + } + if (!bytes) return; + try { + await this.api.sendOriginal(need.photoId, new Blob([bytes], { type: "image/jpeg" }), `${need.sha256}.jpg`); + } catch { + /* offline / not the same photo: server asks again */ + } + } +} diff --git a/apps/app/src/library/uploads.ts b/apps/app/src/library/uploads.ts index 095b81a..ebbf6be 100644 --- a/apps/app/src/library/uploads.ts +++ b/apps/app/src/library/uploads.ts @@ -2,6 +2,7 @@ import type { PhotoSummary } from "@photoreport/contracts"; import { ApiError, type ApiClient } from "@photoreport/sdk"; import { isNetworkError, offlineQueue } from "../offline/queue.js"; import { useCallback, useRef, useState } from "react"; +import { prefs } from "../platform.js"; import { settleLocalUpload, showLocalJpeg } from "./localIngest.js"; export type UploadStatus = "queued" | "uploading" | "done" | "duplicate" | "failed"; @@ -15,7 +16,12 @@ export interface UploadItem { error?: string | undefined; } -const CONCURRENCY = 4; +/** Parallel JPEG uploads. Pref `upload.concurrency` (3–8); default 4. One failure never holds the others. */ +function uploadConcurrency(): number { + const n = Number(prefs.get("upload.concurrency")); + if (Number.isFinite(n) && n >= 3 && n <= 8) return Math.floor(n); + return 4; +} const ACCEPTED = /\.jpe?g$/i; const CHUNK = 4 * 1024 * 1024; @@ -172,7 +178,7 @@ export function useUploadQueue(api: ApiClient, orgId: string) { }, []); const pump = useCallback(() => { - while (!paused.current && running.current < CONCURRENCY && queue.current.length) { + while (!paused.current && running.current < uploadConcurrency() && queue.current.length) { const next = queue.current.shift()!; running.current++; void (async () => { diff --git a/apps/app/src/pages/DeliveryPage.tsx b/apps/app/src/pages/DeliveryPage.tsx index 16558da..ce1db41 100644 --- a/apps/app/src/pages/DeliveryPage.tsx +++ b/apps/app/src/pages/DeliveryPage.tsx @@ -122,7 +122,13 @@ export function DeliveryPage() { {i.sequence} {i.remotePath ?? —} - {i.lastError && {t.deliveryErrors[i.lastError as keyof typeof t.deliveryErrors] ?? i.lastError}} + {i.lastError && ( + + {i.lastError === "waiting_for_original" && isDesktop() + ? t.deliveryErrors.waiting_for_original_here + : (t.deliveryErrors[i.lastError as keyof typeof t.deliveryErrors] ?? i.lastError)} + + )} {t.deliveryStatus[i.status]} diff --git a/apps/app/src/pages/LibraryPage.tsx b/apps/app/src/pages/LibraryPage.tsx index 5cd4b15..4daf277 100644 --- a/apps/app/src/pages/LibraryPage.tsx +++ b/apps/app/src/pages/LibraryPage.tsx @@ -321,11 +321,6 @@ export function LibraryPage() { const games = openEvent && !events.some((event) => event.id === openEvent.id) ? [openEvent, ...events] : events; syncGames(games); }, [events, openEvent, syncGames]); - const sending = uploads.items.filter((i) => i.status === "queued" || i.status === "uploading"); - const failed = uploads.items.filter((i) => i.status === "failed"); - const sentCount = uploads.items.filter((i) => i.status === "done" || i.status === "duplicate").length; - const overall = uploads.items.length ? uploads.items.reduce((sum, i) => sum + (i.status === "failed" ? 1 : i.progress), 0) / uploads.items.length : 0; - const playerIds = useMemo(() => photoIdsOf(players), [players]); const visible = useMemo(() => state.photos.filter((p) => matchesFilter(p, filter) && (playerIds === null || playerIds.has(p.id))), [state.photos, filter, playerIds]); const selectedPlayerIds = useMemo(() => players.map((p) => p.id), [players]); @@ -774,23 +769,6 @@ export function LibraryPage() { )} - {uploads.items.length > 0 && ( -
- - {sending.length ? t.uploading(sentCount, uploads.items.length) : t.uploaded(sentCount)} - {failed.length > 0 && · {t.uploadFailed(failed.length)}} - - - - - {failed.length > 0 && `${f.name}: ${f.error}`).join("\n")}>{failed[0]?.name}: {failed[0]?.error}} - {!sending.length && ( - - )} -
- )} {desktop && }
{t.shortcuts}
diff --git a/apps/app/src/pages/Shell.tsx b/apps/app/src/pages/Shell.tsx index fb7475d..012cc4c 100644 --- a/apps/app/src/pages/Shell.tsx +++ b/apps/app/src/pages/Shell.tsx @@ -8,6 +8,7 @@ import { LocalDeliveries } from "../desktop/localDeliveries.js"; import { UiReadyNotice, UpdateNotice } from "../desktop/UpdateNotice.js"; import { FolderScanProvider } from "../library/folderScan.js"; import { IngestProvider } from "../library/ingest.js"; +import { TransferBar } from "../library/TransferBar.js"; const moduleClass = ({ isActive }: { isActive: boolean }) => `px-3 py-1 font-display text-[19px] max-sm:px-2 max-sm:text-[15px] font-semibold uppercase tracking-wide transition-colors ${ @@ -141,13 +142,14 @@ export function Shell() { -
- + +
- -
+
+ + ); }