Cotton code
568 lines · 23.4 KB · RustRaw
//! The Apple Photos library, decided on the Mac (sealing plan L8): what the//! Worker's `/v1/import/photos` decided (apps/business/src/import/photos.ts,//! `planPhotos`), run over the importer's own copy with the same rules in the//! same order, so a sealed `person`, `person_handle`,//! `photo`, `video`, `face` or `sighting` table costs the decision nothing and//! the object never reads a picture's words.//!//! The Mac read the library, hashed each original and put its bytes under//! `<database id>/photos/<sha256>.<ext>` (a video under `videos/`) before it//! plans, so "is the original really there, and how big is it" is what the//! put answered: no `HEAD`. Then, per asset, in the Worker'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 is "not downloaded", counted,//!    never a failure) and inside the media limits;//! 4. the sighting probe: an asset the copy 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//!    (the "same as?" questions a new person raised went with the//!    `person_suggestion` table, TABLE DROP 1).//!//! Every read is of the copy as it stood when the page began: the whole page//! is planned, then landed, and the first change for a row wins.use std::collections::{BTreeMap, HashMap};use cotton_client::ingest::sources::photos::apple::{    apple_date_to_iso, caption_of, enrichment_of, face_box_of, face_quality_of, format_for, original_path_of, person_name_of, subtypes_of,    AppleFaceRow, AppleFormat, ApplePersonRow, Enrichment, MediaKind, OriginalPath,};use cotton_client::ingest::sources::photos::{PhotoAsset, PhotoWork};use cotton_client::ingest::IngestNotes;use cotton_store::protocol::derived_id::{media_face_id, media_sighting_id, photo_record_id, video_record_id};use serde_json::{json, Map, Value};use crate::copy::{Change, Landing, Result};/// `cotton_core::media::keys::media_limits` for a photo: the most bytes, the types admitted.const PHOTO_LIMITS: (u64, &[&str]) = (52_428_800, &["image/jpeg", "image/png", "image/webp", "image/heic", "image/gif"]);/// … and for a video.const VIDEO_LIMITS: (u64, &[&str]) = (524_288_000, &["video/mp4", "video/quicktime", "image/jpeg"]);fn kind_name(kind: MediaKind) -> &'static str {    match kind {        MediaKind::Photo => "photo",        MediaKind::Video => "video",    }}/// `photo_key` / `video_key`: `<database id>/photos/<sha256>.<ext>` or `…/videos/…`.pub fn media_key_of(database_id: &str, format: &AppleFormat, sha256: &str) -> String {    let folder = match format.kind {        MediaKind::Photo => "photos",        MediaKind::Video => "videos",    };    format!("{database_id}/{folder}/{sha256}.{}", format.ext)}/// The media key an asset's original is put under, or `None` when it cannot have one.pub fn original_key_of(database_id: &str, asset: &PhotoAsset) -> Option<String> {    let format = format_for(asset.row.uti.as_deref())?;    asset.sha256.as_deref().map(|sha| media_key_of(database_id, &format, sha))}/// Case- and whitespace-insensitive, for the name rule that ASSIGNS: the/// Worker's `collapse(name).toLowerCase()`.pub fn normalise_name(name: &str) -> String {    cotton_rules::js::collapse_whitespace_and_trim(name).to_lowercase()}fn upsert(table: &str, id: &str, patch: Value) -> Change {    Change { table: table.to_string(), id: id.to_string(), patch: Some(patch.as_object().cloned().unwrap_or_default()) }}// ── people: Apple's face clusters → Cotton's people ─────────────────────────/// `person_source.kind` for a person in Apple Photos; its id there is the cluster's uuid, the same on every Mac.const PHOTOS_SOURCE: &str = "apple_photos";/// The `person_source` row keeping that `person` is this Photos person: its id derived from the source alone, so a/// re-read writes the same row, and a row already held keeps the person it points at (a merge may have moved it).fn source_change(namespace: &str, person: &str, cluster: &ApplePersonRow, now: &str) -> Change {    let id = cotton_rules::ids::person_source_id(namespace, PHOTOS_SOURCE, "", &cluster.uuid);    upsert(        "person_source",        &id,        json!({            "id": id,            "person": person,            "kind": PHOTOS_SOURCE,            "device": "",            "source_id": cluster.uuid,            "name": person_name_of(cluster.full_name.as_deref(), cluster.display_name.as_deref()),            "first_seen": now,            "created_at": now,            "updated_at": now,        }),    )}/// Who a cluster is, and how that was decided.#[derive(Debug, Clone, PartialEq)]pub enum Resolution {    /// The contact this Photos person was kept under before (`person_source`).    BySource(String),    Existing(String),    ByContact(String),    ByName(String),    Created { person_id: String },    Ambiguous { person_id: String, reason: String },    Unnamed,}impl Resolution {    /// The note's own name for the rule that answered (`read:photosPerson:<how>`).    pub fn how(&self) -> &'static str {        match self {            Resolution::BySource(_) => "bySource",            Resolution::Existing(_) => "existing",            Resolution::ByContact(_) => "byContact",            Resolution::ByName(_) => "byName",            Resolution::Created { .. } => "created",            Resolution::Ambiguous { .. } => "ambiguous",            Resolution::Unnamed => "unnamed",        }    }    pub fn person(&self) -> Option<&str> {        match self {            Resolution::BySource(id) | Resolution::Existing(id) | Resolution::ByContact(id) | Resolution::ByName(id) => Some(id),            Resolution::Created { person_id, .. } | Resolution::Ambiguous { person_id, .. } => Some(person_id),            Resolution::Unnamed => None,        }    }}/// 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/// contact this Photos person was kept under before (`person_source`, so a/// renamed or merged contact is found again), the faces' own answer (the/// majority), the Contacts card Photos matched,/// exactly one active person with that name; otherwise the person is created. Memoised per cluster; a person this page/// created answers every later cluster with the same name.pub struct PersonResolver<'n> {    decided: HashMap<String, Resolution>,    by_name: HashMap<String, Vec<String>>,    created_by_name: HashMap<String, String>,    loaded: bool,    new_person_id: &'n mut dyn FnMut() -> String,    now: String,    /// What `person_source` ids are made under; None while the object has no such table.    sources: Option<String>,}impl<'n> PersonResolver<'n> {    pub fn new(new_person_id: &'n mut dyn FnMut() -> String, now: &str) -> PersonResolver<'n> {        PersonResolver {            decided: HashMap::new(),            by_name: HashMap::new(),            created_by_name: HashMap::new(),            loaded: false,            new_person_id,            now: now.to_string(),            sources: None,        }    }    /// Keep and read where each person came from (`person_source`), its ids made under `namespace`.    pub fn with_sources(mut self, namespace: String) -> Self {        self.sources = Some(namespace);        self    }    pub fn resolve(&mut self, landing: &Landing<'_>, cluster: &ApplePersonRow, contact_identifier: Option<&str>) -> Result<(Resolution, Vec<Change>)> {        if let Some(known) = self.decided.get(&cluster.uuid) {            return Ok((known.clone(), Vec::new()));        }        let (resolution, mut changes) = self.decide(landing, cluster, contact_identifier)?;        if let (Some(namespace), Some(person)) = (&self.sources, resolution.person()) {            if !matches!(resolution, Resolution::BySource(_)) {                changes.push(source_change(namespace, person, cluster, &self.now));            }        }        self.decided.insert(cluster.uuid.clone(), resolution.clone());        Ok((resolution, changes))    }    fn decide(&mut self, landing: &Landing<'_>, cluster: &ApplePersonRow, contact_identifier: Option<&str>) -> Result<(Resolution, Vec<Change>)> {        let Some(name) = person_name_of(cluster.full_name.as_deref(), cluster.display_name.as_deref()) else {            return Ok((Resolution::Unnamed, Vec::new()));        };        if self.sources.is_some() {            if let Some(person) = landing.person_by_source(PHOTOS_SOURCE, "", &cluster.uuid)? {                return Ok((Resolution::BySource(person), Vec::new()));            }        }        if let Some(majority) = landing.cluster_majority_person(&cluster.uuid)? {            return Ok((Resolution::Existing(majority), Vec::new()));        }        self.load(landing)?;        if let Some(card) = contact_identifier.filter(|c| !c.is_empty()) {            if let Some(person) = landing.person_by_device_contact(card)? {                return Ok((Resolution::ByContact(person), Vec::new()));            }        }        let key = normalise_name(&name);        let same_name = self.by_name.get(&key).cloned().unwrap_or_default();        if same_name.len() == 1 {            return Ok((Resolution::ByName(same_name[0].clone()), Vec::new()));        }        if let Some(mine) = self.created_by_name.get(&key) {            return Ok((Resolution::ByName(mine.clone()), Vec::new()));        }        let person_id = (self.new_person_id)();        let changes = vec![upsert(            "person",            &person_id,            json!({                "id": person_id,                "full_name": name,                "contact_source": "apple_library",                "device_contact_id": contact_identifier,                "created_at": self.now,                "updated_at": self.now,            }),        )];        self.remember(&key, &person_id);        let resolution = if same_name.len() > 1 {            Resolution::Ambiguous {                person_id,                reason: format!("{} people are called \"{name}\" — created", same_name.len()),            }        } else {            Resolution::Created { person_id }        };        Ok((resolution, changes))    }    fn load(&mut self, landing: &Landing<'_>) -> Result<()> {        if self.loaded {            return Ok(());        }        for (id, full_name) in landing.active_people()? {            if id.is_empty() {                continue;            }            let name = full_name.unwrap_or_default();            let key = normalise_name(&name);            if !key.is_empty() {                self.by_name.entry(key).or_default().push(id.clone());            }        }        self.loaded = true;        Ok(())    }    fn remember(&mut self, key: &str, person_id: &str) {        if key.is_empty() {            return;        }        self.by_name.entry(key.to_string()).or_default().push(person_id.to_string());        self.created_by_name.entry(key.to_string()).or_insert_with(|| person_id.to_string());    }}// ── one asset, decided ──────────────────────────────────────────────────────#[derive(Debug, Clone, PartialEq)]pub enum AssetOutcome {    Imported(String),    Merged(String),    Already(String),    Unsupported(String),    NotDownloaded,    Removed,    Unlocatable(String),}#[derive(Debug, Clone, Default, PartialEq)]pub struct AssetWrites {    pub changes: Vec<Change>,    pub unknown_subtype: Option<i64>,    pub labels_from_index: bool,}/// The columns a picture knows about itself, re-written on every run; `phash`/// belongs to the analyze worker.fn enrichment_patch(e: &Enrichment, now: &str) -> Map<String, Value> {    let patch = json!({        "taken_offset": e.taken_offset,        "latitude": e.latitude,        "longitude": e.longitude,        "place_name": e.place_name,        "place_city": e.place_city,        "place_region": e.place_region,        "place_country": e.place_country,        "camera_make": e.camera_make,        "camera_model": e.camera_model,        "orientation": e.orientation,        "favourite": e.favourite,        "subtypes": e.subtypes,        "original_filename": e.original_filename,        "aesthetic_score": e.aesthetic_score,        "curation_score": e.curation_score,        "labels": e.labels,        "updated_at": now,    });    patch.as_object().cloned().unwrap_or_default()}/// 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.fn enrichment_change(kind: &str, record_id: &str, e: &Enrichment, now: &str) -> Change {    let mut patch = Map::new();    patch.insert("id".into(), json!(record_id));    for (key, value) in enrichment_patch(e, now) {        if key != "favourite" {            patch.insert(key, value);        }    }    Change { table: kind.to_string(), id: record_id.to_string(), patch: Some(patch) }}/// Decide one asset over the copy. `sizes` is what the Mac put under each/// media key this page names: the original's own size. Reads; writes nothing.pub fn plan_asset(landing: &Landing<'_>, asset: &PhotoAsset, database_id: &str, sizes: &BTreeMap<String, u64>, now: &str) -> Result<(AssetOutcome, AssetWrites)> {    let row = &asset.row;    let no_type = row.uti.clone().unwrap_or_else(|| "(no type)".to_string());    // 1. THE FORMAT, and a ZKIND that agrees with it.    let Some(format) = format_for(row.uti.as_deref()) else {        return Ok((AssetOutcome::Unsupported(no_type), AssetWrites::default()));    };    if (row.kind == 1) != (format.kind == MediaKind::Video) {        return Ok((AssetOutcome::Unsupported(no_type), AssetWrites::default()));    }    let mut writes = AssetWrites { changes: Vec::new(), unknown_subtype: subtypes_of(row).unknown_subtype, labels_from_index: !asset.place.labels.is_empty() };    // 2. WHERE THE ORIGINAL IS.    if let OriginalPath::Unknown(reason) = original_path_of(row.directory.as_deref(), row.filename.as_deref(), row.saved_asset_type) {        return Ok((AssetOutcome::Unlocatable(reason), writes));    }    // 3. WHETHER ITS BYTES ARE HERE: the Mac hashed and put them, or it had none.    let sha256 = asset.sha256.as_deref().filter(|s| !s.is_empty());    let key = sha256.map(|sha| media_key_of(database_id, &format, sha));    let (Some(sha256), Some(key), Some(size_bytes)) = (sha256, key.clone(), key.as_ref().and_then(|k| sizes.get(k)).copied()) else {        return Ok((AssetOutcome::NotDownloaded, writes));    };    let (max_bytes, content_types) = match format.kind {        MediaKind::Photo => PHOTO_LIMITS,        MediaKind::Video => VIDEO_LIMITS,    };    if !content_types.contains(&format.content_type) {        return Ok((AssetOutcome::Unsupported(row.uti.clone().unwrap_or_default()), writes));    }    if size_bytes > max_bytes {        return Ok((AssetOutcome::Unsupported(format!("{no_type} (over the size limit)")), writes));    }    let enrichment = enrichment_of(row, &asset.place);    let taken_at = apple_date_to_iso(row.date_created).unwrap_or_else(|| now.to_string());    let kind = kind_name(format.kind);    // 4. THE SIGHTING PROBE: an asset already held re-writes Apple's knowledge of it and nothing else.    if let Some(sighted) = landing.apple_sighting_record(&row.uuid)? {        match landing.held_state(kind, &sighted)? {            // The owner removed the picture its sighting names: it stays removed.            Some(true) => return Ok((AssetOutcome::Removed, writes)),            Some(false) => {                writes.changes.push(enrichment_change(kind, &sighted, &enrichment, now));                return Ok((AssetOutcome::Already(sighted), writes));            }            None => {}        }    }    // 5. A PICTURE THE OWNER REMOVED stays removed.    let record_id = match format.kind {        MediaKind::Video => video_record_id(sha256),        MediaKind::Photo => photo_record_id(sha256),    };    let held = landing.held_state(kind, &record_id)?;    if held == Some(true) {        return Ok((AssetOutcome::Removed, writes));    }    // 6. THE ROWS: one change per row; a record already here takes the enrichment alone.    let met = held == Some(false);    if met {        writes.changes.push(enrichment_change(kind, &record_id, &enrichment, now));    } else {        let mut patch = json!({            "id": record_id,            "key": key,            "sha256": sha256,            "content_type": format.content_type,            "size_bytes": size_bytes,            // A zero is not a width: Apple writes one for an asset it has not measured.            "width": row.width.filter(|w| *w > 0),            "height": row.height.filter(|h| *h > 0),            "taken_at": taken_at,            "caption": caption_of(row),            "created_at": now,        });        let fields = patch.as_object_mut().expect("an object");        fields.extend(enrichment_patch(&enrichment, now));        writes.changes.push(upsert(kind, &record_id, patch));    }    let sighting_id = media_sighting_id(kind, &record_id, "apple_library", Some(&row.uuid));    writes.changes.push(upsert(        "sighting",        &sighting_id,        json!({            "id": sighting_id,            "record_kind": kind,            "record_id": record_id,            "source": "apple_library",            "source_id": row.uuid,            "key": key,            "seen_at": taken_at,            "created_at": now,            "updated_at": now,        }),    ));    let outcome = if met { AssetOutcome::Merged(record_id) } else { AssetOutcome::Imported(record_id) };    Ok((outcome, writes))}/// 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.pub fn face_changes(record_kind: &str, record_id: &str, face: &AppleFaceRow, cluster_uuid: Option<&str>, person_id: Option<&str>, now: &str) -> Vec<Change> {    if face.is_in_trash == Some(1) || face.hidden == Some(1) {        return Vec::new();    }    let Some(face_box) = face_box_of(face.center_x, face.center_y, face.size) else {        return Vec::new();    };    let id = media_face_id(record_kind, record_id, "apple", &face.uuid);    vec![upsert(        "face",        &id,        json!({            "id": id,            "record_kind": record_kind,            "record_id": record_id,            "source": "apple",            "source_id": face.uuid,            "x": face_box.x,            "y": face_box.y,            "w": face_box.w,            "h": face_box.h,            "quality": face_quality_of(face.quality),            "cluster_id": cluster_uuid,            "person_id": person_id,            "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.pub fn one_per_row(changes: Vec<Change>) -> Vec<Change> {    let mut seen = std::collections::HashSet::new();    changes.into_iter().filter(|c| seen.insert((c.table.clone(), c.id.clone()))).collect()}// ── one page ────────────────────────────────────────────────────────────────#[derive(Debug, Clone, Default, PartialEq)]pub struct PhotosPlan {    pub changes: Vec<Change>,    /// Assets that produced a record (imported or merged): photos, videos.    pub written_photos: i64,    pub written_videos: i64,    /// Assets already held, or removed by the owner.    pub skipped: i64,    /// The run's counts, under the Worker's keys.    pub notes: IngestNotes,}/// Plan one page over `landing`'s copy. `sizes` is each put original's size by/// its media key; `new_person_id` makes a new person's id.pub fn plan_photos(landing: &Landing<'_>, work: &PhotoWork, database_id: &str, sizes: &BTreeMap<String, u64>, now: &str, new_person_id: &mut dyn FnMut() -> String) -> Result<PhotosPlan> {    let mut resolver = PersonResolver::new(new_person_id, now);    if landing.defines("person_source") {        resolver = resolver.with_sources(landing.namespace_for(&["person_source"])?);    }    let mut plan = PhotosPlan::default();    let mut changes: Vec<Change> = Vec::new();    let count = |notes: &mut IngestNotes, key: &str| *notes.entry(key.to_string()).or_insert(0) += 1;    for asset in &work.assets {        let (outcome, writes) = plan_asset(landing, asset, database_id, sizes, now)?;        if writes.unknown_subtype.is_some() {            count(&mut plan.notes, "read:photosUnknownSubtype");        }        if writes.labels_from_index {            count(&mut plan.notes, "read:photosLabelled");        }        changes.extend(writes.changes);        let video = asset.row.kind == 1;        let kind = if video { "video" } else { "photo" };        let note = match &outcome {            AssetOutcome::Merged(_) => "read:photosMerged",            _ => "read:photosImported",        };        let record_id = match outcome {            AssetOutcome::Imported(id) | AssetOutcome::Merged(id) => {                count(&mut plan.notes, note);                if video {                    plan.written_videos += 1;                } else {                    plan.written_photos += 1;                }                Some(id)            }            AssetOutcome::Already(id) => {                plan.skipped += 1;                count(&mut plan.notes, "read:photosAlready");                Some(id)            }            AssetOutcome::Unsupported(uti) => {                count(&mut plan.notes, &format!("unsupported:{uti}"));                None            }            AssetOutcome::Removed => {                plan.skipped += 1;                count(&mut plan.notes, "read:photosRemoved");                None            }            AssetOutcome::NotDownloaded => {                count(&mut plan.notes, "notDownloaded");                None            }            AssetOutcome::Unlocatable(reason) => {                count(&mut plan.notes, &format!("unlocatable:{reason}"));                None            }        };        let Some(record_id) = record_id else { continue };        for face in &asset.faces {            let cluster = face.person_uuid.as_ref().and_then(|uuid| work.clusters.get(uuid));            let (mut person_id, mut cluster_uuid) = (None, None);            if let Some(cluster) = cluster {                let (resolution, decided) = resolver.resolve(landing, &cluster.person, cluster.contact_identifier.as_deref())?;                count(&mut plan.notes, &format!("read:photosPerson:{}", resolution.how()));                changes.extend(decided);                person_id = resolution.person().map(str::to_string);                cluster_uuid = Some(cluster.person.uuid.clone());            }            changes.extend(face_changes(kind, &record_id, face, cluster_uuid.as_deref(), person_id.as_deref(), now));        }    }    plan.changes = one_per_row(changes);    Ok(plan)}