Compare commits

...
Author SHA1 Message Date
sparkandClaude Opus 5.5 003b8fceb8 Desktop 0.3.12: originals changed by Photo Mechanic are sent anyway; "the best" can be sent again
desktop-release / build (--target universal-apple-darwin, dmg,app, darwin-universal, macos) (push) Successful in 7m45s
ci / rust (push) Successful in 14m15s
ci / typescript (push) Successful in 17m16s
desktop-release / build (deb,appimage, linux-x86_64, ubuntu-latest) (push) Successful in 37m8s
A delivery waiting for an original never got it when Photo Mechanic had written captions into the file on the computer (its fingerprint changed, so the desktop could not find it). The desktop now sends the file it recorded for that photo to POST /v1/photos/:id/original, which takes it when it has the photo's pixel size. The "best" delivery gets an option to send again the ones the destination already has.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01HT6iXLYUUp9pJz5Kza9xCW
2026-10-14 04:44:22 +01:00
sparkandClaude Opus 5.5 a5cbbe594d Desktop 0.3.11: importing destinations brings their saved passwords when readable
ci / rust (push) Successful in 10m54s
desktop-release / build (--target universal-apple-darwin, dmg,app, darwin-universal, macos) (push) Successful in 12m29s
ci / typescript (push) Successful in 14m3s
desktop-release / build (deb,appimage, linux-x86_64, ubuntu-latest) (push) Successful in 38m33s
The desktop takes the passwords out of Photo Mechanic's accounts and FileZilla's site manager and hands them over on their own when they are readable (plain, or base64 that decodes to text); the wizard fills them in and says so. Encrypted ones (FileZilla with a master password, binary Photo Mechanic blobs) are flagged to be typed.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01HT6iXLYUUp9pJz5Kza9xCW
2026-10-14 04:24:06 +01:00
sparkandClaude Opus 5.5 e8339cdf3f Deliveries wait for the full original instead of sending the desktop's 2048 px preview
ci / rust (push) Successful in 7m43s
ci / typescript (push) Successful in 11m3s
Photos sent by the desktop's local FTP without originals were delivered at preview size (a 4000 px destination got 1100-2000 px files). Now the delivery asks that computer for the original, waits (up to 72 h, not counted as attempts) and goes as soon as it arrives.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01HT6iXLYUUp9pJz5Kza9xCW
2026-10-14 03:32:23 +01:00
26 changed files with 479 additions and 35 deletions

No files matched your search

