Compare commits

...
Author SHA1 Message Date
spark 9f9f5715af Accept a camera clock with no timezone when grouping a property shoot.
ci / rust (pull_request) Successful in 14m36s
ci / typescript (pull_request) Failing after 16m6s
A Canon body stores the wall time without an offset. Rejecting that date rejected the whole folder, so the page showed a generic error after counting the sidecars.
2026-10-21 04:37:33 +01:00
spark 6c17f98ed8 Desktop 0.3.21 copies each card as one stream and keeps going if the window closes.
ci / rust (push) Successful in 13m27s
ci / typescript (push) Failing after 15m4s
desktop-release / build (--target universal-apple-darwin, dmg,app, darwin-universal, macos) (push) Successful in 23m29s
desktop-release / build (deb,appimage, linux-x86_64, ubuntu-latest) (push) Successful in 43m56s
Um cartão é um leitor. A janela pode fechar-se sem parar, dá para parar depois do ficheiro atual, e os presets ficam neste computador.
2026-10-21 04:25:45 +01:00
spark 1998189109 Desktop 0.3.21 copies each card as one stream and keeps going if the window closes.
ci / rust (pull_request) Successful in 13m3s
ci / typescript (pull_request) Failing after 14m57s
A second card is a second reader. The dialog can stop after the current file, shows how much is left, and stores named presets. The property area is a checkbox like the other preferences.
2026-10-21 04:25:15 +01:00
24 changed files with 1036 additions and 291 deletions

No files matched your search

