diff --git a/apps/app/src/desktop/fileMarks.ts b/apps/app/src/desktop/fileMarks.ts index ac11960..e350869 100644 --- a/apps/app/src/desktop/fileMarks.ts +++ b/apps/app/src/desktop/fileMarks.ts @@ -3,7 +3,7 @@ import type { ApiClient, EventSummary } from "@photoreport/sdk"; import { useEffect } from "react"; import { useLibraryLive } from "../library/realtime.js"; import { isDesktop } from "../platform.js"; -import { flushFailedPhotoFiles, settingsFromDevelop, writePhotoCommands, writePhotoFile, type FileIptc, type FileMarkUpdate } from "./lightroomSidecar.js"; +import { flushFailedPhotoFiles, flushRecentPhotoFiles, settingsFromDevelop, writePhotoCommands, writePhotoFile, type FileIptc, type FileMarkUpdate } from "./lightroomSidecar.js"; const LOCAL = "local:"; const idToSha = new Map(); @@ -14,18 +14,52 @@ function remember(id: string, sha256: string | null | undefined): void { idToSha.set(id, sha256); } +let shaByPhotoId: Map | null = null; +let shaByPhotoIdRaw = ""; + +/** Hash of the original on disk for this server photo, recorded when the file was uploaded. */ +function originalSha(photoId: string): string | null { + if (!photoId || photoId.startsWith(LOCAL)) return null; + let raw = ""; + try { + raw = localStorage.getItem("pr.localmap") ?? ""; + } catch { + return null; + } + if (!shaByPhotoId || raw !== shaByPhotoIdRaw) { + const next = new Map(); + try { + const map = JSON.parse(raw || "{}") as Record; + for (const [sha, serverId] of Object.entries(map)) { + if (!sha || typeof serverId !== "string" || !serverId) continue; + next.set(serverId, sha); + } + } catch { + // A broken map falls back to the sha the server stored. + } + shaByPhotoId = next; + shaByPhotoIdRaw = raw; + } + return shaByPhotoId.get(photoId) ?? null; +} + +/** + * The file Lightroom has is the original on disk. Its hash is often not the sha the server stored + * (that one can be the preview). Writing the server sha looks up a file that is not in the work folder. + */ +function diskSha(photoId: string, apiSha: string | null | undefined): string | null { + const onDisk = originalSha(photoId); + if (onDisk) return onDisk; + if (apiSha) return apiSha; + return null; +} + function shaOf(id: string): string | null { if (id.startsWith(LOCAL)) return id.slice(LOCAL.length); + const onDisk = originalSha(id); + if (onDisk) return onDisk; const known = idToSha.get(id); if (known) return known; - try { - const map = JSON.parse(localStorage.getItem("pr.localmap") ?? "{}") as Record; - 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; } @@ -110,10 +144,12 @@ function writeKnown(sha: string, update: FileMarkUpdate, developSeq: number, pho export function onFileMarkMessage(api: ApiClient, message: LibraryMessage): void { if (!isDesktop()) return; if (message.type === "photo.added") { - remember(message.photo.id, message.photo.sha256); + const sha = diskSha(message.photo.id, message.photo.sha256); + if (!sha) return; + remember(message.photo.id, sha); 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); + writeKnown(sha, marks ?? {}, message.photo.developSeq, message.photo.id, api, true); return; } if (message.type === "photo.updated") { @@ -164,6 +200,7 @@ export async function catchUpFileMarks(api: ApiClient, orgId: string): Promise eventIsCurrent(event, Date.now())); @@ -187,11 +224,13 @@ export async function catchUpFileMarks(api: ApiClient, orgId: string): Promise { 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. + // The first pass often runs before the session token is ready. Retry until one pass sticks. + // A write also fails while the JPEG is still in the ingest folder; retry those, not the whole library. const retry = window.setInterval(() => { flushFailedPhotoFiles(); - }, 30 * 1000); + void catchUpFileMarks(api, orgId); + }, 15 * 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(() => { diff --git a/apps/app/src/desktop/lightroomSidecar.test.ts b/apps/app/src/desktop/lightroomSidecar.test.ts index 0c8476a..ed653ff 100644 --- a/apps/app/src/desktop/lightroomSidecar.test.ts +++ b/apps/app/src/desktop/lightroomSidecar.test.ts @@ -61,7 +61,7 @@ describe("Lightroom sidecar", () => { }, ); expect(xml).toContain("Pavlidis"); - expect(xml).not.toContain('dc:title="Pavlidis"'); + 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("ANDEBOL"); diff --git a/apps/app/src/desktop/lightroomSidecar.ts b/apps/app/src/desktop/lightroomSidecar.ts index 381616c..49b9642 100644 --- a/apps/app/src/desktop/lightroomSidecar.ts +++ b/apps/app/src/desktop/lightroomSidecar.ts @@ -153,6 +153,8 @@ function iptcParts(iptc: FileIptc | undefined): { attrs: string[]; children: str let children = ""; if (title) { need("dc", "http://purl.org/dc/elements/1.1/"); + // Attribute: shells that only copy attributes onto the camera description. Element: Lightroom's Read Metadata. + attrs.push(`dc:title="${xmlAttr(title)}"`); children += `${xmlText(title)}`; } if (headline) { @@ -326,26 +328,49 @@ interface RememberedFile { iptc: FileIptc; } +/** Rows this session must write even when the stored history no longer fits. */ +const rememberedNow = new Map(); + function loadRemembered(): Record { + let all: Record = {}; 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; + if (parsed && typeof parsed === "object") all = parsed as Record; } catch { - return {}; + all = {}; } + for (const [sha, row] of rememberedNow) { + all[sha] = row; + } + return all; } function saveRemembered(all: Record): void { + // Each row carries the develop JSON. A few thousand of them exceed what the web view will store, + // and a failed save used to drop the write of the file Lightroom imports. const keys = Object.keys(all); - if (keys.length > 4000) { - for (const key of keys.slice(0, keys.length - 4000)) delete all[key]; + const kept = 400; + if (keys.length > kept) { + for (const key of keys.slice(0, keys.length - kept)) { + if (rememberedNow.has(key)) continue; + delete all[key]; + } } try { localStorage.setItem(FILE_MARKS_KEY, JSON.stringify(all)); + return; } catch { - // A full localStorage must not stop the edit itself. + // Still over the quota. Keep only what this session is writing. + } + const slim: Record = {}; + for (const [sha, row] of rememberedNow) { + slim[sha] = row; + } + try { + localStorage.setItem(FILE_MARKS_KEY, JSON.stringify(slim)); + } catch { + // flushPhotoFile reads rememberedNow, so the file is still written this session. } } @@ -411,7 +436,7 @@ function invokeWithTimeout(command: string, args: Record): Prom } async function flushPhotoFile(sha256: string): Promise { - const row = loadRemembered()[sha256]; + const row = rememberedNow.get(sha256) ?? 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; @@ -446,6 +471,22 @@ export function flushFailedPhotoFiles(): void { for (const sha256 of flushFailed) scheduleFlush(sha256); } +/** + * The photos remembered most recently (today's event is at the end of the list). Written first, + * so a catch-up that has not reached the server yet still updates the files Lightroom imports. + */ +export function flushRecentPhotoFiles(): void { + if (!isDesktop()) return; + const keys = Object.keys(loadRemembered()); + const start = Math.max(0, keys.length - 120); + const recent = keys.slice(start); + for (let index = recent.length - 1; index >= 0; index -= 1) { + const sha256 = recent[index]; + if (!sha256) continue; + 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; @@ -495,6 +536,7 @@ export function writePhotoFile(sha256: string, update: FileMarkUpdate): void { iptc: "iptc" in update ? iptcOf(update.iptc) : prev.iptc, }; all[sha256] = next; + rememberedNow.set(sha256, next); saveRemembered(all); scheduleFlush(sha256); } diff --git a/apps/desktop/src-tauri/build.rs b/apps/desktop/src-tauri/build.rs index 7c73240..39c9dd0 100644 --- a/apps/desktop/src-tauri/build.rs +++ b/apps/desktop/src-tauri/build.rs @@ -32,6 +32,7 @@ fn main() { "ftp_retry", "ftp_read", "ftp_sent", + "ftp_write_xmp", "ftp_open_folder", "ftp_save_settings", "local_original", diff --git a/apps/desktop/src-tauri/capabilities/default.json b/apps/desktop/src-tauri/capabilities/default.json index 71420a0..747f987 100644 --- a/apps/desktop/src-tauri/capabilities/default.json +++ b/apps/desktop/src-tauri/capabilities/default.json @@ -29,6 +29,7 @@ "allow-ftp-retry", "allow-ftp-read", "allow-ftp-sent", + "allow-ftp-write-xmp", "allow-ftp-open-folder", "allow-ftp-save-settings", "allow-local-original", diff --git a/apps/desktop/src-tauri/permissions/autogenerated/ftp_write_xmp.toml b/apps/desktop/src-tauri/permissions/autogenerated/ftp_write_xmp.toml new file mode 100644 index 0000000..9af6ad5 --- /dev/null +++ b/apps/desktop/src-tauri/permissions/autogenerated/ftp_write_xmp.toml @@ -0,0 +1,11 @@ +# Automatically generated - DO NOT EDIT! + +[[permission]] +identifier = "allow-ftp-write-xmp" +description = "Enables the ftp_write_xmp command without any pre-configured scope." +commands.allow = ["ftp_write_xmp"] + +[[permission]] +identifier = "deny-ftp-write-xmp" +description = "Denies the ftp_write_xmp command without any pre-configured scope." +commands.deny = ["ftp_write_xmp"] diff --git a/docs/ARCHITECTURE.md b/docs/ARCHITECTURE.md index 683e408..ccf89b6 100644 --- a/docs/ARCHITECTURE.md +++ b/docs/ARCHITECTURE.md @@ -490,7 +490,9 @@ fields onto that first description — caption and title as `rdf:Alt`, keywords `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. +already picked before this screen was open, without rewriting every older original first. The write addresses +the original by the hash recorded when that file was uploaded (`pr.localmap`), not by the preview hash the +server may store on the photo. **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