Cotton code
668 lines · 22.3 KB · RustRaw
//! What Apple's Photos database MEANS, as pure functions.//!//! Every mapping here is a MEASUREMENT, taken on a copy of a real library on//! 2026-09-05, not a reading of a README: the subtype codes, the epoch, the//! `-180` sentinel, the face coordinate space, the directory shapes. Nothing in//! this file opens a database, touches the filesystem or knows about a store —//! it turns Apple's rows into Cotton's inputs, and the tests beside it are the//! whole of what it promises.//!//! The port's rule: where the TypeScript measured something, the number travels//! unchanged. A measurement re-derived is a measurement re-guessed.use std::collections::BTreeSet;use serde::{Deserialize, Serialize};// ------------------------------------------------------------------ the band/// One `PLModelVersion` × `LibrarySchemaVersion` pair this reader was tested on.#[derive(Debug, Clone, Copy, PartialEq, Eq)]pub struct Band {    pub model_low: i64,    pub model_high: i64,    pub schema: i64,    pub photos: &'static str,}/// The pairs this reader was tested on.////// osxphotos's `_PHOTOS_11_1_MODEL_VERSION`; the Mac this was measured on/// (macOS 26.6) reads 19607 / 5001.////// macOS 27.0 is admitted from `pnpm photos:measure` on another Mac: 270010300 //// 5001, and every statement the reader runs (assets, count, faces, people,/// contact match) prepares. That library had no search index, which the reader/// already reads as none. The band is that one model version, nothing either side.pub const TESTED_BANDS: &[Band] = &[    Band {        model_low: 19320,        model_high: 19999,        schema: 5001,        photos: "Photos 11.1",    },    Band {        model_low: 270_010_300,        model_high: 270_010_300,        schema: 5001,        photos: "Photos on macOS 27.0",    },];/// REFUSE a library this reader has not been tested on, with the numbers in the/// sentence.////// Guessing across a band is how a person's faces end up on the wrong pictures.pub fn check_band(model_version: i64, library_schema_version: i64) -> Result<&'static str, String> {    for band in TESTED_BANDS {        if model_version >= band.model_low            && model_version <= band.model_high            && library_schema_version == band.schema        {            return Ok(band.photos);        }    }    let newest = TESTED_BANDS        .last()        .expect("the band table is never empty — a reader with no tested band could read nothing");    Err(format!(        "This Photos library is model version {model_version} (library schema \         {library_schema_version}); Cotton has been tested up to {} ({}–{}, schema {}). \         Nothing was imported.",        newest.photos, newest.model_low, newest.model_high, newest.schema    ))}/// `PLModelVersion` out of `Z_METADATA.Z_PLIST`, once it is XML.pub fn model_version_from_plist_xml(xml: &str) -> Option<i64> {    integer_after_key(xml, "PLModelVersion")}/// `LibrarySchemaVersion` out of `database/DataModelVersion.plist`.pub fn library_schema_version_from_plist_xml(xml: &str) -> Option<i64> {    integer_after_key(xml, "LibrarySchemaVersion")}/// `<key>NAME</key> … <integer>N</integer>`, whitespace between them.////// A hand-written scan rather than a regex crate: it is two tags, and the/// alternative is a dependency for one lookup.fn integer_after_key(xml: &str, key: &str) -> Option<i64> {    let needle = format!("<key>{key}</key>");    let after = &xml[xml.find(&needle)? + needle.len()..];    let rest = after.trim_start();    let rest = rest.strip_prefix("<integer>")?;    let end = rest.find("</integer>")?;    rest[..end].trim().parse().ok()}// ------------------------------------------------------------------ time/// Core Data's epoch: seconds since 2001-01-01T00:00:00Z.pub const APPLE_EPOCH_MS: i64 = 978_307_200_000;/// Apple's seconds → an ISO-8601 UTC instant, or `None` when there is none.pub fn apple_date_to_iso(seconds: Option<f64>) -> Option<String> {    let seconds = seconds?;    if !seconds.is_finite() {        return None;    }    let millis = APPLE_EPOCH_MS + (seconds * 1000.0).round() as i64;    let moment = chrono::DateTime::from_timestamp_millis(millis)?;    Some(moment.format("%Y-%m-%dT%H:%M:%S%.3fZ").to_string())}// ------------------------------------------------------------------ formats#[derive(Debug, Clone, Copy, PartialEq, Eq)]pub struct AppleFormat {    pub content_type: &'static str,    /// Without the dot.    pub ext: &'static str,    pub kind: MediaKind,}#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]#[serde(rename_all = "lowercase")]pub enum MediaKind {    Photo,    Video,}/// Uniform type identifier → what Cotton stores it as.////// A UTI outside this table is `skippedUnsupported` in the report, listed by/// type, NEVER guessed: `public.tiff` and `public.jpeg-2000` are the two the/// measured library holds that the media limits do not admit.pub fn format_for(uti: Option<&str>) -> Option<AppleFormat> {    let uti = uti?;    let format = match uti {        "public.heic" => AppleFormat {            content_type: "image/heic",            ext: "heic",            kind: MediaKind::Photo,        },        "public.jpeg" => AppleFormat {            content_type: "image/jpeg",            ext: "jpg",            kind: MediaKind::Photo,        },        "public.png" => AppleFormat {            content_type: "image/png",            ext: "png",            kind: MediaKind::Photo,        },        "org.webmproject.webp" => AppleFormat {            content_type: "image/webp",            ext: "webp",            kind: MediaKind::Photo,        },        "com.compuserve.gif" => AppleFormat {            content_type: "image/gif",            ext: "gif",            kind: MediaKind::Photo,        },        "com.apple.quicktime-movie" => AppleFormat {            content_type: "video/quicktime",            ext: "mov",            kind: MediaKind::Video,        },        "public.mpeg-4" => AppleFormat {            content_type: "video/mp4",            ext: "mp4",            kind: MediaKind::Video,        },        _ => return None,    };    Some(format)}// ------------------------------------------------------------- the asset row/// The columns the reader selects — one row per asset, attributes joined.#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]#[serde(rename_all = "camelCase")]pub struct AppleAssetRow {    pub pk: i64,    pub uuid: String,    /// 0 photo, 1 video.    pub kind: i64,    pub kind_subtype: Option<i64>,    pub uti: Option<String>,    pub directory: Option<String>,    pub filename: Option<String>,    /// 4 = iCloud shared library, 6 = the library's own, 10 = a referenced file.    pub saved_asset_type: Option<i64>,    /// Core Data seconds.    pub date_created: Option<f64>,    /// Seconds east of UTC.    pub timezone_offset: Option<i64>,    pub latitude: Option<f64>,    pub longitude: Option<f64>,    /// DISPLAYED (already-rotated) dimensions.    pub width: Option<i64>,    pub height: Option<i64>,    /// EXIF 1–8.    pub orientation: Option<i64>,    pub favorite: Option<i64>,    pub hdr_type: Option<i64>,    pub depth_type: Option<i64>,    pub adjustments_state: Option<i64>,    pub avalanche_uuid: Option<String>,    pub is_detected_screenshot: Option<i64>,    pub camera_capture_device: Option<i64>,    pub camera_make: Option<String>,    pub camera_model: Option<String>,    pub original_filename: Option<String>,    /// 0.5 everywhere on a Mac that has not analysed — the unanalysed default.    pub overall_aesthetic_score: Option<f64>,    pub curation_score: Option<f64>,    pub scene_analysis_version: Option<i64>,    pub title: Option<String>,    pub long_description: Option<String>,}/// The subtypes `cotton_photos.subtypes` admits, in the order core declares/// them.pub const PHOTO_SUBTYPES: [&str; 11] = [    "screenshot",    "selfie",    "burst",    "live",    "hdr",    "panorama",    "portrait",    "edited",    "slow_motion",    "time_lapse",    "screen_recording",];/// A `ZKINDSUBTYPE` the table names.fn named_subtype(code: i64) -> Option<&'static str> {    match code {        1 => Some("panorama"),        2 => Some("live"),        10 => Some("screenshot"),        101 => Some("slow_motion"),        102 => Some("time_lapse"),        103 => Some("screen_recording"),        _ => None,    }}#[derive(Debug, Clone, PartialEq, Eq, Default)]pub struct SubtypeReading {    pub subtypes: Vec<String>,    /// A `ZKINDSUBTYPE` the table does not name — COUNTED, never guessed.    pub unknown_subtype: Option<i64>,}/// Everything a row says about what KIND of picture it is.////// The order is the order the FLAGS are read, and it is fixed — two runs over/// the same row write the same array, because an array that reordered itself is/// a change nobody made and it would sync as one.pub fn subtypes_of(row: &AppleAssetRow) -> SubtypeReading {    let mut found: Vec<&'static str> = Vec::new();    let mut seen: BTreeSet<&'static str> = BTreeSet::new();    let mut add = |name: &'static str| {        if seen.insert(name) {            found.push(name);        }    };    let mut unknown_subtype = None;    let code = row.kind_subtype.unwrap_or(0);    if code != 0 {        match named_subtype(code) {            Some(name) => add(name),            None => unknown_subtype = Some(code),        }    }    if row.is_detected_screenshot == Some(1) {        add("screenshot");    }    if row.camera_capture_device == Some(1) {        add("selfie");    }    if row        .avalanche_uuid        .as_deref()        .is_some_and(|id| !id.is_empty())    {        add("burst");    }    if row.hdr_type.unwrap_or(0) > 0 {        add("hdr");    }    if row.depth_type == Some(1) {        add("portrait");    }    if row.adjustments_state.unwrap_or(0) > 0 {        add("edited");    }    SubtypeReading {        subtypes: found.into_iter().map(str::to_string).collect(),        unknown_subtype,    }}/// Apple writes `-180` for "no location" (23,574 of 41,077 rows in the measured/// library).pub fn coordinate_of(value: Option<f64>) -> Option<f64> {    let value = value?;    if !value.is_finite() || value == -180.0 {        return None;    }    Some(value)}/// A place, as the search index names it.////// Every field optional, because on a Mac that has not run analysis the index/// is empty and every asset imports with no place at all.#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]#[serde(rename_all = "camelCase")]pub struct PlaceReading {    pub name: Option<String>,    pub city: Option<String>,    pub region: Option<String>,    pub country: Option<String>,    pub labels: Vec<String>,}/// The enrichment for one asset — what `cotton_photos` / `cotton_videos` learn/// about themselves from the library.#[derive(Debug, Clone, Default, PartialEq)]pub struct Enrichment {    pub taken_offset: Option<i64>,    pub latitude: Option<f64>,    pub longitude: Option<f64>,    pub place_name: Option<String>,    pub place_city: Option<String>,    pub place_region: Option<String>,    pub place_country: Option<String>,    pub camera_make: Option<String>,    pub camera_model: Option<String>,    pub orientation: Option<i64>,    pub favourite: bool,    pub subtypes: Vec<String>,    pub original_filename: Option<String>,    pub aesthetic_score: Option<f64>,    pub curation_score: Option<f64>,    pub labels: Vec<String>,}/// The enrichment input for one asset.////// Scores are written ONLY when analysis has actually run on this Mac: an/// unanalysed row carries Apple's 0.5 placeholder, and a placeholder is not a/// score.pub fn enrichment_of(row: &AppleAssetRow, place: &PlaceReading) -> Enrichment {    let analysed = row.scene_analysis_version.unwrap_or(0) > 0;    let latitude = coordinate_of(row.latitude);    let longitude = coordinate_of(row.longitude);    // Both or neither: half a coordinate is a point in the sea.    let both = latitude.is_some() && longitude.is_some();    Enrichment {        taken_offset: row.timezone_offset,        latitude: if both { latitude } else { None },        longitude: if both { longitude } else { None },        place_name: place.name.clone(),        place_city: place.city.clone(),        place_region: place.region.clone(),        place_country: place.country.clone(),        camera_make: row.camera_make.clone(),        camera_model: row.camera_model.clone(),        orientation: row.orientation.filter(|value| (1..=8).contains(value)),        favourite: row.favorite == Some(1),        subtypes: subtypes_of(row).subtypes,        original_filename: row.original_filename.clone(),        aesthetic_score: if analysed {            row.overall_aesthetic_score.map(clamp_score)        } else {            None        },        curation_score: if analysed {            row.curation_score.map(clamp_score)        } else {            None        },        labels: place.labels.clone(),    }}fn clamp_score(value: f64) -> f64 {    value.clamp(-1.0, 1.0)}/// What the person typed in Photos — a caption for the row, when there is one.pub fn caption_of(row: &AppleAssetRow) -> Option<String> {    let parts: Vec<&str> = [row.title.as_deref(), row.long_description.as_deref()]        .into_iter()        .flatten()        .map(str::trim)        .filter(|part| !part.is_empty())        .collect();    if parts.is_empty() {        None    } else {        Some(parts.join(" — "))    }}// ------------------------------------------------------------------ files/// Where the original lives.#[derive(Debug, Clone, PartialEq, Eq)]pub enum OriginalPath {    /// Relative to the library.    Library(String),    /// Relative to the library, inside a shared scope.    Shared(String),    /// Somewhere else on this Mac entirely.    Referenced(String),    /// Nothing this reader recognises. The reason is counted, never guessed.    Unknown(String),}/// `originals/<X>/<file>` for a one-character `ZDIRECTORY`,/// `scopes/cloudsharing/data/<scope>/<uuid>/<file>` for a shared-library asset,/// and the absolute path of a referenced file.////// Whether it is THERE is a `stat` — the database's opinion is not trusted.pub fn original_path_of(    directory: Option<&str>,    filename: Option<&str>,    saved_asset_type: Option<i64>,) -> OriginalPath {    let directory = directory.unwrap_or("");    let filename = filename.unwrap_or("");    if filename.is_empty() {        return OriginalPath::Unknown("the asset names no file".to_string());    }    if saved_asset_type == Some(10) {        return if directory.starts_with('/') {            OriginalPath::Referenced(format!("{directory}/{filename}"))        } else {            OriginalPath::Unknown("a referenced file without an absolute directory".to_string())        };    }    if directory.len() == 1 && directory.chars().all(|c| c.is_ascii_hexdigit()) {        return OriginalPath::Library(format!("originals/{directory}/{filename}"));    }    if directory.contains('/') {        return OriginalPath::Shared(format!("scopes/cloudsharing/data/{directory}/{filename}"));    }    OriginalPath::Unknown(format!("an unrecognised directory shape \"{directory}\""))}// ------------------------------------------------------------------ faces#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]#[serde(rename_all = "camelCase")]pub struct AppleFaceRow {    pub uuid: String,    pub asset_pk: i64,    /// Normalised, in the DISPLAYED image, origin BOTTOM-LEFT.    pub center_x: f64,    pub center_y: f64,    /// Normalised HALF-side of the square.    pub size: f64,    /// `-1` = unknown.    pub quality: Option<f64>,    /// `ZPERSON.Z_PK`, or `None` for a face nobody clustered.    pub person_pk: Option<i64>,    pub person_uuid: Option<String>,    pub is_in_trash: Option<i64>,    pub hidden: Option<i64>,}/// Cotton's box: top-left corner, width and height, all normalised.#[derive(Debug, Clone, Copy, PartialEq)]pub struct FaceBox {    pub x: f64,    pub y: f64,    pub w: f64,    pub h: f64,}/// Apple's centre + half-side in a bottom-left frame → Cotton's top-left corner/// box, clamped to the unit square.////// MEASURED, not read: drawn on two of the measuring Mac's own thumbnail/// renders (portrait, EXIF orientation 6). The flip is Apple's bottom-left/// origin — without it the box lands in the person's chest. The side is TWICE/// `ZSIZE`: the first reading (`w = h = size`) framed the mouth alone, and/// `2 × size` frames the face.pub fn face_box_of(center_x: f64, center_y: f64, size: f64) -> Option<FaceBox> {    let half = size;    // `half > 0.0` is false for a zero size AND for a NaN one, which is the    // reading this wants: neither is a face.    if !(half > 0.0 && center_x.is_finite() && center_y.is_finite()) {        return None;    }    let x = clamp_unit(center_x - half);    let y = clamp_unit(1.0 - center_y - half);    let w = clamp_unit(center_x + half) - x;    let h = clamp_unit(1.0 - center_y + half) - y;    if !(w > 0.0 && h > 0.0) {        return None;    }    Some(FaceBox { x, y, w, h })}fn clamp_unit(value: f64) -> f64 {    value.clamp(0.0, 1.0)}/// `-1` is Apple's "not measured", and a quality that was not measured is null.pub fn face_quality_of(value: Option<f64>) -> Option<f64> {    let value = value?;    if !value.is_finite() || value < 0.0 {        return None;    }    Some(value.min(1.0))}// ------------------------------------------------------------------ people#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]#[serde(rename_all = "camelCase")]pub struct ApplePersonRow {    pub pk: i64,    pub uuid: String,    pub full_name: Option<String>,    pub display_name: Option<String>,    pub face_count: Option<i64>,    /// Another `ZPERSON.Z_PK` this cluster was merged into.    pub merge_target_pk: Option<i64>,}/// The name a cluster carries, or `None` when nobody named it.pub fn person_name_of(full_name: Option<&str>, display_name: Option<&str>) -> Option<String> {    let full = full_name.unwrap_or("").trim();    if !full.is_empty() {        return Some(full.to_string());    }    let display = display_name.unwrap_or("").trim();    if display.is_empty() {        None    } else {        Some(display.to_string())    }}/// Case- and whitespace-insensitive, for the name rule.pub fn normalise_name(name: &str) -> String {    name.split_whitespace()        .collect::<Vec<_>>()        .join(" ")        .to_lowercase()}/// The Contacts identifier out of `ZCONTACTMATCHINGDICTIONARY`, once the keyed/// archive is XML.////// MEASURED: the dictionary's keys are `first-name`, `last-name`,/// `phone-numbers`, `email-addresses`, `carddav-uuids`, `unified`, `version`,/// and `carddav-uuids` is where the card's identifiers live. The first/// uuid-shaped string under it is the one `cotton_people.device_contact_id`/// holds when the phone's contact mirror wrote the same card. `None` when the/// dictionary is empty (44 of 54 in the measured library) or names no card.pub fn contact_identifier_from_plist_xml(xml: &str) -> Option<String> {    let strings = plist_strings(xml);    let at = strings.iter().position(|value| value == "carddav-uuids")?;    for candidate in strings.iter().skip(at + 1) {        let trimmed = candidate.strip_suffix(":ABPerson").unwrap_or(candidate);        if is_uuid(trimmed) {            return Some(trimmed.to_string());        }    }    None}fn plist_strings(xml: &str) -> Vec<String> {    let mut out = Vec::new();    let mut rest = xml;    while let Some(start) = rest.find("<string>") {        rest = &rest[start + "<string>".len()..];        let Some(end) = rest.find("</string>") else {            break;        };        out.push(rest[..end].to_string());        rest = &rest[end + "</string>".len()..];    }    out}fn is_uuid(value: &str) -> bool {    let groups = [8, 4, 4, 4, 12];    let parts: Vec<&str> = value.split('-').collect();    parts.len() == groups.len()        && parts.iter().zip(groups).all(|(part, wanted)| {            part.len() == wanted && part.chars().all(|c| c.is_ascii_hexdigit())        })}// ------------------------------------------------------------ the search index/// `search/psi.sqlite` keys an asset by its uuid split into two signed 64-bit/// halves (`assets.uuid_0`, `assets.uuid_1`): the uuid's 16 bytes in order,/// each half read big-endian as a SIGNED integer.pub fn psi_uuid_halves(uuid: &str) -> Option<(i64, i64)> {    let hex: String = uuid.chars().filter(|c| *c != '-').collect();    if hex.len() != 32 || !hex.chars().all(|c| c.is_ascii_hexdigit()) {        return None;    }    let first = u64::from_str_radix(&hex[..16], 16).ok()?;    let second = u64::from_str_radix(&hex[16..], 16).ok()?;    Some((first as i64, second as i64))}/// Photos 8+ search categories (osxphotos's `LEO_CATEGORY_TO_PHOTOS8`).pub mod psi_category {    pub const PLACE_NAME: i64 = 1;    pub const STREET: i64 = 2;    pub const NEIGHBOURHOOD: i64 = 3;    pub const CITY: i64 = 5;    pub const REGION: i64 = 10;    pub const COUNTRY: i64 = 12;    pub const LABEL: i64 = 1500;}/// Fold the index's rows for one asset into a place reading.////// FIRST wins for each single-valued field, which is what `??=` meant: the/// index can carry two city rows, and the second is not a correction.pub fn place_from_index_rows(rows: &[(i64, String)]) -> PlaceReading {    let mut place = PlaceReading::default();    for (category, content) in rows {        let content = content.trim();        if content.is_empty() {            continue;        }        let slot = match *category {            psi_category::PLACE_NAME => &mut place.name,            psi_category::CITY => &mut place.city,            psi_category::REGION => &mut place.region,            psi_category::COUNTRY => &mut place.country,            psi_category::LABEL => {                place.labels.push(content.to_string());                continue;            }            // Street and neighbourhood are read and deliberately unused: the            // columns do not exist, and inventing a place name out of a street            // would put an address on a picture.            _ => continue,        };        if slot.is_none() {            *slot = Some(content.to_string());        }    }    place}#[cfg(test)]#[path = "apple_tests.rs"]mod tests;