+1 -1
View File
@@ -204,7 +204,7 @@ export async function registerDeliveryRoutes(
const chosen = await bestOfEvent(db, event.id, body.count);
if (body.dryRun || !chosen.length) return { chosen, queued: [], skipped: [] };
try {
const result = await delivery.enqueue({ organizationId: orgId, targetId: body.targetId, photoIds: chosen, again: false, requestedById: currentUserId(req) });
const result = await delivery.enqueue({ organizationId: orgId, targetId: body.targetId, photoIds: chosen, again: body.again, requestedById: currentUserId(req) });
return reply.code(202).send({ chosen, queued: result.queued.map(toItemSummary), skipped: result.skipped });
} catch (err) {
return fail(err);
+16
View File
@@ -15,6 +15,10 @@ import { type Transport, type TransportKind, ZerozeroTransport, createTransport,
import { type ZerozeroGame, matchGame, zerozeroGameId } from "./zerozero.js";
export const MAX_ATTEMPTS = 5;
/** How long a delivery waits for an original still on the photographer's computer before it gives up. */
export const ORIGINAL_WAIT_MS = 72 * 3600_000;
/** How often it asks that computer again while waiting. */
export const ORIGINAL_ASK_MS = 60_000;
/** Running items older than this belonged to a worker that died; they go back in the queue. */
const STALE_RUNNING_MS = 10 * 60_000;
@@ -217,6 +221,18 @@ export class DeliveryService {
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 } });
let update: Partial<DeliveryItem>;
if (!item.photo.originalStored) {
// Only the desktop's 2048 px preview is here: delivering it would send a small photo. Ask the desktop app
// that keeps the original to send it, and try again shortly (waiting does not count as an attempt).
this.deps.broadcaster.library(item.organizationId, { type: "original.requested", photoId: item.photoId, sha256: item.photo.sha256 });
update =
Date.now() - item.createdAt.getTime() > ORIGINAL_WAIT_MS
? { status: "FAILED", lastError: "original_not_here", finishedAt: new Date() }
: { status: "QUEUED", attempts: Math.max(0, item.attempts - 1), lastError: "waiting_for_original", nextAttemptAt: new Date(Date.now() + ORIGINAL_ASK_MS) };
const saved = await db.deliveryItem.update({ where: { id: itemId }, data: update });
this.deps.broadcaster.library(saved.organizationId, { type: "delivery.updated", item: toItemSummary(saved) });
return saved;
}
try {
const vars = buildVars(
eventInfoOf(item.event),
+4 -1
View File
@@ -204,7 +204,8 @@ export class IngestService {
return outcome;
}
private async storeOriginal(photo: { id: string; organizationId: string; sha256: string; storageKey: string }, file: string, ext: string): Promise<{ status: "ingested"; photoId: string; eventId: string | null }> {
/** The full original of a photo that so far only had the desktop's preview (moved into place: `file` is consumed). */
async storeOriginal(photo: { id: string; organizationId: string; sha256: string; storageKey: string }, file: string, ext: string): Promise<{ status: "ingested"; photoId: string; eventId: string | null }> {
const { db, storage, log } = this.deps;
const key = storage.originalKey(photo.organizationId, photo.sha256, ext === ".jpeg" ? ".jpg" : ext);
const size = (await stat(file)).size;
@@ -218,6 +219,8 @@ export class IngestService {
data: { storageKey: key, byteSize: size, originalStored: true, ...(org?.biometricsEnabled && { facesStatus: "PENDING" }) },
});
log.info({ photoId: photo.id }, "ingest: original replaces the desktop preview");
// Deliveries waiting for it go now.
await db.deliveryItem.updateMany({ where: { photoId: photo.id, status: "QUEUED" }, data: { nextAttemptAt: new Date() } });
this.deps.broadcaster.library(photo.organizationId, { type: "original.stored", photoId: photo.id });
return { status: "ingested", photoId: photo.id, eventId: updated.eventId };
}
+35
View File
@@ -5,6 +5,7 @@ import { appendFile, mkdir, rm, stat } from "node:fs/promises";
import path from "node:path";
import { pipeline } from "node:stream/promises";
import type { FastifyInstance } from "fastify";
import sharp from "sharp";
import { z } from "zod";
import { currentUserId, requireAuth, requireMembership } from "../auth/guard.js";
import type { SessionService } from "../auth/sessions.js";
@@ -16,6 +17,7 @@ import { photoInclude, toSummary } from "./serialize.js";
const OrgParams = z.object({ orgId: z.uuid() });
const UploadQuery = z.object({ eventId: z.uuid().optional() });
const PhotoParams = z.object({ photoId: z.uuid() });
export const MAX_UPLOAD_BYTES = 200 * 1024 * 1024;
/**
@@ -59,6 +61,39 @@ export async function registerUploadRoutes(
}
});
/**
* The desktop app sends the original of a photo that only has its preview here, when the file on that computer
* no longer has the fingerprint it had on arrival (Photo Mechanic wrote captions into it afterwards). Same photo:
* the same pixel size as declared then; the library keeps the photo's own fingerprint and metadata.
*/
app.post("/v1/photos/:photoId/original", { preHandler: authenticate }, async (req, reply) => {
const { photoId } = PhotoParams.parse(req.params);
const photo = await db.photo.findUnique({ where: { id: photoId }, select: { id: true, organizationId: true, sha256: true, storageKey: true, originalStored: true, width: true, height: true } });
if (!photo) throw new AppError(404, "photo_not_found");
await requireMembership(db, req, photo.organizationId, "PHOTOGRAPHER");
const part = await req.file();
if (!part) throw badRequest("file_missing");
if (photo.originalStored) {
part.file.resume();
return { stored: true };
}
const tmpDir = storage.resolve(".uploads");
await mkdir(tmpDir, { recursive: true });
const tmp = path.join(tmpDir, `${randomUUID()}.part`);
try {
await pipeline(part.file, createWriteStream(tmp));
if (part.file.truncated) throw new AppError(413, "file_too_large");
const meta = await sharp(tmp).metadata().catch(() => null);
const turned = (meta?.orientation ?? 1) >= 5;
const [w, h] = turned ? [meta?.height, meta?.width] : [meta?.width, meta?.height];
if (meta?.format !== "jpeg" || !photo.width || w !== photo.width || h !== photo.height) return reply.code(409).send({ error: "not_the_same_photo" });
await ingest.storeOriginal(photo, tmp, ".jpg");
return { stored: true };
} finally {
await rm(tmp, { force: true });
}
});
// ---- resumable (chunked) uploads ----------------------------------------------------------------
// Weak venue Wi-Fi and mobile data drop big uploads: the client sends 4 MB chunks, and after a failure (or a
// reload, same file) asks where the server is and carries on from there.
+24
View File
@@ -410,6 +410,30 @@ describe("delivery", () => {
expect((await ctx.app.inject({ method: "GET", url: `/v1/orgs/${orgId}/deliveries/${claim.items[0]!.id}/local-file`, headers: bearer(token) })).statusCode).toBe(404);
});
it("waits for an original still on the photographer's computer instead of delivering its preview", async () => {
const { orgId, token } = await setup();
const created = await ctx.app.inject({
method: "POST",
url: `/v1/orgs/${orgId}/delivery-targets`,
headers: bearer(token),
payload: { name: "Disco", kind: "LOCAL", baseUrl: "/Users/peter/Entregas", username: "mac-0001-peter", folderTemplate: "/{event}/", fileNameTemplate: "{originalName}" },
});
const targetId = (created.json() as { id: string }).id;
const a = await photo("preview-only.jpg", "2026:09:23 21:10:00");
await ctx.db.photo.update({ where: { id: a }, data: { originalStored: false } });
await ctx.app.inject({ method: "POST", url: `/v1/orgs/${orgId}/deliveries`, headers: bearer(token), payload: { targetId, photoIds: [a] } });
await drain();
const waiting = await ctx.db.deliveryItem.findFirstOrThrow({ where: { targetId } });
expect([waiting.status, waiting.lastError, waiting.attempts]).toEqual(["QUEUED", "waiting_for_original", 0]);
expect(waiting.nextAttemptAt!.getTime()).toBeGreaterThan(Date.now());
// The original arrives (the ingest moves waiting deliveries forward): now it is rendered.
await ctx.db.photo.update({ where: { id: a }, data: { originalStored: true } });
await ctx.db.deliveryItem.updateMany({ where: { photoId: a, status: "QUEUED" }, data: { nextAttemptAt: new Date() } });
await drain();
expect(await ctx.db.deliveryItem.findFirstOrThrow({ where: { targetId } })).toMatchObject({ status: "WAITING", lastError: null });
});
it("retries transient errors with back-off and stops at auth errors", async () => {
const { orgId, token, target } = await setup();
const id = await photo("a.jpg", "2026:09:23 21:10:00");
+26
View File
@@ -81,6 +81,32 @@ describe("resumable uploads", () => {
expect((await ctx.app.inject({ method: "POST", url: `/v1/photos/${photo.id}/original/request`, headers: bearer(token) })).json()).toEqual({ stored: true });
});
it("takes an original changed on the desktop since (captions written into it) as that photo's original, if it is the same photo", async () => {
const { org } = await seedUser(ctx.db, "[email protected]", { org: "fpa", role: "PHOTOGRAPHER" });
const token = (await login(ctx.app, "[email protected]")).body.accessToken;
const original = await sharp({ create: { width: 1200, height: 800, channels: 3, noise: { type: "gaussian", mean: 128, sigma: 40 } } }).jpeg({ quality: 95 }).toBuffer();
const sha256 = createHash("sha256").update(original).digest("hex");
const preview = await sharp(original).resize(600).jpeg().toBuffer();
const { id } = (await ctx.app.inject({ method: "POST", url: `/v1/orgs/${org!.id}/uploads/resumable`, headers: bearer(token), payload: { name: "IMG_0003.JPG", size: preview.length, fingerprint: "p", original: { sha256, size: original.length, width: 1200, height: 800 } } })).json() as { id: string };
const photo = ((await ctx.app.inject({ method: "PUT", url: `/v1/uploads/${id}?offset=0`, headers: { ...bearer(token), "content-type": "application/offset+octet-stream" }, payload: preview })).json() as { photo: { id: string } }).photo;
const post = (file: Buffer) => {
const boundary = "----pr-original";
const head = Buffer.from(`--${boundary}\r\nContent-Disposition: form-data; name="file"; filename="${sha256}.jpg"\r\nContent-Type: image/jpeg\r\n\r\n`);
return ctx.app.inject({ method: "POST", url: `/v1/photos/${photo.id}/original`, headers: { ...bearer(token), "content-type": `multipart/form-data; boundary=${boundary}` }, payload: Buffer.concat([head, file, Buffer.from(`\r\n--${boundary}--\r\n`)]) });
};
// Another photo (another size) is refused.
const other = await sharp({ create: { width: 1000, height: 800, channels: 3, background: "#808080" } }).jpeg().toBuffer();
expect((await post(other)).statusCode).toBe(409);
// The same photo with a caption written into it: a different file, the same pixel size.
const captioned = await sharp(original).withMetadata({ exif: { IFD0: { ImageDescription: "SC Braga x Sporting CP" } } }).jpeg({ quality: 95 }).toBuffer();
expect(createHash("sha256").update(captioned).digest("hex")).not.toBe(sha256);
expect((await post(captioned)).json()).toEqual({ stored: true });
const after = await ctx.db.photo.findUniqueOrThrow({ where: { id: photo.id } });
expect(after).toMatchObject({ originalStored: true, sha256 });
expect(await ctx.db.photo.count()).toBe(1);
expect((await ctx.app.inject({ method: "GET", url: `/v1/photos/${photo.id}/original`, headers: bearer(token) })).statusCode).toBe(200);
});
it("counts a full original from the desktop app's FTP as camera ingest (the autopilot edits it), not a hand upload", async () => {
const { org } = await seedUser(ctx.db, "[email protected]", { org: "fpa", role: "PHOTOGRAPHER" });
const token = (await login(ctx.app, "[email protected]")).body.accessToken;
+25
View File
@@ -87,6 +87,31 @@ describe("importing destinations", () => {
expect(await screen.findByText("Importado")).toBeTruthy();
});
it("brings the saved password along when the other app keeps it readable", async () => {
const created: { name: string; password?: string }[] = [];
const api = {
createDeliveryTarget: vi.fn(async (_org: string, input: { name: string; password?: string }) => {
created.push(input);
return { id: `t${created.length}`, ...input } as unknown as DeliveryTarget;
}),
} as unknown as ApiClient;
render(
<ImportTargets
api={api}
orgId="org"
existing={[]}
shell={shell({ profiles: async () => ({ photoMechanic: [], photoMechanicAccounts: [], filezilla: SITES, passwords: { "fz:Clube:ftp.clube.pt": "guardada" }, unreadable: ["fz:Jornal:ftp.jornal.pt"] }) })}
onClose={() => {}}
onImported={() => {}}
/>,
);
expect(await screen.findByText("senha guardada no FileZilla")).toBeTruthy();
expect(screen.getByText("o FileZilla guarda esta senha cifrada: escreve-a")).toBeTruthy();
fireEvent.click(screen.getByRole("checkbox", { name: "Clube" }));
fireEvent.click(screen.getByRole("button", { name: "Importar 1" }));
await waitFor(() => expect(created).toEqual([expect.objectContaining({ name: "Clube", password: "guardada" })]));
});
it("says when the desktop app is too old for it", async () => {
render(<ImportTargets api={{} as ApiClient} orgId="org" existing={[]} shell={shell({ profiles: async () => Promise.reject(new Error("command not found")) })} onClose={() => {}} onImported={() => {}} />);
expect(await screen.findByText(/atualiza a app/)).toBeTruthy();
+8 -1
View File
@@ -61,6 +61,7 @@ export const t = {
bestButton: "Melhores…",
bestHelp: "Envia só as melhores fotos deste jogo: momentos de jogo (bola, duelos, festejos), nítidas e espalhadas pelo jogo, sem repetidas. As fotos com estrelas têm prioridade e as rejeitadas nunca vão.",
bestCount: "Quantas fotos",
bestAgain: "Enviar de novo as que já foram entregues",
bestSend: (target: string) => `Enviar as melhores para ${target}`,
bestSent: (queued: number, chosen: number) => (queued === chosen ? `${chosen} melhores na fila` : `${chosen} escolhidas, ${queued} na fila (as outras já tinham ido)`),
bestNone: "Não há fotos de jogo para escolher",
@@ -198,7 +199,7 @@ export const t = {
importTargets: {
title: "Importar destinos",
button: "Importar…",
help: "Destinos guardados no Photo Mechanic (contas e modelos de upload) e no FileZilla, neste computador. Servidor, utilizador, pasta, tamanho, qualidade e nome do ficheiro vêm de lá; a senha escreves aqui (essas apps não a deixam ler). Escolhe os que queres e escreve a senha de cada um.",
help: "Destinos guardados no Photo Mechanic (contas e modelos de upload) e no FileZilla, neste computador. Servidor, utilizador, senha, pasta, tamanho, qualidade e nome do ficheiro vêm de lá. Uma senha que a outra app guarda cifrada tens de a escrever aqui.",
none: "Não encontrei destinos do Photo Mechanic nem do FileZilla neste computador.",
tooOld: "Esta versão da app ainda não sabe importar destinos: atualiza a app.",
showArchived: "Mostrar os modelos arquivados do Photo Mechanic",
@@ -208,6 +209,8 @@ export const t = {
password: "Senha",
key: "Chave privada (PEM) ou senha",
missingPassword: "Falta a senha nalguns dos escolhidos.",
savedPassword: (app: string) => `senha guardada no ${app}`,
encryptedPassword: (app: string) => `o ${app} guarda esta senha cifrada: escreve-a`,
done: "Importado",
import: (n: number) => (n ? `Importar ${n}` : "Importar"),
},
@@ -278,6 +281,10 @@ export const t = {
shareLink: "Link de partilha",
copyLink: "Copiar link",
copied: "Copiado",
deliveryErrors: {
waiting_for_original: "À espera do original (está no computador do fotógrafo; abre a app PhotoReport nesse computador)",
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" },
codeList: "Substituição de códigos",
codeListHelp: "Uma linha por código: código, tab, texto. Escreve \\v7\\ numa legenda e é trocado pelo texto. Listas do Photo Mechanic servem tal como estão.",
+17 -10
View File
@@ -9,13 +9,15 @@ interface Row {
selected: boolean;
name: string;
password: string;
/** The password came from the other app ("saved"), or it keeps it encrypted ("encrypted"). */
saved: "saved" | "encrypted" | null;
result: "ok" | string | null;
}
/**
* Desktop: the upload destinations saved in Photo Mechanic and FileZilla on this computer, to bring in as
* destinations. Server, user, folders and output settings come from there; passwords are typed here (the other
* apps keep them to themselves).
* destinations. Server, user, folders, output settings and the saved password (when the other app keeps it readable)
* come from there; an encrypted password is typed here.
*/
export function ImportTargets(props: { api: ApiClient; orgId: string; existing: DeliveryTarget[]; shell?: DeliveryShell; onClose: () => void; onImported: (targets: DeliveryTarget[]) => void }) {
const L = t.importTargets;
@@ -30,13 +32,17 @@ export function ImportTargets(props: { api: ApiClient; orgId: string; existing:
shell.profiles().then(
(sources) =>
setRows(
importCandidates(sources).map((c) => ({
c,
selected: false,
name: taken.has(c.name.toLowerCase()) ? `${c.name} (${c.source === "FileZilla" ? "FileZilla" : "PM"})` : c.name,
password: "",
result: null,
})),
importCandidates(sources).map((c) => {
const saved = sources.passwords?.[c.passwordKey];
return {
c,
selected: false,
name: taken.has(c.name.toLowerCase()) ? `${c.name} (${c.source === "FileZilla" ? "FileZilla" : "PM"})` : c.name,
password: saved ?? "",
saved: saved ? "saved" : sources.unreadable?.includes(c.passwordKey) ? "encrypted" : null,
result: null,
};
}),
),
() => setError(L.tooOld),
);
@@ -123,8 +129,9 @@ export function ImportTargets(props: { api: ApiClient; orgId: string; existing:
) : r.c.keyAuth ? (
<textarea className={`${input} h-16 font-mono text-[10.5px]`} placeholder={L.key} value={r.password} onChange={(e) => set(i, { password: e.target.value, selected: true })} spellCheck={false} />
) : (
<input type="password" autoComplete="new-password" className={input} placeholder={L.password} value={r.password} onChange={(e) => set(i, { password: e.target.value, selected: true })} />
<input type="password" autoComplete="new-password" className={input} placeholder={L.password} value={r.password} onChange={(e) => set(i, { password: e.target.value, selected: true, saved: null })} />
)}
{!r.c.problem && r.result !== "ok" && r.saved && <p className={`text-[11px] ${r.saved === "saved" ? "text-faint" : "text-[#f0a35a]"}`}>{r.saved === "saved" ? L.savedPassword(r.c.source) : L.encryptedPassword(r.c.source)}</p>}
{r.result && r.result !== "ok" && <p className="text-danger">{r.result}</p>}
</div>
</li>
+6 -1
View File
@@ -18,6 +18,7 @@ export function SendButton(props: { api: ApiClient; orgId: string; selection: Ph
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);
const navigate = useNavigate();
const [targetId, setTargetId] = useState(() => prefs.get(LAST_TARGET) ?? "");
const [busy, setBusy] = useState(false);
@@ -61,7 +62,7 @@ export function SendButton(props: { api: ApiClient; orgId: string; selection: Ph
if (!eventId) return;
setBusy(true);
try {
const r = await api.deliverBest(orgId, { targetId, eventId, count: bestCount });
const r = await api.deliverBest(orgId, { targetId, eventId, count: bestCount, again: bestAgain });
prefs.set(LAST_TARGET, targetId);
prefs.set(BEST_COUNT, String(bestCount));
props.onQueued(r.queued);
@@ -112,6 +113,10 @@ export function SendButton(props: { api: ApiClient; orgId: string; selection: Ph
<span>{t.bestCount}</span>
<input type="number" min={1} max={300} value={bestCount} onChange={(e) => setBestCount(Math.max(1, Math.min(300, Number(e.target.value) || 1)))} className="h-6 w-20 border border-black bg-[#161617] px-1 text-ink" />
</label>
<label className="flex items-center gap-2 text-muted">
<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>
+9
View File
@@ -14,6 +14,10 @@ export interface ImportSources {
photoMechanic: { kind: string; name: string; archived: boolean; text: string }[];
photoMechanicAccounts: { kind: string; name: string; text: string }[];
filezilla: string | null;
/** Saved passwords the desktop app could read, by `passwordKey` (older apps: none). */
passwords?: Record<string, string>;
/** Keys of saved passwords that are encrypted (typed by hand). */
unreadable?: string[];
}
export interface ImportCandidate {
@@ -38,6 +42,8 @@ export interface ImportCandidate {
keyAuth: boolean;
/** Why it cannot be imported as it is (no server known). */
problem: string | null;
/** Where its saved password is found in `ImportSources.passwords` (the account or site). */
passwordKey: string;
}
interface PmAccount {
@@ -218,6 +224,7 @@ export function importCandidates(src: ImportSources): ImportCandidate[] {
dpi: Math.min(1200, Math.max(72, Number(s.render_res_edit) || 300)),
keyAuth: found?.account.keyAuth ?? false,
problem: found ? null : accountName ? `a conta "${accountName}" não está nas contas do Photo Mechanic` : "sem conta",
passwordKey: `pm:${kind}:${accountName}`,
});
}
for (const [k, { kind, account }] of accounts) {
@@ -241,6 +248,7 @@ export function importCandidates(src: ImportSources): ImportCandidate[] {
dpi: 300,
keyAuth: account.keyAuth,
problem: account.host ? null : "sem servidor",
passwordKey: `pm:${kind}:${account.name}`,
});
}
if (src.filezilla) out.push(...fileZillaCandidates(src.filezilla));
@@ -298,6 +306,7 @@ export function fileZillaCandidates(xml: string): ImportCandidate[] {
dpi: 300,
keyAuth: text(server, "Logontype") === "5",
problem: host ? null : "sem servidor",
passwordKey: `fz:${name}:${host}`,
});
}
return out;
+15 -6
View File
@@ -2,7 +2,7 @@ import type { LibraryMessage } from "@photoreport/contracts";
import type { PhotoSummary } from "@photoreport/contracts";
import { createContext, type ReactNode, useCallback, useContext, useEffect, useRef } from "react";
import { useAuth } from "../auth.js";
import { isDesktop, localOriginal } from "../platform.js";
import { isDesktop, localOriginal, localOriginalChanged } from "../platform.js";
import { useLocalFtp } from "./LocalFtp.js";
import { useLibraryLive } from "./realtime.js";
import { useUploadQueue } from "./uploads.js";
@@ -49,15 +49,24 @@ function OriginalResponder({ api, add }: { api: ReturnType<typeof useAuth>["api"
(m: LibraryMessage) => {
if (m.type !== "original.requested" || sending.current.has(m.sha256)) return;
sending.current.add(m.sha256);
void localOriginal(m.sha256).then((bytes) => {
if (!bytes) {
sending.current.delete(m.sha256);
void localOriginal(m.sha256).then(async (bytes) => {
if (bytes) {
add([new File([bytes], `${m.sha256}.jpg`, { type: "image/jpeg" })], undefined, () => sending.current.delete(m.sha256));
return;
}
add([new File([bytes], `${m.sha256}.jpg`, { type: "image/jpeg" })], undefined, () => sending.current.delete(m.sha256));
// 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 localOriginalChanged(m.sha256);
if (changed) await api.sendOriginal(m.photoId, new Blob([changed], { type: "image/jpeg" }), `${m.sha256}.jpg`);
} catch {
/* not the same photo, or offline: asked again later */
} finally {
sending.current.delete(m.sha256);
}
});
},
[add],
[add, api],
);
useLibraryLive(api, onMessage);
return null;
+1 -1
View File
@@ -121,7 +121,7 @@ export function DeliveryPage() {
<td className="border-b border-line px-3 py-1.5 font-mono text-[11px] text-faint">{i.sequence}</td>
<td className="border-b border-line px-3 py-1.5 font-mono text-[11px] break-all">
{i.remotePath ?? <span className="text-faint">—</span>}
{i.lastError && <span className="block text-[10px] text-[#f0a35a]">{i.lastError}</span>}
{i.lastError && <span className="block text-[10px] text-[#f0a35a]">{t.deliveryErrors[i.lastError as keyof typeof t.deliveryErrors] ?? i.lastError}</span>}
</td>
<td className={`border-b border-line px-3 py-1.5 font-mono text-[11px] ${STATUS_COLOR[i.status]}`}>
{t.deliveryStatus[i.status]}
+14
View File
@@ -92,6 +92,20 @@ export function asArrayBuffer(data: unknown): ArrayBuffer {
throw new Error("not binary data");
}
/**
* The file that was this photo's original when it arrived, changed since (another app wrote captions into it), or
* null. Only for sending to the server as that photo's original; older desktop apps answer null.
*/
export async function localOriginalChanged(sha256: string, invokeImpl?: Invoke): Promise<ArrayBuffer | null> {
if (!invokeImpl && !isDesktop()) return null;
try {
const invoke: Invoke = invokeImpl ?? (async (cmd, args) => (await import("@tauri-apps/api/core")).invoke(cmd, args));
return asArrayBuffer(await invoke<unknown>("local_original_changed", { sha256 }));
} catch {
return null;
}
}
/**
* The original of a photo from this computer (desktop app), found by its SHA-256: photos that came in through the
* local FTP open straight from disk. Null when this computer doesn't have it (or in the browser).
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "@photoreport/desktop",
"version": "0.3.10",
"version": "0.3.12",
"private": true,
"type": "module",
"scripts": {
+1 -1
View File
@@ -1,6 +1,6 @@
[package]
name = "photoreport-desktop"
version = "0.3.10"
version = "0.3.12"
edition = "2024"
publish = false
description = "PhotoReport desktop: the web app in a native shell, with keychain sign-in and (later) local FTP and the native engine."
+1
View File
@@ -17,6 +17,7 @@ fn main() {
"ftp_open_folder",
"ftp_save_settings",
"local_original",
"local_original_changed",
"ftp_preview",
"ftp_info",
"catalog_folders",
@@ -32,6 +32,7 @@
"allow-ftp-open-folder",
"allow-ftp-save-settings",
"allow-local-original",
"allow-local-original-changed",
"allow-ftp-preview",
"allow-ftp-info",
"allow-catalog-folders",
@@ -0,0 +1,11 @@
# Automatically generated - DO NOT EDIT!
[[permission]]
identifier = "allow-local-original-changed"
description = "Enables the local_original_changed command without any pre-configured scope."
commands.allow = ["local_original_changed"]
[[permission]]
identifier = "deny-local-original-changed"
description = "Denies the local_original_changed command without any pre-configured scope."
commands.deny = ["local_original_changed"]
+213 -7
View File
@@ -5,9 +5,10 @@
//! folder picker (kept in the app's config folder), never anywhere a page asks: the web app is loaded from the server.
//!
//! Importing reads two fixed places, never a path a page passes: Photo Mechanic's upload accounts and templates
//! (`fileupload`), and FileZilla's site manager. Passwords are removed here and never reach the page: the person
//! types them once when importing.
//! (`fileupload`), and FileZilla's site manager. Saved passwords are taken out of those texts and handed over on
//! their own, when the other app keeps them readable (plain or base64); encrypted ones are typed by the person.
use std::collections::BTreeMap;
use std::path::{Component, Path, PathBuf};
use std::sync::Mutex;
@@ -180,6 +181,173 @@ pub struct ImportSources {
pub photo_mechanic_accounts: Vec<Snapshot>,
/// FileZilla's site manager (XML, passwords removed).
pub filezilla: Option<String>,
/// The saved passwords that could be read, by destination: `pm:<KIND>:<account>` (Photo Mechanic) and
/// `fz:<site name>:<host>` (FileZilla). They go straight into the destinations the person imports.
pub passwords: BTreeMap<String, String>,
/// Destinations with a saved password that cannot be read (encrypted by the other app): typed by hand.
pub unreadable: Vec<String>,
}
/// Standard base64 (whitespace ignored). None when it is not base64.
fn base64_decode(s: &str) -> Option<Vec<u8>> {
let mut out = Vec::new();
let (mut acc, mut bits) = (0u32, 0u32);
for c in s.bytes().filter(|c| !c.is_ascii_whitespace()) {
let v = match c {
b'A'..=b'Z' => c - b'A',
b'a'..=b'z' => c - b'a' + 26,
b'0'..=b'9' => c - b'0' + 52,
b'+' => 62,
b'/' => 63,
b'=' => break,
_ => return None,
} as u32;
acc = (acc << 6) | v;
bits += 6;
if bits >= 8 {
bits -= 8;
out.push((acc >> bits) as u8);
acc &= (1 << bits) - 1;
}
}
Some(out)
}
/// A password as text: readable UTF-8 without control characters, else None (encrypted or binary).
fn readable(bytes: Vec<u8>) -> Option<String> {
let s = String::from_utf8(bytes).ok()?;
(!s.is_empty() && !s.chars().any(char::is_control)).then_some(s)
}
fn unquote(v: &str) -> String {
let v = v.trim();
if v.len() >= 2
&& ((v.starts_with('\'') && v.ends_with('\'')) || (v.starts_with('"') && v.ends_with('"')))
{
v[1..v.len() - 1].replace("''", "'")
} else {
v.to_string()
}
}
/// The password of each Photo Mechanic account (`name: [user, password, settings]`, the second item): plain text,
/// or `!binary` base64 when it decodes to text. Some(None): saved but not readable.
pub fn pm_passwords(yaml: &str) -> Vec<(String, Option<String>)> {
let lines: Vec<&str> = yaml.lines().collect();
let mut out = Vec::new();
let mut account: Option<String> = None;
let mut item_indent: Option<usize> = None;
let mut items = 0;
let mut i = 0;
while i < lines.len() {
let line = lines[i];
let indent = line.len() - line.trim_start().len();
let t = line.trim();
i += 1;
if t.ends_with(':') && !t.starts_with('-') && !t.starts_with(':') {
account = Some(unquote(&t[..t.len() - 1]));
item_indent = None;
items = 0;
continue;
}
if !(t.starts_with("- ") || t == "-") {
continue;
}
if item_indent.is_none() {
item_indent = Some(indent);
}
if item_indent != Some(indent) {
continue;
}
items += 1;
if items != 2 {
continue;
}
let Some(name) = account.clone() else {
continue;
};
let value = t[1..].trim();
// What belongs to the item: its value and any deeper lines (a block scalar).
let mut block = String::new();
while i < lines.len() {
let l = lines[i];
let ind = l.len() - l.trim_start().len();
if l.trim().is_empty() || ind > indent {
block.push_str(l.trim());
i += 1;
} else {
break;
}
}
let password = if let Some(rest) = value.strip_prefix("!binary") {
let inline = rest.trim().trim_start_matches(['|', '>', '-']).trim();
base64_decode(&format!("{inline}{block}")).and_then(readable)
} else {
let v = unquote(value);
(!v.is_empty() && v != "~" && v != "null").then_some(v)
};
if password.is_some() || !value.is_empty() && value != "''" {
out.push((name, password));
}
}
out
}
fn tag<'a>(xml: &'a str, name: &str) -> Option<(&'a str, &'a str)> {
let open = format!("<{name}");
let start = xml.find(&open)?;
let after = &xml[start + open.len()..];
if !after.starts_with('>') && !after.starts_with(' ') {
return None;
}
let gt = after.find('>')?;
let attrs = &after[..gt];
let body = &after[gt + 1..];
let end = body.find(&format!("</{name}>"))?;
Some((attrs, &body[..end]))
}
fn xml_text(s: &str) -> String {
s.trim()
.replace("&lt;", "<")
.replace("&gt;", ">")
.replace("&quot;", "\"")
.replace("&apos;", "'")
.replace("&amp;", "&")
}
/// FileZilla's saved passwords per site (`<Pass encoding="base64">`, or plain); one protected by a master password
/// (`encoding="crypt"`) is not readable.
pub fn filezilla_passwords(xml: &str) -> Vec<(String, Option<String>)> {
let mut out = Vec::new();
let mut rest = xml;
while let Some(start) = rest.find("<Server") {
let after = &rest[start..];
let Some(end) = after.find("</Server>") else {
break;
};
let server = &after[..end];
rest = &after[end + "</Server>".len()..];
let Some((attrs, pass)) = tag(server, "Pass") else {
continue;
};
let host = tag(server, "Host")
.map(|(_, v)| xml_text(v))
.unwrap_or_default();
let name = tag(server, "Name")
.map(|(_, v)| xml_text(v))
.filter(|n| !n.is_empty())
.unwrap_or_else(|| host.clone());
let password = if attrs.contains("encoding=\"base64\"") {
base64_decode(pass.trim()).and_then(readable)
} else if attrs.contains("encoding=") {
None
} else {
Some(xml_text(pass)).filter(|p| !p.is_empty())
};
out.push((format!("{name}:{host}"), password));
}
out
}
/// Photo Mechanic's account files list each account as `name: [user, password, settings]`; the password (the second
@@ -284,6 +452,15 @@ pub fn import_sources(home: &Path, config: Option<&Path>) -> ImportSources {
};
if let Some(text) = read_text(&e.path()) {
if text.contains(":settings:") {
for (account, password) in pm_passwords(&text) {
let key = format!("pm:{}:{account}", kind.to_uppercase());
match password {
Some(p) => {
sources.passwords.insert(key, p);
}
None => sources.unreadable.push(key),
}
}
sources.photo_mechanic_accounts.push(Snapshot {
kind: kind.to_string(),
name: kind.to_string(),
@@ -334,10 +511,18 @@ pub fn import_sources(home: &Path, config: Option<&Path>) -> ImportSources {
fz.push(config.join("FileZilla").join("sitemanager.xml"));
fz.push(config.join("filezilla").join("sitemanager.xml"));
}
sources.filezilla = fz
.iter()
.find_map(|p| read_text(p))
.map(|t| strip_filezilla_passwords(&t));
if let Some(xml) = fz.iter().find_map(|p| read_text(p)) {
for (site, password) in filezilla_passwords(&xml) {
let key = format!("fz:{site}");
match password {
Some(p) => {
sources.passwords.insert(key, p);
}
None => sources.unreadable.push(key),
}
}
sources.filezilla = Some(strip_filezilla_passwords(&xml));
}
sources
}
@@ -400,7 +585,7 @@ pub fn delivery_write(
.map(|p| p.to_string_lossy().to_string())
}
/// Upload destinations saved in Photo Mechanic and FileZilla on this computer (without passwords).
/// Upload destinations saved in Photo Mechanic and FileZilla on this computer, with the passwords that can be read.
#[tauri::command]
pub fn import_upload_profiles() -> ImportSources {
let home = dirs::home_dir().unwrap_or_default();
@@ -478,6 +663,27 @@ mod tests {
assert_eq!(out.matches("- ''").count(), 2);
}
#[test]
fn reads_saved_passwords_when_they_are_text() {
let yaml = "---\n:connection_settings_dialog:\n :settings:\n COFINA - ARQUIVO:\n - mnoticiasex\n - !binary |-\n c2VjcmV0\n - :server_addr_edit:\n :value: ftp.cofina.pt\n FPF:\n - fpf\n - plainsecret\n - :server_addr_edit:\n :value: ftp.fpf.pt\n CIFRADA:\n - c\n - !binary |-\n /wCAgQ==\n - :x: 1\n SEM:\n - s\n - ''\n - :x: 1\n";
assert_eq!(
pm_passwords(yaml),
vec![
("COFINA - ARQUIVO".to_string(), Some("secret".to_string())),
("FPF".to_string(), Some("plainsecret".to_string())),
("CIFRADA".to_string(), None),
]
);
let xml = r#"<Servers><Server><Host>ftp.x.pt</Host><User>u</User><Pass encoding="base64">c2VjcmV0</Pass><Name>X &amp; Y</Name></Server><Server><Host>ftp.z.pt</Host><Pass encoding="crypt" pubkey="k">zz</Pass><Name>Z</Name></Server><Server><Host>ftp.n.pt</Host></Server></Servers>"#;
assert_eq!(
filezilla_passwords(xml),
vec![
("X & Y:ftp.x.pt".to_string(), Some("secret".to_string())),
("Z:ftp.z.pt".to_string(), None),
]
);
}
#[test]
fn filezilla_passwords_never_leave() {
let xml = r#"<Server><Host>ftp.x.pt</Host><User>u</User><Pass encoding="base64">c2VjcmV0</Pass><Name>X</Name></Server>"#;
+1
View File
@@ -119,6 +119,7 @@ pub fn run() {
ftp::ftp_open_folder,
ftp::ftp_save_settings,
local::local_original,
local::local_original_changed,
ftp::ftp_preview,
ftp::ftp_info,
catalog::catalog_folders,
+24
View File
@@ -92,6 +92,27 @@ impl LocalIndex {
}
}
impl LocalIndex {
/// The file recorded for this hash, even if it changed since it arrived (another app, Photo Mechanic, wrote
/// captions into it): the same photo, with other metadata. Never handed out as the fingerprinted original.
pub fn find_changed(&self, sha256: &str) -> Option<PathBuf> {
let path = PathBuf::from(self.with(|m| m.get(sha256).cloned())?);
path.is_file().then_some(path)
}
}
/// The file that was the original with this SHA-256 when it arrived, changed since (its metadata): sent to the
/// server as that photo's original when the exact file is no longer here. Error `not_found` when it is gone.
#[tauri::command]
pub async fn local_original_changed(
index: tauri::State<'_, LocalIndex>,
sha256: String,
) -> Result<tauri::ipc::Response, String> {
let path = index.find_changed(&sha256).ok_or("not_found")?;
let bytes = tokio::fs::read(&path).await.map_err(|e| e.to_string())?;
Ok(tauri::ipc::Response::new(bytes))
}
/// The original with this SHA-256 from this computer, or an error `not_found` (then the app downloads it).
#[tauri::command]
pub async fn local_original(
@@ -123,6 +144,7 @@ mod tests {
assert!(index.find(&sha).is_none());
index.record(&sha, &photo);
assert_eq!(index.find(&sha), Some(photo.clone()));
assert_eq!(index.find_changed(&sha), Some(photo.clone()));
// Kept across restarts.
let again = LocalIndex {
file: Some(dir.join("index.json")),
@@ -132,6 +154,8 @@ mod tests {
// A different file under that name is not served as the photo.
std::fs::write(&photo, b"something else").unwrap();
assert!(again.find(&sha).is_none());
// Still there for sending as that photo's original (captions written into it by another app).
assert_eq!(again.find_changed(&sha), Some(photo.clone()));
let _ = std::fs::remove_dir_all(&dir);
}
}
+1 -1
View File
@@ -1,7 +1,7 @@
{
"$schema": "https://schema.tauri.app/config/2",
"productName": "PhotoReport",
"version": "0.3.10",
"version": "0.3.12",
"identifier": "pt.photoreport.desktop",
"build": {
"devUrl": "http://localhost:5173",
+11 -3
View File
@@ -323,9 +323,17 @@ The same queue also delivers to SFTP, FTP/FTPS and Dropbox (`delivery/transports
the finished files to choose from later.
- **Importing destinations** (desktop, "Importar…" in Destinos): Photo Mechanic's upload accounts
(`fileupload/templates/builtin/<kind>-conn.yml`) and templates (`fileupload/snapshot/builtin/<kind>/*.snap`), and
FileZilla's `sitemanager.xml`, read by the desktop app from their fixed places with the passwords removed there;
`library/importSources.ts` turns them into destinations (server, user, folder, size, quality, rename) and the
person types each password.
FileZilla's `sitemanager.xml`, read by the desktop app from their fixed places. The desktop takes the saved
passwords out of those texts and hands them over separately when they are readable (plain, or base64 that decodes
to text; FileZilla's `encoding="crypt"` and binary Photo Mechanic blobs are not); `library/importSources.ts` turns
the rest into destinations (server, user, folder, size, quality, rename), and an encrypted password is typed by
the person.
- **Originals still on the photographer's computer** (the desktop's local FTP sends a 2048 px preview unless told
to send originals): a delivery never renders that preview. It asks the desktop app for the original
(`original.requested`) and waits, re-asking every minute, up to 72 h, without counting attempts. The desktop
sends the file it recorded for that fingerprint; if another app (Photo Mechanic) has written captions into it
since, it goes to `POST /v1/photos/:id/original`, accepted when it has the photo's pixel size; the photo keeps its
fingerprint and library metadata.
- **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=<game>` with the file name and the
+2
View File
@@ -135,6 +135,8 @@ export const DeliveryBestRequest = z.object({
count: z.number().int().min(1).max(300),
/** Only work out the choice (to show it), send nothing. */
dryRun: z.boolean().default(false),
/** Send again the ones this destination already has (a new export, a fixed file). */
again: z.boolean().default(false),
});
export type DeliveryBestRequest = z.infer<typeof DeliveryBestRequest>;
+11 -1
View File
@@ -93,6 +93,16 @@ export class ApiClient {
return this.request("POST", `/v1/photos/${photoId}/original/request`);
}
/**
* Desktop app: the original of a photo that only has its preview on the server, when the file here changed since
* it arrived (captions written into it by another app). Refused (409 `not_the_same_photo`) when it is not.
*/
sendOriginal(photoId: string, file: Blob, name = "original.jpg") {
const form = new FormData();
form.append("file", file, name);
return this.request<{ stored: boolean }>("POST", `/v1/photos/${photoId}/original`, form);
}
/** Desktop app: takes the deliveries waiting for this computer's folders (rendered on the server). */
claimLocalDeliveries(orgId: string, machine: string) {
return this.request<{ items: { id: string; folder: string; path: string; byteSize: number | null }[] }>("POST", `/v1/orgs/${orgId}/deliveries/local/claim`, { machine });
@@ -790,7 +800,7 @@ export class ApiClient {
}
/** Only the best of an event (game moments spread over the match); `dryRun` only works out the choice. */
deliverBest(orgId: string, input: { targetId: string; eventId: string; count: number; dryRun?: boolean }) {
deliverBest(orgId: string, input: { targetId: string; eventId: string; count: number; dryRun?: boolean; again?: boolean }) {
return this.request<{ chosen: string[]; queued: DeliveryItemSummary[]; skipped: { photoId: string; reason: string }[] }>("POST", `/v1/orgs/${orgId}/deliveries/best`, input);
}