/** * One page of the Apple Photos library, decided by the object and nowhere * else, over the pure readings of Apple's rows (…/photos/apple.rs). * The body is `PhotoWork` as serde serialises …/photos/mod.rs. * * The Mac read the library, hashed each original and PUT its bytes under * `/photos/.` (a video under `videos/`, as * `cotton_core::media::keys` names it) before it posted the page. So the one * step of the Rust that touched the disk — "is the original really there, * and how big is it" — is a HEAD of that key in R2 here, made before the * write; everything else is the Rust's decision, in the Rust's order: * * 1. the format, before anything else (a type outside the table is counted by * its own name, a ZKIND that disagrees with its type is refused); * 2. where the original is (an unknown directory shape is named, not guessed); * 3. whether its bytes are here (no sha256, or nothing under the key, is * "not downloaded" — counted, never a failure) and inside the media limits; * 4. the sighting probe: an asset the object already holds by its local * identifier re-writes what Apple knows about it and nothing else; * 5. a picture the owner removed stays removed; * 6. the rows — the photo or video (met, not made, when its bytes are already * here under another sighting), its sighting, its faces and their people. */ import type { Store } from "../store.ts"; import { upsert, type Change } from "./contacts.ts"; import { mediaFaceId, mediaSightingId, photoRecordId, videoRecordId } from "./ids.ts"; import { LIVE_PERSON } from "./reader.ts"; import { collapse, isRecord } from "./text.ts"; // ── the body: PhotoWork, as serde serialises it ────────────────────────── export interface AppleAssetRow { pk: number; uuid: string; /** 0 photo, 1 video. */ kind: number; kindSubtype?: number | null; uti?: string | null; directory?: string | null; filename?: string | null; /** 4 = iCloud shared library, 6 = the library's own, 10 = a referenced file. */ savedAssetType?: number | null; /** Core Data seconds. */ dateCreated?: number | null; timezoneOffset?: number | null; latitude?: number | null; longitude?: number | null; width?: number | null; height?: number | null; orientation?: number | null; favorite?: number | null; hdrType?: number | null; depthType?: number | null; adjustmentsState?: number | null; avalancheUuid?: string | null; isDetectedScreenshot?: number | null; cameraCaptureDevice?: number | null; cameraMake?: string | null; cameraModel?: string | null; originalFilename?: string | null; overallAestheticScore?: number | null; curationScore?: number | null; sceneAnalysisVersion?: number | null; title?: string | null; longDescription?: string | null; } export interface PlaceReading { name?: string | null; city?: string | null; region?: string | null; country?: string | null; labels: string[]; } export interface AppleFaceRow { uuid: string; assetPk: number; centerX: number; centerY: number; size: number; quality?: number | null; personPk?: number | null; personUuid?: string | null; isInTrash?: number | null; hidden?: number | null; } export interface ApplePersonRow { pk: number; uuid: string; fullName?: string | null; displayName?: string | null; faceCount?: number | null; mergeTargetPk?: number | null; } export interface PhotoAsset { row: AppleAssetRow; place: PlaceReading; faces: AppleFaceRow[]; /** The original's sha256, filled by the Mac as it PUT the bytes; absent when it had none to hash. */ sha256?: string | null; } export interface PhotoCluster { person: ApplePersonRow; contactIdentifier?: string | null; } export interface PhotoWork { library: string; assets: PhotoAsset[]; clusters: Record; } /** A page's ceiling: each asset costs one R2 HEAD before the write. The reader sends 100. */ export const MAX_BATCH_ASSETS = 500; type Check = (v: unknown) => boolean; const str: Check = (v) => typeof v === "string"; const num: Check = (v) => typeof v === "number" && Number.isFinite(v); const int: Check = (v) => Number.isSafeInteger(v); const opt = (check: Check): Check => (v) => v === undefined || v === null || check(v); const SAID = new Map(); const said = (check: Check, words: string): Check => (SAID.set(check, words), check); const STR = said(str, "a string"); const NUM = said(num, "a number"); const INT = said(int, "a whole number"); const OSTR = said(opt(str), "a string or null"); const ONUM = said(opt(num), "a number or null"); const OINT = said(opt(int), "a whole number or null"); const ROW: Record = { pk: INT, uuid: STR, kind: INT, kindSubtype: OINT, uti: OSTR, directory: OSTR, filename: OSTR, savedAssetType: OINT, dateCreated: ONUM, timezoneOffset: OINT, latitude: ONUM, longitude: ONUM, width: OINT, height: OINT, orientation: OINT, favorite: OINT, hdrType: OINT, depthType: OINT, adjustmentsState: OINT, avalancheUuid: OSTR, isDetectedScreenshot: OINT, cameraCaptureDevice: OINT, cameraMake: OSTR, cameraModel: OSTR, originalFilename: OSTR, overallAestheticScore: ONUM, curationScore: ONUM, sceneAnalysisVersion: OINT, title: OSTR, longDescription: OSTR, }; const PLACE: Record = { name: OSTR, city: OSTR, region: OSTR, country: OSTR }; const FACE: Record = { uuid: STR, assetPk: INT, centerX: NUM, centerY: NUM, size: NUM, quality: ONUM, personPk: OINT, personUuid: OSTR, isInTrash: OINT, hidden: OINT }; const PERSON: Record = { pk: INT, uuid: STR, fullName: OSTR, displayName: OSTR, faceCount: OINT, mergeTargetPk: OINT }; function fieldsProblem(at: string, value: unknown, fields: Record): string | null { if (!isRecord(value)) return `${at}: expected an object`; for (const [field, check] of Object.entries(fields)) if (!check(value[field])) return `${at}.${field}: expected ${SAID.get(check)}`; return null; } /** The first field serde would refuse in a `PhotoWork`, said as `callsProblem` says one; null when the page reads. */ export function photosProblem(body: unknown): string | null { if (!isRecord(body)) return "body: expected an object"; if (typeof body.library !== "string") return "library: expected a string"; if (!Array.isArray(body.assets)) return "assets: expected an array"; if (body.assets.length > MAX_BATCH_ASSETS) return `assets: ${body.assets.length} exceeds the ${MAX_BATCH_ASSETS}-asset cap`; if (!isRecord(body.clusters)) return "clusters: expected an object"; for (const [i, asset] of (body.assets as unknown[]).entries()) { const at = `assets[${i}]`; if (!isRecord(asset)) return `${at}: expected an object`; const row = fieldsProblem(`${at}.row`, asset.row, ROW); if (row) return row; const place = fieldsProblem(`${at}.place`, asset.place, PLACE); if (place) return place; const labels = (asset.place as Record).labels; if (!Array.isArray(labels) || !labels.every(str)) return `${at}.place.labels: expected an array of strings`; if (!Array.isArray(asset.faces)) return `${at}.faces: expected an array`; for (const [f, face] of (asset.faces as unknown[]).entries()) { const bad = fieldsProblem(`${at}.faces[${f}]`, face, FACE); if (bad) return bad; } // The object names a media key with it, so it must be a digest and nothing else. if (asset.sha256 !== undefined && asset.sha256 !== null && !(typeof asset.sha256 === "string" && /^[0-9a-f]{64}$/.test(asset.sha256))) return `${at}.sha256: expected a lowercase hex sha256 or null`; } for (const [key, cluster] of Object.entries(body.clusters)) { const at = `clusters.${key}`; if (!isRecord(cluster)) return `${at}: expected an object`; const person = fieldsProblem(`${at}.person`, cluster.person, PERSON); if (person) return person; if (!OSTR(cluster.contactIdentifier)) return `${at}.contactIdentifier: expected a string or null`; } return null; } // ── apple.rs: what Apple's rows mean ───────────────────────────────────── export const APPLE_EPOCH_MS = 978_307_200_000; /** `f64::round`: a half goes away from zero. */ const roundAway = (x: number): number => Math.sign(x) * Math.round(Math.abs(x)); /** Apple's seconds → an ISO-8601 UTC instant with milliseconds, or null. */ export function appleDateToIso(seconds: number | null | undefined): string | null { if (seconds === null || seconds === undefined || !Number.isFinite(seconds)) return null; const moment = new Date(APPLE_EPOCH_MS + roundAway(seconds * 1000)); return Number.isFinite(moment.getTime()) ? moment.toISOString() : null; } export interface AppleFormat { contentType: string; /** Without the dot. */ ext: string; kind: "photo" | "video"; } const FORMATS: Record = { "public.heic": { contentType: "image/heic", ext: "heic", kind: "photo" }, "public.jpeg": { contentType: "image/jpeg", ext: "jpg", kind: "photo" }, "public.png": { contentType: "image/png", ext: "png", kind: "photo" }, "org.webmproject.webp": { contentType: "image/webp", ext: "webp", kind: "photo" }, "com.compuserve.gif": { contentType: "image/gif", ext: "gif", kind: "photo" }, "com.apple.quicktime-movie": { contentType: "video/quicktime", ext: "mov", kind: "video" }, "public.mpeg-4": { contentType: "video/mp4", ext: "mp4", kind: "video" }, }; /** Uniform type identifier → what Cotton stores it as; a type outside the table is never guessed. */ export function formatFor(uti: string | null | undefined): AppleFormat | null { return uti != null && Object.hasOwn(FORMATS, uti) ? FORMATS[uti]! : null; } /** `cotton_core::media::keys::media_limits` for a photo and a video. */ const MEDIA_LIMITS: Record<"photo" | "video", { maxBytes: number; contentTypes: string[] }> = { photo: { maxBytes: 52_428_800, contentTypes: ["image/jpeg", "image/png", "image/webp", "image/heic", "image/gif"] }, video: { maxBytes: 524_288_000, contentTypes: ["video/mp4", "video/quicktime", "image/jpeg"] }, }; /** `photo_key` / `video_key`: `/photos/.` or `…/videos/…`. */ export const mediaKeyOf = (databaseId: string, format: AppleFormat, sha256: string): string => `${databaseId}/${format.kind === "video" ? "videos" : "photos"}/${sha256}.${format.ext}`; const NAMED_SUBTYPES: Record = { 1: "panorama", 2: "live", 10: "screenshot", 101: "slow_motion", 102: "time_lapse", 103: "screen_recording" }; /** Every kind a row says it is, in the fixed order the flags are read; an unknown ZKINDSUBTYPE is counted, never guessed. */ export function subtypesOf(row: AppleAssetRow): { subtypes: string[]; unknownSubtype: number | null } { const found: string[] = []; const add = (name: string): void => { if (!found.includes(name)) found.push(name); }; let unknownSubtype: number | null = null; const code = row.kindSubtype ?? 0; if (code !== 0) { const name = NAMED_SUBTYPES[code]; if (name) add(name); else unknownSubtype = code; } if (row.isDetectedScreenshot === 1) add("screenshot"); if (row.cameraCaptureDevice === 1) add("selfie"); if (row.avalancheUuid) add("burst"); if ((row.hdrType ?? 0) > 0) add("hdr"); if (row.depthType === 1) add("portrait"); if ((row.adjustmentsState ?? 0) > 0) add("edited"); return { subtypes: found, unknownSubtype }; } /** Apple writes -180 for "no location". */ export function coordinateOf(value: number | null | undefined): number | null { if (value === null || value === undefined || !Number.isFinite(value) || value === -180) return null; return value; } export interface Enrichment { taken_offset: number | null; latitude: number | null; longitude: number | null; place_name: string | null; place_city: string | null; place_region: string | null; place_country: string | null; camera_make: string | null; camera_model: string | null; orientation: number | null; favourite: boolean; subtypes: string[]; original_filename: string | null; aesthetic_score: number | null; curation_score: number | null; labels: string[]; } const clampScore = (v: number): number => Math.min(1, Math.max(-1, v)); /** What a picture knows about itself; scores only when analysis ran (0.5 is Apple's placeholder), a coordinate only as a pair. */ export function enrichmentOf(row: AppleAssetRow, place: PlaceReading): Enrichment { const analysed = (row.sceneAnalysisVersion ?? 0) > 0; const latitude = coordinateOf(row.latitude); const longitude = coordinateOf(row.longitude); const both = latitude !== null && longitude !== null; const orientation = row.orientation ?? null; return { taken_offset: row.timezoneOffset ?? null, latitude: both ? latitude : null, longitude: both ? longitude : null, place_name: place.name ?? null, place_city: place.city ?? null, place_region: place.region ?? null, place_country: place.country ?? null, camera_make: row.cameraMake ?? null, camera_model: row.cameraModel ?? null, orientation: orientation !== null && orientation >= 1 && orientation <= 8 ? orientation : null, favourite: row.favorite === 1, subtypes: subtypesOf(row).subtypes, original_filename: row.originalFilename ?? null, aesthetic_score: analysed && row.overallAestheticScore != null ? clampScore(row.overallAestheticScore) : null, curation_score: analysed && row.curationScore != null ? clampScore(row.curationScore) : null, labels: [...place.labels], }; } /** The title and description the person typed, joined by an em dash; null when both are blank. */ export function captionOf(row: AppleAssetRow): string | null { const parts = [row.title, row.longDescription].filter((p): p is string => typeof p === "string").map((p) => p.trim()).filter(Boolean); return parts.length ? parts.join(" — ") : null; } export type OriginalPath = { library: string } | { shared: string } | { referenced: string } | { unknown: string }; /** Where the original lives, by the shapes measured on a real library; anything else is named, never guessed. */ export function originalPathOf(directory: string | null | undefined, filename: string | null | undefined, savedAssetType: number | null | undefined): OriginalPath { const dir = directory ?? ""; const file = filename ?? ""; if (!file) return { unknown: "the asset names no file" }; if (savedAssetType === 10) return dir.startsWith("/") ? { referenced: `${dir}/${file}` } : { unknown: "a referenced file without an absolute directory" }; if (/^[0-9A-Fa-f]$/.test(dir)) return { library: `originals/${dir}/${file}` }; if (dir.includes("/")) return { shared: `scopes/cloudsharing/data/${dir}/${file}` }; return { unknown: `an unrecognised directory shape "${dir}"` }; } export interface FaceBox { x: number; y: number; w: number; h: number; } const clampUnit = (v: number): number => Math.min(1, Math.max(0, v)); /** Apple's bottom-left centre and half-side → Cotton's top-left box, clamped to the unit square; null for no area. */ export function faceBoxOf(centerX: number, centerY: number, size: number): FaceBox | null { const half = size; if (!(half > 0 && Number.isFinite(centerX) && Number.isFinite(centerY))) return null; const x = clampUnit(centerX - half); const y = clampUnit(1 - centerY - half); const w = clampUnit(centerX + half) - x; const h = clampUnit(1 - centerY + half) - y; if (!(w > 0 && h > 0)) return null; return { x, y, w, h }; } /** -1 is Apple's "not measured", and that is null rather than a bad score. */ export function faceQualityOf(value: number | null | undefined): number | null { if (value === null || value === undefined || !Number.isFinite(value) || value < 0) return null; return Math.min(value, 1); } /** The name a cluster carries — the full name, else the display name — or null. */ export function personNameOf(fullName: string | null | undefined, displayName: string | null | undefined): string | null { const full = (fullName ?? "").trim(); if (full) return full; const display = (displayName ?? "").trim(); return display || null; } /** Case- and whitespace-insensitive, for the name rule that ASSIGNS. */ export const normaliseName = (name: string): string => collapse(name).toLowerCase(); // ── the reads ──────────────────────────────────────────────────────────── const j = (column: string): string => `json_extract(data, '$.${column}')`; /** The fixed statements the photo pass asks the object; one database per object, so no workspace filter. */ export class PhotoReader { private readonly store: Store; constructor(store: Store) { this.store = store; } /** The record a sighting from the Apple library already carries for this asset. */ sightingRecord(assetUuid: string): string | null { return ( this.store.query<{ record_id: string | null }>( `SELECT ${j("record_id")} AS record_id FROM rows WHERE table_id = 'sighting' AND deleted = 0 AND ${j("source")} = 'apple_library' AND ${j("source_id")} = ? ORDER BY created_at, id LIMIT 1`, assetUuid, )[0]?.record_id ?? null ); } /** "live" for a held row, "gone" for a tombstone (the owner removed it), null for a row never held. */ record(table: "photo" | "video", id: string): "live" | "gone" | null { const held = this.store.any(table, id); return held ? (held.deleted ? "gone" : "live") : null; } /** The person a cluster's faces already point at: the majority, ties on the id; a binned or merged person is never one. */ majorityPerson(clusterUuid: string): string | null { return ( this.store.query<{ person_id: string }>( `SELECT p.id AS person_id FROM rows f JOIN rows p ON ${LIVE_PERSON("p")} AND p.id = json_extract(f.data, '$.person_id') WHERE f.table_id = 'face' AND f.deleted = 0 AND json_extract(f.data, '$.source') = 'apple' AND json_extract(f.data, '$.cluster_id') = ? GROUP BY p.id ORDER BY COUNT(*) DESC, p.id ASC LIMIT 1`, clusterUuid, )[0]?.person_id ?? null ); } /** The active person carrying this Contacts card. */ byContact(contactIdentifier: string): string | null { return ( this.store.query<{ id: string }>( `SELECT p.id AS id FROM rows p WHERE ${LIVE_PERSON("p")} AND json_extract(p.data, '$.device_contact_id') = ? ORDER BY p.created_at, p.id LIMIT 1`, contactIdentifier, )[0]?.id ?? null ); } /** Every active person, with the name the rules compare. */ activePeople(): { id: string; full_name: string | null }[] { return this.store.query<{ id: string; full_name: string | null }>(`SELECT p.id AS id, json_extract(p.data, '$.full_name') AS full_name FROM rows p WHERE ${LIVE_PERSON("p")} ORDER BY p.created_at, p.id`); } /** Whether a row is held, live or not. */ holds(table: string, id: string): boolean { return this.store.any(table, id) !== null; } } // ── people.rs: Apple's face clusters → Cotton's people ─────────────────── /** A person as the resolver matches one by name. */ export interface PersonNamed { id: string; name: string; } export type Resolution = | { how: "existing"; personId: string } | { how: "byContact"; personId: string } | { how: "byName"; personId: string } | { how: "created"; personId: string; suggested: number } | { how: "ambiguous"; personId: string; suggested: number; reason: string } | { how: "unnamed" }; export const resolvedPerson = (r: Resolution): string | null => (r.how === "unnamed" ? null : r.personId); /** * Who each cluster IS, for the length of one page — the one place the importer * assigns a person, and only by these rules in this order: the faces' own * answer (the majority), the Contacts card Photos matched, exactly one active * person with that name; otherwise the person is created and every namesake is * a question. Memoised per cluster; a person this page created answers every * later cluster with the same name. */ export class PersonResolver { private readonly decided = new Map(); private readonly active: PersonNamed[] = []; private readonly byName = new Map(); private readonly createdByName = new Map(); private loaded = false; private readonly db: PhotoReader; private readonly newPersonId: () => string; private readonly now: string; constructor(db: PhotoReader, newPersonId: () => string, now: string) { this.db = db; this.newPersonId = newPersonId; this.now = now; } resolve(cluster: ApplePersonRow, contactIdentifier: string | null | undefined): { resolution: Resolution; changes: Change[] } { const known = this.decided.get(cluster.uuid); if (known) return { resolution: known, changes: [] }; const decided = this.decide(cluster, contactIdentifier ?? null); this.decided.set(cluster.uuid, decided.resolution); return decided; } private decide(cluster: ApplePersonRow, contactIdentifier: string | null): { resolution: Resolution; changes: Change[] } { const name = personNameOf(cluster.fullName, cluster.displayName); if (name === null) return { resolution: { how: "unnamed" }, changes: [] }; const majority = this.db.majorityPerson(cluster.uuid); if (majority) return { resolution: { how: "existing", personId: majority }, changes: [] }; this.load(); if (contactIdentifier) { const person = this.db.byContact(contactIdentifier); if (person) return { resolution: { how: "byContact", personId: person }, changes: [] }; } const key = normaliseName(name); const sameName = [...(this.byName.get(key) ?? [])]; if (sameName.length === 1) return { resolution: { how: "byName", personId: sameName[0]! }, changes: [] }; const mine = this.createdByName.get(key); if (mine) return { resolution: { how: "byName", personId: mine }, changes: [] }; const personId = this.newPersonId(); const changes: Change[] = [ upsert("person", personId, { id: personId, full_name: name, contact_source: "apple_library", device_contact_id: contactIdentifier, created_at: this.now, updated_at: this.now, }), ]; this.remember(key, personId, name); // A new person once asked "is this the same as …?" (person_suggestion); that table is retired (TABLE DROP 1), so no // question is written. return { resolution: sameName.length > 1 ? { how: "ambiguous", personId, suggested: 0, reason: `${sameName.length} people are called "${name}" — created as another` } : { how: "created", personId, suggested: 0 }, changes, }; } private load(): void { if (this.loaded) return; for (const row of this.db.activePeople()) { if (!row.id) continue; const name = row.full_name ?? ""; const key = normaliseName(name); if (key) this.byName.set(key, [...(this.byName.get(key) ?? []), row.id]); this.active.push({ id: row.id, name }); } this.loaded = true; } private remember(key: string, personId: string, name: string): void { this.active.push({ id: personId, name }); if (!key) return; this.byName.set(key, [...(this.byName.get(key) ?? []), personId]); if (!this.createdByName.has(key)) this.createdByName.set(key, personId); } } // ── run.rs: one asset, decided ─────────────────────────────────────────── export type AssetOutcome = | { outcome: "imported"; recordId: string } | { outcome: "merged"; recordId: string } | { outcome: "already"; recordId: string } | { outcome: "unsupported"; uti: string } | { outcome: "notDownloaded" } | { outcome: "removed" } | { outcome: "unlocatable"; reason: string }; export interface AssetWrites { changes: Change[]; unknownSubtype: number | null; labelsFromIndex: boolean; } export interface AssetArgs { databaseId: string; /** What R2 holds under each media key the page names: its size, or null when it holds nothing. */ sizes: ReadonlyMap; now: string; } /** The media key an asset's original was PUT under, or null when it cannot have one. */ export function originalKeyOf(databaseId: string, asset: PhotoAsset): string | null { const format = formatFor(asset.row.uti); return format && asset.sha256 ? mediaKeyOf(databaseId, format, asset.sha256) : null; } /** Decide one asset. Reads the object; writes nothing. */ export function planAsset(db: PhotoReader, asset: PhotoAsset, args: AssetArgs): { outcome: AssetOutcome; writes: AssetWrites } { const row = asset.row; const noType = row.uti ?? "(no type)"; const nothing: AssetWrites = { changes: [], unknownSubtype: null, labelsFromIndex: false }; // 1. THE FORMAT, and a ZKIND that agrees with it. const format = formatFor(row.uti); if (!format) return { outcome: { outcome: "unsupported", uti: noType }, writes: nothing }; if ((row.kind === 1) !== (format.kind === "video")) return { outcome: { outcome: "unsupported", uti: noType }, writes: nothing }; const writes: AssetWrites = { changes: [], unknownSubtype: subtypesOf(row).unknownSubtype, labelsFromIndex: asset.place.labels.length > 0 }; // 2. WHERE THE ORIGINAL IS. const original = originalPathOf(row.directory, row.filename, row.savedAssetType); if ("unknown" in original) return { outcome: { outcome: "unlocatable", reason: original.unknown }, writes }; // 3. WHETHER ITS BYTES ARE HERE — the Mac hashed and PUT them, or it had none. const key = asset.sha256 ? mediaKeyOf(args.databaseId, format, asset.sha256) : null; const sizeBytes = key ? (args.sizes.get(key) ?? null) : null; if (key === null || sizeBytes === null) return { outcome: { outcome: "notDownloaded" }, writes }; const sha256 = asset.sha256!; const limits = MEDIA_LIMITS[format.kind]; if (!limits.contentTypes.includes(format.contentType)) return { outcome: { outcome: "unsupported", uti: row.uti ?? "" }, writes }; if (sizeBytes > limits.maxBytes) return { outcome: { outcome: "unsupported", uti: `${noType} (over the size limit)` }, writes }; const enrichment = enrichmentOf(row, asset.place); const takenAt = appleDateToIso(row.dateCreated) ?? args.now; const kind = format.kind; // 4. THE SIGHTING PROBE: an asset already held re-writes Apple's knowledge of it and nothing else. const sighted = db.sightingRecord(row.uuid); if (sighted !== null) { const held = db.record(kind, sighted); // The owner removed the picture its sighting names: it stays removed. if (held === "gone") return { outcome: { outcome: "removed" }, writes }; if (held === "live") { writes.changes.push(enrichmentChange(kind, sighted, enrichment, args.now)); return { outcome: { outcome: "already", recordId: sighted }, writes }; } } // 5. A PICTURE THE OWNER REMOVED stays removed. const recordId = kind === "video" ? videoRecordId(sha256) : photoRecordId(sha256); const held = db.record(kind, recordId); if (held === "gone") return { outcome: { outcome: "removed" }, writes }; // 6. THE ROWS: one change per row — a record already here takes the enrichment alone. const met = held === "live"; writes.changes.push( met ? enrichmentChange(kind, recordId, enrichment, args.now) : upsert(kind, recordId, { id: recordId, key, sha256, content_type: format.contentType, size_bytes: sizeBytes, // A zero is not a width: Apple writes one for an asset it has not measured. width: row.width != null && row.width > 0 ? row.width : null, height: row.height != null && row.height > 0 ? row.height : null, taken_at: takenAt, caption: captionOf(row), created_at: args.now, ...enrichmentPatch(enrichment, args.now), }), ); const sightingId = mediaSightingId(kind, recordId, "apple_library", row.uuid); writes.changes.push( upsert("sighting", sightingId, { id: sightingId, record_kind: kind, record_id: recordId, source: "apple_library", source_id: row.uuid, key, seen_at: takenAt, created_at: args.now, updated_at: args.now, }), ); return { outcome: met ? { outcome: "merged", recordId } : { outcome: "imported", recordId }, writes }; } /** The columns a picture knows about itself, re-written on every run; `phash` belongs to the analyze worker. */ function enrichmentPatch(e: Enrichment, now: string): Record { return { ...e, subtypes: [...e.subtypes], labels: [...e.labels], updated_at: now }; } /** * A picture already held takes what Apple learned about it, but never its * star: Apple's favourite is where a new picture starts, and once it is here * the star is the person's, set or taken on the phone, and a later run of the * Mac's library never sets it back. */ function enrichmentChange(kind: "photo" | "video", recordId: string, e: Enrichment, now: string): Change { const { favourite: _apples, ...learned } = enrichmentPatch(e, now); return upsert(kind, recordId, { id: recordId, ...learned }); } /** * One face: evidence, so a face whose cluster nobody named lands anyway, * pointing at no one. A face in the bin or hidden is the person's own answer * and is not written; a face with no area is dropped. */ export function faceChanges(recordKind: "photo" | "video", recordId: string, face: AppleFaceRow, clusterUuid: string | null, personId: string | null, now: string): Change[] { if (face.isInTrash === 1 || face.hidden === 1) return []; const box = faceBoxOf(face.centerX, face.centerY, face.size); if (!box) return []; const id = mediaFaceId(recordKind, recordId, "apple", face.uuid); return [ upsert("face", id, { id, record_kind: recordKind, record_id: recordId, source: "apple", source_id: face.uuid, x: box.x, y: box.y, w: box.w, h: box.h, quality: faceQualityOf(face.quality), cluster_id: clusterUuid, person_id: personId, created_at: now, updated_at: now, }), ]; } /** Keep the FIRST change for each row: two faces of one person, or two assets of the same bytes, reach one row twice. */ export function onePerRow(changes: Change[]): Change[] { const seen = new Set(); return changes.filter((c) => { const key = `${c.table}\u0000${c.id}`; if (seen.has(key)) return false; seen.add(key); return true; }); } // ── apply.rs: one page ─────────────────────────────────────────────────── export interface PhotosPlan { changes: Change[]; /** Assets that produced a record (imported or merged), by kind. */ written: { photo: number; video: number }; /** Assets already held, or removed by the owner. */ skipped: number; /** The Rust run's counts, under its own keys. */ notes: Record; } export function planPhotos(db: PhotoReader, work: PhotoWork, args: AssetArgs & { newPersonId: () => string }): PhotosPlan { const resolver = new PersonResolver(db, args.newPersonId, args.now); const notes: Record = {}; const count = (key: string): void => { notes[key] = (notes[key] ?? 0) + 1; }; const written = { photo: 0, video: 0 }; let skipped = 0; const changes: Change[] = []; for (const asset of work.assets) { const { outcome, writes } = planAsset(db, asset, args); if (writes.unknownSubtype !== null) count("read:photosUnknownSubtype"); if (writes.labelsFromIndex) count("read:photosLabelled"); changes.push(...writes.changes); const kind = asset.row.kind === 1 ? "video" : "photo"; let recordId: string | null = null; switch (outcome.outcome) { case "imported": written[kind]++; count("read:photosImported"); recordId = outcome.recordId; break; case "merged": written[kind]++; count("read:photosMerged"); recordId = outcome.recordId; break; case "already": skipped++; count("read:photosAlready"); recordId = outcome.recordId; break; case "unsupported": count(`unsupported:${outcome.uti}`); break; case "removed": skipped++; count("read:photosRemoved"); break; case "notDownloaded": count("notDownloaded"); break; case "unlocatable": count(`unlocatable:${outcome.reason}`); break; } if (recordId === null) continue; for (const face of asset.faces) { const cluster = face.personUuid != null && Object.hasOwn(work.clusters, face.personUuid) ? work.clusters[face.personUuid]! : null; let personId: string | null = null; let clusterUuid: string | null = null; if (cluster) { const { resolution, changes: decided } = resolver.resolve(cluster.person, cluster.contactIdentifier); count(`read:photosPerson:${resolution.how}`); changes.push(...decided); personId = resolvedPerson(resolution); clusterUuid = cluster.person.uuid; } changes.push(...faceChanges(kind, recordId, face, clusterUuid, personId, args.now)); } } return { changes: onePerRow(changes), written, skipped, notes }; }