diff --git a/apps/app/src/i18n.ts b/apps/app/src/i18n.ts index 6162ee8..f0fa558 100644 --- a/apps/app/src/i18n.ts +++ b/apps/app/src/i18n.ts @@ -239,6 +239,57 @@ export const t = { real_estate_disabled: "O imobiliário está desligado nesta organização.", } as Record, }, + 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`, diff --git a/apps/app/src/library/CardIngest.tsx b/apps/app/src/library/CardIngest.tsx index 4c90278..346ef20 100644 --- a/apps/app/src/library/CardIngest.tsx +++ b/apps/app/src/library/CardIngest.tsx @@ -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 ( <> {open && setOpen(false)} />} @@ -63,180 +55,216 @@ export function CardIngestButton() { } function CardDialog({ onClose }: { onClose: () => void }) { + const jobs = useCardJobs(); const [s, setS] = useState(DEFAULTS); const [source, setSource] = useState(""); - const [scan, setScan] = useState(null); - const [busy, setBusy] = useState(false); - const [progress, setProgress] = useState<{ done: number; total: number; name: string } | null>(null); - const [result, setResult] = useState(null); const [error, setError] = useState(null); + const [stopNote, setStopNote] = useState(null); + const canStart = jobs.some((job) => job.status === "queued"); useEffect(() => { desktopInvoke("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("delivery_folder_pick").catch(() => null); - if (!p) return; - setSource(p); - setScan(null); - setResult(null); - try { - setScan(await desktopInvoke("card_scan", { source: p })); - } catch (e) { - setError(String(e)); - } + const path = await desktopInvoke("delivery_folder_pick").catch(() => null); + if (!path) return; + setSource(path); + await enqueueCard(path); }; const pickDest = async () => { - const p = await desktopInvoke("delivery_folder_pick").catch(() => null); - if (p) setS({ ...s, destination: p }); + const path = await desktopInvoke("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("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 ( -
+
-
-

Importar cartão

- +
+

{t.card.title}

+
+ + +
-

Copia (ou move) as fotos de um cartão para uma pasta datada neste computador. Não envia nada para o servidor.

+

{t.card.intro}

+

{t.card.closeKeeps}

+ {jobs.length > 0 && ( +
    + {jobs.map((job) => ( + 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); + }); + }} + /> + ))} +
+ )} +
- {s.mv &&

Mover apaga os originais do cartão (só depois de a cópia ser verificada por tamanho e checksum).

} + {s.mv &&

{t.card.moveWarn}

} {error &&

{error}

} - {progress && busy && ( -

- A processar {progress.done}/{progress.total}… {progress.name} -

- )} - {result && ( -
-

- {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." : ""} -

-

{result.destination}

- {result.notes.length > 0 && ( -
    - {result.notes.slice(0, 8).map((n, i) => ( -
  • {n}
  • - ))} -
- )} -
- )} + {stopNote &&

{stopNote}

}
); } + +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 ( +
  • +
    + {name} + {job.status !== "running" && ( + + )} + {job.status === "running" && ( + + )} + {job.status === "stopped" && {t.card.stopped}} +
    + {scan &&

    {scan}

    } + {job.status === "running" && job.progress && ( + <> +
    +
    +
    +

    + {t.card.progress(job.progress.done, job.progress.total, job.progress.name)} + {pace.left ? ` · ${t.card.remaining(pace.left)}` : ""} +

    + + )} + {job.error &&

    {job.error}

    } + {job.result && } +
  • + ); +} + +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 ( +
    +

    {parts.length > 0 ? parts.join(" · ") : t.card.result.empty}

    +

    {result.destination}

    + {result.notes.length > 0 && ( +
      + {result.notes.slice(0, 8).map((note) => ( +
    • {note}
    • + ))} +
    + )} +
    + ); +} diff --git a/apps/app/src/library/LocalFtp.tsx b/apps/app/src/library/LocalFtp.tsx index 1c56bf0..88d3489 100644 --- a/apps/app/src/library/LocalFtp.tsx +++ b/apps/app/src/library/LocalFtp.tsx @@ -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()); }} > +
    + +
    ))} - - - {role === "OWNER" && organization && ( -
    -
    -
    - {t.realEstate.setting} - {realEstateOn ? t.realEstate.enabled : t.realEstate.off} -
    -
    -

    {t.realEstate.settingHelp}

    - {realEstateError &&

    {realEstateError}

    } -
    - -
    -
    -
    -
    - )} + /> + {t.realEstate.setting} + + + )} + + {role === "OWNER" && organization &&

    {t.realEstate.settingHelp}

    } + {realEstateError && {realEstateError}} + {isDesktop() && } ); diff --git a/apps/app/src/pages/RealEstatePage.test.tsx b/apps/app/src/pages/RealEstatePage.test.tsx index 275ea1c..e4d9a4e 100644 --- a/apps/app/src/pages/RealEstatePage.test.tsx +++ b/apps/app/src/pages/RealEstatePage.test.tsx @@ -103,7 +103,7 @@ describe("real estate area", () => { window.history.pushState({}, "", "/preferences"); const api = fakeApi(me("OWNER", false)); render(); - 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); }); }); diff --git a/apps/desktop/package.json b/apps/desktop/package.json index 153f381..077cb67 100644 --- a/apps/desktop/package.json +++ b/apps/desktop/package.json @@ -1,6 +1,6 @@ { "name": "@photoreport/desktop", - "version": "0.3.20", + "version": "0.3.21", "private": true, "type": "module", "scripts": { diff --git a/apps/desktop/src-tauri/Cargo.toml b/apps/desktop/src-tauri/Cargo.toml index 8468734..b0a6005 100644 --- a/apps/desktop/src-tauri/Cargo.toml +++ b/apps/desktop/src-tauri/Cargo.toml @@ -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." diff --git a/apps/desktop/src-tauri/build.rs b/apps/desktop/src-tauri/build.rs index 39a2725..acbdee5 100644 --- a/apps/desktop/src-tauri/build.rs +++ b/apps/desktop/src-tauri/build.rs @@ -28,6 +28,7 @@ fn main() { "catalog_cancel", "card_scan", "card_ingest", + "card_cancel", "card_settings", "card_save_settings", "faces_local", diff --git a/apps/desktop/src-tauri/capabilities/default.json b/apps/desktop/src-tauri/capabilities/default.json index e97f04a..92bc1bf 100644 --- a/apps/desktop/src-tauri/capabilities/default.json +++ b/apps/desktop/src-tauri/capabilities/default.json @@ -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", diff --git a/apps/desktop/src-tauri/permissions/autogenerated/card_cancel.toml b/apps/desktop/src-tauri/permissions/autogenerated/card_cancel.toml new file mode 100644 index 0000000..9cfbc43 --- /dev/null +++ b/apps/desktop/src-tauri/permissions/autogenerated/card_cancel.toml @@ -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"] diff --git a/apps/desktop/src-tauri/src/card.rs b/apps/desktop/src-tauri/src/card.rs index 7f55c75..4970c82 100644 --- a/apps/desktop/src-tauri/src/card.rs +++ b/apps/desktop/src-tauri/src/card.rs @@ -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>, config_path: Option, + /// One flag per running card. A second card is another command, so the cards run side by side. + cancel: Mutex>>, } fn config_file() -> PathBuf { @@ -126,6 +132,22 @@ impl CardState { *self.settings.lock().unwrap() = Some(s); Ok(()) } + + fn begin(&self, job_id: &str) -> Arc { + 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 { - 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, 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, 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 { - 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 { + 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 = 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 = 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 = 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 = 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, state: tauri::State<'_, CardState>) -> Result { + 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); + } +} diff --git a/apps/desktop/src-tauri/src/lib.rs b/apps/desktop/src-tauri/src/lib.rs index e9206ef..b86c3e0 100644 --- a/apps/desktop/src-tauri/src/lib.rs +++ b/apps/desktop/src-tauri/src/lib.rs @@ -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, diff --git a/apps/desktop/src-tauri/tauri.conf.json b/apps/desktop/src-tauri/tauri.conf.json index 8dabd83..0ea2aa6 100644 --- a/apps/desktop/src-tauri/tauri.conf.json +++ b/apps/desktop/src-tauri/tauri.conf.json @@ -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",