diff --git a/apps/api/src/ingest/jpeg.test.ts b/apps/api/src/ingest/jpeg.test.ts new file mode 100644 index 0000000..c48767d --- /dev/null +++ b/apps/api/src/ingest/jpeg.test.ts @@ -0,0 +1,28 @@ +import { mkdtemp, rm, writeFile } from "node:fs/promises"; +import { tmpdir } from "node:os"; +import path from "node:path"; +import sharp from "sharp"; +import { describe, expect, it } from "vitest"; +import { jpegComplete, jpegFileComplete } from "./jpeg.js"; + +describe("finished JPEG", () => { + it("accepts a file that ends with the end marker and refuses one still arriving", async () => { + const full = await sharp({ create: { width: 8, height: 8, channels: 3, background: "#336699" } }).jpeg().toBuffer(); + expect(jpegComplete(full)).toBe(true); + expect(jpegComplete(Buffer.concat([full, Buffer.from([0x00, 0x00])]))).toBe(true); + expect(jpegComplete(full.subarray(0, full.length - 20))).toBe(false); + expect(jpegComplete(Buffer.from("not really a jpeg"))).toBe(false); + expect(jpegComplete(Buffer.from([0xff, 0xd8, 0xff, 0xd9]))).toBe(true); + + const dir = await mkdtemp(path.join(tmpdir(), "pr-jpeg-")); + try { + const file = path.join(dir, "a.jpg"); + await writeFile(file, full.subarray(0, full.length - 20)); + expect(await jpegFileComplete(file)).toBe(false); + await writeFile(file, full); + expect(await jpegFileComplete(file)).toBe(true); + } finally { + await rm(dir, { recursive: true, force: true }); + } + }); +}); diff --git a/apps/api/src/ingest/jpeg.ts b/apps/api/src/ingest/jpeg.ts new file mode 100644 index 0000000..670906b --- /dev/null +++ b/apps/api/src/ingest/jpeg.ts @@ -0,0 +1,49 @@ +import { open } from "node:fs/promises"; + +const TAIL = 64; + +/** + * A JPEG the camera has finished writing: it starts with SOI and the end-of-image marker is at the tail. + * A few padding bytes after that marker are normal. Entropy-coded data never contains a raw FFD9 + * (a 0xFF there is stuffed), so the marker at the end means the transfer of this file is done. + */ +export function jpegComplete(bytes: Uint8Array): boolean { + if (bytes.length < 4 || bytes[0] !== 0xff || bytes[1] !== 0xd8) return false; + return eoiAtEnd(bytes); +} + +/** Reads the head and the tail only, and checks the size again so a file still growing is not complete. */ +export async function jpegFileComplete(file: string): Promise { + const fh = await open(file, "r"); + try { + const size = (await fh.stat()).size; + if (size < 4) return false; + const head = Buffer.alloc(2); + const headRead = await fh.read(head, 0, 2, 0); + if (headRead.bytesRead !== 2 || head[0] !== 0xff || head[1] !== 0xd8) return false; + const n = Math.min(size, TAIL); + const tail = Buffer.alloc(n); + const tailRead = await fh.read(tail, 0, n, size - n); + if (tailRead.bytesRead !== n) return false; + if ((await fh.stat()).size !== size) return false; + return eoiAtEnd(tail); + } catch { + return false; + } finally { + await fh.close(); + } +} + +function eoiAtEnd(tail: Uint8Array): boolean { + if (tail.length < 2) return false; + const from = Math.max(0, tail.length - TAIL); + for (let i = tail.length - 2; i >= from; i--) { + if (tail[i] !== 0xff || tail[i + 1] !== 0xd9) continue; + for (let j = i + 2; j < tail.length; j++) { + const b = tail[j]; + if (b !== 0x00 && b !== 0xff) return false; + } + return true; + } + return false; +} diff --git a/apps/api/src/ingest/scanner.ts b/apps/api/src/ingest/scanner.ts index 00deaa2..d3a5035 100644 --- a/apps/api/src/ingest/scanner.ts +++ b/apps/api/src/ingest/scanner.ts @@ -1,6 +1,7 @@ import { readdir, stat } from "node:fs/promises"; import path from "node:path"; import { waitUntil } from "../lib/idle.js"; +import { jpegFileComplete } from "./jpeg.js"; import type { IngestLogger, IngestService } from "./service.js"; interface Seen { @@ -9,9 +10,11 @@ interface Seen { } /** - * Polls the FTP drop folder. A file is processed once its size and modification time stay the same between two - * scans (the upload has finished). Folders starting with `_` (set-aside files) and dot files (temporary - * uploads) are ignored. The SFTPGo upload hook can push a file earlier; the scanner is the safety net. + * Polls the FTP drop folder. A JPEG is processed once two scans see the same size and modification time and the + * file ends with the end-of-image marker. A pause while the camera is still sending leaves the file where it is: + * moving it then stores the grey fill of the rows that have not arrived. Folders starting with `_` (set-aside + * files) and dot files (temporary uploads) are ignored. The SFTPGo upload hook can push a file earlier; the + * scanner is the safety net. */ export class IngestScanner { private readonly seen = new Map(); @@ -76,7 +79,10 @@ export class IngestScanner { if (!s) continue; const before = this.seen.get(file); this.seen.set(file, { size: s.size, mtimeMs: s.mtimeMs }); - if (before && before.size === s.size && before.mtimeMs === s.mtimeMs && s.size > 0) ready.push(file); + if (!before || before.size !== s.size || before.mtimeMs !== s.mtimeMs || s.size === 0) continue; + const ext = path.extname(file).toLowerCase(); + // Anything else is set aside by the service. A JPEG also has to be finished, not merely quiet. + if ((ext !== ".jpg" && ext !== ".jpeg") || (await jpegFileComplete(file))) ready.push(file); } for (const file of this.seen.keys()) if (!present.has(file)) this.seen.delete(file); diff --git a/apps/api/src/ingest/service.ts b/apps/api/src/ingest/service.ts index 2b4001e..f4c1138 100644 --- a/apps/api/src/ingest/service.ts +++ b/apps/api/src/ingest/service.ts @@ -9,6 +9,7 @@ import type { Broadcaster } from "../realtime.js"; import { LocalStorage, sha256File, UrlSigner, VARIANT_SIZE } from "../storage/storage.js"; import { readEmbeddedIptc } from "./embedded.js"; import { readCameraInfo } from "./exif.js"; +import { jpegFileComplete } from "./jpeg.js"; export const ACCEPTED_EXTENSIONS = new Set([".jpg", ".jpeg"]); @@ -16,7 +17,7 @@ export type IngestOutcome = | { status: "ingested"; photoId: string; eventId: string | null } | { status: "duplicate"; photoId: string } | { status: "failed"; photoId: string; error: string } - | { status: "skipped"; reason: "unknown_login" | "unsupported_type" | "outside_root" }; + | { status: "skipped"; reason: "unknown_login" | "unsupported_type" | "outside_root" | "incomplete" }; export interface IngestLogger { info(obj: object, msg: string): void; @@ -82,6 +83,12 @@ export class IngestService { log.warn({ file }, "ingest: unsupported file type set aside (JPEG only for now)"); return { status: "skipped", reason: "unsupported_type" }; } + // Still arriving: leave it in the drop folder. Moving it now (and decoding with a lenient JPEG loader) + // stores a grey rectangle for the rows the camera has not sent yet. + if (!(await jpegFileComplete(file))) { + log.info({ file }, "ingest: transfer still in progress, file left in place"); + return { status: "skipped", reason: "incomplete" }; + } const account = await db.ftpAccount.findUnique({ where: { login } }); if (!account) { await this.setAside(file, "_unclaimed"); @@ -268,15 +275,14 @@ export class IngestService { private async makeDerivatives(orgId: string, sha256: string, storageKey: string): Promise<{ width: number; height: number }> { const { storage } = this.deps; const source = storage.resolve(storageKey); - // A truncated upload (interrupted FTP) still has a usable image: decode what is there - // instead of failing the whole photo, as Photo Mechanic does. Genuinely unreadable - // files still throw below (no width/height). - const meta = await sharp(source, { failOn: "none" }).metadata(); + // A cut-off file must fail. libvips otherwise paints the missing rows grey and we store that as the photo. + // The failed row is replaced when the same bytes arrive again; a file still transferring never gets here. + const meta = await sharp(source, { failOn: "error" }).metadata(); if (!meta.width || !meta.height) throw new Error("not a readable image"); const rotated = (meta.orientation ?? 1) >= 5; for (const variant of ["thumb", "preview"] as const) { const side = VARIANT_SIZE[variant]; - const data = await sharp(source, { failOn: "none" }) + const data = await sharp(source, { failOn: "error" }) .rotate() .resize({ width: side, height: side, fit: "inside", withoutEnlargement: true }) .jpeg({ quality: variant === "thumb" ? 80 : 88, mozjpeg: true }) diff --git a/apps/api/test/library.test.ts b/apps/api/test/library.test.ts index 785863c..7862c16 100644 --- a/apps/api/test/library.test.ts +++ b/apps/api/test/library.test.ts @@ -1,4 +1,4 @@ -import { mkdir, mkdtemp, readdir, rm, writeFile } from "node:fs/promises"; +import { mkdir, mkdtemp, readdir, rm, stat, writeFile } from "node:fs/promises"; import { tmpdir } from "node:os"; import path from "node:path"; import sharp from "sharp"; @@ -254,7 +254,9 @@ describe("library", () => { it("says why a photo failed", async () => { const { orgId, admin } = await setup(); - await service.ingestFile(await drop("foto.r1", "cut.jpg", Buffer.from("not really a jpeg"))); + // End marker present, so this is a finished file that cannot be decoded, not one still arriving. + const unreadable = Buffer.concat([Buffer.from([0xff, 0xd8]), Buffer.from("not really a jpeg"), Buffer.from([0xff, 0xd9])]); + await service.ingestFile(await drop("foto.r1", "cut.jpg", unreadable)); const list = await ctx.app.inject({ method: "GET", url: `/v1/orgs/${orgId}/photos?status=FAILED`, headers: bearer(admin) }); const [photo] = (list.json() as { photos: { status: string; error?: string }[] }).photos; expect(photo).toMatchObject({ status: "FAILED", error: expect.any(String) }); @@ -262,7 +264,8 @@ describe("library", () => { it("marks unreadable files as failed instead of losing them", async () => { await setup(); - const outcome = await service.ingestFile(await drop("foto.r1", "broken.jpg", Buffer.from("not really a jpeg"))); + const unreadable = Buffer.concat([Buffer.from([0xff, 0xd8]), Buffer.from("not really a jpeg"), Buffer.from([0xff, 0xd9])]); + const outcome = await service.ingestFile(await drop("foto.r1", "broken.jpg", unreadable)); expect(outcome.status).toBe("failed"); const photo = await ctx.db.photo.findFirstOrThrow(); expect(photo.status).toBe("FAILED"); @@ -277,6 +280,19 @@ describe("library", () => { expect(await ctx.db.photo.count()).toBe(1); }); + it("leaves a jpeg that is still transferring where the camera is writing it", async () => { + await setup(); + const scanner = new IngestScanner(service, ingestRoot, { intervalMs: 10, concurrency: 2, log: quiet }); + const file = await drop("foto.r1", "part.jpg", Buffer.from([0xff, 0xd8, 0x00, 0x11, 0x22])); + expect(await scanner.scanOnce()).toEqual([]); + expect(await scanner.scanOnce()).toEqual([]); + expect(await ctx.db.photo.count()).toBe(0); + expect((await stat(file)).size).toBe(5); + const outcome = await service.ingestFile(file); + expect(outcome).toEqual({ status: "skipped", reason: "incomplete" }); + expect((await stat(file)).size).toBe(5); + }); + it("culls in batch, live, and keeps photographers to their own photos", async () => { const { orgId, admin, foto } = await setup(); const a = await service.ingestFile(await drop("foto.r1", "a.jpg", await jpeg({ color: "#101010" }))); diff --git a/apps/app/src/library/LocalFtp.tsx b/apps/app/src/library/LocalFtp.tsx index e279cdb..686de1b 100644 --- a/apps/app/src/library/LocalFtp.tsx +++ b/apps/app/src/library/LocalFtp.tsx @@ -54,6 +54,11 @@ const tauriInvoke: Invoke = async (cmd, args) => (await import("@tauri-apps/api/ const IN_FLIGHT = 6; const POLL_MS = 1000; +/** The shell put the file back on the queue because the camera has not finished sending it. */ +function isIncomplete(err: unknown): boolean { + return err === "incomplete" || (err instanceof Error && err.message === "incomplete"); +} + type Add = (files: Iterable, eventId?: string, onSettled?: (file: File, status: UploadStatus, photo?: PhotoSummary) => void, original?: DesktopOrigin) => void; export const eventLabel = (e: Pick) => e.title || [e.home, e.away].filter(Boolean).join(" x "); @@ -141,9 +146,10 @@ export function useLocalFtp(add: Add, enabled: boolean, invoke: Invoke = tauriIn localPhotos.remove(localId(info.sha256)); pump(); }, full ? "original" : info); - } catch { + } catch (err) { inFlight.current--; - setCounts((c) => ({ ...c, failed: c.failed + 1 })); + // A pause mid-transfer is not a failed photo: the shell hands it out again once the file is whole. + if (!isIncomplete(err)) setCounts((c) => ({ ...c, failed: c.failed + 1 })); pump(); } })(); diff --git a/apps/desktop/package.json b/apps/desktop/package.json index 0ff1be5..b612830 100644 --- a/apps/desktop/package.json +++ b/apps/desktop/package.json @@ -1,6 +1,6 @@ { "name": "@photoreport/desktop", - "version": "0.3.18", + "version": "0.3.19", "private": true, "type": "module", "scripts": { diff --git a/apps/desktop/src-tauri/Cargo.toml b/apps/desktop/src-tauri/Cargo.toml index d11f203..aa96c0d 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.18" +version = "0.3.19" 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/src/ftp.rs b/apps/desktop/src-tauri/src/ftp.rs index 432e505..a984b06 100644 --- a/apps/desktop/src-tauri/src/ftp.rs +++ b/apps/desktop/src-tauri/src/ftp.rs @@ -7,8 +7,9 @@ //! //! Every finished upload (STOR) is picked up by scanning the ingest folder; the web app polls `ftp_take`, reads the //! bytes with `ftp_read` and, once the server has the photo, calls `ftp_sent`, which moves the original into the -//! event's work folder. Anything still in the ingest folder (app closed mid-match, no network) goes again on the -//! next start, so nothing is lost: the ingest folder is the queue. +//! event's work folder. A file is finished only when it starts with the JPEG marker and ends with the end-of-image +//! marker: a pause while the camera is still sending is not enough, and the file stays in the queue. Anything still +//! in the ingest folder (app closed mid-match, no network) goes again on the next start, so nothing is lost. use std::collections::{HashMap, HashSet}; use std::net::IpAddr; @@ -27,9 +28,8 @@ use unftp_core::auth::{AuthenticationError, Authenticator, Credentials, Principa use unftp_sbe_fs::Filesystem; const PASSIVE_PORTS: std::ops::RangeInclusive = 50000..=50100; -/// A file nobody has written to for this long is complete (or abandoned by the camera, which then resends it). -const SETTLED_MS: u64 = 10_000; -/// Two scans in a row with the same size and time, and this quiet, also count as complete. +/// Two scans in a row with the same size and time, and this quiet, may be a finished file. It still has to end +/// with the JPEG end marker: a Wi-Fi pause mid-transfer looks the same and must not be moved. const STABLE_MS: u64 = 2_000; #[derive(Debug, Clone, Serialize, Deserialize, PartialEq)] @@ -154,7 +154,7 @@ pub struct FtpState { /// (file name, bytes) of uploads the FTP session reported as finished. The session only gives the name /// relative to its current folder, so the folder scan matches them up by name and size. finished: Arc>>, - /// Size and time of each file at the previous scan: a file that stopped changing is complete. + /// Size and time of each file at the previous scan. Quiet is not enough; the end marker has to be there too. seen: Mutex>, /// Paths already handed to the web app (so the next scan does not send them twice). taken: Mutex>, @@ -593,10 +593,12 @@ impl FtpState { continue; } let quiet = now.saturating_sub(f.modified_ms); - let done = finished.remove(&(f.name.clone(), f.size)) - || quiet >= SETTLED_MS - || (quiet >= STABLE_MS && seen.get(&f.path) == Some(&(f.size, f.modified_ms))); + let reported = finished.contains(&(f.name.clone(), f.size)); + let stable = quiet >= STABLE_MS && seen.get(&f.path) == Some(&(f.size, f.modified_ms)); + let done = (reported || stable) && jpeg_complete(Path::new(&f.path)); if done { + let name = f.name.clone(); + finished.retain(|(n, _)| n != &name); seen.remove(&f.path); taken.insert(f.path.clone()); ready.push(f); @@ -609,7 +611,7 @@ impl FtpState { /// The server has the photo: move the original into the event's work folder (kept, never deleted). pub fn sent(&self, path: &str, event: &str, date: &str) -> Result { - let p = self.inside_ingest(path)?; + let p = self.finished_jpeg(path)?; let dir = work_folder(&self.settings().work_folder, event, date); std::fs::create_dir_all(&dir).map_err(|e| e.to_string())?; let name = p @@ -631,6 +633,64 @@ impl FtpState { self.taken.lock().unwrap().remove(path); Ok(target.to_string_lossy().into_owned()) } + + /// The path is inside the ingest folder and the JPEG is finished. Otherwise it goes back on the queue. + fn finished_jpeg(&self, path: &str) -> Result { + let p = self.inside_ingest(path)?; + if !jpeg_complete(&p) { + self.taken.lock().unwrap().remove(path); + return Err("incomplete".into()); + } + Ok(p) + } +} + +/// SOI at the start and the end-of-image marker in the tail. The size is read again afterwards so a file +/// that grew while we looked is not treated as finished. +fn jpeg_complete(path: &Path) -> bool { + let Ok(mut file) = std::fs::File::open(path) else { + return false; + }; + let Ok(meta) = file.metadata() else { + return false; + }; + let size = meta.len(); + if size < 4 { + return false; + } + use std::io::{Read, Seek, SeekFrom}; + let mut head = [0u8; 2]; + if file.read(&mut head).ok() != Some(2) || head != [0xFF, 0xD8] { + return false; + } + let n = std::cmp::min(64u64, size) as usize; + if file.seek(SeekFrom::Start(size - n as u64)).is_err() { + return false; + } + let mut tail = vec![0u8; n]; + if file.read(&mut tail).ok() != Some(n) { + return false; + } + let Ok(after) = file.metadata() else { + return false; + }; + if after.len() != size { + return false; + } + eoi_at_end(&tail) +} + +fn eoi_at_end(tail: &[u8]) -> bool { + if tail.len() < 2 { + return false; + } + let from = tail.len().saturating_sub(64); + for i in (from..tail.len() - 1).rev() { + if tail[i] == 0xFF && tail[i + 1] == 0xD9 { + return tail[i + 2..].iter().all(|b| *b == 0x00 || *b == 0xFF); + } + } + false } /// rename(), or copy + remove when the work folder is on another disk. @@ -726,7 +786,7 @@ pub async fn ftp_read( state: tauri::State<'_, FtpState>, path: String, ) -> Result { - let p = state.inside_ingest(&path)?; + let p = state.finished_jpeg(&path)?; let bytes = tokio::fs::read(&p).await.map_err(|e| e.to_string())?; Ok(tauri::ipc::Response::new(bytes)) } @@ -738,7 +798,7 @@ pub async fn ftp_preview( state: tauri::State<'_, FtpState>, path: String, ) -> Result { - let p = state.inside_ingest(&path)?; + let p = state.finished_jpeg(&path)?; let bytes = tokio::fs::read(&p).await.map_err(|e| e.to_string())?; let preview = tauri::async_runtime::spawn_blocking(move || crate::preview::make_preview(&bytes)) @@ -754,7 +814,7 @@ pub async fn ftp_info( index: tauri::State<'_, crate::local::LocalIndex>, path: String, ) -> Result { - let p = state.inside_ingest(&path)?; + let p = state.finished_jpeg(&path)?; let at = p.clone(); let info = tauri::async_runtime::spawn_blocking(move || crate::preview::original_info(&p)) .await @@ -980,7 +1040,7 @@ mod tests { std::thread::sleep(std::time::Duration::from_millis(300)); let photo = dir.join("IMG_0001.JPG"); - std::fs::write(&photo, b"\xff\xd8 not really a jpeg").unwrap(); + std::fs::write(&photo, b"\xff\xd8\xff\xd9").unwrap(); let curl = |user: &str, url: String| { std::process::Command::new("curl") .args(["-s", "--ftp-create-dirs", "-T"]) @@ -1033,15 +1093,80 @@ mod tests { assert!(Path::new(&moved).exists()); assert!(state.take().is_empty()); - // A fresh file with no "finished" report is handed out once it has stopped changing. + // A fresh file with no "finished" report is handed out once it has stopped changing and it is a whole JPEG. state.stop(); - std::fs::write(dir.join("ingest/late.jpg"), b"x").unwrap(); + std::fs::write(dir.join("ingest/partial.jpg"), b"\xff\xd8 not yet").unwrap(); + assert!(state.take().is_empty()); + std::thread::sleep(std::time::Duration::from_millis(STABLE_MS + 200)); + assert!( + state.take().is_empty(), + "a quiet file without the end marker is still transferring" + ); + std::fs::write(dir.join("ingest/late.jpg"), b"\xff\xd8\xff\xd9").unwrap(); assert!(state.take().is_empty()); std::thread::sleep(std::time::Duration::from_millis(STABLE_MS + 200)); assert_eq!(state.take().len(), 1); let _ = std::fs::remove_dir_all(&dir); } + #[test] + fn an_unfinished_jpeg_is_not_moved_even_when_the_session_says_it_finished() { + let dir = std::env::temp_dir().join(format!("pr-ftp-partial-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + std::fs::create_dir_all(dir.join("ingest")).unwrap(); + let state = FtpState { + config_path: Some(dir.join("ftp.json")), + ..Default::default() + }; + let partial = dir.join("ingest/partial.jpg"); + let bytes = b"\xff\xd8 still coming"; + std::fs::write(&partial, bytes).unwrap(); + state + .save(FtpSettings { + port: 2121, + users: vec![FtpUser { + name: "1dx".into(), + password: "1dx".into(), + enabled: true, + }], + ingest: dir.join("ingest").to_string_lossy().into_owned(), + work_folder: dir + .join("{year}/{date} - {event}") + .to_string_lossy() + .into_owned(), + auto_start: false, + upload_originals: false, + }) + .unwrap(); + state + .finished + .lock() + .unwrap() + .insert(("partial.jpg".into(), bytes.len() as u64)); + assert!(state.take().is_empty()); + assert!(partial.exists()); + assert_eq!( + state + .sent(partial.to_str().unwrap(), "Game", "2026-10-18") + .unwrap_err(), + "incomplete" + ); + assert!(partial.exists()); + + std::fs::write(&partial, b"\xff\xd8\xff\xd9").unwrap(); + state + .finished + .lock() + .unwrap() + .insert(("partial.jpg".into(), 4)); + let got = state.take(); + assert_eq!(got.len(), 1); + let moved = state.sent(&got[0].path, "Game", "2026-10-18").unwrap(); + assert!(Path::new(&moved).exists()); + assert!(!partial.exists()); + let _ = std::fs::remove_dir_all(&dir); + } + #[test] fn date_folder() { assert_eq!(today().len(), 10); diff --git a/apps/desktop/src-tauri/tauri.conf.json b/apps/desktop/src-tauri/tauri.conf.json index d018f08..a801d87 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.18", + "version": "0.3.19", "identifier": "pt.photoreport.desktop", "build": { "devUrl": "http://localhost:5173",