+34
View File
@@ -0,0 +1,34 @@
import { groupBrackets } from "@photoreport/metadata";
import { describe, expect, it } from "vitest";
import { frameClock, groupFrames } from "./clock.js";
describe("camera clock", () => {
it("keeps a wall time with no timezone, and an offset when the file has one", () => {
expect(frameClock("2026-10-21T10:00:00")).toBe("2026-10-21T10:00:00");
expect(frameClock("2026-10-21T10:00:00.200")).toBe("2026-10-21T10:00:00.200");
expect(frameClock("2026-10-21T10:00:00+01:00")).toBe("2026-10-21T10:00:00+01:00");
expect(frameClock("2026-10-21T10:00:00Z")).toBe("2026-10-21T10:00:00Z");
});
it("drops a date that is not a time instead of rejecting the folder", () => {
const frames = groupFrames({
frames: [
{ id: "a", capturedAt: "2026-10-21T10:00:00", exposureBias: -2 },
{ id: "b", capturedAt: "not a date", exposureBias: 0 },
{ id: "c", exposureBias: 2 },
],
});
expect(frames.map((frame) => frame.capturedAt)).toEqual(["2026-10-21T10:00:00", null, null]);
});
it("groups a Canon bracket whose clock has no timezone", () => {
const frames = groupFrames({
frames: [
{ id: "a", fileName: "a.CR3", capturedAt: "2026-10-21T10:00:00", cameraSerial: "body", focalLength: 16, aperture: 8, iso: 100, exposureBias: -2, exposureTime: 0.01 },
{ id: "b", fileName: "b.CR3", capturedAt: "2026-10-21T10:00:00.200", cameraSerial: "body", focalLength: 16, aperture: 8, iso: 100, exposureBias: 0, exposureTime: 0.04 },
{ id: "c", fileName: "c.CR3", capturedAt: "2026-10-21T10:00:00.400", cameraSerial: "body", focalLength: 16, aperture: 8, iso: 100, exposureBias: 2, exposureTime: 0.1 },
],
});
expect(groupBrackets(frames)).toEqual({ stacks: [{ frameIds: ["a", "b", "c"] }], aside: [] });
});
});
+61
View File
@@ -0,0 +1,61 @@
import type { BracketFrame } from "@photoreport/metadata";
import { z } from "zod";
/**
* A camera clock. Canon (and most bodies) store wall time with no timezone, so `2026-10-21T10:00:00`
* is a real capture time. The offset is kept when the file recorded one. Anything else is dropped:
* one bad sidecar must not reject the whole folder.
*/
const cameraInstant = z.iso.datetime({ local: true, offset: true });
export function frameClock(value: string | null | undefined): string | null {
if (value == null) return null;
const trimmed = value.trim();
if (trimmed === "" || trimmed.length > 64) return null;
return cameraInstant.safeParse(trimmed).success ? trimmed : null;
}
const optionalText = z.string().trim().max(300).nullable().optional();
const optionalNumber = z.number().nullable().optional();
const FrameBody = z.object({
id: z.string().trim().min(1).max(2000),
fileName: optionalText,
capturedAt: z.string().nullable().optional().transform((value) => frameClock(value)),
cameraSerial: optionalText,
cameraMake: optionalText,
cameraModel: optionalText,
focalLength: optionalNumber,
aperture: optionalNumber,
iso: optionalNumber,
width: optionalNumber,
height: optionalNumber,
exposureBias: optionalNumber,
exposureTime: optionalNumber,
});
const GroupBody = z.object({ frames: z.array(FrameBody).max(4000) });
function finite(value: number | null | undefined): number | null {
if (value == null || !Number.isFinite(value)) return null;
return value;
}
/** The exposure metadata of one shoot. A date the camera did not write as a time becomes empty. */
export function groupFrames(body: unknown): BracketFrame[] {
return GroupBody.parse(body).frames.map((frame) => ({
id: frame.id,
fileName: frame.fileName ?? null,
capturedAt: frame.capturedAt ?? null,
cameraSerial: frame.cameraSerial ?? null,
cameraMake: frame.cameraMake ?? null,
cameraModel: frame.cameraModel ?? null,
focalLength: finite(frame.focalLength),
aperture: finite(frame.aperture),
iso: finite(frame.iso),
width: finite(frame.width),
height: finite(frame.height),
exposureBias: finite(frame.exposureBias),
exposureTime: finite(frame.exposureTime),
}));
}
+3 -47
View File
@@ -1,35 +1,15 @@
import { groupBrackets, type BracketFrame } from "@photoreport/metadata";
import { groupBrackets } from "@photoreport/metadata";
import type { FastifyInstance } from "fastify";
import { z } from "zod";
import { requireAuth, requireMembership } from "../auth/guard.js";
import type { SessionService } from "../auth/sessions.js";
import type { Db } from "../db.js";
import { conflict } from "../lib/errors.js";
import { groupFrames } from "./clock.js";
const OrgParams = z.object({ orgId: z.uuid() });
const SettingBody = z.object({ enabled: z.boolean() });
const optionalText = z.string().trim().max(300).nullable().optional();
const optionalNumber = z.number().nullable().optional();
const FrameBody = z.object({
id: z.string().trim().min(1).max(400),
fileName: optionalText,
capturedAt: z.iso.datetime().nullable().optional(),
cameraSerial: optionalText,
cameraMake: optionalText,
cameraModel: optionalText,
focalLength: optionalNumber,
aperture: optionalNumber,
iso: optionalNumber,
width: optionalNumber,
height: optionalNumber,
exposureBias: optionalNumber,
exposureTime: optionalNumber,
});
const GroupBody = z.object({ frames: z.array(FrameBody).max(4000) });
/**
* The interior-bracket area. It never touches sports ingest: files stay on the photographer's
* computer and only the exposure metadata is sent, to be grouped. Merging the frames is later.
@@ -60,30 +40,6 @@ export async function registerRealEstateRoutes(app: FastifyInstance, deps: { db:
await requireMembership(db, req, orgId, "PHOTOGRAPHER");
const org = await db.organization.findUniqueOrThrow({ where: { id: orgId }, select: { realEstateEnabled: true } });
if (!org.realEstateEnabled) throw conflict("real_estate_disabled");
const body = GroupBody.parse(req.body);
return groupBrackets(body.frames.map(finiteFrame));
return groupBrackets(groupFrames(req.body));
});
}
function finite(value: number | null | undefined): number | null {
if (value == null || !Number.isFinite(value)) return null;
return value;
}
function finiteFrame(frame: z.infer<typeof FrameBody>): BracketFrame {
return {
id: frame.id,
fileName: frame.fileName ?? null,
capturedAt: frame.capturedAt ?? null,
cameraSerial: frame.cameraSerial ?? null,
cameraMake: frame.cameraMake ?? null,
cameraModel: frame.cameraModel ?? null,
focalLength: finite(frame.focalLength),
aperture: finite(frame.aperture),
iso: finite(frame.iso),
width: finite(frame.width),
height: finite(frame.height),
exposureBias: finite(frame.exposureBias),
exposureTime: finite(frame.exposureTime),
};
}
+16
View File
@@ -79,5 +79,21 @@ describe("real estate", () => {
});
expect(grouped.statusCode).toBe(200);
expect(grouped.json()).toEqual({ stacks: [{ frameIds: ["a", "b", "c"] }], aside: ["solo"] });
const localClock = await ctx.app.inject({
method: "POST",
url: `${url}/groups`,
headers: bearer(photographer.body.accessToken),
payload: {
frames: [
{ ...shot("a", -2, 0), id: "local-a", capturedAt: "2026-10-21T10:00:00" },
{ ...shot("b", 0, 200), id: "local-b", capturedAt: "2026-10-21T10:00:00.200" },
{ ...shot("c", 2, 400), id: "local-c", capturedAt: "2026-10-21T10:00:00.400" },
{ id: "bad", fileName: "nota.XMP", capturedAt: "not a date", cameraSerial: "other", exposureBias: 0 },
],
},
});
expect(localClock.statusCode).toBe(200);
expect(localClock.json()).toEqual({ stacks: [{ frameIds: ["local-a", "local-b", "local-c"] }], aside: ["bad"] });
});
});
+51
View File
@@ -239,6 +239,57 @@ export const t = {
real_estate_disabled: "O imobiliário está desligado nesta organização.",
} as Record<string, string>,
},
snapshots: {
button: "Presets",
name: "Nome do preset",
save: "Guardar",
manage: "Gerir…",
empty: "Ainda não há presets.",
remove: "Apagar",
},
card: {
title: "Importar cartão",
open: "Cartão…",
progressButton: (done: number, total: number) => `Cartão ${done}/${total}`,
openTitle: "Descarregar um cartão para uma pasta datada (copiar ou mover)",
close: "Fechar",
closeKeeps: "Fechar não pára a cópia.",
intro: "Copia (ou move) as fotos de um cartão para uma pasta datada neste computador. Não envia nada para o servidor.",
source: "Origem (cartão/pasta)",
sourcePlaceholder: "Escolhe o cartão…",
add: "Adicionar cartão",
dest: "Destino",
template: "Subpastas (template)",
templateHelp: "Variáveis: {iptcyear4} {iptcmonth0} {iptcday0} {type} {ext} — data pela hora da fotografia, ou pela hora do ficheiro se não houver.",
rawJpeg: "RAW + JPEG",
both: "RAW e JPEG",
rawOnly: "Só RAW",
jpegOnly: "Só JPEG",
move: "Mover (apaga do cartão depois de verificar)",
moveWarn: "Mover apaga os originais do cartão (só depois de a cópia ser verificada por tamanho e checksum).",
overwrite: "Sobrescrever existentes",
sidecars: "Levar WAV/XMP",
needSource: "Escolhe primeiro o cartão/pasta de origem.",
progress: (done: number, total: number, name: string) => `A processar ${done}/${total}… ${name}`,
remaining: (label: string) => `faltam cerca de ${label}`,
stop: "Parar",
stopping: "Pára depois do ficheiro que está a copiar.",
oldShellStop: "Esta versão da app de secretária ainda não consegue parar a meio. Atualiza-a; a cópia que já vai continua.",
remove: "Tirar",
stopped: "Parado",
copy: "Copiar",
moveAction: "Mover",
scan: (raw: number, jpeg: number, other: number, size: string) =>
other > 0 ? `${raw} RAW · ${jpeg} JPEG · ${other} outras · ${size}` : `${raw} RAW · ${jpeg} JPEG · ${size}`,
result: {
moved: (n: number) => `${n} movidas`,
copied: (n: number) => `${n} copiadas`,
skipped: (n: number) => `${n} ignoradas`,
failed: (n: number) => `${n} falhadas`,
empty: "Nada a fazer.",
},
running: (n: number) => (n === 1 ? "1 cartão" : `${n} cartões`),
},
uploading: (done: number, total: number) => `A enviar ${done} de ${total}`,
uploaded: (n: number) => (n === 1 ? "1 foto enviada" : `${n} fotos enviadas`),
uploadFailed: (n: number) => `${n} com erro`,
+153 -125
View File
@@ -1,35 +1,17 @@
import { useEffect, useState } from "react";
import { useEffect, useState, useSyncExternalStore } from "react";
import { t } from "../i18n.js";
import { desktopInvoke } from "../platform.js";
import { copyPace } from "./cardPace.js";
import { cardJobList, dismissCard, enqueueCard, startQueued, stopCard, subscribeCardJobs, type CardJob, type CardResult, type CardSettings, type RawJpeg } from "./cardJobs.js";
import { SnapshotMenu } from "./SnapshotMenu.js";
/**
* "Importar cartão": copies (or moves) photos from a memory card into a dated folder on this computer, like Photo
* Mechanic's Ingest (Cmd+Y). Desktop only. Pure filesystem — it does not send anything to the server. The last
* settings used are remembered. Labels are inline (desktop-only dialog); they can move to i18n later.
* Mechanic's Ingest. Desktop only. Nothing is sent to the server. The copy keeps running if this dialog closes;
* the job list lives outside the component. The last settings are remembered, and named presets sit beside them.
*/
type RawJpeg = "both" | "raw" | "jpeg";
interface CardSettings {
destination: string;
folderTemplate: string;
rawJpeg: RawJpeg;
mv: boolean;
overwrite: boolean;
sidecars: boolean;
}
interface CardScan {
raw: number;
jpeg: number;
other: number;
bytes: number;
}
interface CardResult {
copied: number;
moved: number;
skipped: number;
failed: number;
notes: string[];
destination: string;
}
export type { CardResult, CardScan, CardSettings, RawJpeg } from "./cardJobs.js";
const DEFAULTS: CardSettings = {
destination: "~/Pictures",
@@ -46,16 +28,26 @@ const human = (bytes: number): string => {
return `${Math.max(1, Math.round(bytes / 1e3))} KB`;
};
function useCardJobs(): CardJob[] {
return useSyncExternalStore(subscribeCardJobs, cardJobList, cardJobList);
}
export function CardIngestButton() {
const [open, setOpen] = useState(false);
const jobs = useCardJobs();
const running = jobs.filter((job) => job.status === "running");
let label: string = t.card.open;
if (running.length > 1) label = t.card.running(running.length);
else if (running[0]?.progress) label = t.card.progressButton(running[0].progress.done, running[0].progress.total);
else if (running.length === 1) label = t.card.running(1);
return (
<>
<button
onClick={() => setOpen(true)}
title="Descarregar um cartão para uma pasta datada (copiar ou mover)"
title={t.card.openTitle}
className="h-6 border border-black bg-cell px-2.5 text-[12px] text-ink hover:bg-cell-on"
>
Cartão…
{label}
</button>
{open && <CardDialog onClose={() => setOpen(false)} />}
</>
@@ -63,180 +55,216 @@ export function CardIngestButton() {
}
function CardDialog({ onClose }: { onClose: () => void }) {
const jobs = useCardJobs();
const [s, setS] = useState<CardSettings>(DEFAULTS);
const [source, setSource] = useState("");
const [scan, setScan] = useState<CardScan | null>(null);
const [busy, setBusy] = useState(false);
const [progress, setProgress] = useState<{ done: number; total: number; name: string } | null>(null);
const [result, setResult] = useState<CardResult | null>(null);
const [error, setError] = useState<string | null>(null);
const [stopNote, setStopNote] = useState<string | null>(null);
const canStart = jobs.some((job) => job.status === "queued");
useEffect(() => {
desktopInvoke<CardSettings>("card_settings").then(setS).catch(() => {});
}, []);
useEffect(() => {
let alive = true;
let stop: (() => void) | undefined;
void import("@tauri-apps/api/event").then(({ listen }) =>
listen<{ done: number; total: number; name: string }>("card-progress", (e) => setProgress(e.payload)).then(
(un) => (alive ? (stop = un) : un()),
),
);
return () => {
alive = false;
stop?.();
};
}, []);
const total = scan ? scan.raw + scan.jpeg + scan.other : 0;
const pickSource = async () => {
setError(null);
const p = await desktopInvoke<string | null>("delivery_folder_pick").catch(() => null);
if (!p) return;
setSource(p);
setScan(null);
setResult(null);
try {
setScan(await desktopInvoke<CardScan>("card_scan", { source: p }));
} catch (e) {
setError(String(e));
}
const path = await desktopInvoke<string | null>("delivery_folder_pick").catch(() => null);
if (!path) return;
setSource(path);
await enqueueCard(path);
};
const pickDest = async () => {
const p = await desktopInvoke<string | null>("delivery_folder_pick").catch(() => null);
if (p) setS({ ...s, destination: p });
const path = await desktopInvoke<string | null>("delivery_folder_pick").catch(() => null);
if (path) setS({ ...s, destination: path });
};
const run = async () => {
if (!source) {
setError("Escolhe primeiro o cartão/pasta de origem.");
if (!jobs.some((job) => job.status === "queued")) {
setError(t.card.needSource);
return;
}
setBusy(true);
setError(null);
setResult(null);
setProgress({ done: 0, total, name: "" });
setStopNote(null);
try {
await desktopInvoke("card_save_settings", { settings: s }); // remember the last settings used
setResult(await desktopInvoke<CardResult>("card_ingest", { source, settings: s }));
} catch (e) {
setError(String(e));
} finally {
setBusy(false);
setProgress(null);
await desktopInvoke("card_save_settings", { settings: s });
} catch {
// The copy still uses the settings on screen. Remembering them can wait.
}
await startQueued(s);
};
const field = "h-7 w-full border border-black bg-[#161617] px-2 text-[12px] text-ink focus:border-accent focus:outline-none";
const row = "flex items-center gap-2 text-[12px]";
return (
<div role="dialog" aria-modal="true" aria-label="Importar cartão" className="fixed inset-0 z-40 flex items-center justify-center bg-black/60 p-4">
<div role="dialog" aria-modal="true" aria-label={t.card.title} className="fixed inset-0 z-40 flex items-center justify-center bg-black/60 p-4">
<div className="max-h-full w-full max-w-lg space-y-3 overflow-y-auto border border-line bg-panel p-4 shadow-2xl">
<div className="flex items-center justify-between">
<h2 className="font-semibold uppercase tracking-wide text-ink">Importar cartão</h2>
<button onClick={onClose} className="h-6 border border-black bg-cell px-2 text-[12px] text-ink hover:bg-cell-on">
Fechar
</button>
<div className="flex items-center justify-between gap-2">
<h2 className="font-semibold uppercase tracking-wide text-ink">{t.card.title}</h2>
<div className="flex items-center gap-2">
<SnapshotMenu kind="card" current={s} onApply={setS} />
<button onClick={onClose} className="h-6 border border-black bg-cell px-2 text-[12px] text-ink hover:bg-cell-on">
{t.card.close}
</button>
</div>
</div>
<p className="text-[11px] text-faint">Copia (ou move) as fotos de um cartão para uma pasta datada neste computador. Não envia nada para o servidor.</p>
<p className="text-[11px] text-faint">{t.card.intro}</p>
<p className="text-[11px] text-faint">{t.card.closeKeeps}</p>
<label className="block">
<span className="mb-1 block text-[11px] text-faint">Origem (cartão/pasta)</span>
<span className="mb-1 block text-[11px] text-faint">{t.card.source}</span>
<div className="flex gap-2">
<input readOnly value={source} placeholder="Escolhe o cartão…" className={field} />
<button onClick={() => void pickSource()} className="h-7 shrink-0 border border-black bg-cell px-2.5 text-[12px] text-ink hover:bg-cell-on">
<input readOnly value={source} placeholder={t.card.sourcePlaceholder} className={field} />
<button type="button" aria-label={t.card.add} onClick={() => void pickSource()} className="h-7 shrink-0 border border-black bg-cell px-2.5 text-[12px] text-ink hover:bg-cell-on">
…
</button>
</div>
{scan && (
<span className="mt-1 block text-[11px] text-muted">
{scan.raw} RAW · {scan.jpeg} JPEG{scan.other ? ` · ${scan.other} outras` : ""} · {human(scan.bytes)}
</span>
)}
</label>
{jobs.length > 0 && (
<ul className="space-y-2">
{jobs.map((job) => (
<CardJobRow
key={job.id}
job={job}
onRemove={() => dismissCard(job.id)}
onStop={() => {
setStopNote(null);
void stopCard(job.id).then((note) => {
if (note === "old-shell") setStopNote(t.card.oldShellStop);
else if (note) setStopNote(note);
else setStopNote(t.card.stopping);
});
}}
/>
))}
</ul>
)}
<label className="block">
<span className="mb-1 block text-[11px] text-faint">Destino</span>
<span className="mb-1 block text-[11px] text-faint">{t.card.dest}</span>
<div className="flex gap-2">
<input value={s.destination} onChange={(e) => setS({ ...s, destination: e.target.value })} className={field} />
<button onClick={() => void pickDest()} className="h-7 shrink-0 border border-black bg-cell px-2.5 text-[12px] text-ink hover:bg-cell-on">
<button type="button" onClick={() => void pickDest()} className="h-7 shrink-0 border border-black bg-cell px-2.5 text-[12px] text-ink hover:bg-cell-on">
…
</button>
</div>
</label>
<label className="block">
<span className="mb-1 block text-[11px] text-faint">Subpastas (template)</span>
<span className="mb-1 block text-[11px] text-faint">{t.card.template}</span>
<input value={s.folderTemplate} onChange={(e) => setS({ ...s, folderTemplate: e.target.value })} className={`${field} font-mono`} />
<span className="mt-1 block text-[11px] text-faint">{"Variáveis: {iptcyear4} {iptcmonth0} {iptcday0} {type} {ext} — data pela hora do ficheiro."}</span>
<span className="mt-1 block text-[11px] text-faint">{t.card.templateHelp}</span>
</label>
<div className="grid grid-cols-2 gap-2">
<label className="block">
<span className="mb-1 block text-[11px] text-faint">RAW + JPEG</span>
<span className="mb-1 block text-[11px] text-faint">{t.card.rawJpeg}</span>
<select value={s.rawJpeg} onChange={(e) => setS({ ...s, rawJpeg: e.target.value as RawJpeg })} className={field}>
<option value="both">RAW e JPEG</option>
<option value="raw">Só RAW</option>
<option value="jpeg">Só JPEG</option>
<option value="both">{t.card.both}</option>
<option value="raw">{t.card.rawOnly}</option>
<option value="jpeg">{t.card.jpegOnly}</option>
</select>
</label>
<div className="flex flex-col justify-end gap-1">
<label className={row}>
<input type="checkbox" checked={s.mv} onChange={(e) => setS({ ...s, mv: e.target.checked })} />
Mover (apaga do cartão depois de verificar)
{t.card.move}
</label>
<label className={row}>
<input type="checkbox" checked={s.overwrite} onChange={(e) => setS({ ...s, overwrite: e.target.checked })} />
Sobrescrever existentes
{t.card.overwrite}
</label>
<label className={row}>
<input type="checkbox" checked={s.sidecars} onChange={(e) => setS({ ...s, sidecars: e.target.checked })} />
Levar WAV/XMP
{t.card.sidecars}
</label>
</div>
</div>
{s.mv && <p className="text-[11px] text-[#f0c27a]">Mover apaga os originais do cartão (só depois de a cópia ser verificada por tamanho e checksum).</p>}
{s.mv && <p className="text-[11px] text-[#f0c27a]">{t.card.moveWarn}</p>}
{error && <p className="text-[11px] text-danger">{error}</p>}
{progress && busy && (
<p className="text-[11px] text-muted">
A processar {progress.done}/{progress.total}… {progress.name}
</p>
)}
{result && (
<div className="border border-line bg-cell p-2 text-[11px] text-ink">
<p>
{result.moved ? `${result.moved} movidas · ` : ""}
{result.copied ? `${result.copied} copiadas · ` : ""}
{result.skipped ? `${result.skipped} ignoradas · ` : ""}
{result.failed ? `${result.failed} falhadas` : ""}
{!result.moved && !result.copied && !result.skipped && !result.failed ? "Nada a fazer." : ""}
</p>
<p className="mt-1 break-all text-faint">{result.destination}</p>
{result.notes.length > 0 && (
<ul className="mt-1 list-inside list-disc text-faint">
{result.notes.slice(0, 8).map((n, i) => (
<li key={i}>{n}</li>
))}
</ul>
)}
</div>
)}
{stopNote && <p className="text-[11px] text-muted">{stopNote}</p>}
<div className="flex justify-end gap-2 pt-1">
<button
onClick={() => void run()}
disabled={busy || !source}
disabled={!canStart}
className="h-7 bg-accent px-3 text-[12px] font-semibold text-white hover:bg-accent-strong disabled:opacity-40"
>
{s.mv ? "Mover" : "Copiar"}
{s.mv ? t.card.moveAction : t.card.copy}
</button>
</div>
</div>
</div>
);
}
function CardJobRow({ job, onRemove, onStop }: { job: CardJob; onRemove: () => void; onStop: () => void }) {
const [, setTick] = useState(0);
useEffect(() => {
if (job.status !== "running") return;
const timer = setInterval(() => setTick((n) => n + 1), 1000);
return () => clearInterval(timer);
}, [job.status]);
const pace = copyPace(job.progress, job.startedAt, Date.now());
const name = job.source.split("/").filter(Boolean).pop() ?? job.source;
const scan = job.scan ? t.card.scan(job.scan.raw, job.scan.jpeg, job.scan.other, human(job.scan.bytes)) : null;
return (
<li className="border border-line bg-cell p-2 text-[11px] text-ink">
<div className="flex items-center justify-between gap-2">
<span className="min-w-0 truncate">{name}</span>
{job.status !== "running" && (
<button type="button" onClick={onRemove} className="shrink-0 text-faint hover:text-ink">
{t.card.remove}
</button>
)}
{job.status === "running" && (
<button type="button" onClick={onStop} className="shrink-0 border border-black bg-panel px-2 py-0.5 text-ink hover:bg-cell-on">
{t.card.stop}
</button>
)}
{job.status === "stopped" && <span className="shrink-0 text-faint">{t.card.stopped}</span>}
</div>
{scan && <p className="mt-1 text-muted">{scan}</p>}
{job.status === "running" && job.progress && (
<>
<div className="mt-2 h-1.5 overflow-hidden bg-black">
<div className="h-full bg-accent" style={{ width: `${Math.round(pace.fraction * 100)}%` }} />
</div>
<p className="mt-1 text-muted">
{t.card.progress(job.progress.done, job.progress.total, job.progress.name)}
{pace.left ? ` · ${t.card.remaining(pace.left)}` : ""}
</p>
</>
)}
{job.error && <p className="mt-1 text-danger">{job.error}</p>}
{job.result && <JobResult result={job.result} />}
</li>
);
}
function JobResult({ result }: { result: CardResult }) {
const parts = [
result.moved ? t.card.result.moved(result.moved) : "",
result.copied ? t.card.result.copied(result.copied) : "",
result.skipped ? t.card.result.skipped(result.skipped) : "",
result.failed ? t.card.result.failed(result.failed) : "",
].filter(Boolean);
return (
<div className="mt-1">
<p>{parts.length > 0 ? parts.join(" · ") : t.card.result.empty}</p>
<p className="mt-1 break-all text-faint">{result.destination}</p>
{result.notes.length > 0 && (
<ul className="mt-1 list-inside list-disc text-faint">
{result.notes.slice(0, 8).map((note) => (
<li key={note}>{note}</li>
))}
</ul>
)}
</div>
);
}
+4
View File
@@ -7,6 +7,7 @@ import { exifDateTime, lisbonInstant, localPhoto, localPhotos, routeLocally } fr
import { localId, offlineQueue } from "../offline/queue.js";
import { useCallback, useEffect, useRef, useState } from "react";
import { t } from "../i18n.js";
import { SnapshotMenu } from "./SnapshotMenu.js";
import { asArrayBuffer, prefs } from "../platform.js";
import type { DesktopOrigin, PreviewOf, UploadStatus } from "./uploads.js";
@@ -349,6 +350,9 @@ function SettingsForm({ ftp, initial, onDone }: { ftp: LocalFtpState; initial: F
void ftp.save(s).then((ok) => ok && onDone());
}}
>
<div className="flex justify-end">
<SnapshotMenu kind="ftp" current={s} onApply={setS} />
</div>
<label className="block">
<span className="text-[11px] uppercase tracking-wide text-faint">{L.port}</span>
<input className={field} type="number" min={1024} max={65535} value={s.port} onChange={(e) => setS({ ...s, port: Number(e.target.value) })} />
+100
View File
@@ -0,0 +1,100 @@
import { useState } from "react";
import { t } from "../i18n.js";
import { deleteSnapshot, loadSnapshots, saveSnapshot } from "./snapshots.js";
/**
* Photo Mechanic's snapshot menu: the dialog remembers the last settings on its own, and a named preset
* brings a whole setup back (destination and template, or an FTP login set).
*/
export function SnapshotMenu<T>({ kind, current, onApply }: { kind: string; current: T; onApply: (settings: T) => void }) {
const [open, setOpen] = useState(false);
const [manage, setManage] = useState(false);
const [name, setName] = useState("");
const [items, setItems] = useState(() => loadSnapshots<T>(kind));
const refresh = () => setItems(loadSnapshots<T>(kind));
return (
<div className="relative">
<button
type="button"
aria-expanded={open}
aria-label={t.snapshots.button}
onClick={() => {
refresh();
setOpen((value) => !value);
}}
className="h-6 border border-black bg-cell px-2 text-[12px] text-ink hover:bg-cell-on"
>
{t.snapshots.button}
</button>
{open && (
<div className="absolute right-0 z-10 mt-1 w-56 border border-black bg-panel p-2 text-[12px] shadow-xl">
<div className="flex gap-1">
<input
aria-label={t.snapshots.name}
value={name}
onChange={(event) => setName(event.target.value)}
onKeyDown={(event) => {
if (event.key !== "Enter") return;
event.preventDefault();
setItems(saveSnapshot(kind, name, current));
setName("");
}}
placeholder={t.snapshots.name}
className="h-7 min-w-0 flex-1 border border-black bg-[#161617] px-2 text-ink focus:border-accent focus:outline-none"
/>
<button
type="button"
onClick={() => {
setItems(saveSnapshot(kind, name, current));
setName("");
}}
className="h-7 shrink-0 border border-black bg-cell px-2 text-ink hover:bg-cell-on"
>
{t.snapshots.save}
</button>
</div>
<button
type="button"
onClick={() => setManage((value) => !value)}
className="mt-2 block text-left text-accent underline"
>
{t.snapshots.manage}
</button>
{items.length === 0 ? (
<p className="mt-2 text-faint">{t.snapshots.empty}</p>
) : (
<ul className="mt-1 max-h-48 overflow-y-auto">
{items.map((item) => (
<li key={item.name} className="flex items-center gap-1">
<button
type="button"
onClick={() => {
onApply(item.settings);
setOpen(false);
setManage(false);
}}
className="min-w-0 flex-1 truncate py-1 text-left text-ink hover:bg-cell"
>
{item.name}
</button>
{manage && (
<button
type="button"
aria-label={`${t.snapshots.remove} ${item.name}`}
onClick={() => setItems(deleteSnapshot(kind, item.name))}
className="px-1 text-faint hover:text-ink"
>
×
</button>
)}
</li>
))}
</ul>
)}
</div>
)}
</div>
);
}
+56
View File
@@ -0,0 +1,56 @@
import { beforeEach, describe, expect, it, vi } from "vitest";
const invoke = vi.fn();
vi.mock("../platform.js", () => ({
desktopInvoke: (...args: unknown[]) => invoke(...args),
}));
import { cardJobList, enqueueCard, resetCardJobsForTests, startQueued } from "./cardJobs.js";
const settings = {
destination: "/tmp/out",
folderTemplate: "{type}",
rawJpeg: "both" as const,
mv: false,
overwrite: false,
sidecars: true,
};
describe("card jobs", () => {
beforeEach(() => {
resetCardJobsForTests();
invoke.mockReset();
});
it("runs several cards together when the shell can stop one", async () => {
invoke.mockImplementation(async (cmd: string, args: { source?: string; jobId?: string }) => {
if (cmd === "card_cancel") return null;
if (cmd === "card_scan") return { raw: 1, jpeg: 2, other: 0, bytes: 30 };
if (cmd === "card_ingest") return { copied: 3, moved: 0, skipped: 0, failed: 0, notes: [], destination: "/tmp/out", stopped: false, source: args.source, jobId: args.jobId };
throw new Error(cmd);
});
await enqueueCard("/Volumes/ONE");
await enqueueCard("/Volumes/TWO");
await startQueued(settings);
const copies = invoke.mock.calls.filter((call) => call[0] === "card_ingest");
expect(copies).toHaveLength(2);
expect(copies.every((call) => typeof call[1].jobId === "string" && call[1].jobId !== "")).toBe(true);
expect(cardJobList().every((job) => job.status === "done")).toBe(true);
});
it("queues cards one after another on a shell that cannot stop", async () => {
invoke.mockImplementation(async (cmd: string) => {
if (cmd === "card_cancel") throw new Error("Command card_cancel not found");
if (cmd === "card_scan") return { raw: 0, jpeg: 1, other: 0, bytes: 10 };
if (cmd === "card_ingest") return { copied: 1, moved: 0, skipped: 0, failed: 0, notes: [], destination: "/tmp/out", stopped: false };
throw new Error(cmd);
});
await enqueueCard("/Volumes/ONE");
await enqueueCard("/Volumes/TWO");
await startQueued(settings);
const copies = invoke.mock.calls.filter((call) => call[0] === "card_ingest");
expect(copies).toHaveLength(2);
expect(copies.every((call) => call[1].jobId === undefined)).toBe(true);
});
});
+175
View File
@@ -0,0 +1,175 @@
import { desktopInvoke } from "../platform.js";
export type RawJpeg = "both" | "raw" | "jpeg";
export interface CardSettings {
destination: string;
folderTemplate: string;
rawJpeg: RawJpeg;
mv: boolean;
overwrite: boolean;
sidecars: boolean;
}
export interface CardScan {
raw: number;
jpeg: number;
other: number;
bytes: number;
}
export interface CardResult {
copied: number;
moved: number;
skipped: number;
failed: number;
notes: string[];
destination: string;
stopped?: boolean;
}
export interface CardProgress {
done: number;
total: number;
name: string;
jobId?: string;
bytesDone?: number;
bytesTotal?: number;
}
export type CardJobStatus = "queued" | "running" | "done" | "stopped" | "error";
export interface CardJob {
id: string;
source: string;
settings: CardSettings | null;
scan: CardScan | null;
status: CardJobStatus;
progress: CardProgress | null;
startedAt: number | null;
result: CardResult | null;
error: string | null;
}
type Listener = () => void;
let jobs: CardJob[] = [];
let canStop: boolean | null = null;
const listeners = new Set<Listener>();
let listening = false;
function emit() {
for (const listener of listeners) listener();
}
function patch(id: string, next: Partial<CardJob>) {
jobs = jobs.map((job) => (job.id === id ? { ...job, ...next } : job));
emit();
}
export function cardJobList(): CardJob[] {
return jobs;
}
/** Clears the in-memory queue. Tests only. */
export function resetCardJobsForTests() {
jobs = [];
canStop = null;
listeners.clear();
}
export function subscribeCardJobs(listener: Listener): () => void {
listeners.add(listener);
ensureProgress();
return () => {
listeners.delete(listener);
};
}
/** The installed shell can stop a card when `card_cancel` exists. An older shell throws. */
export async function shellCanStop(): Promise<boolean> {
if (canStop !== null) return canStop;
try {
await desktopInvoke("card_cancel", { jobId: "" });
canStop = true;
} catch {
canStop = false;
}
return canStop;
}
function ensureProgress() {
if (listening || typeof window === "undefined") return;
listening = true;
void import("@tauri-apps/api/event")
.then(({ listen }) =>
listen<CardProgress>("card-progress", (event) => {
const progress = event.payload;
const named = progress.jobId ? jobs.find((job) => job.id === progress.jobId) : undefined;
const job = named ?? jobs.find((item) => item.status === "running");
if (!job) return;
patch(job.id, { progress, startedAt: job.startedAt ?? Date.now() });
}),
)
.catch(() => {
listening = false;
});
}
export async function enqueueCard(source: string): Promise<void> {
const id = `${Date.now().toString(36)}-${Math.random().toString(36).slice(2, 8)}`;
jobs = [...jobs, { id, source, settings: null, scan: null, status: "queued", progress: null, startedAt: null, result: null, error: null }];
emit();
try {
const scan = await desktopInvoke<CardScan>("card_scan", { source });
patch(id, { scan });
} catch (err) {
const job = jobs.find((item) => item.id === id);
if (job?.status === "queued") patch(id, { status: "error", error: String(err) });
}
}
/** Drops a card that is not copying. A running copy stays until it finishes or is stopped. */
export function dismissCard(id: string) {
jobs = jobs.filter((job) => job.id !== id || job.status === "running");
emit();
}
async function runJob(id: string, settings: CardSettings, withId: boolean) {
const job = jobs.find((item) => item.id === id);
if (!job || job.status !== "queued") return;
patch(id, { settings, status: "running", startedAt: Date.now(), error: null, result: null });
const args: Record<string, unknown> = { source: job.source, settings };
if (withId) args.jobId = id;
try {
const result = await desktopInvoke<CardResult>("card_ingest", args);
patch(id, { status: result.stopped ? "stopped" : "done", result });
} catch (err) {
patch(id, { status: "error", error: String(err) });
}
}
/** Starts every card still waiting. A shell that can stop runs them together; an older one, one after another. */
export async function startQueued(settings: CardSettings): Promise<void> {
ensureProgress();
const parallel = await shellCanStop();
const ids = jobs.filter((job) => job.status === "queued").map((job) => job.id);
if (parallel) {
await Promise.all(ids.map((id) => runJob(id, settings, true)));
return;
}
for (const id of ids) {
await runJob(id, settings, false);
}
}
export async function stopCard(id: string): Promise<string | null> {
const ok = await shellCanStop();
if (!ok) return "old-shell";
try {
await desktopInvoke("card_cancel", { jobId: id });
return null;
} catch (err) {
return String(err);
}
}
+20
View File
@@ -0,0 +1,20 @@
import { describe, expect, it } from "vitest";
import { copyPace, formatRemaining, remainingMs } from "./cardPace.js";
describe("card copy pace", () => {
it("estimates the rest from the bytes already written", () => {
const started = 1_000;
expect(remainingMs(10, 40, started, started + 10_000)).toBe(30_000);
expect(formatRemaining(30_000)).toBe("1 min");
expect(formatRemaining(90 * 60_000)).toBe("1 h 30 min");
const pace = copyPace({ done: 1, total: 4, bytesDone: 10, bytesTotal: 40 }, started, started + 10_000);
expect(pace.fraction).toBeCloseTo(0.25);
expect(pace.left).toBe("1 min");
});
it("waits for a little progress before guessing", () => {
expect(remainingMs(0, 10, 0, 5_000)).toBeNull();
expect(remainingMs(1, 10, 0, 100)).toBeNull();
expect(copyPace(null, 0, 1_000)).toEqual({ fraction: 0, left: null });
});
});
+32
View File
@@ -0,0 +1,32 @@
/** How far a card copy has got, and how long the rest should take at the pace so far. */
export function remainingMs(done: number, total: number, startedAt: number, now: number): number | null {
if (done <= 0 || total <= 0 || done >= total) return null;
const elapsed = now - startedAt;
if (elapsed < 500) return null;
return Math.round((elapsed / done) * (total - done));
}
export function formatRemaining(ms: number): string {
const minutes = Math.round(ms / 60_000);
if (minutes < 1) return "menos de 1 min";
if (minutes < 60) return minutes === 1 ? "1 min" : `${minutes} min`;
const hours = Math.floor(minutes / 60);
const rest = minutes % 60;
if (rest === 0) return hours === 1 ? "1 h" : `${hours} h`;
return `${hours} h ${rest} min`;
}
export function copyPace(
progress: { done: number; total: number; bytesDone?: number; bytesTotal?: number } | null,
startedAt: number | null,
now: number,
): { fraction: number; left: string | null } {
if (!progress || startedAt === null || progress.total <= 0) return { fraction: 0, left: null };
const byBytes = (progress.bytesTotal ?? 0) > 0;
const done = byBytes ? (progress.bytesDone ?? 0) : progress.done;
const total = byBytes ? (progress.bytesTotal as number) : progress.total;
if (total <= 0) return { fraction: 0, left: null };
const fraction = Math.max(0, Math.min(1, done / total));
const left = remainingMs(done, total, startedAt, now);
return { fraction, left: left === null ? null : formatRemaining(left) };
}
+24
View File
@@ -0,0 +1,24 @@
import { beforeEach, describe, expect, it } from "vitest";
import { deleteSnapshot, loadSnapshots, saveSnapshot } from "./snapshots.js";
describe("dialog presets", () => {
beforeEach(() => localStorage.clear());
it("remembers a named preset and replaces one with the same name", () => {
saveSnapshot("card", "Estúdio", { destination: "/a" });
saveSnapshot("card", "Arquivo", { destination: "/b" });
saveSnapshot("card", "Estúdio", { destination: "/c" });
expect(loadSnapshots<{ destination: string }>("card").map((item) => [item.name, item.settings.destination])).toEqual([
["Arquivo", "/b"],
["Estúdio", "/c"],
]);
});
it("drops a preset without touching another dialog", () => {
saveSnapshot("card", "Estúdio", { destination: "/a" });
saveSnapshot("ftp", "Campo", { port: 2121 });
deleteSnapshot("card", "Estúdio");
expect(loadSnapshots("card")).toEqual([]);
expect(loadSnapshots<{ port: number }>("ftp")[0]?.settings.port).toBe(2121);
});
});
+44
View File
@@ -0,0 +1,44 @@
import { prefs } from "../platform.js";
/** A named set of dialog settings, the same idea as a Photo Mechanic snapshot. */
export interface Snapshot<T> {
name: string;
settings: T;
}
function storageKey(kind: string): string {
return `snapshot.${kind}`;
}
export function loadSnapshots<T>(kind: string): Snapshot<T>[] {
const raw = prefs.get(storageKey(kind));
if (!raw) return [];
try {
const parsed = JSON.parse(raw) as unknown;
if (!Array.isArray(parsed)) return [];
return parsed.filter((item): item is Snapshot<T> => {
if (!item || typeof item !== "object") return false;
const row = item as { name?: unknown; settings?: unknown };
return typeof row.name === "string" && row.name.trim() !== "" && row.settings !== undefined;
});
} catch {
return [];
}
}
/** Saves under `name`, replacing a preset with the same name. Names sort in Portuguese. */
export function saveSnapshot<T>(kind: string, name: string, settings: T): Snapshot<T>[] {
const trimmed = name.trim();
if (trimmed === "") return loadSnapshots(kind);
const next = loadSnapshots<T>(kind).filter((item) => item.name !== trimmed);
next.push({ name: trimmed, settings });
next.sort((a, b) => a.name.localeCompare(b.name, "pt"));
prefs.set(storageKey(kind), JSON.stringify(next));
return next;
}
export function deleteSnapshot<T>(kind: string, name: string): Snapshot<T>[] {
const next = loadSnapshots<T>(kind).filter((item) => item.name !== name);
prefs.set(storageKey(kind), JSON.stringify(next));
return next;
}
+17 -24
View File
@@ -54,22 +54,15 @@ export function PreferencesPage() {
</label>
</li>
))}
</ul>
</section>
{role === "OWNER" && organization && (
<section className="max-w-2xl px-6 pb-6">
<div className="border border-line bg-panel">
<div className="panel-head">
<span>{t.realEstate.setting}</span>
<span className={realEstateOn ? "text-ok" : "text-faint"}>{realEstateOn ? t.realEstate.enabled : t.realEstate.off}</span>
</div>
<div className="space-y-3 p-4">
<p className="text-[13px] text-muted">{t.realEstate.settingHelp}</p>
{realEstateError && <p className="text-[12px] text-danger">{realEstateError}</p>}
<div className="flex justify-end">
<button
{role === "OWNER" && organization && (
<li>
<label className="flex h-11 cursor-pointer items-center gap-3 rounded-md border border-line bg-panel px-3 text-sm hover:border-faint">
<input
type="checkbox"
className="h-4 w-4 accent-[var(--color-accent)]"
checked={realEstateOn}
disabled={realEstateBusy}
onClick={() => {
onChange={() => {
setRealEstateBusy(true);
setRealEstateError(null);
void (async () => {
@@ -84,15 +77,15 @@ export function PreferencesPage() {
}
})();
}}
className="h-8 border border-black bg-cell px-4 text-[13px] hover:bg-cell-on disabled:opacity-50"
>
{realEstateOn ? t.realEstate.disable : t.realEstate.enable}
</button>
</div>
</div>
</div>
</section>
)}
/>
{t.realEstate.setting}
</label>
</li>
)}
</ul>
{role === "OWNER" && organization && <p className="mt-3 text-sm text-muted">{t.realEstate.settingHelp}</p>}
{realEstateError && <Alert>{realEstateError}</Alert>}
</section>
{isDesktop() && <LocalCatalog />}
</>
);
+1 -1
View File
@@ -103,7 +103,7 @@ describe("real estate area", () => {
window.history.pushState({}, "", "/preferences");
const api = fakeApi(me("OWNER", false));
render(<App api={api} />);
await userEvent.click(await screen.findByRole("button", { name: "Ligar" }));
await userEvent.click(await screen.findByRole("checkbox", { name: "Imobiliário" }));
expect(api.setRealEstate).toHaveBeenCalledWith("o1", true);
});
});
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "@photoreport/desktop",
"version": "0.3.20",
"version": "0.3.21",
"private": true,
"type": "module",
"scripts": {
+1 -1
View File
@@ -1,6 +1,6 @@
[package]
name = "photoreport-desktop"
version = "0.3.20"
version = "0.3.21"
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
@@ -28,6 +28,7 @@ fn main() {
"catalog_cancel",
"card_scan",
"card_ingest",
"card_cancel",
"card_settings",
"card_save_settings",
"faces_local",
@@ -43,6 +43,7 @@
"allow-catalog-cancel",
"allow-card-scan",
"allow-card-ingest",
"allow-card-cancel",
"allow-card-settings",
"allow-card-save-settings",
"allow-faces-local",
@@ -0,0 +1,11 @@
# Automatically generated - DO NOT EDIT!
[[permission]]
identifier = "allow-card-cancel"
description = "Enables the card_cancel command without any pre-configured scope."
commands.allow = ["card_cancel"]
[[permission]]
identifier = "deny-card-cancel"
description = "Denies the card_cancel command without any pre-configured scope."
commands.deny = ["card_cancel"]
+228 -91
View File
@@ -5,11 +5,15 @@
//! then deletes the original; on any mismatch or error it never deletes, so a card is never emptied of a file
//! that did not arrive whole. The last settings used are remembered (like Photo Mechanic's dialog).
use std::io::{Read, Write};
use std::path::{Path, PathBuf};
use std::sync::Mutex;
use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::{Arc, Mutex};
use std::collections::HashMap;
use chrono::{Datelike, Local, TimeZone};
use serde::{Deserialize, Serialize};
use sha2::{Digest, Sha256};
use tauri::{AppHandle, Emitter};
use crate::local::sha256_file;
@@ -92,6 +96,8 @@ impl Default for CardSettings {
pub struct CardState {
settings: Mutex<Option<CardSettings>>,
config_path: Option<PathBuf>,
/// One flag per running card. A second card is another command, so the cards run side by side.
cancel: Mutex<HashMap<String, Arc<AtomicBool>>>,
}
fn config_file() -> PathBuf {
@@ -126,6 +132,22 @@ impl CardState {
*self.settings.lock().unwrap() = Some(s);
Ok(())
}
fn begin(&self, job_id: &str) -> Arc<AtomicBool> {
let flag = Arc::new(AtomicBool::new(false));
self.cancel.lock().unwrap().insert(job_id.to_string(), flag.clone());
flag
}
fn end(&self, job_id: &str) {
self.cancel.lock().unwrap().remove(job_id);
}
fn stop(&self, job_id: &str) {
if let Some(flag) = self.cancel.lock().unwrap().get(job_id) {
flag.store(true, Ordering::Relaxed);
}
}
}
/// The type folder for a file: "RAW", "JPEG", or the extension upper-cased for anything else.
@@ -178,15 +200,28 @@ fn ymd_from_capture(bytes: &[u8]) -> Option<(i32, u32, u32)> {
}
}
/// The capture day of a photo. LightCraft reads EXIF, then IPTC, then XMP, including a CR3 with no JPEG
/// beside it. A JPEG whose header the engine cannot read still tries the short EXIF scan. Otherwise the
/// file's modification time — on a card straight from the camera that is when the frame was shot.
/// Capture day from the bytes already in memory. The header is enough for a JPEG; a CR3 sometimes
/// keeps the metadata at the end, so the caller reads the rest only when the head had no clock.
fn ymd_of(bytes: &[u8]) -> Option<(i32, u32, u32)> {
ymd_from_capture(bytes).or_else(|| crate::preview::exif_date(bytes))
}
/// The capture day of a photo. LightCraft reads EXIF, then IPTC, then XMP. A JPEG is not read whole:
/// the clock is in the header. A raw whose header has no clock is read whole (a CR3 can park it at the
/// end). Otherwise the file's modification time — on a card straight from the camera that is the shot.
fn capture_day(path: &Path, ext: &str) -> chrono::DateTime<Local> {
let from_engine = || std::fs::read(path).ok().and_then(|bytes| ymd_from_capture(&bytes));
let ymd = if is_jpeg(ext) {
from_engine().or_else(|| crate::preview::exif_date(&read_head(path)))
} else if is_image(ext) {
from_engine().or_else(|| sibling_jpeg(path).and_then(|j| crate::preview::exif_date(&read_head(&j))))
let from_file = |path: &Path| {
let head = read_head(path);
if let Some(day) = ymd_of(&head) {
return Some(day);
}
if head.len() < 256 * 1024 {
return None;
}
std::fs::read(path).ok().and_then(|bytes| ymd_of(&bytes))
};
let ymd = if is_image(ext) {
from_file(path).or_else(|| sibling_jpeg(path).and_then(|j| from_file(&j)))
} else {
None
};
@@ -289,6 +324,8 @@ pub struct CardResult {
/// A few lines describing what failed or was skipped, for the person to see.
pub notes: Vec<String>,
pub destination: String,
/// The photographer asked to stop. Files already verified stay; the rest were not touched.
pub stopped: bool,
}
#[derive(Serialize, Clone)]
@@ -297,6 +334,9 @@ struct Progress {
done: usize,
total: usize,
name: String,
job_id: String,
bytes_done: u64,
bytes_total: u64,
}
fn wanted(ext: &str, mode: RawJpeg) -> bool {
@@ -307,112 +347,177 @@ fn wanted(ext: &str, mode: RawJpeg) -> bool {
}
}
/// Copies one file and checks the copy is whole (same size, same SHA-256). Returns Ok only when it is.
/// Copies one file, hashing the card as the bytes are read, then checks the copy on disk.
/// The card is read once. A second read of the same card, only to hash it, is what made a full
/// offload take about twice as long. Returns Ok only when the copy matches.
fn copy_verified(src: &Path, dst: &Path) -> Result<(), String> {
std::fs::copy(src, dst).map_err(|e| format!("copy: {e}"))?;
let src_len = std::fs::metadata(src).map_err(|e| e.to_string())?.len();
let dst_len = std::fs::metadata(dst).map_err(|e| e.to_string())?.len();
if src_len != dst_len {
let _ = std::fs::remove_file(dst);
return Err("size mismatch after copy".into());
let mut input = std::fs::File::open(src).map_err(|e| format!("copy: {e}"))?;
let mut output = std::fs::File::create(dst).map_err(|e| format!("copy: {e}"))?;
let mut hasher = Sha256::new();
let mut buf = vec![0u8; 1 << 20];
loop {
let n = input.read(&mut buf).map_err(|e| format!("copy: {e}"))?;
if n == 0 {
break;
}
hasher.update(&buf[..n]);
if let Err(e) = output.write_all(&buf[..n]) {
let _ = std::fs::remove_file(dst);
return Err(format!("copy: {e}"));
}
}
if sha256_file(src).map_err(|e| e.to_string())? != sha256_file(dst).map_err(|e| e.to_string())? {
let _ = output.sync_all();
drop(output);
let src_hex = hex_of(&hasher.finalize());
let dst_hex = match sha256_file(dst) {
Ok(hex) => hex,
Err(e) => {
let _ = std::fs::remove_file(dst);
return Err(e.to_string());
}
};
if src_hex != dst_hex {
let _ = std::fs::remove_file(dst);
return Err("checksum mismatch after copy".into());
}
Ok(())
}
fn hex_of(bytes: &[u8]) -> String {
bytes.iter().map(|b| format!("{b:02x}")).collect()
}
fn note(notes: &mut Vec<String>, line: &str) {
if notes.len() < 20 {
notes.push(line.to_string());
}
}
/// Copies (or moves) the chosen photos from `source` into the dated folders under the destination. Emits
/// `card-progress` events as it goes.
#[tauri::command]
pub async fn card_ingest(app: AppHandle, source: String, settings: CardSettings) -> Result<CardResult, String> {
tauri::async_runtime::spawn_blocking(move || {
let root = expand(&source);
if !root.is_dir() {
return Err("not_a_folder".to_string());
fn report(app: Option<&AppHandle>, progress: &Progress) {
if let Some(app) = app {
let _ = app.emit("card-progress", progress);
}
}
/// One card, one stream. A memory card has a single reader: several threads on it seek back and forth and
/// usually finish later, not sooner. A second card is a second call, so the two readers work at once.
fn ingest_dir(app: Option<&AppHandle>, root: &Path, settings: &CardSettings, job_id: &str, cancel: &AtomicBool) -> Result<CardResult, String> {
if !root.is_dir() {
return Err("not_a_folder".to_string());
}
let base = expand(&settings.destination);
let mut files = Vec::new();
collect(root, &mut files);
let photos: Vec<PathBuf> = files.into_iter().filter(|f| wanted(&ext_of(f), settings.raw_jpeg)).collect();
let total = photos.len();
let bytes_total: u64 = photos.iter().map(|p| std::fs::metadata(p).map(|m| m.len()).unwrap_or(0)).sum();
let mut bytes_done = 0u64;
let mut r = CardResult {
copied: 0,
moved: 0,
skipped: 0,
failed: 0,
notes: Vec::new(),
destination: base.to_string_lossy().to_string(),
stopped: false,
};
for (i, src) in photos.iter().enumerate() {
if cancel.load(Ordering::Relaxed) {
r.stopped = true;
break;
}
let base = expand(&settings.destination);
let mut files = Vec::new();
collect(&root, &mut files);
let photos: Vec<PathBuf> = files.iter().filter(|f| wanted(&ext_of(f), settings.raw_jpeg)).cloned().collect();
let total = photos.len();
let mut r = CardResult {
copied: 0,
moved: 0,
skipped: 0,
failed: 0,
notes: Vec::new(),
destination: base.to_string_lossy().to_string(),
};
for (i, src) in photos.iter().enumerate() {
let name = src.file_name().map(|n| n.to_string_lossy().to_string()).unwrap_or_default();
let _ = app.emit("card-progress", Progress { done: i, total, name: name.clone() });
let name = src.file_name().map(|n| n.to_string_lossy().to_string()).unwrap_or_default();
let len = std::fs::metadata(src).map(|m| m.len()).unwrap_or(0);
report(app, &Progress { done: i + 1, total, name: name.clone(), job_id: job_id.to_string(), bytes_done, bytes_total });
let ext = ext_of(src);
let folder = render_folder(&settings.folder_template, &capture_day(src, &ext), &ext);
let dir = base.join(folder.trim_start_matches('/'));
if let Err(e) = std::fs::create_dir_all(&dir) {
r.failed += 1;
note(&mut r.notes, &format!("{name}: pasta — {e}"));
continue;
}
let ext = ext_of(src);
let folder = render_folder(&settings.folder_template, &capture_day(src, &ext), &ext);
let dir = base.join(folder.trim_start_matches('/'));
if let Err(e) = std::fs::create_dir_all(&dir) {
r.failed += 1;
bytes_done += len;
note(&mut r.notes, &format!("{name}: pasta — {e}"));
continue;
}
// The photo itself first. A file already there is skipped (unless "overwrite"); nothing is deleted then.
let target = dir.join(&name);
if target.exists() && !settings.overwrite {
r.skipped += 1;
continue;
}
if let Err(e) = copy_verified(src, &target) {
r.failed += 1;
note(&mut r.notes, &format!("{name}: {e}"));
continue;
}
// The photo itself first. A file already there is skipped (unless "overwrite"); nothing is deleted then.
let target = dir.join(&name);
if target.exists() && !settings.overwrite {
r.skipped += 1;
bytes_done += len;
continue;
}
if let Err(e) = copy_verified(src, &target) {
r.failed += 1;
bytes_done += len;
note(&mut r.notes, &format!("{name}: {e}"));
continue;
}
// Its sidecars (same stem): best effort — a sidecar that fails is noted but does not fail the photo.
let mut sidecars_done: Vec<PathBuf> = Vec::new();
if settings.sidecars {
if let (Some(stem), Some(parent)) = (src.file_stem().and_then(|s| s.to_str()), src.parent()) {
for s in SIDECAR_EXTS {
let side = parent.join(format!("{stem}.{s}"));
if !side.exists() {
continue;
}
let side_target = dir.join(format!("{stem}.{s}"));
if side_target.exists() && !settings.overwrite {
continue;
}
match copy_verified(&side, &side_target) {
Ok(()) => sidecars_done.push(side),
Err(e) => note(&mut r.notes, &format!("{stem}.{s}: {e}")),
}
// Its sidecars (same stem): best effort — a sidecar that fails is noted but does not fail the photo.
let mut sidecars_done: Vec<PathBuf> = Vec::new();
if settings.sidecars {
if let (Some(stem), Some(parent)) = (src.file_stem().and_then(|s| s.to_str()), src.parent()) {
for s in SIDECAR_EXTS {
let side = parent.join(format!("{stem}.{s}"));
if !side.exists() {
continue;
}
let side_target = dir.join(format!("{stem}.{s}"));
if side_target.exists() && !settings.overwrite {
continue;
}
match copy_verified(&side, &side_target) {
Ok(()) => sidecars_done.push(side),
Err(e) => note(&mut r.notes, &format!("{stem}.{s}: {e}")),
}
}
}
// Move: the copy is verified, so the originals can go. Only what arrived whole is deleted.
if settings.mv {
let _ = std::fs::remove_file(src);
for side in &sidecars_done {
let _ = std::fs::remove_file(side);
}
r.moved += 1;
} else {
r.copied += 1;
}
}
let _ = app.emit("card-progress", Progress { done: total, total, name: String::new() });
Ok(r)
// Move: the copy is verified, so the originals can go. Only what arrived whole is deleted.
if settings.mv {
let _ = std::fs::remove_file(src);
for side in &sidecars_done {
let _ = std::fs::remove_file(side);
}
r.moved += 1;
} else {
r.copied += 1;
}
bytes_done += len;
}
let finished = r.copied + r.moved + r.skipped + r.failed;
report(
app,
&Progress { done: finished, total, name: String::new(), job_id: job_id.to_string(), bytes_done, bytes_total },
);
Ok(r)
}
/// Copies (or moves) the chosen photos from `source` into the dated folders under the destination. Emits
/// `card-progress` events as it goes. `job_id` lets several cards report progress without mixing, and lets
/// [`card_cancel`] stop one of them. Omitted, the job is named `default` (one card at a time).
#[tauri::command]
pub async fn card_ingest(app: AppHandle, source: String, settings: CardSettings, job_id: Option<String>, state: tauri::State<'_, CardState>) -> Result<CardResult, String> {
let job_id = job_id.unwrap_or_else(|| "default".to_string());
let cancel = state.begin(&job_id);
let end_id = job_id.clone();
let result = tauri::async_runtime::spawn_blocking(move || {
let root = expand(&source);
ingest_dir(Some(&app), &root, &settings, &job_id, &cancel)
})
.await
.map_err(|e| e.to_string())?
.map_err(|e| e.to_string());
state.end(&end_id);
result?
}
/// Stops one card after the file it is copying now. An unknown id does nothing, so a probe can ask
/// whether this shell knows how to stop.
#[tauri::command]
pub fn card_cancel(job_id: String, state: tauri::State<'_, CardState>) {
state.stop(&job_id);
}
#[tauri::command]
@@ -425,3 +530,35 @@ pub fn card_save_settings(state: tauri::State<'_, CardState>, settings: CardSett
state.save(settings.clone())?;
Ok(settings)
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn a_stop_copies_nothing_and_a_clear_flag_copies_the_card() {
let dir = std::env::temp_dir().join(format!("pr-card-{}", std::process::id()));
let _ = std::fs::remove_dir_all(&dir);
let src = dir.join("src");
let dst = dir.join("dst");
std::fs::create_dir_all(&src).unwrap();
std::fs::write(src.join("a.jpg"), b"hello card").unwrap();
std::fs::write(src.join("b.jpg"), b"second").unwrap();
let settings = CardSettings {
destination: dst.to_string_lossy().to_string(),
folder_template: String::new(),
..CardSettings::default()
};
let stopped = ingest_dir(None, &src, &settings, "job", &AtomicBool::new(true)).unwrap();
assert!(stopped.stopped);
assert_eq!(stopped.copied, 0);
assert!(!dst.join("a.jpg").exists());
let done = ingest_dir(None, &src, &settings, "job", &AtomicBool::new(false)).unwrap();
assert!(!done.stopped);
assert_eq!(done.copied, 2);
assert_eq!(std::fs::read(dst.join("a.jpg")).unwrap(), b"hello card");
let _ = std::fs::remove_dir_all(&dir);
}
}
+1
View File
@@ -135,6 +135,7 @@ pub fn run() {
catalog::catalog_cancel,
card::card_scan,
card::card_ingest,
card::card_cancel,
card::card_settings,
card::card_save_settings,
faces::faces_local,
+1 -1
View File
@@ -1,7 +1,7 @@
{
"$schema": "https://schema.tauri.app/config/2",
"productName": "PhotoReport",
"version": "0.3.20",
"version": "0.3.21",
"identifier": "pt.photoreport.desktop",
"build": {
"devUrl": "http://localhost:5173",