Make disk XMP picks/edits reliable (BIT-33124) #300

Merged
spark merged 1 commits from task/BIT-33124-disk-marks-reliable into main 2026-11-23 13:14:31 +00:00
8 changed files with 145 additions and 84 deletions

No files matched your search

+8 -9
View File
@@ -94,22 +94,21 @@ export function cullFromCameraRating(rating: number | undefined): { rating: numb
* Cull from Lightroom / Photo Mechanic XMP on the file: `xmpDM:pick`, stars, colour.
* Prefer this over stars alone — a flagged file with Rating 0 must still land as PICK.
*/
export function cullFromXmpPacket(xmp: string | null | undefined): {
export type XmpCull = {
rating?: number;
flag?: "PICK" | "REJECT";
colorLabel?: "RED" | "YELLOW" | "GREEN" | "BLUE" | "PURPLE";
} {
};
export function cullFromXmpPacket(xmp: string | null | undefined): XmpCull {
if (!xmp) return {};
const marks = libraryMarksFromXmp(xmp);
const out: {
rating?: number;
flag?: "PICK" | "REJECT";
colorLabel?: "RED" | "YELLOW" | "GREEN" | "BLUE" | "PURPLE";
} = {};
const out: XmpCull = {};
if (marks.flag === "REJECT") out.flag = "REJECT";
else if (marks.flag === "PICK") out.flag = "PICK";
if (marks.rating > 0) {
out.rating = marks.rating;
const rating = marks.rating;
if (typeof rating === "number" && rating > 0) {
out.rating = rating;
if (!out.flag) out.flag = "PICK";
}
const color = marks.colorLabel;
+43 -29
View File
@@ -181,9 +181,12 @@ export class IngestService {
const camera = await readCameraInfo(file).catch(() => ({}) as Awaited<ReturnType<typeof readCameraInfo>>);
const embedded = await readEmbeddedIptc(file);
// Lightroom / Photo Mechanic pick, stars and colour on the file — not stars alone.
const xmpCull = await readFile(file)
.then((buf) => cullFromJpegBytes(buf))
.catch(() => ({}));
let xmpCull: Awaited<ReturnType<typeof cullFromJpegBytes>> = {};
try {
xmpCull = cullFromJpegBytes(await readFile(file));
} catch {
xmpCull = {};
}
const capturedAt = camera.capturedAt ? new Date(camera.capturedAt.getTime() + (origin.clockOffsetSec ?? 0) * 1000) : undefined;
// Archive imports name their own event. No camera time: keep the folder/pin the photographer named — do not
// invent "now" (that would also force today's open event). With a capture time, the pin only wins inside its
@@ -365,29 +368,33 @@ export class IngestService {
const existing = await db.photo.findUnique({ where: { id: photo.id }, select: { rating: true, flag: true, colorLabel: true, exif: true } });
const needCull = (existing?.rating ?? photo.rating ?? 0) <= 0 || existing?.flag === "NONE";
const camera = needCull ? await readCameraInfo(file).catch(() => null) : null;
const xmpCull = needCull
? await readFile(file)
.then((buf) => cullFromJpegBytes(buf))
.catch(() => ({}))
: {};
let xmpCull: Awaited<ReturnType<typeof cullFromJpegBytes>> = {};
if (needCull) {
try {
xmpCull = cullFromJpegBytes(await readFile(file));
} catch {
xmpCull = {};
}
}
const cull = { ...cullFromCameraRating(camera?.rating), ...xmpCull };
if (key !== photo.storageKey) await rm(storage.resolve(photo.storageKey), { force: true });
await storage.adopt(file, key);
// Previews (thumb/preview) stay: they already show this photo. Only the stored file changes.
// Faces and shirt numbers were read from the 2048 px preview: read them again from the full photo.
const org = await db.organization.findUnique({ where: { id: photo.organizationId }, select: { biometricsEnabled: true } });
const data: Prisma.PhotoUpdateInput = {
storageKey: key,
byteSize: size,
originalStored: true,
};
if (org?.biometricsEnabled) data.facesStatus = "PENDING";
if (typeof cull.rating === "number" && cull.rating > 0) data.rating = cull.rating;
if (cull.flag && existing?.flag === "NONE") data.flag = cull.flag;
if (cull.colorLabel && existing?.colorLabel === "NONE") data.colorLabel = cull.colorLabel;
if (needCull) data.exif = withCameraRatingChecked(existing?.exif) as Prisma.InputJsonValue;
const updated = await db.photo.update({
where: { id: photo.id },
data: {
storageKey: key,
byteSize: size,
originalStored: true,
...(org?.biometricsEnabled && { facesStatus: "PENDING" }),
...("rating" in cull ? { rating: cull.rating } : {}),
...("flag" in cull && existing?.flag === "NONE" ? { flag: cull.flag } : {}),
...("colorLabel" in cull && existing?.colorLabel === "NONE" ? { colorLabel: cull.colorLabel } : {}),
...(needCull ? { exif: withCameraRatingChecked(existing?.exif) as Prisma.InputJsonValue } : {}),
},
data,
});
log.info({ photoId: photo.id }, "ingest: original replaces the desktop preview");
// Deliveries waiting for it go now.
@@ -503,24 +510,35 @@ export class IngestService {
for (const row of rows) {
const file = storage.resolve(row.storage_key);
const camera = await readCameraInfo(file).catch(() => null);
const xmpCull = await readFile(file)
.then((buf) => cullFromJpegBytes(buf))
.catch(() => ({}));
let xmpCull: Awaited<ReturnType<typeof cullFromJpegBytes>> = {};
try {
xmpCull = cullFromJpegBytes(await readFile(file));
} catch {
xmpCull = {};
}
const cull = { ...cullFromCameraRating(camera?.rating), ...xmpCull };
const data: Prisma.PhotoUpdateInput = {
exif: withCameraRatingChecked(row.exif) as Prisma.InputJsonValue,
};
const patch: {
rating?: number;
flag?: "PICK" | "REJECT";
colorLabel?: "RED" | "YELLOW" | "GREEN" | "BLUE" | "PURPLE";
} = {};
let changed = false;
if ("rating" in cull && cull.rating) {
if (typeof cull.rating === "number" && cull.rating > 0) {
data.rating = cull.rating;
patch.rating = cull.rating;
changed = true;
}
if ("flag" in cull && row.flag === "NONE") {
if (cull.flag && row.flag === "NONE") {
data.flag = cull.flag;
patch.flag = cull.flag;
changed = true;
}
if ("colorLabel" in cull) {
if (cull.colorLabel) {
data.colorLabel = cull.colorLabel;
patch.colorLabel = cull.colorLabel;
changed = true;
}
if (changed) applied++;
@@ -529,11 +547,7 @@ export class IngestService {
broadcaster.library(row.organization_id, {
type: "photo.updated",
ids: [row.id],
patch: {
...("rating" in cull ? { rating: cull.rating } : {}),
...("flag" in cull && row.flag === "NONE" ? { flag: cull.flag } : {}),
...("colorLabel" in cull ? { colorLabel: cull.colorLabel } : {}),
},
patch,
});
}
}
+13 -1
View File
@@ -1,5 +1,7 @@
import { useEffect } from "react";
import { useAuth } from "../auth.js";
import { localPhotos } from "../offline/local.js";
import { isLocalId, offlineQueue } from "../offline/queue.js";
import { isDesktop } from "../platform.js";
import { reconcileSoftCrops } from "./softCropWatch.js";
@@ -8,7 +10,7 @@ const EVERY_MS = 4_000;
/**
* Desktop only: while signed in, notice Lightroom / Photo Mechanic soft-crop writes on local originals
* and apply them as develop crops (same path as cropping in Revelar — including autopilot learning).
* A colour class Photo Mechanic paints on the same file is copied onto the library photo.
* Pick / stars / colour on the same file are copied onto the library photo (offline queue when still local).
*/
export function SoftCropWatch({ enabled = isDesktop(), everyMs = EVERY_MS }: { enabled?: boolean; everyMs?: number }) {
const { api, organization } = useAuth();
@@ -21,9 +23,19 @@ export function SoftCropWatch({ enabled = isDesktop(), everyMs = EVERY_MS }: { e
try {
await reconcileSoftCrops(
async (id, photoId, color) => {
if (isLocalId(photoId)) {
localPhotos.patch(photoId, { colorLabel: color });
offlineQueue(id).add({ kind: "patch", ids: [photoId], patch: { colorLabel: color } });
return;
}
await api.updatePhotos(id, [photoId], { colorLabel: color });
},
async (id, photoId, patch) => {
if (isLocalId(photoId)) {
localPhotos.patch(photoId, patch);
offlineQueue(id).add({ kind: "patch", ids: [photoId], patch });
return;
}
await api.updatePhotos(id, [photoId], patch);
},
);
+1 -1
View File
@@ -116,7 +116,7 @@ export async function marksFromLocalSha(sha256: string): Promise<DiskFileMarks>
/**
* Read marks from a JPEG still in the local FTP ingest tree (path from `ftp_take`).
* The 2048 px preview strips XMP — always read the original.
* Prefer `marksFromLocalSha` after `ftp_info` (sidecar + embedded). This path only sees the embedded packet.
*/
export async function marksFromFtpPath(path: string): Promise<DiskFileMarks> {
if (!isDesktop() || !path) return { ...EMPTY };
+16 -4
View File
@@ -9,7 +9,8 @@ import { forgetSoftCrop, localXmpText } from "./softCrop.js";
* Photo Mechanic). Crop → develop `crop.set`; pick / stars / colour → library patch. Same path as
* editing inside the app, including the autopilot learner.
*/
const STORE_KEY = "softcrop:watch";
/** v2: re-read every watched file once after JPEG-sidecar + cull fixes (BIT-33124). */
const STORE_KEY = "softcrop:watch:v2";
const MAX_WATCH = 800;
const OWN_WRITE_GRACE_MS = 4_000;
@@ -147,9 +148,20 @@ export async function reconcileSoftCrops(
}
forgetSoftCrop(row.sha256);
const xmp = await localXmpText(row.sha256);
const crop = xmp ? cropFromXmp(xmp) : null;
const color = xmp ? colorClassFromXmp(xmp) : null;
const marks = xmp ? libraryMarksFromXmp(xmp) : { flag: "NONE" as const, rating: 0, colorLabel: "NONE" as const };
if (!xmp) {
// No packet yet (sidecar still writing). Remember mtime; a later sidecar bumps it via local_stat.
next.push({
...row,
mtimeMs: stat.mtimeMs || row.mtimeMs,
color: row.color !== undefined ? row.color : "",
flag: row.flag !== undefined ? row.flag : "NONE",
rating: row.rating !== undefined ? row.rating : 0,
});
continue;
}
const crop = cropFromXmp(xmp);
const color = colorClassFromXmp(xmp);
const marks = libraryMarksFromXmp(xmp);
let colorApplied = color ? row.color : (row.color ?? "");
let flagApplied = row.flag ?? "NONE";
let ratingApplied = row.rating ?? 0;
+11 -8
View File
@@ -185,11 +185,11 @@ export function useLocalFtp(add: Add, enabled: boolean, invoke: Invoke = tauriIn
} catch {
/* no blob URLs here (tests): shown without a thumbnail */
}
// Preview strips XMP — read pick / stars / colour / soft crop from the original on disk.
const { marksFromFtpPath, cullPatchFromMarks, cropCommandFromMarks, hasDiskMarks } = await import(
// Preview strips XMP — read pick / stars / colour / soft crop from the indexed original (sidecar or embedded).
const { marksFromLocalSha, cullPatchFromMarks, cropCommandFromMarks, hasDiskMarks } = await import(
"../desktop/readFileMarks.js"
);
const disk = await marksFromFtpPath(f.path);
const disk = await marksFromLocalSha(info.sha256);
const cull = cullPatchFromMarks(disk);
localPhotos.put(
localPhoto({
@@ -203,13 +203,16 @@ export function useLocalFtp(add: Add, enabled: boolean, invoke: Invoke = tauriIn
...cull,
}),
);
if (orgId && hasDiskMarks(disk)) {
if (orgId) {
const id = localId(info.sha256);
if (Object.keys(cull).length) {
offlineQueue(orgId).add({ kind: "patch", ids: [id], patch: cull });
if (hasDiskMarks(disk)) {
if (Object.keys(cull).length) {
offlineQueue(orgId).add({ kind: "patch", ids: [id], patch: cull });
}
const cropOp = cropCommandFromMarks(disk);
if (cropOp) offlineQueue(orgId).enqueueEdit(id, cropOp);
}
const cropOp = cropCommandFromMarks(disk);
if (cropOp) offlineQueue(orgId).enqueueEdit(id, cropOp);
// Always watch: marks written later in Photo Mechanic / Lightroom still land in the library.
const { watchSoftCropPhoto } = await import("../desktop/softCropWatch.js");
watchSoftCropPhoto(orgId, id, info.sha256);
}
+19 -10
View File
@@ -75,11 +75,18 @@ export async function showLocalJpeg(args: {
}
const capturedAt = lisbonInstant(exifDateTime(previewBytes));
const eventId = events ? eventForArrival(args.eventId ?? null, events, capturedAt) : (args.eventId ?? null);
// Hand-dropped JPEGs keep embedded XMP: pick / stars / colour / soft crop must land in the library.
const { marksFromJpegBytes, cullPatchFromMarks, cropCommandFromMarks, hasDiskMarks } = await import(
"../desktop/readFileMarks.js"
);
const disk = marksFromJpegBytes(previewBytes);
// Hand-dropped JPEGs keep embedded XMP. Desktop previews strip it — read the indexed original by SHA.
const {
marksFromJpegBytes,
marksFromLocalSha,
cullPatchFromMarks,
cropCommandFromMarks,
hasDiskMarks,
} = await import("../desktop/readFileMarks.js");
let disk = marksFromJpegBytes(previewBytes);
if (!hasDiskMarks(disk) && origin && origin !== "original" && origin.sha256) {
disk = await marksFromLocalSha(origin.sha256);
}
const cull = cullPatchFromMarks(disk);
localPhotos.put(
localPhoto({
@@ -93,13 +100,15 @@ export async function showLocalJpeg(args: {
...cull,
}),
);
if (orgId && hasDiskMarks(disk)) {
if (orgId) {
const id = localId(sha256);
if (Object.keys(cull).length) {
offlineQueue(orgId).add({ kind: "patch", ids: [id], patch: cull });
if (hasDiskMarks(disk)) {
if (Object.keys(cull).length) {
offlineQueue(orgId).add({ kind: "patch", ids: [id], patch: cull });
}
const cropOp = cropCommandFromMarks(disk);
if (cropOp) offlineQueue(orgId).enqueueEdit(id, cropOp);
}
const cropOp = cropCommandFromMarks(disk);
if (cropOp) offlineQueue(orgId).enqueueEdit(id, cropOp);
if (isDesktop()) {
const { watchSoftCropPhoto } = await import("../desktop/softCropWatch.js");
watchSoftCropPhoto(orgId, id, sha256);
+34 -22
View File
@@ -195,45 +195,57 @@ 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");
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()
.ok()
.and_then(|t| t.duration_since(std::time::UNIX_EPOCH).ok())
.map(|d| d.as_millis() as u64)
{
mtime_ms = mtime_ms.max(ms);
// Sidecar next to the file (RAW always; JPEG when Photo Mechanic / Bridge wrote one).
for side in xmp_sidecar_paths(&path) {
if let Ok(meta) = tokio::fs::metadata(&side).await {
size = size.saturating_add(meta.len());
if let Some(ms) = meta
.modified()
.ok()
.and_then(|t| t.duration_since(std::time::UNIX_EPOCH).ok())
.map(|d| d.as_millis() as u64)
{
mtime_ms = mtime_ms.max(ms);
}
}
}
Ok(LocalStat { size, mtime_ms })
}
/// `photo.xmp` and `photo.jpg.xmp` beside an original — Photo Mechanic writes both forms for JPEG.
fn xmp_sidecar_paths(path: &Path) -> Vec<PathBuf> {
let mut out = Vec::with_capacity(2);
out.push(path.with_extension("xmp"));
if let Some(name) = path.file_name().and_then(|n| n.to_str()) {
if let Some(parent) = path.parent() {
out.push(parent.join(format!("{name}.xmp")));
}
}
out
}
/// The XMP packet (or the head of the file) for a local original, so the app can draw Lightroom's soft crop
/// without loading a 12 MB JPEG. Also tries `name.xmp` beside a raw. `not_found` when this computer lacks it.
/// without loading a 12 MB JPEG. Sidecar first (RAW and JPEG), then the packet embedded in a JPEG.
/// `not_found` when this computer lacks the file.
#[tauri::command]
pub async fn local_xmp(
index: tauri::State<'_, LocalIndex>,
sha256: String,
) -> Result<tauri::ipc::Response, String> {
let path = index.find_changed(&sha256).ok_or("not_found")?;
for side in xmp_sidecar_paths(&path) {
if side.is_file() {
let bytes = tokio::fs::read(&side).await.map_err(|e| e.to_string())?;
if !bytes.is_empty() {
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))