feat(desktop): Lightroom Attribute Pick/Reject sync + retract (BIT-174) #175

Merged
spark merged 1 commits from task/BIT-174-lr-pick-xmp into main 2026-11-03 23:40:50 +00:00
9 changed files with 338 additions and 42 deletions

No files matched your search

+5 -5
View File
@@ -570,8 +570,8 @@ export class DeliveryService {
const fileName = renderFileName(recipe.fileNameTemplate, named, sendOriginals && untouched ? item.photo.originalName : deliveredName(item.photo));
const edit = sendOriginals ? undefined : await this.editFor(item.photoId, item.photo.developSeq);
const created = item.photo.capturedAt ? createdStamp(item.photo.capturedAt) : undefined;
// Cull marks (pick / reject / stars) go into XMP so Lightroom sees rating + green label on import.
const marks = { flag: item.photo.flag, rating: item.photo.rating };
// Cull marks → Lightroom Attribute bar (XMP-xmpDM:Pick / Rating / Label) and Photo Mechanic.
const marks = { flag: item.photo.flag, rating: item.photo.rating, colorLabel: item.photo.colorLabel };
const rendered = sendOriginals
? untouched
? await readFile(source)
@@ -676,7 +676,7 @@ export class DeliveryService {
* The desktop app of a computer takes what is waiting for its folders: marked running (a crash puts them back in
* the queue after 10 minutes, rendered again), with where each file goes under the folder.
*/
async localClaim(organizationId: string, machine: string, limit = 10): Promise<{ id: string; folder: string; path: string; byteSize: number | null }[]> {
async localClaim(organizationId: string, machine: string, limit = 10): Promise<{ id: string; photoId: string; folder: string; path: string; byteSize: number | null }[]> {
const { db } = this.deps;
const waiting = await db.deliveryItem.findMany({
where: { organizationId, status: "WAITING", target: { kind: "LOCAL", username: machine, disabledAt: null } },
@@ -684,10 +684,10 @@ export class DeliveryService {
orderBy: { sequence: "asc" },
take: limit,
});
const out: { id: string; folder: string; path: string; byteSize: number | null }[] = [];
const out: { id: string; photoId: string; folder: string; path: string; byteSize: number | null }[] = [];
for (const item of waiting) {
const taken = await db.deliveryItem.updateMany({ where: { id: item.id, status: "WAITING" }, data: { status: "RUNNING", startedAt: new Date() } });
if (taken.count) out.push({ id: item.id, folder: item.target.baseUrl, path: item.remotePath ?? "", byteSize: item.byteSize });
if (taken.count) out.push({ id: item.id, photoId: item.photoId, folder: item.target.baseUrl, path: item.remotePath ?? "", byteSize: item.byteSize });
}
return out;
}
+4
View File
@@ -3,6 +3,7 @@ import { useEffect } from "react";
import { useAuth } from "../auth.js";
import type { ImportSources } from "../library/importSources.js";
import { desktopInvoke, isDesktop } from "../platform.js";
import { reconcileLightroomMarks, watchDeliveredFile } from "./lrMarksWatch.js";
/** The desktop shell's side of "a folder on this computer" and of importing destinations (src-tauri/src/deliver.rs). */
export interface DeliveryShell {
@@ -38,6 +39,7 @@ export async function saveWaitingDeliveries(api: ApiClient, orgId: string, shell
const bytes = await api.localDeliveryFile(orgId, item.id);
const where = await shell.write(item.folder, item.path, bytes);
await api.localDeliveryResult(orgId, item.id, { ok: true, path: where });
if (item.photoId) watchDeliveredFile(orgId, item.photoId, where);
saved++;
} catch (err) {
failed++;
@@ -65,6 +67,8 @@ export function LocalDeliveries({ shell = desktopDeliveryShell, enabled = isDesk
const r = await saveWaitingDeliveries(api, orgId, shell);
if (r.saved + r.failed < 10) break;
}
// Lightroom Reject on a delivered file → library REJECT → server retracts the export.
await reconcileLightroomMarks(api);
} catch {
// Offline, or a desktop app too old for this: try again later.
}
+114
View File
@@ -0,0 +1,114 @@
import { libraryMarksFromXmp, xmpPacketFromJpeg } from "@photoreport/metadata";
import type { ApiClient } from "@photoreport/sdk";
import { desktopInvoke, isDesktop } from "../platform.js";
/**
* Delivered files this computer saved, watched for Lightroom Reject (XMP-xmpDM:Pick=-1). When found, the library
* flag becomes REJECT and the server retracts any delivery of that photo.
*/
const STORE_KEY = "lr:delivered-watch";
const MAX_WATCH = 2000;
export interface WatchedDelivery {
path: string;
photoId: string;
orgId: string;
/** Last mtime we already reconciled (ms). */
seenAt: number;
}
function load(): WatchedDelivery[] {
try {
const raw = localStorage.getItem(STORE_KEY);
const parsed = raw ? (JSON.parse(raw) as WatchedDelivery[]) : [];
return Array.isArray(parsed) ? parsed.slice(-MAX_WATCH) : [];
} catch {
return [];
}
}
function save(rows: WatchedDelivery[]): void {
try {
localStorage.setItem(STORE_KEY, JSON.stringify(rows.slice(-MAX_WATCH)));
} catch {
/* quota */
}
}
/** Remember a file just written into a local delivery folder. */
export function watchDeliveredFile(orgId: string, photoId: string, path: string): void {
if (!photoId || !path) return;
const rows = load().filter((r) => r.path !== path);
rows.push({ path, photoId, orgId, seenAt: 0 });
save(rows);
}
async function readFileBytes(path: string): Promise<Uint8Array | null> {
try {
const raw = await desktopInvoke<number[] | Uint8Array>("delivery_read", { path });
return raw instanceof Uint8Array ? raw : new Uint8Array(raw);
} catch {
return null;
}
}
function stemXmpPath(path: string): string {
const slash = Math.max(path.lastIndexOf("/"), path.lastIndexOf("\\"));
const base = slash >= 0 ? path.slice(slash + 1) : path;
const dot = base.lastIndexOf(".");
const stem = dot > 0 ? base.slice(0, dot) : base;
const dir = slash >= 0 ? path.slice(0, slash + 1) : "";
return `${dir}${stem}.xmp`;
}
async function readSidecarOrJpegXmp(path: string): Promise<string | null> {
for (const side of [`${path}.xmp`, stemXmpPath(path)]) {
const sidecar = await readFileBytes(side);
if (sidecar) return new TextDecoder("utf-8", { fatal: false }).decode(sidecar);
}
const jpeg = await readFileBytes(path);
if (!jpeg) return null;
return xmpPacketFromJpeg(jpeg);
}
async function deleteDeliveredFile(path: string): Promise<void> {
try {
await desktopInvoke<void>("delivery_remove", { path });
} catch {
/* gone already, or older desktop without the command */
}
}
/**
* One pass over watched deliveries: Reject in Lightroom → delete the local export, library REJECT
* (server retracts FTP/SFTP/ZeroZero/… deliveries). Returns how many photos were marked rejected.
*/
export async function reconcileLightroomMarks(api: ApiClient): Promise<number> {
if (!isDesktop()) return 0;
const rows = load();
if (!rows.length) return 0;
let rejected = 0;
const next: WatchedDelivery[] = [];
for (const row of rows) {
const xmp = await readSidecarOrJpegXmp(row.path);
if (!xmp) {
next.push(row);
continue;
}
const marks = libraryMarksFromXmp(xmp);
if (marks.flag === "REJECT") {
try {
await deleteDeliveredFile(row.path);
await api.updatePhotos(row.orgId, [row.photoId], { flag: "REJECT" });
rejected++;
continue;
} catch {
next.push(row);
continue;
}
}
next.push({ ...row, seenAt: Date.now() });
}
save(next);
return rejected;
}
+87
View File
@@ -109,6 +109,60 @@ impl Deliveries {
})?;
Ok(target)
}
/// Reads a file only if it sits under a delivery folder chosen on this computer (Lightroom XMP watch).
pub fn read_watched(&self, path: &str) -> Result<Vec<u8>, String> {
let target = PathBuf::from(path);
let canon = target.canonicalize().map_err(|e| e.to_string())?;
let allowed = self.folders().iter().any(|f| {
Path::new(f)
.canonicalize()
.map(|root| canon.starts_with(&root))
.unwrap_or(false)
});
// Also allow the `.xmp` sidecar next to a delivered JPEG.
let allowed_xmp = path.ends_with(".xmp")
&& self.folders().iter().any(|f| {
Path::new(f)
.canonicalize()
.ok()
.and_then(|root| {
canon
.parent()
.map(|p| p.starts_with(&root))
})
.unwrap_or(false)
});
if !allowed && !allowed_xmp {
return Err("path_not_under_delivery_folder".into());
}
std::fs::read(&canon).map_err(|e| e.to_string())
}
/// Deletes a delivered file (and its `.xmp` sidecar) under a chosen delivery folder — Lightroom Reject retract.
pub fn remove_watched(&self, path: &str) -> Result<(), String> {
let target = PathBuf::from(path);
let canon = target.canonicalize().map_err(|e| e.to_string())?;
let allowed = self.folders().iter().any(|f| {
Path::new(f)
.canonicalize()
.map(|root| canon.starts_with(&root))
.unwrap_or(false)
});
if !allowed {
return Err("path_not_under_delivery_folder".into());
}
std::fs::remove_file(&canon).map_err(|e| e.to_string())?;
// Sidecar next to the JPEG (`photo.jpg.xmp` or `photo.xmp`).
let sidecar_jpg = PathBuf::from(format!("{path}.xmp"));
let sidecar_stem = canon.with_extension("xmp");
for side in [sidecar_jpg, sidecar_stem] {
if side.exists() {
let _ = std::fs::remove_file(&side);
}
}
Ok(())
}
}
/// `base` + a relative path from a template, refusing anything that climbs out (`..`) or is absolute.
@@ -585,6 +639,18 @@ pub fn delivery_write(
.map(|p| p.to_string_lossy().to_string())
}
/// Bytes of a delivered file (or its `.xmp` sidecar) — only under a chosen delivery folder (Lightroom XMP watch).
#[tauri::command]
pub fn delivery_read(path: String, state: tauri::State<'_, Deliveries>) -> Result<Vec<u8>, String> {
state.read_watched(&path)
}
/// Deletes a delivered file under a chosen folder (and sidecar) after Lightroom Reject.
#[tauri::command]
pub fn delivery_remove(path: String, state: tauri::State<'_, Deliveries>) -> Result<(), String> {
state.remove_watched(&path)
}
/// Upload destinations saved in Photo Mechanic and FileZilla on this computer, with the passwords that can be read.
#[tauri::command]
pub fn import_upload_profiles() -> ImportSources {
@@ -636,6 +702,27 @@ mod tests {
assert!(odd.ends_with("Jogo_ 1/foto_.jpg"), "{odd:?}");
}
#[test]
fn reads_and_removes_only_inside_chosen_folders() {
let dir = tmp("cfg-watch");
let out = tmp("out-watch");
let d = Deliveries::at(dir);
d.add_folder(&out);
let folder = out.to_string_lossy().to_string();
let p = d.write(&folder, "lr/pick.jpg", b"jpeg-bytes").unwrap();
let path = p.to_string_lossy().to_string();
assert_eq!(d.read_watched(&path).unwrap(), b"jpeg-bytes");
let other = tmp("other-watch");
let outsider = other.join("nope.jpg");
std::fs::write(&outsider, b"x").unwrap();
assert_eq!(
d.read_watched(&outsider.to_string_lossy()).unwrap_err(),
"path_not_under_delivery_folder"
);
d.remove_watched(&path).unwrap();
assert!(!p.exists());
}
#[test]
fn decodes_headers() {
assert_eq!(
+2
View File
@@ -181,6 +181,8 @@ pub fn run() {
deliver::delivery_folders,
deliver::delivery_folder_pick,
deliver::delivery_write,
deliver::delivery_read,
deliver::delivery_remove,
deliver::import_upload_profiles,
camera::camera_status,
camera::camera_take,
+5 -4
View File
@@ -427,10 +427,11 @@ Each target also has Photo Mechanic's uploader output options: fit-in-box size,
sharpening, ppi, keep or drop the camera EXIF, and conversion to sRGB. Targets can be duplicated (same server and
credentials, another name and folder).
**Cull marks on delivery.** A pick (⚑), reject (✕) and star rating are written into the delivered JPEG
(`XMP-xmp:Rating`, colour label Green for picks, digiKam `PickLabel`, IPTC Urgency). Lightroom's Flagged
filter is catalog-only and will not show third-party picks; filter by **rating** or **green label** after
import. Photo Mechanic reads Urgency / PickLabel.
**Cull marks on delivery.** A pick (⚑), reject (✕), stars and colour label are written into the delivered JPEG
for Lightroom Classic ≥ 13.2 Attribute filters: `XMP-xmpDM:Pick` (1 / 0 / −1) + `Good`, `XMP-xmp:Rating`,
`XMP-xmp:Label`, plus digiKam `PickLabel` and IPTC Urgency for Photo Mechanic. When the desktop app is open it
watches local delivery folders; a Reject written back by Lightroom (XMP auto-write) sets the photo to REJECT
and retracts any delivery of that file.
**Photo Mechanic compatibility (templates and IPTC).** Every template (IPTC pad, folders, file names, rename on
arrival) takes every variable of Photo Mechanic's list, under its names and short names, in any case
+98 -13
View File
@@ -246,35 +246,120 @@ export interface CreatedStamp {
iso: string; // YYYY-MM-DDTHH:MM:SS+hh:mm (XMP)
}
/** Library cull (⚑ / ✕ / stars) written into the delivered file so Lightroom and Photo Mechanic see it on import. */
/** Library cull (⚑ / ✕ / stars / colour) written into the delivered file so Lightroom and Photo Mechanic see it. */
export interface LibraryMarks {
flag?: "NONE" | "PICK" | "REJECT" | string | null;
rating?: number | null;
colorLabel?: "NONE" | "RED" | "YELLOW" | "GREEN" | "BLUE" | "PURPLE" | string | null;
}
/** Lightroom Classic 13.2+ Attribute filters: Flagged / Unflagged / Rejected ↔ `xmpDM:Pick` (ExifTool `XMP:Pick`). */
const LR_LABEL: Record<string, string> = {
RED: "Red",
YELLOW: "Yellow",
GREEN: "Green",
BLUE: "Blue",
PURPLE: "Purple",
};
/**
* Stars, pick and reject as XMP/EXIF/IPTC.
* Stars, pick/reject flag and colour label as XMP/EXIF/IPTC — the Lightroom Attribute bar and Photo Mechanic.
*
* Lightroom's **Flagged** filter is catalog-only — Adobe does not read a third-party pick flag from XMP. What does
* import: star rating (`XMP-xmp:Rating`) and colour label (`XMP-xmp:Label`). A PhotoReport pick with no stars is
* written as rating 1 + green label; a reject as rating −1. digiKam `PickLabel` and IPTC Urgency help Photo Mechanic.
* Lightroom Classic ≥ 13.2 reads and writes `XMP-xmpDM:Pick` (1 flagged, 0 unflagged, −1 rejected) and
* `XMP-xmpDM:Good`. Rating and Label cover stars and colour. digiKam PickLabel + IPTC Urgency help Photo Mechanic.
*/
export function marksToExiftoolArgs(marks: LibraryMarks): string[] {
const flag = marks.flag ?? "NONE";
const rating = Math.max(0, Math.min(5, Math.round(Number(marks.rating) || 0)));
if (flag !== "PICK" && flag !== "REJECT" && rating === 0) return [];
if (flag === "REJECT") {
return ["-XMP-xmp:Rating=-1", "-Rating=-1", "-XMP-xmp:Label=", "-XMP-digiKam:PickLabel=1", "-IPTC:Urgency=", "-XMP-photoshop:Urgency="];
}
const stars = rating > 0 ? rating : flag === "PICK" ? 1 : 0;
const color = marks.colorLabel && marks.colorLabel !== "NONE" ? LR_LABEL[marks.colorLabel] : undefined;
if (flag !== "PICK" && flag !== "REJECT" && rating === 0 && !color) return [];
const args: string[] = [];
if (stars > 0) args.push(`-XMP-xmp:Rating=${stars}`, `-Rating=${stars}`);
if (flag === "PICK") {
args.push("-XMP-xmp:Label=Green", "-XMP-digiKam:PickLabel=3", "-IPTC:Urgency=1", "-XMP-photoshop:Urgency=1");
if (flag === "REJECT") {
args.push(
"-XMP-xmpDM:Pick=-1",
"-XMP-xmpDM:Good=False",
"-XMP-xmp:Rating=-1",
"-Rating=-1",
"-XMP-digiKam:PickLabel=1",
"-IPTC:Urgency=",
"-XMP-photoshop:Urgency=",
);
} else if (flag === "PICK") {
args.push("-XMP-xmpDM:Pick=1", "-XMP-xmpDM:Good=True", "-XMP-digiKam:PickLabel=3", "-IPTC:Urgency=1", "-XMP-photoshop:Urgency=1");
if (rating > 0) args.push(`-XMP-xmp:Rating=${rating}`, `-Rating=${rating}`);
} else if (rating > 0) {
args.push(`-XMP-xmp:Rating=${rating}`, `-Rating=${rating}`, "-XMP-xmpDM:Pick=0");
}
if (flag === "REJECT") {
args.push("-XMP-xmp:Label=");
} else if (color) {
args.push(`-XMP-xmp:Label=${color}`);
} else if (flag === "PICK") {
// Default select colour when the library has no label — still filterable in Lightroom's colour row.
args.push("-XMP-xmp:Label=Green");
}
return args;
}
/**
* Read cull marks from an XMP packet (sidecar or embedded). Used when Lightroom writes Pick back to a delivered file.
*/
export function libraryMarksFromXmp(xmp: string): LibraryMarks {
const pick = xmpMatchNum(xmp, /(?:xmpDM:pick|xmp:Pick|Pick)\s*(?:=|:|>)\s*"?(-?\d+)/i) ?? xmpMatchNum(xmp, /<xmpDM:pick>(-?\d+)<\/xmpDM:pick>/i);
const rating = xmpMatchNum(xmp, /(?:xmp:Rating|Rating)\s*(?:=|:|>)\s*"?(-?\d+)/i) ?? xmpMatchNum(xmp, /<xmp:Rating>(-?\d+)<\/xmp:Rating>/i);
const labelRaw = xmpMatchStr(xmp, /(?:xmp:Label|Label)\s*(?:=|:|>)\s*"?([A-Za-z]+)/i) ?? xmpMatchStr(xmp, /<xmp:Label>([^<]+)<\/xmp:Label>/i);
let flag: LibraryMarks["flag"] = "NONE";
if (pick === -1 || rating === -1) flag = "REJECT";
else if (pick === 1) flag = "PICK";
const colorLabel =
labelRaw && ["Red", "Yellow", "Green", "Blue", "Purple"].includes(labelRaw)
? (labelRaw.toUpperCase() as "RED" | "YELLOW" | "GREEN" | "BLUE" | "PURPLE")
: "NONE";
return {
flag,
rating: rating !== null && rating > 0 ? Math.min(5, rating) : 0,
colorLabel,
};
}
function xmpMatchNum(xmp: string, re: RegExp): number | null {
const m = xmp.match(re);
if (!m?.[1]) return null;
const n = Number(m[1]);
return Number.isFinite(n) ? n : null;
}
function xmpMatchStr(xmp: string, re: RegExp): string | null {
return xmp.match(re)?.[1] ?? null;
}
/** Pull the XMP packet out of a JPEG (APP1) or return the whole buffer if it already looks like XMP. */
export function xmpPacketFromJpeg(bytes: Uint8Array): string | null {
const asText = new TextDecoder("utf-8", { fatal: false }).decode(bytes.subarray(0, Math.min(bytes.length, 256)));
if (asText.includes("<x:xmpmeta") || asText.includes("xmpDM:pick")) return new TextDecoder("utf-8", { fatal: false }).decode(bytes);
// Scan APP1 segments for the XMP namespace.
if (bytes.length < 4 || bytes[0] !== 0xff || bytes[1] !== 0xd8) return null;
let i = 2;
while (i + 4 < bytes.length) {
if (bytes[i] !== 0xff) break;
const marker = bytes[i + 1]!;
const size = (bytes[i + 2]! << 8) | bytes[i + 3]!;
if (marker === 0xe1 && size > 4) {
const start = i + 4;
const end = i + 2 + size;
const head = new TextDecoder("utf-8", { fatal: false }).decode(bytes.subarray(start, Math.min(start + 64, end)));
if (head.startsWith("http://ns.adobe.com/xap/1.0/") || head.includes("xmpmeta")) {
return new TextDecoder("utf-8", { fatal: false }).decode(bytes.subarray(start, end));
}
}
if (marker === 0xda) break;
i += 2 + size;
}
return null;
}
/**
* ExifTool arguments (`-TAG=value`) for the given values; list fields repeat the tag once per item.
* IIM is written as UTF-8 and flagged as such (CodedCharacterSet), so accents survive in every reader; files
+22 -19
View File
@@ -15,6 +15,7 @@ import {
renderFileName,
renderFolder,
seasonOf,
libraryMarksFromXmp,
marksToExiftoolArgs,
toExiftoolArgs,
variablesIn,
@@ -121,26 +122,28 @@ describe("IPTC template", () => {
]);
});
it("writes pick/reject/stars so Lightroom and Photo Mechanic see the cull on import", () => {
it("writes Lightroom Attribute flags (XMP:Pick) plus stars/label for Photo Mechanic", () => {
expect(marksToExiftoolArgs({ flag: "NONE", rating: 0 })).toEqual([]);
expect(marksToExiftoolArgs({ flag: "PICK", rating: 0 })).toEqual([
"-XMP-xmp:Rating=1",
"-Rating=1",
"-XMP-xmp:Label=Green",
"-XMP-digiKam:PickLabel=3",
"-IPTC:Urgency=1",
"-XMP-photoshop:Urgency=1",
]);
expect(marksToExiftoolArgs({ flag: "PICK", rating: 4 })).toContain("-XMP-xmp:Rating=4");
expect(marksToExiftoolArgs({ flag: "REJECT", rating: 3 })).toEqual([
"-XMP-xmp:Rating=-1",
"-Rating=-1",
"-XMP-xmp:Label=",
"-XMP-digiKam:PickLabel=1",
"-IPTC:Urgency=",
"-XMP-photoshop:Urgency=",
]);
expect(toExiftoolArgs({ title: "A" }, undefined, { flag: "PICK", rating: 0 })).toContain("-XMP-xmp:Label=Green");
const pick = marksToExiftoolArgs({ flag: "PICK", rating: 0 });
expect(pick).toContain("-XMP-xmpDM:Pick=1");
expect(pick).toContain("-XMP-xmpDM:Good=True");
expect(pick).toContain("-XMP-xmp:Label=Green");
expect(marksToExiftoolArgs({ flag: "PICK", rating: 4, colorLabel: "RED" })).toEqual(
expect.arrayContaining(["-XMP-xmpDM:Pick=1", "-XMP-xmp:Rating=4", "-XMP-xmp:Label=Red"]),
);
const reject = marksToExiftoolArgs({ flag: "REJECT", rating: 3 });
expect(reject).toContain("-XMP-xmpDM:Pick=-1");
expect(reject).toContain("-XMP-xmp:Rating=-1");
expect(toExiftoolArgs({ title: "A" }, undefined, { flag: "PICK", rating: 0 })).toContain("-XMP-xmpDM:Pick=1");
});
it("reads Lightroom Pick/Reject back from an XMP packet", () => {
expect(libraryMarksFromXmp(`<xmpDM:pick>1</xmpDM:pick><xmp:Rating>3</xmp:Rating><xmp:Label>Blue</xmp:Label>`)).toEqual({
flag: "PICK",
rating: 3,
colorLabel: "BLUE",
});
expect(libraryMarksFromXmp(`xmpDM:pick="-1"`).flag).toBe("REJECT");
});
});
+1 -1
View File
@@ -142,7 +142,7 @@ export class ApiClient {
/** Desktop app: takes the deliveries waiting for this computer's folders (rendered on the server). */
claimLocalDeliveries(orgId: string, machine: string) {
return this.request<{ items: { id: string; folder: string; path: string; byteSize: number | null }[] }>("POST", `/v1/orgs/${orgId}/deliveries/local/claim`, { machine });
return this.request<{ items: { id: string; photoId: string; folder: string; path: string; byteSize: number | null }[] }>("POST", `/v1/orgs/${orgId}/deliveries/local/claim`, { machine });
}
/** The rendered file of a delivery this computer took. */