From a9d89eae1964247d6807ace8352ccef1ec500d53 Mon Sep 17 00:00:00 2001 From: spark Date: Mon, 23 Nov 2026 14:39:04 +0000 Subject: [PATCH] Write Lightroom metadata onto the camera XMP description. A metadata rescan reads the first description, and today's originals were never rewritten because earlier flushes waited behind the rest of the library. --- apps/app/src/desktop/fileMarks.ts | 16 +- apps/app/src/desktop/lightroomSidecar.test.ts | 3 +- apps/app/src/desktop/lightroomSidecar.ts | 72 +++++- apps/app/src/library/LocalFtp.tsx | 7 +- apps/app/src/library/UsbCamera.tsx | 7 +- apps/desktop/src-tauri/src/ftp.rs | 207 ++++++++++++++++-- docs/ARCHITECTURE.md | 9 +- 7 files changed, 285 insertions(+), 36 deletions(-) diff --git a/apps/app/src/desktop/fileMarks.ts b/apps/app/src/desktop/fileMarks.ts index 3cab243..ac11960 100644 --- a/apps/app/src/desktop/fileMarks.ts +++ b/apps/app/src/desktop/fileMarks.ts @@ -3,7 +3,7 @@ import type { ApiClient, EventSummary } from "@photoreport/sdk"; import { useEffect } from "react"; import { useLibraryLive } from "../library/realtime.js"; import { isDesktop } from "../platform.js"; -import { flushAllPhotoFiles, settingsFromDevelop, writePhotoCommands, writePhotoFile, type FileIptc, type FileMarkUpdate } from "./lightroomSidecar.js"; +import { flushFailedPhotoFiles, settingsFromDevelop, writePhotoCommands, writePhotoFile, type FileIptc, type FileMarkUpdate } from "./lightroomSidecar.js"; const LOCAL = "local:"; const idToSha = new Map(); @@ -161,8 +161,9 @@ function marksOf(flag: string, rating: number, colorLabel: string, sent: boolean export async function catchUpFileMarks(api: ApiClient, orgId: string): Promise { if (!isDesktop() || !orgId || caughtUp.has(orgId)) return; caughtUp.add(orgId); - // Re-apply anything already remembered (survives a desktop update that swallowed earlier writes). - flushAllPhotoFiles(); + // Only retry writes that failed. Rewriting every remembered original first left today's files + // waiting behind thousands of older JPEGs, so Lightroom imported them with no metadata. + flushFailedPhotoFiles(); let events: EventSummary[] = []; try { events = (await api.listEvents(orgId)).events.filter((event) => eventIsCurrent(event, Date.now())); @@ -202,13 +203,20 @@ export function FileMarksSync({ api, orgId }: { api: ApiClient; orgId: string }) useEffect(() => { if (!orgId) return; void catchUpFileMarks(api, orgId); + // A write often fails because the JPEG is still in the ingest folder. Retry those, not the whole library. + const retry = window.setInterval(() => { + flushFailedPhotoFiles(); + }, 30 * 1000); // Periodic retry: a one-shot catch-up at login misses photos that arrive later, and a failed // ftp_write_xmp must not leave the work folder empty for the rest of the day. const timer = window.setInterval(() => { caughtUp.delete(orgId); void catchUpFileMarks(api, orgId); }, 10 * 60 * 1000); - return () => window.clearInterval(timer); + return () => { + window.clearInterval(retry); + window.clearInterval(timer); + }; }, [api, orgId]); return null; } diff --git a/apps/app/src/desktop/lightroomSidecar.test.ts b/apps/app/src/desktop/lightroomSidecar.test.ts index 3c7df63..0c8476a 100644 --- a/apps/app/src/desktop/lightroomSidecar.test.ts +++ b/apps/app/src/desktop/lightroomSidecar.test.ts @@ -60,7 +60,8 @@ describe("Lightroom sidecar", () => { creator: "Fotógrafo / PhotoReport.pt", }, ); - expect(xml).toContain('dc:title="Pavlidis"'); + expect(xml).toContain("Pavlidis"); + expect(xml).not.toContain('dc:title="Pavlidis"'); expect(xml).toContain("Águas Santas Milaneza x SL Benfica, em Maia"); expect(xml).toContain('photoshop:City="Maia"'); expect(xml).toContain("ANDEBOL"); diff --git a/apps/app/src/desktop/lightroomSidecar.ts b/apps/app/src/desktop/lightroomSidecar.ts index 21a83b8..381616c 100644 --- a/apps/app/src/desktop/lightroomSidecar.ts +++ b/apps/app/src/desktop/lightroomSidecar.ts @@ -150,9 +150,10 @@ function iptcParts(iptc: FileIptc | undefined): { attrs: string[]; children: str const caption = text("caption"); const creator = text("creator"); const keywords = Array.isArray(iptc.keywords) ? iptc.keywords.map((k) => k.trim()).filter(Boolean) : []; + let children = ""; if (title) { need("dc", "http://purl.org/dc/elements/1.1/"); - attrs.push(`dc:title="${xmlAttr(title)}"`); + children += `${xmlText(title)}`; } if (headline) { need("photoshop", "http://ns.adobe.com/photoshop/1.0/"); @@ -182,7 +183,6 @@ function iptcParts(iptc: FileIptc | undefined): { attrs: string[]; children: str need("photoshop", "http://ns.adobe.com/photoshop/1.0/"); attrs.push(`photoshop:Source="${xmlAttr(source)}"`); } - let children = ""; if (caption) { need("dc", "http://purl.org/dc/elements/1.1/"); children += `${xmlText(caption)}`; @@ -350,7 +350,35 @@ function saveRemembered(all: Record): void { } const flushTimers = new Map(); -let flushChain = Promise.resolve(); +const flushFailed = new Set(); +const flushSoon: string[] = []; +let flushRunning = false; + +const FLUSH_TIMEOUT_MS = 20_000; + +function enqueueFlush(sha256: string): void { + if (!sha256) return; + if (flushSoon.includes(sha256)) return; + flushSoon.push(sha256); + void runFlushQueue(); +} + +async function runFlushQueue(): Promise { + if (flushRunning) return; + flushRunning = true; + try { + while (flushSoon.length > 0) { + const sha256 = flushSoon.shift(); + if (!sha256) break; + await flushPhotoFile(sha256); + } + } finally { + flushRunning = false; + if (flushSoon.length > 0) { + void runFlushQueue(); + } + } +} function scheduleFlush(sha256: string): void { const pending = flushTimers.get(sha256); @@ -359,11 +387,29 @@ function scheduleFlush(sha256: string): void { sha256, window.setTimeout(() => { flushTimers.delete(sha256); - flushChain = flushChain.then(() => flushPhotoFile(sha256)).catch(() => {}); + enqueueFlush(sha256); }, 400), ); } +function invokeWithTimeout(command: string, args: Record): Promise { + return new Promise((resolve, reject) => { + const timer = window.setTimeout(() => { + reject(new Error("timeout")); + }, FLUSH_TIMEOUT_MS); + desktopInvoke(command, args).then( + (value) => { + window.clearTimeout(timer); + resolve(value); + }, + (err: unknown) => { + window.clearTimeout(timer); + reject(err); + }, + ); + }); +} + async function flushPhotoFile(sha256: string): Promise { const row = loadRemembered()[sha256]; if (!row) return; @@ -371,8 +417,11 @@ async function flushPhotoFile(sha256: string): Promise { if (!xml) return; // Write the file first. Soft-crop bookkeeping must not block or abort the Lightroom packet. try { - await desktopInvoke("ftp_write_xmp", { sha256, xml }); + await invokeWithTimeout("ftp_write_xmp", { sha256, xml }); + flushFailed.delete(sha256); } catch (err) { + // The original is often still in the ingest folder. Retry once it has been filed. + flushFailed.add(sha256); console.error("ftp_write_xmp", sha256.slice(0, 12), err); return; } @@ -391,6 +440,19 @@ export function flushAllPhotoFiles(): void { for (const sha256 of Object.keys(loadRemembered())) scheduleFlush(sha256); } +/** Writes that failed (file still in ingest, or the shell was busy) — not the whole library. */ +export function flushFailedPhotoFiles(): void { + if (!isDesktop()) return; + for (const sha256 of flushFailed) scheduleFlush(sha256); +} + +/** The original just moved into the work folder. Write the marks already waiting for it. */ +export function retryPhotoFile(sha256: string): void { + if (!isDesktop() || !sha256) return; + if (!loadRemembered()[sha256]) return; + scheduleFlush(sha256); +} + export interface FileMarkUpdate { settings?: string; flag?: string | null; diff --git a/apps/app/src/library/LocalFtp.tsx b/apps/app/src/library/LocalFtp.tsx index 9b6e8ba..32fadf9 100644 --- a/apps/app/src/library/LocalFtp.tsx +++ b/apps/app/src/library/LocalFtp.tsx @@ -8,6 +8,7 @@ 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 { retryPhotoFile } from "../desktop/lightroomSidecar.js"; import { asArrayBuffer, prefs } from "../platform.js"; import type { DesktopOrigin, PreviewOf, UploadStatus } from "./uploads.js"; @@ -242,7 +243,11 @@ export function useLocalFtp(add: Add, enabled: boolean, invoke: Invoke = tauriIn sentEvent = to.title; sentDate = to.date; } - invoke("ftp_sent", { path: f.path, event: sentEvent, date: sentDate }).catch(() => {}); + invoke("ftp_sent", { path: f.path, event: sentEvent, date: sentDate }) + .then(() => { + retryPhotoFile(info.sha256); + }) + .catch(() => {}); // Changes made to it meanwhile now go to the server's copy. if (photo && orgId) { offlineQueue(orgId).uploaded(info.sha256, photo.id); diff --git a/apps/app/src/library/UsbCamera.tsx b/apps/app/src/library/UsbCamera.tsx index 13bed4e..9dab1c9 100644 --- a/apps/app/src/library/UsbCamera.tsx +++ b/apps/app/src/library/UsbCamera.tsx @@ -3,6 +3,7 @@ import { useCallback, useEffect, useMemo, useRef, useState } from "react"; import { t } from "../i18n.js"; import { cache } from "../offline/cache.js"; import { eventForArrival, exifDateTime, lisbonInstant } from "../offline/local.js"; +import { retryPhotoFile } from "../desktop/lightroomSidecar.js"; import { asArrayBuffer, prefs } from "../platform.js"; import { type FtpTarget, type IncomingFile, type Invoke, eventLabel } from "./LocalFtp.js"; import type { PreviewOf, UploadStatus } from "./uploads.js"; @@ -112,7 +113,11 @@ export function useUsbCamera(add: Add, enabled: boolean, target: FtpTarget | nul path: f.path, event: filed ? eventLabel(filed) : (to?.title ?? ""), date: filed ? filed.startsAt.slice(0, 10) : (to?.date ?? ""), - }).catch(() => {}); + }) + .then(() => { + retryPhotoFile(original.sha256); + }) + .catch(() => {}); } else { setCounts((c) => ({ ...c, failed: c.failed + 1 })); } diff --git a/apps/desktop/src-tauri/src/ftp.rs b/apps/desktop/src-tauri/src/ftp.rs index 348a11d..ea2e540 100644 --- a/apps/desktop/src-tauri/src/ftp.rs +++ b/apps/desktop/src-tauri/src/ftp.rs @@ -568,8 +568,13 @@ impl FtpState { /// JPEG or the RAW beside it, still inside the ingest tree. `ftp_read` stays JPEG-only. fn inside_kept(&self, path: &str) -> Result { - let root = self.ingest_dir().canonicalize().map_err(|e| e.to_string())?; - let p = Path::new(path).canonicalize().map_err(|_| "not_found".to_string())?; + let root = self + .ingest_dir() + .canonicalize() + .map_err(|e| e.to_string())?; + let p = Path::new(path) + .canonicalize() + .map_err(|_| "not_found".to_string())?; if p.starts_with(&root) && (is_photo(&p) || is_raw(&p)) { Ok(p) } else { @@ -705,10 +710,7 @@ impl FtpState { finished.remove(&f.name); seen.remove(&f.path); taken.insert(f.path.clone()); - ready.push(IncomingFile { - login, - ..f - }); + ready.push(IncomingFile { login, ..f }); } else { seen.insert(f.path.clone(), (f.size, f.modified_ms)); } @@ -894,6 +896,7 @@ fn merge_xmp_packet(existing: &str, incoming: &str) -> String { // A later pick must not wipe a crop already written, and a later crop must not wipe the pick. let combined = combine_descriptions(our_description(existing).as_deref(), &incoming_desc); let mut base = strip_our_description(existing); + let had_camera = base.contains(" String { for (key, xmlns_key, xmlns) in [ ("xmp:Rating", "xmlns:xmp", "http://ns.adobe.com/xap/1.0/"), ("xmp:Label", "xmlns:xmp", "http://ns.adobe.com/xap/1.0/"), - ("dc:title", "xmlns:dc", "http://purl.org/dc/elements/1.1/"), - ("photoshop:Headline", "xmlns:photoshop", "http://ns.adobe.com/photoshop/1.0/"), - ("photoshop:City", "xmlns:photoshop", "http://ns.adobe.com/photoshop/1.0/"), - ("photoshop:Credit", "xmlns:photoshop", "http://ns.adobe.com/photoshop/1.0/"), - ("photoshop:Source", "xmlns:photoshop", "http://ns.adobe.com/photoshop/1.0/"), + ( + "photoshop:Headline", + "xmlns:photoshop", + "http://ns.adobe.com/photoshop/1.0/", + ), + ( + "photoshop:City", + "xmlns:photoshop", + "http://ns.adobe.com/photoshop/1.0/", + ), + ( + "photoshop:Credit", + "xmlns:photoshop", + "http://ns.adobe.com/photoshop/1.0/", + ), + ( + "photoshop:Source", + "xmlns:photoshop", + "http://ns.adobe.com/photoshop/1.0/", + ), ( "iptcCore:Location", "xmlns:iptcCore", @@ -919,10 +937,39 @@ fn merge_xmp_packet(existing: &str, incoming: &str) -> String { base = stamp_attr(&base, key, &value, xmlns_key, xmlns); } } + // Caption, title, keywords and creator are RDF elements. Lightroom reads them from the first + // description and ignores the same elements on the packet this app appends afterwards. + for (tag, xmlns_key, xmlns) in [ + ( + "dc:description", + "xmlns:dc", + "http://purl.org/dc/elements/1.1/", + ), + ("dc:title", "xmlns:dc", "http://purl.org/dc/elements/1.1/"), + ("dc:creator", "xmlns:dc", "http://purl.org/dc/elements/1.1/"), + ("dc:subject", "xmlns:dc", "http://purl.org/dc/elements/1.1/"), + ] { + let Some(block) = structured_block(&combined, tag) else { + continue; + }; + if had_camera { + base = upsert_first_child(&base, tag, &block, xmlns_key, xmlns); + } + } if let Some(idx) = base.rfind("") { + // Moved onto the camera description. Leave them off the second packet so a rescan + // does not list the keywords twice. A file with no camera packet keeps them here. + let mut appended = combined.clone(); + if had_camera { + for tag in ["dc:description", "dc:title", "dc:creator", "dc:subject"] { + if let Some((start, end)) = find_element(&appended, tag) { + appended.replace_range(start..end, ""); + } + } + } let mut out = String::new(); out.push_str(&base[..idx]); - out.push_str(&combined); + out.push_str(&appended); out.push('\n'); out.push_str(&base[idx..]); return out; @@ -1137,6 +1184,100 @@ fn inject_after_about(xml: &str, extra: &str) -> String { out } +/// One element (`…` or a self-closing tag), not a longer name that shares the prefix. +fn find_element(xml: &str, tag: &str) -> Option<(usize, usize)> { + let needle = format!("<{tag}"); + let mut from = 0; + while let Some(rel) = xml[from..].find(&needle) { + let start = from + rel; + let boundary = xml.as_bytes().get(start + needle.len()).copied(); + let is_tag = boundary == Some(b'>') + || boundary == Some(b' ') + || boundary == Some(b'/') + || boundary == Some(b'\n') + || boundary == Some(b'\t'); + if !is_tag { + from = start + needle.len(); + continue; + } + let rest = &xml[start..]; + let Some(gt) = rest.find('>') else { + return None; + }; + if gt > 0 && rest.as_bytes()[gt - 1] == b'/' { + return Some((start, start + gt + 1)); + } + let close = format!(""); + let Some(close_at) = rest.find(&close) else { + return None; + }; + return Some((start, start + close_at + close.len())); + } + None +} + +fn element_block(xml: &str, tag: &str) -> Option { + let (start, end) = find_element(xml, tag)?; + Some(xml[start..end].to_string()) +} + +/// The element Lightroom reads, or a title that arrived as an attribute turned into `rdf:Alt`. +fn structured_block(xml: &str, tag: &str) -> Option { + if let Some(block) = element_block(xml, tag) { + return Some(block); + } + if tag != "dc:title" { + return None; + } + let title = attr_of(xml, "dc:title")?; + Some(format!( + "{title}" + )) +} + +/// Puts `block` inside the first `rdf:Description` (the camera packet Lightroom reads on rescan). +fn upsert_first_child(xml: &str, tag: &str, block: &str, xmlns_key: &str, xmlns: &str) -> String { + let Some(start) = xml.find(" String { + let Some(gt) = desc.find('>') else { + return desc.to_string(); + }; + if gt > 0 && desc.as_bytes()[gt - 1] == b'/' { + let mut out = String::new(); + out.push_str(&desc[..gt - 1]); + out.push('>'); + out.push_str(block); + out.push_str(""); + return out; + } + let Some(close) = desc.rfind("") else { + return desc.to_string(); + }; + let mut out = String::new(); + out.push_str(&desc[..close]); + out.push_str(block); + out.push_str(&desc[close..]); + out +} + fn xmp_app1(packet: &str) -> Result, String> { let body = packet.as_bytes(); let size = 2 + XMP_HEADER.len() + body.len(); @@ -1186,7 +1327,10 @@ fn find_xmp_app1(data: &[u8]) -> Result, String> { } let start = i - 2; let end = i + len; - if marker == 0xE1 && len >= 2 + XMP_HEADER.len() && &data[i + 2..i + 2 + XMP_HEADER.len()] == XMP_HEADER { + if marker == 0xE1 + && len >= 2 + XMP_HEADER.len() + && &data[i + 2..i + 2 + XMP_HEADER.len()] == XMP_HEADER + { return Ok(Some((start, end))); } i = end; @@ -1232,7 +1376,9 @@ fn embed_xmp_jpeg(path: &Path, xml: &str) -> Result<(), String> { }; let tmp = path.with_file_name(format!( "{}.photoreport-part", - path.file_name().and_then(|s| s.to_str()).unwrap_or("photo.jpg") + path.file_name() + .and_then(|s| s.to_str()) + .unwrap_or("photo.jpg") )); std::fs::write(&tmp, &next).map_err(|e| e.to_string())?; std::fs::rename(&tmp, path).map_err(|e| { @@ -1593,7 +1739,10 @@ mod tests { member_user_id: String::new(), }], ingest: dir.join("ingest").to_string_lossy().into_owned(), - work_folder: dir.join("work/{date} - {event}").to_string_lossy().into_owned(), + work_folder: dir + .join("work/{date} - {event}") + .to_string_lossy() + .into_owned(), auto_start: false, upload_originals: false, }) @@ -1618,11 +1767,7 @@ mod tests { .unwrap(); assert_eq!(PathBuf::from(&again), moved); assert!(!ingest.join("IMG_0001.JPG").exists()); - assert!(!moved - .parent() - .unwrap() - .join("IMG_0001-1.JPG") - .exists()); + assert!(!moved.parent().unwrap().join("IMG_0001-1.JPG").exists()); let _ = std::fs::remove_dir_all(&dir); } @@ -1886,10 +2031,30 @@ mod tests { assert!(both.contains("4")); assert!(!both.contains("0")); assert!(both.contains("xmpDM:pick=\"1\"")); - assert!(both.contains("dc:title=\"Jogador\"")); + let first_end = both.find("").expect("camera description"); + let first = &both[..first_end]; + assert!(first.contains("Jogador")); + assert!(!first.contains("photoreport:embed")); assert!(both.contains("photoreport:embed=\"1\"")); } + /// Lightroom's Read Metadata uses the first description. Caption, keywords and creator have to be there. + #[test] + fn caption_lands_on_the_camera_description() { + let camera = r#"0"#; + let incoming = r#"SNAFConcentração no HotelPeter SparkANDEBOL"#; + let both = merge_xmp_packet(camera, incoming); + let first_end = both.find("").expect("camera description"); + let first = &both[..first_end]; + assert!(first.contains("Concentração no Hotel")); + assert!(first.contains(">SNAF<")); + assert!(first.contains("Peter Spark")); + assert!(first.contains("ANDEBOL")); + assert!(first.contains("photoshop:City=\"Maia\"")); + assert!(first.contains("xmpDM:pick=\"1\"")); + assert!(!first.contains("photoreport:embed")); + } + /// A JPEG with no camera XMP must still get a full packet Lightroom can parse. #[test] fn empty_camera_packet_is_wrapped() { diff --git a/docs/ARCHITECTURE.md b/docs/ARCHITECTURE.md index 3d43a9b..683e408 100644 --- a/docs/ARCHITECTURE.md +++ b/docs/ARCHITECTURE.md @@ -485,9 +485,12 @@ credentials, another name and folder). **Cull marks and IPTC on the work-folder original.** While the desktop app is open it writes into the local original Lightroom imports (JPEG: embedded XMP; RAW: `.xmp` beside it): pick / reject / stars / colour (`xmpDM:pick`, `xmp:Rating`, `xmp:Label`), develop soft crop (`crs:Crop*`), and the resolved IPTC (caption, -title, city, keywords, creator…). The camera's XMP stays; PhotoReport stamps the flag onto that first -description so Lightroom Classic ≥ 13.2 Attribute filters see it. A catch-up pass covers photos already -picked before this screen was open. +title, city, keywords, creator…). The camera's XMP stays. PhotoReport stamps the flag and the newsroom +fields onto that first description — caption and title as `rdf:Alt`, keywords as `rdf:Bag`, creator as +`rdf:Seq` — because Lightroom Classic reads that description on import and on Read Metadata from Files and +ignores the same fields on a second packet. A write that fails while the file is still in the ingest folder +is retried once the original is filed, and again while the app stays open. A catch-up pass covers photos +already picked before this screen was open, without rewriting every older original first. **Cull marks from disk into the library (XMP → library).** On local FTP arrival, hand import, and server ingest, PhotoReport reads the same XMP fields back into the library (pick / reject / stars / colour). Soft -- 2.47.3