Write Lightroom metadata onto the camera XMP description
ci / rust (push) Successful in 7m12s
ci / typescript (push) Failing after 9m57s

Stamp caption, title, keywords and creator on the camera XMP description Lightroom reads.
This commit was merged in pull request #302.
This commit is contained in:
spark committed 2026-11-23 14:40:26 +00:00
commit 0fa7c91366
7 files changed
+285 -36

No files matched your search

+12 -4
View File
@@ -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<string, string>();
@@ -161,8 +161,9 @@ function marksOf(flag: string, rating: number, colorLabel: string, sent: boolean
export async function catchUpFileMarks(api: ApiClient, orgId: string): Promise<void> {
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;
}
@@ -60,7 +60,8 @@ describe("Lightroom sidecar", () => {
creator: "Fotógrafo / PhotoReport.pt",
},
);
expect(xml).toContain('dc:title="Pavlidis"');
expect(xml).toContain("<dc:title><rdf:Alt><rdf:li xml:lang=\"x-default\">Pavlidis</rdf:li></rdf:Alt></dc:title>");
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("<rdf:li>ANDEBOL</rdf:li>");
+67 -5
View File
@@ -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 += `<dc:title><rdf:Alt><rdf:li xml:lang="x-default">${xmlText(title)}</rdf:li></rdf:Alt></dc: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 += `<dc:description><rdf:Alt><rdf:li xml:lang="x-default">${xmlText(caption)}</rdf:li></rdf:Alt></dc:description>`;
@@ -350,7 +350,35 @@ function saveRemembered(all: Record<string, RememberedFile>): void {
}
const flushTimers = new Map<string, number>();
let flushChain = Promise.resolve();
const flushFailed = new Set<string>();
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<void> {
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<string, unknown>): Promise<unknown> {
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<void> {
const row = loadRemembered()[sha256];
if (!row) return;
@@ -371,8 +417,11 @@ async function flushPhotoFile(sha256: string): Promise<void> {
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;
+6 -1
View File
@@ -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);
+6 -1
View File
@@ -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 }));
}
+186 -21
View File
@@ -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<PathBuf, 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())?;
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("<rdf:Description");
// Lightroom reads the camera's lowercase `xmpDM:pick` and ignores a second description. Stamp that one.
if let Some(pick) = attr_of(&combined, "xmpDM:pick") {
let good = if pick == "1" { "True" } else { "False" };
@@ -903,11 +906,26 @@ fn merge_xmp_packet(existing: &str, incoming: &str) -> 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("</rdf:RDF>") {
// 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 (`<dc:description>…</dc:description>` 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!("</{tag}>");
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<String> {
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<String> {
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!(
"<dc:title><rdf:Alt><rdf:li xml:lang=\"x-default\">{title}</rdf:li></rdf:Alt></dc: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("<rdf:Description") else {
return xml.to_string();
};
let len = description_len(&xml[start..]);
let mut desc = xml[start..start + len].to_string();
if let Some((child_start, child_end)) = find_element(&desc, tag) {
desc.replace_range(child_start..child_end, "");
}
if !desc.contains(xmlns_key) {
desc = inject_after_about(&desc, &format!("{xmlns_key}=\"{xmlns}\""));
}
desc = insert_child_block(&desc, block);
let mut out = String::new();
out.push_str(&xml[..start]);
out.push_str(&desc);
out.push_str(&xml[start + len..]);
out
}
fn insert_child_block(desc: &str, block: &str) -> 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("</rdf:Description>");
return out;
}
let Some(close) = desc.rfind("</rdf:Description>") 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<Vec<u8>, 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<Option<(usize, usize)>, 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("<xmp:Rating>4</xmp:Rating>"));
assert!(!both.contains("<xmp:Rating>0</xmp:Rating>"));
assert!(both.contains("xmpDM:pick=\"1\""));
assert!(both.contains("dc:title=\"Jogador\""));
let first_end = both.find("</rdf:Description>").expect("camera description");
let first = &both[..first_end];
assert!(first.contains("<dc:title><rdf:Alt><rdf:li xml:lang=\"x-default\">Jogador</rdf:li></rdf:Alt></dc:title>"));
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#"<?xpacket begin="" id="W5M0MpCehiHzreSzNTczkc9d"?><x:xmpmeta xmlns:x="adobe:ns:meta/"><rdf:RDF xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#"><rdf:Description rdf:about="" xmlns:xmp="http://ns.adobe.com/xap/1.0/"><xmp:Rating>0</xmp:Rating></rdf:Description></rdf:RDF></x:xmpmeta>"#;
let incoming = r#"<?xml version="1.0"?><x:xmpmeta xmlns:x="adobe:ns:meta/"><rdf:RDF xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#"><rdf:Description rdf:about="" xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:photoshop="http://ns.adobe.com/photoshop/1.0/" xmlns:xmpDM="http://ns.adobe.com/xmp/1.0/DynamicMedia/" photoshop:City="Maia" xmpDM:pick="1" xmpDM:good="True"><dc:title><rdf:Alt><rdf:li xml:lang="x-default">SNAF</rdf:li></rdf:Alt></dc:title><dc:description><rdf:Alt><rdf:li xml:lang="x-default">Concentração no Hotel</rdf:li></rdf:Alt></dc:description><dc:creator><rdf:Seq><rdf:li>Peter Spark</rdf:li></rdf:Seq></dc:creator><dc:subject><rdf:Bag><rdf:li>ANDEBOL</rdf:li></rdf:Bag></dc:subject></rdf:Description></rdf:RDF></x:xmpmeta>"#;
let both = merge_xmp_packet(camera, incoming);
let first_end = both.find("</rdf:Description>").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() {
+6 -3
View File
@@ -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