Compare commits
8
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
7c67a23cb9 | ||
|
|
3d407f5524 | ||
|
|
1e2a5b482e | ||
|
|
8d12e7c995 | ||
|
|
1702c290de | ||
|
|
03df893e34 | ||
|
|
d756d13d69 | ||
|
|
53d8194cd5 |
No files matched your search
@@ -0,0 +1,5 @@
|
||||
-- A delivered photo that is rejected or un-picked is taken back from the destination.
|
||||
-- PostgreSQL 12+ allows ADD VALUE inside a transaction as long as the new value is not used in the same one.
|
||||
ALTER TYPE "DeliveryStatus" ADD VALUE IF NOT EXISTS 'RETRACTED';
|
||||
|
||||
ALTER TABLE "delivery_items" ADD COLUMN "retract" BOOLEAN NOT NULL DEFAULT false;
|
||||
@@ -518,6 +518,8 @@ enum DeliveryStatus {
|
||||
WAITING
|
||||
DONE
|
||||
FAILED
|
||||
/// Taken back from the destination after the photo was rejected, un-picked, or cancelled before upload.
|
||||
RETRACTED
|
||||
}
|
||||
|
||||
/// Where a client's photos go, and how folders and files are named there (each client has its own rules).
|
||||
@@ -582,8 +584,10 @@ model DeliveryItem {
|
||||
remotePath String? @map("remote_path")
|
||||
/// The photo's edit (op-log sequence) the delivered file shows: edited again after it, it is sent again.
|
||||
deliveredSeq Int? @map("delivered_seq")
|
||||
/// Being sent again after an edit: where the previous version is (taken back on ZeroZero once the new one is up).
|
||||
/// Being sent again after an edit: where the previous version is (the old file is removed once the new one lands).
|
||||
replacesPath String? @map("replaces_path")
|
||||
/// Queued to be taken back from the destination (the photo was rejected or un-picked): the worker removes it.
|
||||
retract Boolean @default(false)
|
||||
byteSize Int? @map("byte_size")
|
||||
requestedById String? @map("requested_by_id") @db.Uuid
|
||||
nextAttemptAt DateTime @default(now()) @map("next_attempt_at")
|
||||
|
||||
@@ -78,6 +78,13 @@ export class NextcloudClient {
|
||||
if (res.status !== 201 && res.status !== 204) throw new NextcloudError(`PUT ${remoteFile} failed: ${res.status}`, res.status);
|
||||
}
|
||||
|
||||
/** Removes a file (idempotent: a missing file is not an error). */
|
||||
async remove(remoteFile: string): Promise<void> {
|
||||
const res = await this.call("DELETE", this.davUrl(remoteFile));
|
||||
// 204/200 removed, 404 already gone, 423 locked (worth a retry).
|
||||
if (res.status !== 204 && res.status !== 200 && res.status !== 404) throw new NextcloudError(`DELETE ${remoteFile} failed: ${res.status}`, res.status);
|
||||
}
|
||||
|
||||
/** Public, read-only link to a folder; reuses an existing link when there is one. */
|
||||
async shareLink(folder: string): Promise<string> {
|
||||
const base = this.auth.baseUrl.replace(/\/+$/, "");
|
||||
|
||||
@@ -58,6 +58,26 @@ export function deliveredName(photo: { originalName: string; fileName: string |
|
||||
/** Where a file rendered for a computer's folder waits on the server. */
|
||||
export const localKey = (orgId: string, itemId: string) => `${orgId}/deliveries/${itemId}.jpg`;
|
||||
|
||||
/**
|
||||
* Marks a photo's deliveries to be taken back (the photo was rejected or un-picked). Already on a destination
|
||||
* (DONE) or waiting for a computer (WAITING): queued for the worker to remove. Not uploaded yet (QUEUED):
|
||||
* cancelled outright. Returns how many are queued for removal.
|
||||
*/
|
||||
export async function retractPhotos(db: Db, organizationId: string, photoIds: string[]): Promise<number> {
|
||||
if (!photoIds.length) return 0;
|
||||
// Not uploaded yet: cancel, there is nothing on the destination to remove.
|
||||
await db.deliveryItem.updateMany({
|
||||
where: { organizationId, photoId: { in: photoIds }, status: "QUEUED", retract: false },
|
||||
data: { status: "RETRACTED", finishedAt: new Date() },
|
||||
});
|
||||
// Already delivered, or waiting for a computer to take it: the worker takes it back.
|
||||
const r = await db.deliveryItem.updateMany({
|
||||
where: { organizationId, photoId: { in: photoIds }, status: { in: ["DONE", "WAITING"] }, retract: false },
|
||||
data: { status: "QUEUED", retract: true, attempts: 0, nextAttemptAt: new Date(), lastError: null, finishedAt: null },
|
||||
});
|
||||
return r.count;
|
||||
}
|
||||
|
||||
export class DeliveryRejected extends Error {
|
||||
constructor(readonly code: string) {
|
||||
super(code);
|
||||
@@ -279,6 +299,28 @@ export class DeliveryService {
|
||||
async process(itemId: string): Promise<DeliveryItem> {
|
||||
const { db, storage, log } = this.deps;
|
||||
const item = await db.deliveryItem.findUniqueOrThrow({ where: { id: itemId }, include: { target: true, photo: { include: { uploader: { select: { name: true } } } }, event: true } });
|
||||
// Taking a delivery back: the photo was rejected or un-picked. Remove it from the destination (or drop the
|
||||
// copy still waiting on the server for a computer), never an upload.
|
||||
if (item.retract) {
|
||||
let retractUpdate: Partial<DeliveryItem>;
|
||||
try {
|
||||
if (item.target.kind === "LOCAL") await storage.remove(localKey(item.organizationId, item.id)).catch(() => {});
|
||||
else if (item.remotePath) await this.client(item.target).remove(item.remotePath);
|
||||
retractUpdate = { status: "RETRACTED", retract: false, remotePath: null, lastError: null, finishedAt: new Date() };
|
||||
log.info({ itemId, remotePath: item.remotePath }, "delivery: taken back from the destination");
|
||||
} catch (err) {
|
||||
const message = err instanceof Error ? err.message : String(err);
|
||||
const retry = !(err instanceof DeliveryRejected) && isTransient(err);
|
||||
retractUpdate =
|
||||
retry && item.attempts < MAX_ATTEMPTS
|
||||
? { status: "QUEUED", lastError: message, nextAttemptAt: new Date(Date.now() + backoffMs(item.attempts)) }
|
||||
: { status: "FAILED", retract: false, lastError: `retract: ${message}`, finishedAt: new Date() };
|
||||
log.warn({ itemId, attempt: item.attempts, error: message, final: retractUpdate.status === "FAILED" }, "delivery: retract failed");
|
||||
}
|
||||
const saved = await db.deliveryItem.update({ where: { id: itemId }, data: retractUpdate });
|
||||
this.deps.broadcaster.library(saved.organizationId, { type: "delivery.updated", item: toItemSummary(saved) });
|
||||
return saved;
|
||||
}
|
||||
let update: Partial<DeliveryItem>;
|
||||
// An archive photo: its original is read from the cloud it lives on.
|
||||
let cloud: { file: string; done: () => Promise<void> } | null = null;
|
||||
@@ -339,8 +381,10 @@ export class DeliveryService {
|
||||
// "synced-…" means the desk already had this file, so this attempt did not put a new image up.
|
||||
// Taking the previous one back here would remove the only copy (the new upload never landed).
|
||||
const alreadyThere = remotePath.includes("/synced-");
|
||||
if (!alreadyThere && item.replacesPath && item.replacesPath !== remotePath && client instanceof ZerozeroTransport) {
|
||||
await client.remove(item.replacesPath).catch((err) => log.warn({ err, itemId, previous: item.replacesPath }, "delivery: previous version not taken back"));
|
||||
// When the file lands at a new path (an edit changed the folder or name), remove the old one so no orphan is
|
||||
// left behind; on ZeroZero `alreadyThere` means the desk already had it, so there is nothing to take back.
|
||||
if (!alreadyThere && item.replacesPath && item.replacesPath !== remotePath) {
|
||||
await client.remove(item.replacesPath).catch((err) => log.warn({ err, itemId, previous: item.replacesPath }, "delivery: previous file not removed"));
|
||||
}
|
||||
const storedPath = alreadyThere && item.replacesPath ? item.replacesPath : remotePath;
|
||||
update = { status: "DONE", remotePath: storedPath, byteSize: data.length, lastError: null, finishedAt: new Date(), deliveredSeq: item.photo.developSeq, replacesPath: null };
|
||||
|
||||
@@ -25,6 +25,8 @@ export interface Transport {
|
||||
ensureFolder(folder: string): Promise<void>;
|
||||
/** Returns where the photo ended up when the service names it (an id), else nothing. */
|
||||
upload(remoteFile: string, data: Buffer, meta?: UploadMeta): Promise<void | string>;
|
||||
/** Takes a delivered file back (retraction, or replacing one at a changed path). Missing file is not an error. */
|
||||
remove(remotePath: string): Promise<void>;
|
||||
/** Public read-only link to a folder; undefined when the service has none. */
|
||||
shareLink?(folder: string): Promise<string>;
|
||||
/** Connects and checks the credentials; SFTP also reports the host key fingerprint. */
|
||||
@@ -128,6 +130,9 @@ class NextcloudTransport implements Transport {
|
||||
upload(remoteFile: string, data: Buffer) {
|
||||
return this.client.upload(remoteFile, data);
|
||||
}
|
||||
remove(remoteFile: string) {
|
||||
return this.client.remove(remoteFile);
|
||||
}
|
||||
shareLink(folder: string) {
|
||||
return this.client.shareLink(folder);
|
||||
}
|
||||
@@ -251,6 +256,18 @@ export class SftpTransport implements Transport {
|
||||
});
|
||||
}
|
||||
|
||||
remove(remoteFile: string): Promise<void> {
|
||||
return this.serial.run(async () => {
|
||||
const client = await this.connect();
|
||||
try {
|
||||
// noErrorOK: a file already gone is fine.
|
||||
await client.delete(remoteFile, true);
|
||||
} catch (err) {
|
||||
this.fail(err, `delete ${remoteFile}`);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
test(): Promise<{ fingerprint?: string }> {
|
||||
return this.serial.run(async () => {
|
||||
const client = await this.connect();
|
||||
@@ -329,6 +346,19 @@ export class FtpTransport implements Transport {
|
||||
});
|
||||
}
|
||||
|
||||
remove(remoteFile: string): Promise<void> {
|
||||
return this.serial.run(async () => {
|
||||
const client = await this.connect();
|
||||
try {
|
||||
await client.remove(remoteFile);
|
||||
} catch (err) {
|
||||
// 550: no such file — already gone, not an error.
|
||||
if ((err as { code?: number }).code === 550) return;
|
||||
this.fail(err, `delete ${remoteFile}`);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
test(): Promise<{ account?: string }> {
|
||||
return this.serial.run(async () => {
|
||||
const client = await this.connect();
|
||||
@@ -412,6 +442,16 @@ export class DropboxTransport implements Transport {
|
||||
});
|
||||
}
|
||||
|
||||
async remove(remoteFile: string): Promise<void> {
|
||||
try {
|
||||
await this.rpc("files/delete_v2", { path: remoteFile });
|
||||
} catch (err) {
|
||||
// Already gone is not an error.
|
||||
if (err instanceof TransportError && /not_found/.test(err.message)) return;
|
||||
throw err;
|
||||
}
|
||||
}
|
||||
|
||||
async shareLink(folder: string): Promise<string> {
|
||||
const path = folder.replace(/\/+$/, "");
|
||||
try {
|
||||
|
||||
@@ -14,6 +14,7 @@ import type { Broadcaster } from "../realtime.js";
|
||||
import type { LocalStorage, UrlSigner, Variant } from "../storage/storage.js";
|
||||
import { DEFAULT_CODE_LIST, iptcForPhoto } from "./iptc.js";
|
||||
import { photoInclude, toSummary } from "./serialize.js";
|
||||
import { retractPhotos } from "../delivery/service.js";
|
||||
|
||||
const OrgParams = z.object({ orgId: z.uuid() });
|
||||
const PhotoParams = z.object({ photoId: z.uuid() });
|
||||
@@ -102,8 +103,17 @@ export async function registerPhotoRoutes(
|
||||
if (patch.colorLabel !== undefined) data.colorLabel = patch.colorLabel;
|
||||
if (patch.players !== undefined) data.players = patch.players;
|
||||
if (patch.eventId !== undefined) data.eventId = patch.eventId;
|
||||
// A rejected or un-picked photo that was already delivered is taken back from its destinations. Un-pick is a
|
||||
// PICK -> NONE change, so the photos that are still PICK right now are the ones being un-picked (read first).
|
||||
const retractIds =
|
||||
patch.flag === "REJECT"
|
||||
? ids
|
||||
: patch.flag === "NONE"
|
||||
? (await db.photo.findMany({ where: { id: { in: ids }, organizationId: orgId, flag: "PICK" }, select: { id: true } })).map((p) => p.id)
|
||||
: [];
|
||||
const result = await db.photo.updateMany({ where: { id: { in: ids }, organizationId: orgId }, data });
|
||||
if (result.count !== ids.length) throw notFound("photo_not_found");
|
||||
if (retractIds.length) await retractPhotos(db, orgId, retractIds);
|
||||
// Moved to another event: arrival names, faces and the autopilot follow it.
|
||||
if (patch.eventId) await joinedEvent(db, patch.eventId, ids);
|
||||
broadcaster.library(orgId, { type: "photo.updated", ids, patch });
|
||||
|
||||
@@ -36,6 +36,8 @@ export function EventSettingsButton(props: {
|
||||
const [startsAt, setStartsAt] = useState(isoToLisbonLocal(event.startsAt));
|
||||
const [from, setFrom] = useState(isoToLisbonLocal(event.ingestFrom));
|
||||
const [to, setTo] = useState(isoToLisbonLocal(event.ingestUntil));
|
||||
const [homeShort, setHomeShort] = useState(event.homeShort ?? "");
|
||||
const [awayShort, setAwayShort] = useState(event.awayShort ?? "");
|
||||
const [people, setPeople] = useState<
|
||||
{ id: string; name: string; role: string }[]
|
||||
>([]);
|
||||
@@ -51,6 +53,8 @@ export function EventSettingsButton(props: {
|
||||
setFrom(isoToLisbonLocal(event.ingestFrom));
|
||||
setTo(isoToLisbonLocal(event.ingestUntil));
|
||||
setChosen(new Set(event.photographers.map((p) => p.id)));
|
||||
setHomeShort(event.homeShort ?? "");
|
||||
setAwayShort(event.awayShort ?? "");
|
||||
setConfirm(false);
|
||||
}, [event]);
|
||||
|
||||
@@ -105,6 +109,7 @@ export function EventSettingsButton(props: {
|
||||
ingestFrom: lisbonLocalToIso(from),
|
||||
ingestUntil: lisbonLocalToIso(to),
|
||||
photographerIds: [...chosen],
|
||||
...(event.away ? { homeShort: homeShort.trim() || null, awayShort: awayShort.trim() || null } : {}),
|
||||
}),
|
||||
);
|
||||
});
|
||||
@@ -219,6 +224,31 @@ export function EventSettingsButton(props: {
|
||||
/>
|
||||
</label>
|
||||
</div>
|
||||
{event.away && (
|
||||
/* Siglas curtas para as pastas de entrega (ex.: CDE x CDF); vazio usa o nome completo. Labels inline: i18n.ts por agora noutra branch. */
|
||||
<div className="grid grid-cols-2 gap-2">
|
||||
<label className="block">
|
||||
<span className="text-faint">Sigla casa</span>
|
||||
<input
|
||||
value={homeShort}
|
||||
onChange={(e) => setHomeShort(e.target.value)}
|
||||
placeholder={event.home}
|
||||
maxLength={20}
|
||||
className={input}
|
||||
/>
|
||||
</label>
|
||||
<label className="block">
|
||||
<span className="text-faint">Sigla visitante</span>
|
||||
<input
|
||||
value={awayShort}
|
||||
onChange={(e) => setAwayShort(e.target.value)}
|
||||
placeholder={event.away}
|
||||
maxLength={20}
|
||||
className={input}
|
||||
/>
|
||||
</label>
|
||||
</div>
|
||||
)}
|
||||
<fieldset className="space-y-1">
|
||||
<legend className="text-faint">{L.photographers}</legend>
|
||||
{people.map((p) => (
|
||||
|
||||
@@ -31,6 +31,8 @@ const Cell = memo(function Cell({ photo, index, src, selected, focused, onPick,
|
||||
const label = LABEL_COLOR[photo.colorLabel];
|
||||
// Desktop app: thumbnails are kept on the computer, so the grid shows without a network.
|
||||
const shown = useCachedImage(src, isDesktop());
|
||||
const [imgFailed, setImgFailed] = useState(false);
|
||||
useEffect(() => setImgFailed(false), [shown]);
|
||||
return (
|
||||
<button
|
||||
ref={ref}
|
||||
@@ -49,7 +51,13 @@ const Cell = memo(function Cell({ photo, index, src, selected, focused, onPick,
|
||||
</span>
|
||||
<span className="flex min-h-0 w-full flex-1 items-center justify-center">
|
||||
{photo.status === "READY" ? (
|
||||
shown && <img src={shown} alt="" loading="lazy" decoding="async" draggable={false} className="max-h-full max-w-full object-contain shadow-[0_1px_3px_rgba(0,0,0,0.6)]" />
|
||||
imgFailed ? (
|
||||
<span className="font-mono text-[10px] uppercase text-faint">erro</span>
|
||||
) : shown ? (
|
||||
<img src={shown} onError={() => setImgFailed(true)} alt="" loading="lazy" decoding="async" draggable={false} className="max-h-full max-w-full object-contain shadow-[0_1px_3px_rgba(0,0,0,0.6)]" />
|
||||
) : (
|
||||
<span className="font-mono text-[10px] uppercase text-faint">…</span>
|
||||
)
|
||||
) : (
|
||||
<span className="font-mono text-[10px] uppercase text-faint">{photo.status === "FAILED" ? "erro" : "…"}</span>
|
||||
)}
|
||||
|
||||
@@ -10,25 +10,51 @@ import { ZerozeroGamePicker } from "./ZerozeroGame.js";
|
||||
const LAST_TARGET = "deliver.target";
|
||||
const BEST_COUNT = "deliver.bestCount";
|
||||
|
||||
/** The saved destinations: a list now, but older versions saved one id, so both are read. */
|
||||
function savedTargets(): string[] {
|
||||
const raw = prefs.get(LAST_TARGET) ?? "";
|
||||
if (!raw) return [];
|
||||
try {
|
||||
const v = JSON.parse(raw);
|
||||
if (Array.isArray(v)) return v.filter((x): x is string => typeof x === "string");
|
||||
} catch {
|
||||
/* an older single-id value */
|
||||
}
|
||||
return [raw];
|
||||
}
|
||||
|
||||
/**
|
||||
* Photo Mechanic's Upload Photos, in the library's top bar: sends the selected photos (rejects never) to a
|
||||
* destination. With no destination yet it leads to where one is set up.
|
||||
* Photo Mechanic's Upload Photos, in the library's top bar: sends the selected photos (rejects never) to one or
|
||||
* more destinations at once. With no destination yet it leads to where one is set up.
|
||||
*/
|
||||
export function SendButton(props: { api: ApiClient; orgId: string; selection: PhotoSummary[]; targets: DeliveryTarget[]; eventId?: string | null; onQueued: (items: DeliveryItemSummary[]) => void }) {
|
||||
const { api, orgId, selection, targets, eventId } = props;
|
||||
const [bestOpen, setBestOpen] = useState(false);
|
||||
const [bestCount, setBestCount] = useState(() => Number(prefs.get(BEST_COUNT)) || 30);
|
||||
const [bestAgain, setBestAgain] = useState(false);
|
||||
/** Photos the last send skipped because this destination already has them: offered to send again. */
|
||||
/** Photos the last send skipped because a destination already has them: offered to send again. */
|
||||
const [already, setAlready] = useState<string[]>([]);
|
||||
const navigate = useNavigate();
|
||||
const [targetId, setTargetId] = useState(() => prefs.get(LAST_TARGET) ?? "");
|
||||
const [chosenTargets, setChosenTargets] = useState<string[]>(savedTargets);
|
||||
const [pickOpen, setPickOpen] = useState(false);
|
||||
const [busy, setBusy] = useState(false);
|
||||
const [note, setNote] = useState<string | null>(null);
|
||||
|
||||
/** Remember the chosen destinations across tabs and restarts (persisted on every change, not only on send). */
|
||||
const remember = (ids: string[]) => {
|
||||
setChosenTargets(ids);
|
||||
prefs.set(LAST_TARGET, JSON.stringify(ids));
|
||||
};
|
||||
|
||||
// Drop destinations that no longer exist; with none left, start on the first available one.
|
||||
useEffect(() => {
|
||||
if (targets.length && !targets.some((x) => x.id === targetId)) setTargetId(targets[0]!.id);
|
||||
}, [targets, targetId]);
|
||||
useEffect(() => setAlready([]), [targetId, eventId]);
|
||||
if (!targets.length) return;
|
||||
const valid = chosenTargets.filter((id) => targets.some((x) => x.id === id));
|
||||
if (valid.length !== chosenTargets.length || valid.length === 0) remember(valid.length ? valid : [targets[0]!.id]);
|
||||
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||
}, [targets]);
|
||||
|
||||
useEffect(() => setAlready([]), [chosenTargets, eventId]);
|
||||
useEffect(() => {
|
||||
if (!note) return;
|
||||
const timer = setTimeout(() => setNote(null), 5000);
|
||||
@@ -43,16 +69,28 @@ export function SendButton(props: { api: ApiClient; orgId: string; selection: Ph
|
||||
);
|
||||
}
|
||||
|
||||
const selected = targets.filter((x) => chosenTargets.includes(x.id));
|
||||
const selectedLabel = selected.map((x) => x.name).join(", ");
|
||||
const photos = selection.filter((p) => p.flag !== "REJECT" && p.status === "READY");
|
||||
|
||||
const toggle = (id: string) => {
|
||||
const next = chosenTargets.includes(id) ? chosenTargets.filter((x) => x !== id) : [...chosenTargets, id];
|
||||
remember(next.length ? next : [id]); // keep at least one chosen
|
||||
};
|
||||
|
||||
const send = async (ids = photos.map((p) => p.id), again = false) => {
|
||||
if (!selected.length) return;
|
||||
setBusy(true);
|
||||
try {
|
||||
// Without a network (or photos still uploading) the request waits on this computer and goes when it can.
|
||||
const r = await deliver(api, orgId, targetId, ids, again);
|
||||
prefs.set(LAST_TARGET, targetId);
|
||||
props.onQueued(r.queued);
|
||||
setAlready(r.skipped.filter((s) => s.reason === "already_delivered").map((s) => s.photoId));
|
||||
setNote(r.waiting ? t.offline.queuedDelivery : t.delivered(r.queued.length, r.skipped.length));
|
||||
// Without a network (or photos still uploading) each request waits on this computer and goes when it can.
|
||||
const results: Awaited<ReturnType<typeof deliver>>[] = [];
|
||||
for (const target of selected) results.push(await deliver(api, orgId, target.id, ids, again));
|
||||
const queued = results.flatMap((r) => r.queued);
|
||||
const skipped = results.flatMap((r) => r.skipped);
|
||||
const waiting = results.some((r) => r.waiting);
|
||||
props.onQueued(queued);
|
||||
setAlready([...new Set(skipped.filter((s) => s.reason === "already_delivered").map((s) => s.photoId))]);
|
||||
setNote(waiting ? t.offline.queuedDelivery : t.delivered(queued.length, skipped.length));
|
||||
} catch (err) {
|
||||
setNote(err instanceof ApiError ? err.code : t.unexpectedError);
|
||||
} finally {
|
||||
@@ -60,19 +98,21 @@ export function SendButton(props: { api: ApiClient; orgId: string; selection: Ph
|
||||
}
|
||||
};
|
||||
|
||||
const target = targets.find((x) => x.id === targetId);
|
||||
// Only the best of the open event: a short gallery of game moments, spread over the match.
|
||||
const sendBest = async () => {
|
||||
if (!eventId) return;
|
||||
if (!eventId || !selected.length) return;
|
||||
setBusy(true);
|
||||
try {
|
||||
const r = await api.deliverBest(orgId, { targetId, eventId, count: bestCount, again: bestAgain });
|
||||
prefs.set(LAST_TARGET, targetId);
|
||||
const results: Awaited<ReturnType<ApiClient["deliverBest"]>>[] = [];
|
||||
for (const target of selected) results.push(await api.deliverBest(orgId, { targetId: target.id, eventId, count: bestCount, again: bestAgain }));
|
||||
prefs.set(BEST_COUNT, String(bestCount));
|
||||
props.onQueued(r.queued);
|
||||
setAlready(r.skipped.filter((s) => s.reason === "already_delivered").map((s) => s.photoId));
|
||||
const queued = results.flatMap((r) => r.queued);
|
||||
const skipped = results.flatMap((r) => r.skipped);
|
||||
const chosen = results[0]?.chosen ?? [];
|
||||
props.onQueued(queued);
|
||||
setAlready([...new Set(skipped.filter((s) => s.reason === "already_delivered").map((s) => s.photoId))]);
|
||||
setBestOpen(false);
|
||||
setNote(r.chosen.length ? t.bestSent(r.queued.length, r.chosen.length) : t.bestNone);
|
||||
setNote(chosen.length ? t.bestSent(queued.length, chosen.length) : t.bestNone);
|
||||
} catch (err) {
|
||||
setNote(err instanceof ApiError ? err.code : t.unexpectedError);
|
||||
} finally {
|
||||
@@ -82,20 +122,35 @@ export function SendButton(props: { api: ApiClient; orgId: string; selection: Ph
|
||||
|
||||
return (
|
||||
<span className="relative flex items-center gap-1">
|
||||
{target?.kind === "ZEROZERO" && eventId && <ZerozeroGamePicker api={api} orgId={orgId} targetId={targetId} eventId={eventId} compact />}
|
||||
{eventId && selected.filter((x) => x.kind === "ZEROZERO").map((x) => <ZerozeroGamePicker key={x.id} api={api} orgId={orgId} targetId={x.id} eventId={eventId} compact />)}
|
||||
{targets.length > 1 && (
|
||||
<select aria-label={t.deliverTo} value={targetId} onChange={(e) => setTargetId(e.target.value)} className="h-6 max-w-[140px] border border-black bg-cell px-1 text-[12px] text-ink">
|
||||
{targets.map((x) => (
|
||||
<option key={x.id} value={x.id}>
|
||||
{x.name}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
<span className="relative">
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => setPickOpen((o) => !o)}
|
||||
aria-expanded={pickOpen}
|
||||
aria-label={t.deliverTo}
|
||||
title={selectedLabel}
|
||||
className="h-6 max-w-[180px] truncate border border-black bg-cell px-2 text-[12px] text-ink hover:bg-cell-on"
|
||||
>
|
||||
{selected.length ? selectedLabel : t.deliverTo}
|
||||
</button>
|
||||
{pickOpen && (
|
||||
<div className="absolute left-0 top-7 z-30 max-h-[60vh] w-[220px] space-y-1 overflow-y-auto border border-black bg-panel p-2 text-[12px] shadow-xl" role="group" aria-label={t.deliverTo}>
|
||||
{targets.map((x) => (
|
||||
<label key={x.id} className="flex items-center gap-2">
|
||||
<input type="checkbox" checked={chosenTargets.includes(x.id)} onChange={() => toggle(x.id)} />
|
||||
<span className="min-w-0 truncate text-ink">{x.name}</span>
|
||||
</label>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
</span>
|
||||
)}
|
||||
<button
|
||||
onClick={() => void send()}
|
||||
disabled={busy || !photos.length || !targetId}
|
||||
title={photos.length ? `${t.sendTo} ${targets.find((x) => x.id === targetId)?.name ?? ""}` : t.selectToSend}
|
||||
disabled={busy || !photos.length || !selected.length}
|
||||
title={photos.length ? `${t.sendTo} ${selectedLabel}` : t.selectToSend}
|
||||
className="h-6 bg-accent px-3 text-[12px] font-semibold text-white hover:bg-accent-strong disabled:opacity-40"
|
||||
>
|
||||
{t.sendN(photos.length)}
|
||||
@@ -122,8 +177,8 @@ export function SendButton(props: { api: ApiClient; orgId: string; selection: Ph
|
||||
<input type="checkbox" checked={bestAgain} onChange={(e) => setBestAgain(e.target.checked)} />
|
||||
{t.bestAgain}
|
||||
</label>
|
||||
<button disabled={busy || !targetId} className="h-7 w-full bg-accent font-semibold text-white disabled:opacity-40">
|
||||
{t.bestSend(target?.name ?? "")}
|
||||
<button disabled={busy || !selected.length} className="h-7 w-full bg-accent font-semibold text-white disabled:opacity-40">
|
||||
{t.bestSend(selectedLabel)}
|
||||
</button>
|
||||
</form>
|
||||
)}
|
||||
|
||||
@@ -48,6 +48,20 @@ async function slot<T>(fn: () => Promise<T>): Promise<T> {
|
||||
}
|
||||
}
|
||||
|
||||
/** How long to wait for a single image download before giving up its slot. */
|
||||
const FETCH_TIMEOUT_MS = 20000;
|
||||
|
||||
/** fetch that aborts if it stalls, so one hung request can't hold a concurrency slot forever and starve the grid. */
|
||||
async function fetchWithTimeout(url: string): Promise<Response> {
|
||||
const ctrl = new AbortController();
|
||||
const timer = setTimeout(() => ctrl.abort(), FETCH_TIMEOUT_MS);
|
||||
try {
|
||||
return await fetch(url, { signal: ctrl.signal });
|
||||
} finally {
|
||||
clearTimeout(timer);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* The image as a blob URL: from this computer when it was seen before, else downloaded once and kept. Null when it
|
||||
* can't be had (offline and never seen). The caller revokes the URL when done.
|
||||
@@ -59,7 +73,7 @@ export async function cachedImage(url: string): Promise<string | null> {
|
||||
if (kept) return URL.createObjectURL(kept);
|
||||
try {
|
||||
const blob = await slot(async () => {
|
||||
const res = await fetch(url);
|
||||
const res = await fetchWithTimeout(url);
|
||||
if (!res.ok) throw new Error(`http_${res.status}`);
|
||||
return res.blob();
|
||||
});
|
||||
|
||||
@@ -13,6 +13,7 @@
|
||||
use std::collections::{HashMap, HashSet};
|
||||
use std::net::IpAddr;
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::sync::atomic::{AtomicU64, Ordering};
|
||||
use std::sync::{Arc, Mutex};
|
||||
use std::time::UNIX_EPOCH;
|
||||
|
||||
@@ -158,6 +159,8 @@ pub struct FtpState {
|
||||
/// Paths already handed to the web app (so the next scan does not send them twice).
|
||||
taken: Mutex<HashSet<String>>,
|
||||
last_error: Arc<Mutex<Option<String>>>,
|
||||
/// Bumped on every start/stop so a stopped server's late "shutdown" error can't land on a newer one.
|
||||
epoch: Arc<AtomicU64>,
|
||||
checks: Mutex<Vec<AddressCheck>>,
|
||||
firewall: Mutex<Option<String>>,
|
||||
}
|
||||
@@ -549,9 +552,15 @@ impl FtpState {
|
||||
|
||||
*self.last_error.lock().unwrap() = None;
|
||||
let last_error = self.last_error.clone();
|
||||
let epoch = self.epoch.clone();
|
||||
let generation = epoch.fetch_add(1, Ordering::SeqCst) + 1;
|
||||
tauri::async_runtime::spawn(async move {
|
||||
if let Err(e) = server.listen(format!("0.0.0.0:{port}")).await {
|
||||
*last_error.lock().unwrap() = Some(e.to_string());
|
||||
// Only this server's own failure counts: once it has been stopped or replaced
|
||||
// (the epoch has moved on), its expected shutdown must not overwrite a newer server's status.
|
||||
if epoch.load(Ordering::SeqCst) == generation {
|
||||
*last_error.lock().unwrap() = Some(e.to_string());
|
||||
}
|
||||
}
|
||||
});
|
||||
*self.running.lock().unwrap() = Some(Running { stop: stop_tx });
|
||||
@@ -560,7 +569,11 @@ impl FtpState {
|
||||
|
||||
pub fn stop(&self) {
|
||||
if let Some(r) = self.running.lock().unwrap().take() {
|
||||
// Move the epoch on so this server's own shutdown is ignored by its listen task, and clear the
|
||||
// error: a server we stopped on purpose is not a server in error.
|
||||
self.epoch.fetch_add(1, Ordering::SeqCst);
|
||||
let _ = r.stop.send(());
|
||||
*self.last_error.lock().unwrap() = None;
|
||||
}
|
||||
self.checks.lock().unwrap().clear();
|
||||
}
|
||||
|
||||
@@ -62,9 +62,11 @@ export type PhotoDelivery = "NONE" | "QUEUED" | "DONE" | "FAILED";
|
||||
|
||||
/** A photo's overall delivery state from the status of each of its deliveries. */
|
||||
export function deliveryState(statuses: readonly string[]): PhotoDelivery {
|
||||
if (statuses.includes("DONE")) return "DONE";
|
||||
if (statuses.some((x) => x === "QUEUED" || x === "RUNNING" || x === "WAITING")) return "QUEUED";
|
||||
return statuses.length ? "FAILED" : "NONE";
|
||||
// A retracted (taken-back) delivery no longer counts: a photo with only those reads as not delivered.
|
||||
const live = statuses.filter((x) => x !== "RETRACTED");
|
||||
if (live.includes("DONE")) return "DONE";
|
||||
if (live.some((x) => x === "QUEUED" || x === "RUNNING" || x === "WAITING")) return "QUEUED";
|
||||
return live.length ? "FAILED" : "NONE";
|
||||
}
|
||||
|
||||
export interface PhotoSummary {
|
||||
@@ -104,7 +106,7 @@ export interface PhotoSummary {
|
||||
}
|
||||
|
||||
/** WAITING: rendered for a folder on a computer, until that computer's desktop app takes it. */
|
||||
export type DeliveryStatus = "QUEUED" | "RUNNING" | "WAITING" | "DONE" | "FAILED";
|
||||
export type DeliveryStatus = "QUEUED" | "RUNNING" | "WAITING" | "DONE" | "FAILED" | "RETRACTED";
|
||||
|
||||
export interface DeliveryItemSummary {
|
||||
id: string;
|
||||
|
||||
@@ -138,8 +138,10 @@ describe("vars", () => {
|
||||
|
||||
describe("delivery paths", () => {
|
||||
const vsc = buildVars({
|
||||
home: "VSC",
|
||||
away: "AAAS",
|
||||
home: "Vitória SC",
|
||||
away: "AA Águas Santas",
|
||||
homeShort: "VSC",
|
||||
awayShort: "AAAS",
|
||||
competition: "Campeonato Betclic",
|
||||
competitionCode: "PO01",
|
||||
startsAt: new Date("2026-09-23T19:00:00Z"),
|
||||
|
||||
@@ -68,8 +68,8 @@ export function renderFileName(template: string, vars: TemplateVars, originalFil
|
||||
/** Example destination rules taken from today's deliveries. */
|
||||
export const DESTINATION_EXAMPLES = {
|
||||
fpa: {
|
||||
folder: "/FPA/Fotos/{season}/Competições Nacionais/{competitionCode} - {competition}/{dateCompact} - {home} x {away}/",
|
||||
fileName: "PS_{home} x {away}_{n}.jpg",
|
||||
folder: "/FPA/Fotos/{season}/Competições Nacionais/{competitionCode} - {competition}/{dateCompact} - {homeShort} x {awayShort}/",
|
||||
fileName: "PS_{homeShort} x {awayShort}_{n}.jpg",
|
||||
},
|
||||
liga: {
|
||||
folder: "/LPBetclic {seasonShort}/Jornada {round}/{matchNumber}. {home} x {away}/",
|
||||
|
||||
Reference in new issue
Block a user