Compare commits
3
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
9c6692d868 | ||
|
|
e823d7d848 | ||
|
|
454247364f |
No files matched your search
@@ -0,0 +1,205 @@
|
||||
import type { LibraryMessage } from "@photoreport/contracts";
|
||||
import type { ApiClient, EventSummary } from "@photoreport/sdk";
|
||||
import { useEffect } from "react";
|
||||
import { useLibraryLive } from "../library/realtime.js";
|
||||
import { isDesktop } from "../platform.js";
|
||||
import { settingsFromDevelop, writePhotoCommands, writePhotoFile, type FileIptc, type FileMarkUpdate } from "./lightroomSidecar.js";
|
||||
|
||||
const LOCAL = "local:";
|
||||
const idToSha = new Map<string, string>();
|
||||
const caughtUp = new Set<string>();
|
||||
|
||||
function remember(id: string, sha256: string | null | undefined): void {
|
||||
if (!id || !sha256) return;
|
||||
idToSha.set(id, sha256);
|
||||
}
|
||||
|
||||
function shaOf(id: string): string | null {
|
||||
if (id.startsWith(LOCAL)) return id.slice(LOCAL.length);
|
||||
const known = idToSha.get(id);
|
||||
if (known) return known;
|
||||
try {
|
||||
const map = JSON.parse(localStorage.getItem("pr.localmap") ?? "{}") as Record<string, string>;
|
||||
for (const [sha, serverId] of Object.entries(map)) {
|
||||
if (serverId === id) return sha;
|
||||
}
|
||||
} catch {
|
||||
// A broken map only means this photo is written the next time it is seen.
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
function eventIsCurrent(event: EventSummary, now: number): boolean {
|
||||
const start = Date.parse(event.startsAt);
|
||||
const until = Date.parse(event.ingestUntil);
|
||||
const sixHours = 6 * 60 * 60 * 1000;
|
||||
const eighteenHours = 18 * 60 * 60 * 1000;
|
||||
if (Number.isFinite(until) && until >= now - sixHours) return true;
|
||||
if (Number.isFinite(start) && Math.abs(now - start) <= eighteenHours) return true;
|
||||
return false;
|
||||
}
|
||||
|
||||
async function developSettings(api: ApiClient, photoId: string): Promise<string | undefined> {
|
||||
if (photoId.startsWith(LOCAL)) return undefined;
|
||||
try {
|
||||
return settingsFromDevelop(await api.developState(photoId));
|
||||
} catch {
|
||||
return undefined;
|
||||
}
|
||||
}
|
||||
|
||||
let developActive = 0;
|
||||
const developWait: Array<() => void> = [];
|
||||
const DEVELOP_AT_ONCE = 4;
|
||||
|
||||
function whenDevelopSlot(): Promise<void> {
|
||||
if (developActive < DEVELOP_AT_ONCE) {
|
||||
developActive += 1;
|
||||
return Promise.resolve();
|
||||
}
|
||||
return new Promise((resolve) => {
|
||||
developWait.push(() => {
|
||||
developActive += 1;
|
||||
resolve();
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
function releaseDevelopSlot(): void {
|
||||
developActive -= 1;
|
||||
const next = developWait.shift();
|
||||
if (next) next();
|
||||
}
|
||||
|
||||
async function resolvedIptc(api: ApiClient, photoId: string): Promise<FileIptc | undefined> {
|
||||
if (photoId.startsWith(LOCAL)) return undefined;
|
||||
try {
|
||||
const got = await api.photoIptc(photoId);
|
||||
const values = got.values ?? {};
|
||||
const iptc: FileIptc = {};
|
||||
for (const key of ["title", "caption", "headline", "event", "location", "city", "copyright", "credit", "source", "creator"] as const) {
|
||||
const v = values[key];
|
||||
if (typeof v === "string" && v.trim()) iptc[key] = v.trim();
|
||||
}
|
||||
if (Array.isArray(values.keywords)) {
|
||||
const keywords = values.keywords.filter((k): k is string => typeof k === "string" && !!k.trim()).map((k) => k.trim());
|
||||
if (keywords.length) iptc.keywords = keywords;
|
||||
}
|
||||
return Object.keys(iptc).length ? iptc : undefined;
|
||||
} catch {
|
||||
return undefined;
|
||||
}
|
||||
}
|
||||
|
||||
function writeKnown(sha: string, update: FileMarkUpdate, developSeq: number, photoId: string, api: ApiClient, withIptc: boolean): void {
|
||||
if (update.flag !== undefined || update.sent === true || update.rating !== undefined || update.colorLabel !== undefined) writePhotoFile(sha, update);
|
||||
if (developSeq <= 0 && !withIptc) return;
|
||||
void whenDevelopSlot()
|
||||
.then(async () => {
|
||||
const [settings, iptc] = await Promise.all([
|
||||
developSeq > 0 ? developSettings(api, photoId) : Promise.resolve(undefined),
|
||||
withIptc ? resolvedIptc(api, photoId) : Promise.resolve(undefined),
|
||||
]);
|
||||
if (settings && settings !== "{}") writePhotoFile(sha, { settings });
|
||||
if (iptc) writePhotoFile(sha, { iptc });
|
||||
})
|
||||
.finally(releaseDevelopSlot);
|
||||
}
|
||||
|
||||
/** Live picks, crops and deliveries, including ones made on another screen of this app. */
|
||||
export function onFileMarkMessage(api: ApiClient, message: LibraryMessage): void {
|
||||
if (!isDesktop()) return;
|
||||
if (message.type === "photo.added") {
|
||||
remember(message.photo.id, message.photo.sha256);
|
||||
const marks = marksOf(message.photo.flag, message.photo.rating, message.photo.colorLabel, message.photo.delivery === "DONE");
|
||||
// Always push the resolved IPTC (and any pick / develop) into the work-folder file Lightroom imports.
|
||||
writeKnown(message.photo.sha256, marks ?? {}, message.photo.developSeq, message.photo.id, api, true);
|
||||
return;
|
||||
}
|
||||
if (message.type === "photo.updated") {
|
||||
const patch = message.patch;
|
||||
if (patch.flag === undefined && patch.rating === undefined && patch.colorLabel === undefined) return;
|
||||
const update: FileMarkUpdate = {};
|
||||
if (patch.flag !== undefined) update.flag = patch.flag;
|
||||
if (patch.rating !== undefined) update.rating = patch.rating;
|
||||
if (patch.colorLabel !== undefined) update.colorLabel = patch.colorLabel;
|
||||
for (const id of message.ids) {
|
||||
const sha = shaOf(id);
|
||||
if (sha) writePhotoFile(sha, update);
|
||||
}
|
||||
return;
|
||||
}
|
||||
if (message.type === "photo.edited") {
|
||||
const sha = shaOf(message.photoId);
|
||||
if (!sha) return;
|
||||
writePhotoCommands(sha, message.ops.map((op) => op.command));
|
||||
void developSettings(api, message.photoId).then((settings) => {
|
||||
if (settings && settings !== "{}") writePhotoFile(sha, { settings });
|
||||
});
|
||||
return;
|
||||
}
|
||||
if (message.type === "delivery.updated" && message.item.status === "DONE") {
|
||||
const sha = shaOf(message.item.photoId);
|
||||
if (sha) writePhotoFile(sha, { sent: true });
|
||||
}
|
||||
}
|
||||
|
||||
function marksOf(flag: string, rating: number, colorLabel: string, sent: boolean): FileMarkUpdate | null {
|
||||
const update: FileMarkUpdate = {};
|
||||
if (flag === "PICK" || flag === "REJECT") update.flag = flag;
|
||||
if (rating > 0) update.rating = rating;
|
||||
if (colorLabel && colorLabel !== "NONE") update.colorLabel = colorLabel;
|
||||
if (sent) update.sent = true;
|
||||
if (update.flag === undefined && update.sent !== true && update.rating === undefined && update.colorLabel === undefined) return null;
|
||||
return update;
|
||||
}
|
||||
|
||||
/**
|
||||
* Photos already picked, edited or sent before this screen was open. The file is the copy Lightroom imports,
|
||||
* so the mark has to be there even when nobody opens Revelar.
|
||||
*/
|
||||
export async function catchUpFileMarks(api: ApiClient, orgId: string): Promise<void> {
|
||||
if (!isDesktop() || !orgId || caughtUp.has(orgId)) return;
|
||||
caughtUp.add(orgId);
|
||||
let events: EventSummary[] = [];
|
||||
try {
|
||||
events = (await api.listEvents(orgId)).events.filter((event) => eventIsCurrent(event, Date.now()));
|
||||
} catch {
|
||||
caughtUp.delete(orgId);
|
||||
return;
|
||||
}
|
||||
const now = Date.now();
|
||||
for (const event of events) {
|
||||
if (!eventIsCurrent(event, now)) continue;
|
||||
let offset = 0;
|
||||
let total = 1;
|
||||
while (offset < total) {
|
||||
let page: Awaited<ReturnType<ApiClient["listPhotos"]>>;
|
||||
try {
|
||||
page = await api.listPhotos(orgId, { event: event.id, limit: 200, offset });
|
||||
} catch {
|
||||
break;
|
||||
}
|
||||
total = page.total;
|
||||
offset += page.photos.length;
|
||||
if (!page.photos.length) break;
|
||||
for (const photo of page.photos) {
|
||||
remember(photo.id, photo.sha256);
|
||||
const sent = photo.delivery === "DONE";
|
||||
const marks = marksOf(photo.flag, photo.rating, photo.colorLabel, sent);
|
||||
// Picks, develop and the resolved IPTC (event template + overrides) go into the file Lightroom imports.
|
||||
writeKnown(photo.sha256, marks ?? {}, photo.developSeq, photo.id, api, true);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/** Mounted with ingest, so the file is updated in every module, not only while a photo is open in Revelar. */
|
||||
export function FileMarksSync({ api, orgId }: { api: ApiClient; orgId: string }) {
|
||||
useLibraryLive(api, (message) => onFileMarkMessage(api, message));
|
||||
useEffect(() => {
|
||||
if (!orgId) return;
|
||||
void catchUpFileMarks(api, orgId);
|
||||
}, [api, orgId]);
|
||||
return null;
|
||||
}
|
||||
@@ -26,4 +26,45 @@ describe("Lightroom sidecar", () => {
|
||||
expect(lightroomXmp("{}")).toBeNull();
|
||||
expect(lightroomXmp(JSON.stringify({ crop: { geometry: { angle: 0, rect: { x0: 0, y0: 0, x1: 1, y1: 1 } } } }))).toBeNull();
|
||||
});
|
||||
|
||||
it("writes the lowercase pick Lightroom reads, including on a file that was sent", () => {
|
||||
const pick = lightroomXmp("{}", { flag: "PICK" });
|
||||
expect(pick).toContain('xmpDM:pick="1"');
|
||||
expect(pick).toContain('xmpDM:good="True"');
|
||||
expect(pick).toContain('xmp:Label="Green"');
|
||||
// crs stub keeps older desktop shells that require camera-raw-settings happy.
|
||||
expect(pick).toContain("crs:HasSettings");
|
||||
const sent = lightroomXmp("{}", { flag: "NONE", sent: true });
|
||||
expect(sent).toContain('xmpDM:pick="1"');
|
||||
expect(lightroomXmp("{}", { flag: "REJECT" })).toContain('xmpDM:pick="-1"');
|
||||
expect(lightroomXmp("{}", { flag: "NONE" })).toContain('xmpDM:pick="0"');
|
||||
});
|
||||
|
||||
it("keeps the crop and the pick in the same packet", () => {
|
||||
const xml = lightroomXmp(JSON.stringify({ crop: { geometry: { angle: -0.99, rect: { x0: 0.01, y0: 0.02, x1: 0.98, y1: 0.97 } } } }), { flag: "PICK" });
|
||||
expect(xml).toContain('crs:CropAngle="-0.99"');
|
||||
expect(xml).toContain('xmpDM:pick="1"');
|
||||
});
|
||||
|
||||
it("writes the resolved IPTC Lightroom reads from the work-folder original", () => {
|
||||
const xml = lightroomXmp(
|
||||
"{}",
|
||||
{ flag: "PICK" },
|
||||
{
|
||||
title: "Pavlidis",
|
||||
caption: "Águas Santas Milaneza x SL Benfica, em Maia",
|
||||
headline: "Águas Santas Milaneza x SL Benfica",
|
||||
city: "Maia",
|
||||
location: "Pavilhão",
|
||||
keywords: ["ANDEBOL", "AND"],
|
||||
creator: "Fotógrafo / PhotoReport.pt",
|
||||
},
|
||||
);
|
||||
expect(xml).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>");
|
||||
expect(xml).toContain("<rdf:li>Fotógrafo / PhotoReport.pt</rdf:li>");
|
||||
expect(xml).toContain('xmpDM:pick="1"');
|
||||
});
|
||||
});
|
||||
@@ -1,3 +1,4 @@
|
||||
import type { DevelopState, EditCommand } from "@photoreport/contracts";
|
||||
import { desktopInvoke, isDesktop } from "../platform.js";
|
||||
|
||||
/** Soft crop written as crs:Crop* (same numbers SoftCropGuide / Photo Mechanic draw). */
|
||||
@@ -65,8 +66,140 @@ export function softCropFromSettings(settings: string): SoftCrop | null {
|
||||
return cropOf(doc);
|
||||
}
|
||||
|
||||
/** Cull marks written into the same packet as the crop. `flag: null` means "not known yet" and is left untouched. */
|
||||
export interface FileMarks {
|
||||
flag?: string | null;
|
||||
rating?: number | null;
|
||||
colorLabel?: string | null;
|
||||
/** Delivered. Lightroom's flag stays on so the sent frames are visible after import. */
|
||||
sent?: boolean;
|
||||
}
|
||||
|
||||
const LR_LABEL: Record<string, string> = {
|
||||
RED: "Red",
|
||||
YELLOW: "Yellow",
|
||||
GREEN: "Green",
|
||||
BLUE: "Blue",
|
||||
PURPLE: "Purple",
|
||||
};
|
||||
|
||||
function xmlAttr(value: string): string {
|
||||
return value.replace(/&/g, "&").replace(/"/g, """).replace(/</g, "<");
|
||||
}
|
||||
|
||||
function xmlText(value: string): string {
|
||||
return value.replace(/&/g, "&").replace(/</g, "<").replace(/>/g, ">");
|
||||
}
|
||||
|
||||
/** Resolved IPTC Lightroom / Photo Mechanic read from the work-folder original. */
|
||||
export type FileIptc = {
|
||||
title?: string;
|
||||
caption?: string;
|
||||
headline?: string;
|
||||
event?: string;
|
||||
location?: string;
|
||||
city?: string;
|
||||
copyright?: string;
|
||||
credit?: string;
|
||||
source?: string;
|
||||
creator?: string;
|
||||
keywords?: string[];
|
||||
};
|
||||
|
||||
/**
|
||||
* Lightroom Classic reads the lowercase attribute `xmpDM:pick` (1 flagged, 0 unflagged, −1 rejected).
|
||||
* A capital `Pick` on a second description is ignored when the camera packet already says `pick="0"`.
|
||||
*/
|
||||
function markAttrs(marks: FileMarks | undefined): string[] {
|
||||
if (!marks) return [];
|
||||
const flag = marks.flag;
|
||||
const sent = marks.sent === true;
|
||||
const rejected = flag === "REJECT";
|
||||
const picked = flag === "PICK" || (sent && !rejected);
|
||||
const rating = Math.max(0, Math.min(5, Math.round(Number(marks.rating) || 0)));
|
||||
const color = marks.colorLabel && marks.colorLabel !== "NONE" ? LR_LABEL[marks.colorLabel] : undefined;
|
||||
const attrs: string[] = [];
|
||||
if (rejected) attrs.push(`xmpDM:pick="-1"`, `xmpDM:good="False"`);
|
||||
else if (picked) attrs.push(`xmpDM:pick="1"`, `xmpDM:good="True"`);
|
||||
else if (flag === "NONE" && !sent) attrs.push(`xmpDM:pick="0"`, `xmpDM:good="False"`);
|
||||
if (rating > 0) attrs.push(`xmp:Rating="${rating}"`);
|
||||
if (color) attrs.push(`xmp:Label="${xmlAttr(color)}"`);
|
||||
else if (picked) attrs.push(`xmp:Label="Green"`);
|
||||
return attrs;
|
||||
}
|
||||
|
||||
function iptcParts(iptc: FileIptc | undefined): { attrs: string[]; children: string; ns: string[] } {
|
||||
if (!iptc) return { attrs: [], children: "", ns: [] };
|
||||
const attrs: string[] = [];
|
||||
const ns: string[] = [];
|
||||
const need = (prefix: string, xmlns: string) => {
|
||||
if (!ns.some((n) => n.startsWith(`xmlns:${prefix}=`))) ns.push(`xmlns:${prefix}="${xmlns}"`);
|
||||
};
|
||||
const text = (key: keyof FileIptc) => {
|
||||
const v = iptc[key];
|
||||
return typeof v === "string" && v.trim() ? v.trim() : "";
|
||||
};
|
||||
const title = text("title");
|
||||
const headline = text("headline");
|
||||
const event = text("event");
|
||||
const location = text("location");
|
||||
const city = text("city");
|
||||
const copyright = text("copyright");
|
||||
const credit = text("credit");
|
||||
const source = text("source");
|
||||
const caption = text("caption");
|
||||
const creator = text("creator");
|
||||
const keywords = Array.isArray(iptc.keywords) ? iptc.keywords.map((k) => k.trim()).filter(Boolean) : [];
|
||||
if (title) {
|
||||
need("dc", "http://purl.org/dc/elements/1.1/");
|
||||
attrs.push(`dc:title="${xmlAttr(title)}"`);
|
||||
}
|
||||
if (headline) {
|
||||
need("photoshop", "http://ns.adobe.com/photoshop/1.0/");
|
||||
attrs.push(`photoshop:Headline="${xmlAttr(headline)}"`);
|
||||
}
|
||||
if (event) {
|
||||
need("iptcExt", "http://iptc.org/std/Iptc4xmpExt/2008-02-29/");
|
||||
attrs.push(`iptcExt:Event="${xmlAttr(event)}"`);
|
||||
}
|
||||
if (location) {
|
||||
need("iptcCore", "http://iptc.org/std/Iptc4xmpCore/1.0/xmlns/");
|
||||
attrs.push(`iptcCore:Location="${xmlAttr(location)}"`);
|
||||
}
|
||||
if (city) {
|
||||
need("photoshop", "http://ns.adobe.com/photoshop/1.0/");
|
||||
attrs.push(`photoshop:City="${xmlAttr(city)}"`);
|
||||
}
|
||||
if (copyright) {
|
||||
need("dc", "http://purl.org/dc/elements/1.1/");
|
||||
attrs.push(`dc:rights="${xmlAttr(copyright)}"`);
|
||||
}
|
||||
if (credit) {
|
||||
need("photoshop", "http://ns.adobe.com/photoshop/1.0/");
|
||||
attrs.push(`photoshop:Credit="${xmlAttr(credit)}"`);
|
||||
}
|
||||
if (source) {
|
||||
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>`;
|
||||
}
|
||||
if (creator) {
|
||||
need("dc", "http://purl.org/dc/elements/1.1/");
|
||||
children += `<dc:creator><rdf:Seq><rdf:li>${xmlText(creator)}</rdf:li></rdf:Seq></dc:creator>`;
|
||||
}
|
||||
if (keywords.length) {
|
||||
need("dc", "http://purl.org/dc/elements/1.1/");
|
||||
children += `<dc:subject><rdf:Bag>${keywords.map((k) => `<rdf:li>${xmlText(k)}</rdf:li>`).join("")}</rdf:Bag></dc:subject>`;
|
||||
}
|
||||
return { attrs, children, ns };
|
||||
}
|
||||
|
||||
/** Only the sliders that are actually set. Missing ones stay out of the sidecar, so Lightroom is not given a preset. */
|
||||
export function lightroomXmp(settings: string): string | null {
|
||||
export function lightroomXmp(settings: string, marks?: FileMarks, iptc?: FileIptc): string | null {
|
||||
let doc: Record<string, unknown>;
|
||||
try {
|
||||
const parsed = JSON.parse(settings) as unknown;
|
||||
@@ -119,8 +252,49 @@ export function lightroomXmp(settings: string): string | null {
|
||||
`crs:AlreadyApplied="False"`,
|
||||
);
|
||||
}
|
||||
if (attrs.length <= 3 && !crop) return null;
|
||||
return `<?xml version="1.0" encoding="UTF-8"?>\n<x:xmpmeta xmlns:x="adobe:ns:meta/">\n <rdf:RDF xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#">\n <rdf:Description rdf:about="" xmlns:crs="http://ns.adobe.com/camera-raw-settings/1.0/" ${attrs.join(" ")}/>\n </rdf:RDF>\n</x:xmpmeta>\n`;
|
||||
const marksWritten = markAttrs(marks);
|
||||
const iptcWritten = iptcParts(iptc);
|
||||
const hasDevelop = attrs.length > 3 || !!crop;
|
||||
if (!hasDevelop && marksWritten.length === 0 && iptcWritten.attrs.length === 0 && !iptcWritten.children) return null;
|
||||
const ns = [`xmlns:crs="http://ns.adobe.com/camera-raw-settings/1.0/"`];
|
||||
const body: string[] = [];
|
||||
// Older desktop shells refuse a pick-only packet without camera-raw-settings; keep a crs stub.
|
||||
if (hasDevelop) body.push(...attrs);
|
||||
else body.push(`crs:Version="15.4"`, `crs:ProcessVersion="11.0"`, `crs:HasSettings="True"`);
|
||||
if (marksWritten.length) {
|
||||
ns.push(`xmlns:xmp="http://ns.adobe.com/xap/1.0/"`, `xmlns:xmpDM="http://ns.adobe.com/xmp/1.0/DynamicMedia/"`);
|
||||
body.push(...marksWritten);
|
||||
}
|
||||
if (iptcWritten.attrs.length || iptcWritten.children) {
|
||||
ns.push(...iptcWritten.ns);
|
||||
body.push(...iptcWritten.attrs);
|
||||
}
|
||||
const open = `<rdf:Description rdf:about="" ${ns.join(" ")} ${body.join(" ")}`;
|
||||
const desc = iptcWritten.children ? `${open}>${iptcWritten.children}</rdf:Description>` : `${open}/>`;
|
||||
return `<?xml version="1.0" encoding="UTF-8"?>\n<x:xmpmeta xmlns:x="adobe:ns:meta/">\n <rdf:RDF xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#">\n ${desc}\n </rdf:RDF>\n</x:xmpmeta>\n`;
|
||||
}
|
||||
|
||||
function foldEdit(doc: Record<string, unknown>, command: EditCommand): void {
|
||||
if (command.command === "develop.set") Object.assign(doc, command.params.values);
|
||||
else if (command.command === "crop.set") doc.crop = { geometry: { rect: command.params.rect, angle: command.params.angle ?? 0 } };
|
||||
else if (command.command === "develop.merge") Object.assign(doc, command.params.partial);
|
||||
else if (command.command === "develop.reset") {
|
||||
for (const key of Object.keys(doc)) delete doc[key];
|
||||
}
|
||||
}
|
||||
|
||||
/** Develop commands as the settings document the sidecar reads (flat slider keys and `crop.geometry`). */
|
||||
export function settingsFromCommands(ops: readonly EditCommand[]): string {
|
||||
const doc: Record<string, unknown> = {};
|
||||
for (const command of ops) foldEdit(doc, command);
|
||||
return JSON.stringify(doc);
|
||||
}
|
||||
|
||||
/** The server's develop snapshot plus the ops that came after it. */
|
||||
export function settingsFromDevelop(state: DevelopState): string {
|
||||
const doc: Record<string, unknown> = state.snapshot && typeof state.snapshot === "object" ? { ...(state.snapshot as Record<string, unknown>) } : {};
|
||||
for (const op of state.ops) foldEdit(doc, op.command);
|
||||
return JSON.stringify(doc);
|
||||
}
|
||||
|
||||
function cropOf(doc: Record<string, unknown>): SoftCrop | null {
|
||||
@@ -140,16 +314,129 @@ function cropOf(doc: Record<string, unknown>): SoftCrop | null {
|
||||
return soft;
|
||||
}
|
||||
|
||||
/**
|
||||
* JPEG: the edit is written inside the file. RAW: a `.xmp` beside it (Lightroom does not embed into a raw).
|
||||
* Missing file or an older desktop app: nothing is written.
|
||||
*/
|
||||
export async function writeLightroomSidecar(sha256: string, settings: string): Promise<void> {
|
||||
if (!isDesktop() || !sha256) return;
|
||||
const xml = lightroomXmp(settings);
|
||||
const FILE_MARKS_KEY = "pr.filemarks";
|
||||
|
||||
interface RememberedFile {
|
||||
settings: string;
|
||||
/** null: this session has not been told the flag, so a crop write must not clear it. */
|
||||
flag: string | null;
|
||||
rating: number;
|
||||
colorLabel: string;
|
||||
sent: boolean;
|
||||
iptc: FileIptc;
|
||||
}
|
||||
|
||||
function loadRemembered(): Record<string, RememberedFile> {
|
||||
try {
|
||||
const raw = localStorage.getItem(FILE_MARKS_KEY);
|
||||
const parsed = raw ? (JSON.parse(raw) as unknown) : {};
|
||||
if (!parsed || typeof parsed !== "object") return {};
|
||||
return parsed as Record<string, RememberedFile>;
|
||||
} catch {
|
||||
return {};
|
||||
}
|
||||
}
|
||||
|
||||
function saveRemembered(all: Record<string, RememberedFile>): void {
|
||||
const keys = Object.keys(all);
|
||||
if (keys.length > 4000) {
|
||||
for (const key of keys.slice(0, keys.length - 4000)) delete all[key];
|
||||
}
|
||||
try {
|
||||
localStorage.setItem(FILE_MARKS_KEY, JSON.stringify(all));
|
||||
} catch {
|
||||
// A full localStorage must not stop the edit itself.
|
||||
}
|
||||
}
|
||||
|
||||
const flushTimers = new Map<string, number>();
|
||||
let flushChain = Promise.resolve();
|
||||
|
||||
function scheduleFlush(sha256: string): void {
|
||||
const pending = flushTimers.get(sha256);
|
||||
if (pending) window.clearTimeout(pending);
|
||||
flushTimers.set(
|
||||
sha256,
|
||||
window.setTimeout(() => {
|
||||
flushTimers.delete(sha256);
|
||||
flushChain = flushChain.then(() => flushPhotoFile(sha256)).catch(() => {});
|
||||
}, 400),
|
||||
);
|
||||
}
|
||||
|
||||
async function flushPhotoFile(sha256: string): Promise<void> {
|
||||
const row = loadRemembered()[sha256];
|
||||
if (!row) return;
|
||||
const xml = lightroomXmp(row.settings, { flag: row.flag, rating: row.rating, colorLabel: row.colorLabel, sent: row.sent }, iptcOf(row.iptc));
|
||||
if (!xml) return;
|
||||
const crop = softCropFromSettings(settings);
|
||||
const { noteOwnSoftCropWrite } = await import("./softCropWatch.js");
|
||||
noteOwnSoftCropWrite(sha256, crop);
|
||||
const writtenFlag = row.sent || row.flag === "PICK" ? "PICK" : row.flag === "REJECT" ? "REJECT" : row.flag === "NONE" ? "NONE" : undefined;
|
||||
noteOwnSoftCropWrite(sha256, softCropFromSettings(row.settings), writtenFlag);
|
||||
await desktopInvoke("ftp_write_xmp", { sha256, xml }).catch(() => {});
|
||||
}
|
||||
|
||||
export interface FileMarkUpdate {
|
||||
settings?: string;
|
||||
flag?: string | null;
|
||||
rating?: number | null;
|
||||
colorLabel?: string | null;
|
||||
sent?: boolean;
|
||||
iptc?: FileIptc;
|
||||
}
|
||||
|
||||
function iptcOf(raw: unknown): FileIptc {
|
||||
if (!raw || typeof raw !== "object") return {};
|
||||
const src = raw as Record<string, unknown>;
|
||||
const out: FileIptc = {};
|
||||
for (const key of ["title", "caption", "headline", "event", "location", "city", "copyright", "credit", "source", "creator"] as const) {
|
||||
const v = src[key];
|
||||
if (typeof v === "string" && v.trim()) out[key] = v.trim();
|
||||
}
|
||||
if (Array.isArray(src.keywords)) {
|
||||
const keywords = src.keywords.filter((k): k is string => typeof k === "string" && !!k.trim()).map((k) => k.trim());
|
||||
if (keywords.length) out.keywords = keywords;
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
/**
|
||||
* Remembers the latest crop, cull marks and IPTC for this original and writes them into the file.
|
||||
* A pick, a reject, a delivery, a caption and a develop edit all come through here, including while Revelar is closed.
|
||||
* JPEG: embedded. RAW: a `.xmp` beside it. Missing file or an older desktop app: nothing is written.
|
||||
*/
|
||||
export function writePhotoFile(sha256: string, update: FileMarkUpdate): void {
|
||||
if (!isDesktop() || !sha256) return;
|
||||
const all = loadRemembered();
|
||||
const prev: RememberedFile = all[sha256] ?? { settings: "{}", flag: null, rating: 0, colorLabel: "NONE", sent: false, iptc: {} };
|
||||
const next: RememberedFile = {
|
||||
settings: update.settings ?? prev.settings,
|
||||
flag: "flag" in update ? (update.flag ?? "NONE") : prev.flag,
|
||||
rating: "rating" in update ? Math.max(0, Math.min(5, Math.round(Number(update.rating) || 0))) : prev.rating,
|
||||
colorLabel: "colorLabel" in update ? (update.colorLabel ?? "NONE") : prev.colorLabel,
|
||||
sent: "sent" in update ? update.sent === true : prev.sent,
|
||||
iptc: "iptc" in update ? iptcOf(update.iptc) : prev.iptc,
|
||||
};
|
||||
all[sha256] = next;
|
||||
saveRemembered(all);
|
||||
scheduleFlush(sha256);
|
||||
}
|
||||
|
||||
/** Develop saved the crop. Marks already known for this file go out in the same packet. */
|
||||
export function writeLightroomSidecar(sha256: string, settings: string): void {
|
||||
writePhotoFile(sha256, { settings });
|
||||
}
|
||||
|
||||
/** Fresh edit commands folded onto what this file was already going to receive. */
|
||||
export function writePhotoCommands(sha256: string, ops: readonly EditCommand[]): void {
|
||||
if (!ops.length) return;
|
||||
const prev = loadRemembered()[sha256]?.settings ?? "{}";
|
||||
let doc: Record<string, unknown> = {};
|
||||
try {
|
||||
const parsed = JSON.parse(prev) as unknown;
|
||||
if (parsed && typeof parsed === "object") doc = parsed as Record<string, unknown>;
|
||||
} catch {
|
||||
doc = {};
|
||||
}
|
||||
for (const command of ops) foldEdit(doc, command);
|
||||
writePhotoFile(sha256, { settings: JSON.stringify(doc) });
|
||||
}
|
||||
@@ -24,6 +24,8 @@ export interface WatchedSoftCrop {
|
||||
ownWriteUntil: number;
|
||||
/** Colour last copied from this file, so a repaint in Photo Mechanic is applied once. "" means the file named none. */
|
||||
color?: string | undefined;
|
||||
/** Pick last written or read. A later change in Lightroom is applied once. */
|
||||
flag?: string | undefined;
|
||||
}
|
||||
|
||||
/** Return true when the crop was applied into an open develop session (skip a second queue write). */
|
||||
@@ -62,8 +64,8 @@ export function watchSoftCropPhoto(orgId: string, photoId: string, sha256: strin
|
||||
save(rows);
|
||||
}
|
||||
|
||||
/** Call after this app writes crs:Crop* into the file, so the watcher does not re-apply our own write. */
|
||||
export function noteOwnSoftCropWrite(sha256: string, crop: SoftCrop | null = null): void {
|
||||
/** Call after this app writes into the file, so the watcher does not re-apply our own crop or pick. */
|
||||
export function noteOwnSoftCropWrite(sha256: string, crop: SoftCrop | null = null, flag?: string | null): void {
|
||||
if (!sha256) return;
|
||||
const rows = load();
|
||||
const i = rows.findIndex((r) => r.sha256 === sha256);
|
||||
@@ -73,6 +75,7 @@ export function noteOwnSoftCropWrite(sha256: string, crop: SoftCrop | null = nul
|
||||
...row,
|
||||
ownWriteUntil: Date.now() + OWN_WRITE_GRACE_MS,
|
||||
fingerprint: crop ? softCropFingerprint(crop) : row.fingerprint,
|
||||
...(flag ? { flag } : {}),
|
||||
};
|
||||
save(rows);
|
||||
}
|
||||
|
||||
@@ -1,7 +1,9 @@
|
||||
import type { DeliveryItemSummary, PhotoSummary } from "@photoreport/contracts";
|
||||
import type { ApiClient, DeliveryTarget } from "@photoreport/sdk";
|
||||
import { useCallback, useEffect, useRef, useState } from "react";
|
||||
import { writePhotoFile, type FileIptc } from "../desktop/lightroomSidecar.js";
|
||||
import { t } from "../i18n.js";
|
||||
import { isDesktop } from "../platform.js";
|
||||
import { deliver, setIptc } from "../offline/sync.js";
|
||||
|
||||
/** The fields of Photo Mechanic's Metadata Info window, in its order. Lists are comma separated. */
|
||||
@@ -131,6 +133,28 @@ export function IptcInfo(props: {
|
||||
if (Object.keys(set).length) {
|
||||
const r = await setIptc(api, orgId, photoIds, set);
|
||||
notes.push(r === "queued" ? t.offline.queuedDelivery : t.info.saved);
|
||||
// Work-folder originals are what Lightroom imports: write the resolved IPTC into them now.
|
||||
if (isDesktop()) {
|
||||
for (const photo of editing) {
|
||||
if (!photo.sha256) continue;
|
||||
try {
|
||||
const got = await api.photoIptc(photo.id);
|
||||
const values = got.values ?? {};
|
||||
const iptc: FileIptc = {};
|
||||
for (const key of ["title", "caption", "headline", "event", "location", "city", "copyright", "credit", "source", "creator"] as const) {
|
||||
const v = values[key];
|
||||
if (typeof v === "string" && v.trim()) iptc[key] = v.trim();
|
||||
}
|
||||
if (Array.isArray(values.keywords)) {
|
||||
const keywords = values.keywords.filter((k): k is string => typeof k === "string" && !!k.trim()).map((k) => k.trim());
|
||||
if (keywords.length) iptc.keywords = keywords;
|
||||
}
|
||||
if (Object.keys(iptc).length) writePhotoFile(photo.sha256, { iptc });
|
||||
} catch {
|
||||
// A missing original must not block saving the caption on the server.
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
if (opts.send && targetId) {
|
||||
const r = await deliver(api, orgId, targetId, photoIds);
|
||||
|
||||
@@ -6,6 +6,7 @@ import { useLocalFtp } from "./LocalFtp.js";
|
||||
import { OriginalSender } from "./originals.js";
|
||||
import { useLibraryLive } from "./realtime.js";
|
||||
import { useUploadQueue } from "./uploads.js";
|
||||
import { FileMarksSync } from "../desktop/fileMarks.js";
|
||||
import { useOfflineSync } from "../offline/sync.js";
|
||||
import { useUsbCamera } from "./UsbCamera.js";
|
||||
|
||||
@@ -42,6 +43,7 @@ function IngestState({ api, orgId, children }: { api: ReturnType<typeof useAuth>
|
||||
useOfflineSync(api, orgId);
|
||||
return (
|
||||
<IngestContext.Provider value={{ uploads, localFtp, usb, desktop, originals }}>
|
||||
{desktop && !!orgId && <FileMarksSync api={api} orgId={orgId} />}
|
||||
{desktop && !!orgId && originals && <OriginalResponder api={api} orgId={orgId} sender={originals} />}
|
||||
{desktop && !!orgId && <FailedRepair api={api} orgId={orgId} add={uploads.add} />}
|
||||
{children}
|
||||
|
||||
@@ -3,6 +3,7 @@ import type { ApiClient, AutopilotStyle, EventSummary } from "@photoreport/sdk";
|
||||
import { frameScore, isReportage } from "../../../api/src/composition/compose.js";
|
||||
import { levelAngle, measuredValues, planFrame } from "../../../api/src/composition/planFrame.js";
|
||||
import { bestOf, groupBursts } from "../../../api/src/autopilot/bursts.js";
|
||||
import { settingsFromCommands, writePhotoFile } from "../desktop/lightroomSidecar.js";
|
||||
import { loadEngine } from "../develop/engine.js";
|
||||
import { isDesktop } from "../platform.js";
|
||||
import { detectPreview } from "./detectLocal.js";
|
||||
@@ -144,6 +145,8 @@ function applyPick(orgId: string, sha256: string, ops: EditCommand[]): void {
|
||||
for (const command of ops) queue.enqueueEdit(photoId, command);
|
||||
queue.add({ kind: "patch", ids: [photoId], patch: { flag: "PICK" } });
|
||||
localPhotos.patch(photoId, { flag: "PICK" });
|
||||
// The original on disk is what Lightroom imports. The pick and the crop are written there, not only queued.
|
||||
writePhotoFile(sha256, { settings: settingsFromCommands(ops), flag: "PICK" });
|
||||
}
|
||||
|
||||
async function loadPending(orgId: string, eventId: string): Promise<PendingFrame[]> {
|
||||
|
||||
@@ -38,6 +38,7 @@ import { cache, warmImages, type CachedEvents } from "../offline/cache.js";
|
||||
import { localPhotos } from "../offline/local.js";
|
||||
import { isNetworkError, offlineQueue } from "../offline/queue.js";
|
||||
import { ensureRoster } from "../offline/roster.js";
|
||||
import { writePhotoFile } from "../desktop/lightroomSidecar.js";
|
||||
import { patchPhotos, useQueueSize } from "../offline/sync.js";
|
||||
import { FilterBar } from "../library/FilterBar.js";
|
||||
import { LibraryMenus } from "../library/LibraryMenus.js";
|
||||
@@ -379,6 +380,17 @@ export function LibraryPage() {
|
||||
async (ids: string[], change: PhotoPatch) => {
|
||||
if (!ids.length || !canCull) return;
|
||||
dispatch({ type: "patch", ids, patch: change });
|
||||
if (isDesktop() && (change.flag !== undefined || change.rating !== undefined || change.colorLabel !== undefined)) {
|
||||
for (const id of ids) {
|
||||
const sha = byId.get(id)?.sha256;
|
||||
if (!sha) continue;
|
||||
writePhotoFile(sha, {
|
||||
...(change.flag !== undefined ? { flag: change.flag } : {}),
|
||||
...(change.rating !== undefined ? { rating: change.rating } : {}),
|
||||
...(change.colorLabel !== undefined ? { colorLabel: change.colorLabel } : {}),
|
||||
});
|
||||
}
|
||||
}
|
||||
try {
|
||||
// Without a network the change is kept here and sent when the connection is back.
|
||||
await patchPhotos(api, orgId, ids, change);
|
||||
@@ -387,7 +399,7 @@ export function LibraryPage() {
|
||||
if (state.scope) void open(state.scope);
|
||||
}
|
||||
},
|
||||
[api, orgId, canCull, open, state.scope],
|
||||
[api, orgId, canCull, open, state.scope, byId],
|
||||
);
|
||||
|
||||
useEffect(() => {
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@photoreport/desktop",
|
||||
"version": "0.3.32",
|
||||
"version": "0.3.33",
|
||||
"private": true,
|
||||
"type": "module",
|
||||
"scripts": {
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
[package]
|
||||
name = "photoreport-desktop"
|
||||
version = "0.3.32"
|
||||
version = "0.3.33"
|
||||
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."
|
||||
|
||||
@@ -775,7 +775,17 @@ impl FtpState {
|
||||
|
||||
/// JPEG: the edit is embedded in the file (Lightroom does not use a sidecar for JPEG). RAW: a `.xmp` beside it.
|
||||
pub fn write_xmp(&self, photo_path: &str, xml: &str) -> Result<String, String> {
|
||||
if xml.len() > 60_000 || !xml.contains("camera-raw-settings") {
|
||||
// Picks, stars, colour and IPTC belong in the file even without develop sliders.
|
||||
if xml.len() > 60_000
|
||||
|| !(xml.contains("camera-raw-settings")
|
||||
|| xml.contains("xmpDM:pick")
|
||||
|| xml.contains("xmpDM:Pick")
|
||||
|| xml.contains("xmp:Rating")
|
||||
|| xml.contains("xmp:Label")
|
||||
|| xml.contains("dc:title")
|
||||
|| xml.contains("dc:description")
|
||||
|| xml.contains("photoshop:Headline"))
|
||||
{
|
||||
return Err("not_develop_xmp".into());
|
||||
}
|
||||
let photo = PathBuf::from(photo_path);
|
||||
@@ -835,15 +845,7 @@ fn strip_our_description(xml: &str) -> String {
|
||||
let Some(start) = out[..mark].rfind("<rdf:Description") else {
|
||||
break;
|
||||
};
|
||||
let after = &out[mark..];
|
||||
let end_rel = if let Some(i) = after.find("/>") {
|
||||
i + 2
|
||||
} else if let Some(i) = after.find("</rdf:Description>") {
|
||||
i + "</rdf:Description>".len()
|
||||
} else {
|
||||
break;
|
||||
};
|
||||
let mut end = mark + end_rel;
|
||||
let mut end = start + description_len(&out[start..]);
|
||||
if out.as_bytes().get(end) == Some(&b'\n') {
|
||||
end += 1;
|
||||
}
|
||||
@@ -852,31 +854,282 @@ fn strip_our_description(xml: &str) -> String {
|
||||
out
|
||||
}
|
||||
|
||||
/// Length of one `rdf:Description` (self-closing or with children), from its start tag.
|
||||
fn description_len(from_desc: &str) -> usize {
|
||||
let Some(gt) = from_desc.find('>') else {
|
||||
return from_desc.len();
|
||||
};
|
||||
// `<rdf:Description .../>`
|
||||
if gt > 0 && from_desc.as_bytes()[gt - 1] == b'/' {
|
||||
return gt + 1;
|
||||
}
|
||||
// `<rdf:Description ...>...</rdf:Description>`
|
||||
if let Some(close) = from_desc.find("</rdf:Description>") {
|
||||
return close + "</rdf:Description>".len();
|
||||
}
|
||||
gt + 1
|
||||
}
|
||||
|
||||
fn description_of(xml: &str) -> String {
|
||||
let Some(start) = xml.find("<rdf:Description") else {
|
||||
return xml.to_string();
|
||||
};
|
||||
let rest = &xml[start..];
|
||||
let end = rest
|
||||
.find("/>")
|
||||
.map(|i| i + 2)
|
||||
.or_else(|| rest.find("</rdf:Description>").map(|i| i + "</rdf:Description>".len()))
|
||||
.unwrap_or(rest.len());
|
||||
rest[..end].to_string()
|
||||
rest[..description_len(rest)].to_string()
|
||||
}
|
||||
|
||||
fn wrap_xmp_packet(desc: &str) -> String {
|
||||
format!(
|
||||
"<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<x:xmpmeta xmlns:x=\"adobe:ns:meta/\">\n <rdf:RDF xmlns:rdf=\"http://www.w3.org/1999/02/22-rdf-syntax-ns#\">\n {desc}\n </rdf:RDF>\n</x:xmpmeta>\n"
|
||||
)
|
||||
}
|
||||
|
||||
fn merge_xmp_packet(existing: &str, incoming: &str) -> String {
|
||||
let desc = description_of(&mark_our_description(incoming));
|
||||
let base = strip_our_description(existing);
|
||||
let incoming_desc = description_of(&mark_our_description(incoming));
|
||||
// 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);
|
||||
// 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" };
|
||||
base = stamp_pick(&base, &pick, good);
|
||||
}
|
||||
// Stars, colour and the newsroom IPTC fields Lightroom reads from the first description.
|
||||
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/"),
|
||||
(
|
||||
"iptcCore:Location",
|
||||
"xmlns:iptcCore",
|
||||
"http://iptc.org/std/Iptc4xmpCore/1.0/xmlns/",
|
||||
),
|
||||
("dc:rights", "xmlns:dc", "http://purl.org/dc/elements/1.1/"),
|
||||
] {
|
||||
if let Some(value) = attr_of(&combined, key) {
|
||||
base = stamp_attr(&base, key, &value, xmlns_key, xmlns);
|
||||
}
|
||||
}
|
||||
if let Some(idx) = base.rfind("</rdf:RDF>") {
|
||||
let mut out = String::new();
|
||||
out.push_str(&base[..idx]);
|
||||
out.push_str(&desc);
|
||||
out.push_str(&combined);
|
||||
out.push('\n');
|
||||
out.push_str(&base[idx..]);
|
||||
return out;
|
||||
}
|
||||
mark_our_description(incoming)
|
||||
// No camera XMP yet: wrap our description so Lightroom sees a real packet, not a bare tag.
|
||||
wrap_xmp_packet(&combined)
|
||||
}
|
||||
|
||||
fn our_description(xml: &str) -> Option<String> {
|
||||
let mark = xml.find("photoreport:embed=\"1\"")?;
|
||||
let start = xml[..mark].rfind("<rdf:Description")?;
|
||||
let len = description_len(&xml[start..]);
|
||||
Some(xml[start..start + len].to_string())
|
||||
}
|
||||
|
||||
/// Inner XML of a Description (empty when self-closing).
|
||||
fn description_children(desc: &str) -> String {
|
||||
let Some(gt) = desc.find('>') else {
|
||||
return String::new();
|
||||
};
|
||||
if gt > 0 && desc.as_bytes()[gt - 1] == b'/' {
|
||||
return String::new();
|
||||
}
|
||||
let Some(close) = desc.rfind("</rdf:Description>") else {
|
||||
return String::new();
|
||||
};
|
||||
desc[gt + 1..close].to_string()
|
||||
}
|
||||
|
||||
fn parse_attrs(tag: &str) -> Vec<(String, String)> {
|
||||
let mut attrs = Vec::new();
|
||||
let mut rest = tag;
|
||||
if let Some(i) = rest.find(char::is_whitespace) {
|
||||
rest = &rest[i..];
|
||||
}
|
||||
loop {
|
||||
rest = rest.trim_start();
|
||||
if rest.is_empty() || rest.starts_with("/>") || rest.starts_with('>') {
|
||||
break;
|
||||
}
|
||||
let Some(eq) = rest.find('=') else { break };
|
||||
let key = rest[..eq].trim();
|
||||
if key.is_empty() || key.contains('<') {
|
||||
break;
|
||||
}
|
||||
rest = rest[eq + 1..].trim_start();
|
||||
if !rest.starts_with('"') {
|
||||
break;
|
||||
}
|
||||
rest = &rest[1..];
|
||||
let Some(end) = rest.find('"') else { break };
|
||||
attrs.push((key.to_string(), rest[..end].to_string()));
|
||||
rest = &rest[end + 1..];
|
||||
}
|
||||
attrs
|
||||
}
|
||||
|
||||
fn attr_of(tag: &str, key: &str) -> Option<String> {
|
||||
parse_attrs(tag)
|
||||
.into_iter()
|
||||
.find(|(k, _)| k == key)
|
||||
.map(|(_, v)| v)
|
||||
}
|
||||
|
||||
fn escape_attr(value: &str) -> String {
|
||||
value
|
||||
.replace('&', "&")
|
||||
.replace('"', """)
|
||||
.replace('<', "<")
|
||||
}
|
||||
|
||||
fn combine_descriptions(old: Option<&str>, incoming: &str) -> String {
|
||||
let mut attrs: Vec<(String, String)> = Vec::new();
|
||||
let put = |attrs: &mut Vec<(String, String)>, key: String, value: String| {
|
||||
if key == "rdf:about" {
|
||||
return;
|
||||
}
|
||||
if let Some(found) = attrs.iter_mut().find(|(k, _)| k == &key) {
|
||||
found.1 = value;
|
||||
} else {
|
||||
attrs.push((key, value));
|
||||
}
|
||||
};
|
||||
let mut children = String::new();
|
||||
if let Some(old) = old {
|
||||
for (key, value) in parse_attrs(old) {
|
||||
put(&mut attrs, key, value);
|
||||
}
|
||||
children = description_children(old);
|
||||
}
|
||||
for (key, value) in parse_attrs(incoming) {
|
||||
put(&mut attrs, key, value);
|
||||
}
|
||||
let incoming_children = description_children(incoming);
|
||||
if !incoming_children.is_empty() {
|
||||
children = incoming_children;
|
||||
}
|
||||
put(
|
||||
&mut attrs,
|
||||
"xmlns:photoreport".into(),
|
||||
"https://photoreport.pt/ns/1.0/".into(),
|
||||
);
|
||||
put(&mut attrs, "photoreport:embed".into(), "1".into());
|
||||
let mut out = String::from("<rdf:Description rdf:about=\"\"");
|
||||
for (key, value) in attrs {
|
||||
out.push(' ');
|
||||
out.push_str(&key);
|
||||
out.push_str("=\"");
|
||||
out.push_str(&escape_attr(&value));
|
||||
out.push('"');
|
||||
}
|
||||
if children.is_empty() {
|
||||
out.push_str("/>");
|
||||
} else {
|
||||
out.push('>');
|
||||
out.push_str(&children);
|
||||
out.push_str("</rdf:Description>");
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// Writes the flag onto the camera description. Lightroom uses the first lowercase `xmpDM:pick`.
|
||||
fn stamp_pick(xml: &str, pick: &str, good: &str) -> String {
|
||||
let had = xml.contains("xmpDM:pick=")
|
||||
|| xml.contains("xmpDM:Pick=")
|
||||
|| xml.contains("<xmpDM:pick>")
|
||||
|| xml.contains("<xmpDM:Pick>");
|
||||
let mut out = xml.to_string();
|
||||
let _ = replace_attr(&mut out, &["xmpDM:pick", "xmpDM:Pick"], pick);
|
||||
let _ = replace_attr(&mut out, &["xmpDM:good", "xmpDM:Good"], good);
|
||||
replace_elem(&mut out, &["xmpDM:pick", "xmpDM:Pick"], pick);
|
||||
replace_elem(&mut out, &["xmpDM:good", "xmpDM:Good"], good);
|
||||
if !had {
|
||||
out = inject_after_about(
|
||||
&out,
|
||||
&format!(
|
||||
"xmlns:xmpDM=\"http://ns.adobe.com/xmp/1.0/DynamicMedia/\" xmpDM:pick=\"{pick}\" xmpDM:good=\"{good}\""
|
||||
),
|
||||
);
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
fn stamp_attr(xml: &str, key: &str, value: &str, xmlns_key: &str, xmlns: &str) -> String {
|
||||
let mut out = xml.to_string();
|
||||
let as_attr = replace_attr(&mut out, &[key], value);
|
||||
// Cameras often write Rating as an element (`<xmp:Rating>0</xmp:Rating>`). Update that too,
|
||||
// otherwise Lightroom keeps reading the old element and ignores a new attribute.
|
||||
let had_elem = out.contains(&format!("<{key}>")) || out.contains(&format!("<{key} "));
|
||||
replace_elem(&mut out, &[key], value);
|
||||
if as_attr > 0 || had_elem {
|
||||
return out;
|
||||
}
|
||||
let extra = if out.contains(xmlns_key) {
|
||||
format!("{key}=\"{}\"", escape_attr(value))
|
||||
} else {
|
||||
format!("{xmlns_key}=\"{xmlns}\" {key}=\"{}\"", escape_attr(value))
|
||||
};
|
||||
inject_after_about(&out, &extra)
|
||||
}
|
||||
|
||||
fn replace_attr(xml: &mut String, names: &[&str], value: &str) -> usize {
|
||||
let mut count = 0;
|
||||
for name in names {
|
||||
let needle = format!("{name}=\"");
|
||||
let mut from = 0;
|
||||
while let Some(rel) = xml[from..].find(&needle) {
|
||||
let start = from + rel + needle.len();
|
||||
let Some(end_rel) = xml[start..].find('"') else {
|
||||
break;
|
||||
};
|
||||
let end = start + end_rel;
|
||||
xml.replace_range(start..end, value);
|
||||
count += 1;
|
||||
from = start + value.len() + 1;
|
||||
}
|
||||
}
|
||||
count
|
||||
}
|
||||
|
||||
fn replace_elem(xml: &mut String, tags: &[&str], value: &str) {
|
||||
for tag in tags {
|
||||
let open = format!("<{tag}>");
|
||||
let close = format!("</{tag}>");
|
||||
let mut from = 0;
|
||||
while let Some(rel) = xml[from..].find(&open) {
|
||||
let start = from + rel + open.len();
|
||||
let Some(end_rel) = xml[start..].find(&close) else {
|
||||
break;
|
||||
};
|
||||
let end = start + end_rel;
|
||||
xml.replace_range(start..end, value);
|
||||
from = start + value.len() + close.len();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn inject_after_about(xml: &str, extra: &str) -> String {
|
||||
let Some(i) = xml.find("<rdf:Description") else {
|
||||
return xml.to_string();
|
||||
};
|
||||
let rest = &xml[i..];
|
||||
let Some(j) = rest.find("rdf:about=\"\"") else {
|
||||
return xml.to_string();
|
||||
};
|
||||
let at = i + j + "rdf:about=\"\"".len();
|
||||
let mut out = String::new();
|
||||
out.push_str(&xml[..at]);
|
||||
out.push(' ');
|
||||
out.push_str(extra);
|
||||
out.push_str(&xml[at..]);
|
||||
out
|
||||
}
|
||||
|
||||
fn xmp_app1(packet: &str) -> Result<Vec<u8>, String> {
|
||||
@@ -1591,4 +1844,57 @@ mod tests {
|
||||
fn date_folder() {
|
||||
assert_eq!(today().len(), 10);
|
||||
}
|
||||
|
||||
/// The camera writes `xmpDM:pick="0"`. Lightroom uses that and ignores a second description.
|
||||
#[test]
|
||||
fn pick_replaces_the_camera_flag_and_keeps_the_crop() {
|
||||
let camera = r#"<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:xmpDM="http://ns.adobe.com/xmp/1.0/DynamicMedia/" xmpDM:pick="0" xmpDM:good="False"><xmpDM:pick>0</xmpDM:pick></rdf:Description></rdf:RDF></x:xmpmeta>"#;
|
||||
let crop = 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:crs="http://ns.adobe.com/camera-raw-settings/1.0/" crs:CropLeft="0.010000" crs:HasCrop="True"/></rdf:RDF></x:xmpmeta>"#;
|
||||
let with_crop = merge_xmp_packet(camera, crop);
|
||||
assert!(with_crop.contains("crs:CropLeft=\"0.010000\""));
|
||||
assert!(with_crop.contains("xmpDM:pick=\"0\""));
|
||||
let pick = 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:xmpDM="http://ns.adobe.com/xmp/1.0/DynamicMedia/" xmlns:xmp="http://ns.adobe.com/xap/1.0/" xmpDM:pick="1" xmpDM:good="True" xmp:Label="Green" xmp:Rating="3"/></rdf:RDF></x:xmpmeta>"#;
|
||||
let both = merge_xmp_packet(&with_crop, pick);
|
||||
assert!(both.contains("crs:CropLeft=\"0.010000\""));
|
||||
assert!(both.contains("xmpDM:pick=\"1\""));
|
||||
assert!(!both.contains("xmpDM:pick=\"0\""));
|
||||
assert!(!both.contains("<xmpDM:pick>0</xmpDM:pick>"));
|
||||
assert!(both.contains("xmp:Label=\"Green\""));
|
||||
assert!(both.contains("xmp:Rating=\"3\""));
|
||||
assert!(both.contains("photoreport:embed=\"1\""));
|
||||
}
|
||||
|
||||
/// Canon JPEGs write `<xmp:Rating>0</xmp:Rating>` as an element. Lightroom must see the new value there.
|
||||
#[test]
|
||||
fn rating_element_from_camera_is_replaced() {
|
||||
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 pick = 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:xmp="http://ns.adobe.com/xap/1.0/" xmlns:xmpDM="http://ns.adobe.com/xmp/1.0/DynamicMedia/" xmlns:dc="http://purl.org/dc/elements/1.1/" xmpDM:pick="1" xmpDM:good="True" xmp:Rating="4" xmp:Label="Green" dc:title="Jogador"/></rdf:RDF></x:xmpmeta>"#;
|
||||
let both = merge_xmp_packet(camera, pick);
|
||||
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\""));
|
||||
assert!(both.contains("photoreport:embed=\"1\""));
|
||||
}
|
||||
|
||||
/// A JPEG with no camera XMP must still get a full packet Lightroom can parse.
|
||||
#[test]
|
||||
fn empty_camera_packet_is_wrapped() {
|
||||
let pick = 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:xmpDM="http://ns.adobe.com/xmp/1.0/DynamicMedia/" xmpDM:pick="1" xmpDM:good="True"/></rdf:RDF></x:xmpmeta>"#;
|
||||
let got = merge_xmp_packet("", pick);
|
||||
assert!(got.contains("<x:xmpmeta"));
|
||||
assert!(got.contains("</rdf:RDF>"));
|
||||
assert!(got.contains("xmpDM:pick=\"1\""));
|
||||
assert!(got.contains("photoreport:embed=\"1\""));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn iptc_children_survive_a_later_pick() {
|
||||
let with_caption = 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:photoreport="https://photoreport.pt/ns/1.0/" photoreport:embed="1" dc:title="Jogador"><dc:description><rdf:Alt><rdf:li xml:lang="x-default">Águas Santas x Benfica</rdf:li></rdf:Alt></dc:description></rdf:Description></rdf:RDF></x:xmpmeta>"#;
|
||||
let pick = 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:xmpDM="http://ns.adobe.com/xmp/1.0/DynamicMedia/" xmpDM:pick="1" xmpDM:good="True"/></rdf:RDF></x:xmpmeta>"#;
|
||||
let both = merge_xmp_packet(with_caption, pick);
|
||||
assert!(both.contains("Águas Santas x Benfica"));
|
||||
assert!(both.contains("xmpDM:pick=\"1\""));
|
||||
assert!(both.contains("dc:title=\"Jogador\""));
|
||||
}
|
||||
}
|
||||
@@ -195,8 +195,13 @@ pub async fn local_stat(
|
||||
.and_then(|t| t.duration_since(std::time::UNIX_EPOCH).ok())
|
||||
.map(|d| d.as_millis() as u64)
|
||||
.unwrap_or(0);
|
||||
// JPEG carries its XMP inside the file, so only a raw's sidecar moves the mtime.
|
||||
let sidecar = path.with_extension("xmp");
|
||||
if let Ok(side) = tokio::fs::metadata(&sidecar).await {
|
||||
let jpeg = path
|
||||
.file_name()
|
||||
.and_then(|n| n.to_str())
|
||||
.is_some_and(crate::ftp::is_jpeg_name);
|
||||
if !jpeg && let Ok(side) = tokio::fs::metadata(&sidecar).await {
|
||||
size = size.saturating_add(side.len());
|
||||
if let Some(ms) = side
|
||||
.modified()
|
||||
@@ -218,10 +223,18 @@ pub async fn local_xmp(
|
||||
sha256: String,
|
||||
) -> Result<tauri::ipc::Response, String> {
|
||||
let path = index.find_changed(&sha256).ok_or("not_found")?;
|
||||
let sidecar = path.with_extension("xmp");
|
||||
if sidecar.is_file() {
|
||||
let bytes = tokio::fs::read(&sidecar).await.map_err(|e| e.to_string())?;
|
||||
return Ok(tauri::ipc::Response::new(bytes));
|
||||
let jpeg = path
|
||||
.file_name()
|
||||
.and_then(|n| n.to_str())
|
||||
.is_some_and(crate::ftp::is_jpeg_name);
|
||||
// JPEG: the packet embedded in the file. RAW: the .xmp beside it. Lightroom does not use a JPEG sidecar.
|
||||
if !jpeg {
|
||||
let sidecar = path.with_extension("xmp");
|
||||
if sidecar.is_file() {
|
||||
let bytes = tokio::fs::read(&sidecar).await.map_err(|e| e.to_string())?;
|
||||
return Ok(tauri::ipc::Response::new(bytes));
|
||||
}
|
||||
return Ok(tauri::ipc::Response::new(Vec::<u8>::new()));
|
||||
}
|
||||
let bytes = tokio::task::spawn_blocking(move || read_jpeg_xmp_head(&path))
|
||||
.await
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
{
|
||||
"$schema": "https://schema.tauri.app/config/2",
|
||||
"productName": "PhotoReport",
|
||||
"version": "0.3.32",
|
||||
"version": "0.3.33",
|
||||
"identifier": "pt.photoreport.desktop",
|
||||
"build": {
|
||||
"devUrl": "http://localhost:5173",
|
||||
|
||||
+12
-6
@@ -472,12 +472,18 @@ 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 (✕), 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. A colour Photo Mechanic paints on a local original, or on a delivered
|
||||
file, is copied back (`photomechanic:ColorClass`: 1 red, 3 yellow, 4 green, 5 blue, 7 purple).
|
||||
**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.
|
||||
|
||||
**Cull marks on delivery.** The same pick / reject / stars / colour are written into the delivered JPEG
|
||||
(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. A colour Photo Mechanic paints on a local original, or on a delivered file, is
|
||||
copied back (`photomechanic:ColorClass`: 1 red, 3 yellow, 4 green, 5 blue, 7 purple).
|
||||
|
||||
**Colour ↔ destination.** A delivery target may own one library colour. Painting that colour queues the photo
|
||||
only there; enqueue skips `color_mismatch` otherwise. The library colour is how you see what went where.
|
||||
|
||||
Reference in new issue
Block a user