Cotton code
466 lines · 16.7 KB · RustRaw
//! A synthetic Photos library, with Apple's real COLUMN NAMES and nothing//! else real.//!//! Every uuid, name, place and byte here is invented. A real library is never//! read by a test — not the owner's, not anyone's — and the shape is the whole of//! what the reader is entitled to depend on.//!//! The port of `apps/cotton/scripts/lib/syntheticLibrary.ts`. It stays a//! test fixture rather than a script: the 65k-asset generator that used it is//! the TypeScript lane's, and nothing in this crate has a use for it outside//! `#[cfg(test)]`.use std::path::{Path, PathBuf};use rusqlite::Connection;use super::apple::{psi_uuid_halves, APPLE_EPOCH_MS};/// The columns the reader selects, and NOT one more: a fixture that carried/// Apple's whole schema would be a promise about columns nothing reads.const SCHEMA: &str = "CREATE TABLE Z_METADATA (Z_VERSION INTEGER, Z_UUID VARCHAR(255), Z_PLIST BLOB);CREATE TABLE ZASSET (  Z_PK INTEGER PRIMARY KEY, ZUUID TEXT, ZKIND INTEGER, ZKINDSUBTYPE INTEGER, ZUNIFORMTYPEIDENTIFIER TEXT,  ZDIRECTORY TEXT, ZFILENAME TEXT, ZSAVEDASSETTYPE INTEGER, ZDATECREATED REAL, ZLATITUDE REAL, ZLONGITUDE REAL,  ZWIDTH INTEGER, ZHEIGHT INTEGER, ZORIENTATION INTEGER, ZFAVORITE INTEGER, ZHDRTYPE INTEGER, ZDEPTHTYPE INTEGER,  ZADJUSTMENTSSTATE INTEGER, ZAVALANCHEUUID TEXT, ZISDETECTEDSCREENSHOT INTEGER, ZOVERALLAESTHETICSCORE REAL,  ZCURATIONSCORE REAL, ZTRASHEDSTATE INTEGER, ZHIDDEN INTEGER);CREATE TABLE ZADDITIONALASSETATTRIBUTES (  Z_PK INTEGER PRIMARY KEY, ZASSET INTEGER, ZTIMEZONEOFFSET INTEGER, ZCAMERACAPTUREDEVICE INTEGER,  ZORIGINALFILENAME TEXT, ZSCENEANALYSISVERSION INTEGER, ZTITLE TEXT);CREATE TABLE ZEXTENDEDATTRIBUTES (Z_PK INTEGER PRIMARY KEY, ZASSET INTEGER, ZCAMERAMAKE TEXT, ZCAMERAMODEL TEXT);CREATE TABLE ZASSETDESCRIPTION (Z_PK INTEGER PRIMARY KEY, ZASSETATTRIBUTES INTEGER, ZLONGDESCRIPTION TEXT);CREATE TABLE ZPERSON (  Z_PK INTEGER PRIMARY KEY, ZPERSONUUID TEXT, ZFULLNAME TEXT, ZDISPLAYNAME TEXT, ZFACECOUNT INTEGER,  ZMERGETARGETPERSON INTEGER, ZCONTACTMATCHINGDICTIONARY BLOB);CREATE TABLE ZDETECTEDFACE (  Z_PK INTEGER PRIMARY KEY, ZUUID TEXT, ZASSETFORFACE INTEGER, ZPERSONFORFACE INTEGER, ZCENTERX REAL, ZCENTERY REAL,  ZSIZE REAL, ZQUALITY REAL, ZISINTRASH INTEGER, ZHIDDEN INTEGER);";const PSI_SCHEMA: &str = "CREATE TABLE groups(category INT2, owning_groupid INT, content_string TEXT, normalized_string TEXT, lookup_identifier TEXT, score REAL, token_ranges_0 INT8, token_ranges_1 INT8);CREATE TABLE assets(uuid_0 INT, uuid_1 INT, creationDate INT, UNIQUE(uuid_0, uuid_1));CREATE TABLE ga(groupid INT, assetid INT, PRIMARY KEY(groupid, assetid));";/// One `<key>` / value pair per entry, in the order given.pub fn plist_xml(entries: &[(&str, PlistValue)]) -> String {    let body: String = entries        .iter()        .map(|(key, value)| match value {            PlistValue::Integer(number) => format!("<key>{key}</key><integer>{number}</integer>"),            PlistValue::Text(text) => format!("<key>{key}</key><string>{text}</string>"),        })        .collect();    format!(        "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<plist version=\"1.0\"><dict>{body}</dict></plist>\n"    )}/// The two kinds of value a version plist holds. `Text` is unused by today's/// fixtures and kept deliberately: a plist writer that could only write/// integers would be one more thing to change the day a string key matters.#[allow(dead_code)]pub enum PlistValue {    Integer(i64),    Text(&'static str),}/// The shape `plutil -convert xml1` gives a keyed archive of an NSDictionary.pub fn contact_archive_xml(contact_identifier: &str) -> String {    format!(        "<?xml version=\"1.0\" encoding=\"UTF-8\"?><plist version=\"1.0\"><dict><key>$objects</key><array>\         <string>$null</string><dict><key>NS.keys</key><array/><key>NS.objects</key><array/></dict>\         <string>first-name</string><string>carddav-uuids</string><dict><key>NS.objects</key><array/></dict>\         <string>{contact_identifier}:ABPerson</string></array></dict></plist>"    )}/// A uuid that is obviously invented, and stable per number.pub fn uuid_of(n: u64) -> String {    format!("00000000-0000-4000-8000-{n:012X}")}fn apple_seconds(iso: &str) -> f64 {    let moment = chrono::DateTime::parse_from_rfc3339(iso).expect("a literal instant");    (moment.timestamp_millis() - APPLE_EPOCH_MS) as f64 / 1000.0}#[derive(Debug, Clone)]pub struct SyntheticAsset {    pub pk: i64,    pub uuid: String,    pub kind: i64,    pub kind_subtype: i64,    pub uti: Option<String>,    pub directory: Option<String>,    pub filename: Option<String>,    pub saved_asset_type: i64,    pub taken_at: String,    pub latitude: f64,    pub longitude: f64,    pub width: i64,    pub height: i64,    pub orientation: i64,    pub favorite: i64,    pub hdr_type: i64,    pub depth_type: i64,    pub adjustments_state: i64,    pub avalanche_uuid: Option<String>,    pub is_detected_screenshot: i64,    pub overall_aesthetic_score: f64,    pub curation_score: f64,    pub trashed: i64,    pub hidden: i64,    pub timezone_offset: Option<i64>,    pub camera_capture_device: i64,    pub original_filename: Option<String>,    pub scene_analysis_version: i64,    pub title: Option<String>,    pub long_description: Option<String>,    pub camera_make: Option<String>,    pub camera_model: Option<String>,    /// The bytes of the original. `None` means the original is NOT on disk —    /// which is what an iCloud-only asset looks like, and the commonest    /// interesting case.    pub bytes: Option<Vec<u8>>,}impl SyntheticAsset {    pub fn photo(pk: i64) -> SyntheticAsset {        SyntheticAsset {            pk,            uuid: uuid_of(pk as u64),            kind: 0,            kind_subtype: 0,            uti: None,            directory: None,            filename: None,            saved_asset_type: 6,            taken_at: "2026-08-14T09:00:00.000Z".to_string(),            latitude: -180.0,            longitude: -180.0,            width: 4000,            height: 3000,            orientation: 1,            favorite: 0,            hdr_type: 0,            depth_type: 0,            adjustments_state: 0,            avalanche_uuid: None,            is_detected_screenshot: 0,            overall_aesthetic_score: 0.5,            curation_score: 0.5,            trashed: 0,            hidden: 0,            timezone_offset: Some(19_800),            camera_capture_device: 0,            original_filename: None,            scene_analysis_version: 0,            title: None,            long_description: None,            camera_make: None,            camera_model: None,            bytes: None,        }    }    fn uti_value(&self) -> String {        self.uti.clone().unwrap_or_else(|| {            if self.kind == 1 {                "com.apple.quicktime-movie".to_string()            } else {                "public.jpeg".to_string()            }        })    }    fn directory_value(&self) -> String {        self.directory            .clone()            .unwrap_or_else(|| self.uuid.chars().next().unwrap_or('0').to_string())    }    fn filename_value(&self) -> String {        self.filename.clone().unwrap_or_else(|| {            let uti = self.uti_value();            let ext = match uti.as_str() {                "public.jpeg" => "jpeg",                "public.heic" => "heic",                _ if self.kind == 1 => "mov",                _ => "bin",            };            format!("{}.{ext}", self.uuid)        })    }}#[derive(Debug, Clone, Default)]pub struct SyntheticPerson {    pub pk: i64,    pub uuid: String,    pub full_name: Option<String>,    pub display_name: Option<String>,    pub merge_target_pk: Option<i64>,    pub contact_identifier: Option<String>,}#[derive(Debug, Clone)]pub struct SyntheticFace {    pub uuid: String,    pub asset_pk: i64,    pub center_x: f64,    pub center_y: f64,    pub size: f64,    pub quality: f64,    pub person_pk: Option<i64>,    pub is_in_trash: i64,    pub hidden: i64,}impl SyntheticFace {    pub fn at(uuid: &str, asset_pk: i64) -> SyntheticFace {        SyntheticFace {            uuid: uuid.to_string(),            asset_pk,            center_x: 0.5,            center_y: 0.6,            size: 0.1,            quality: 0.4,            person_pk: None,            is_in_trash: 0,            hidden: 0,        }    }}#[derive(Debug, Clone)]pub struct SyntheticIndexRow {    pub uuid: String,    pub category: i64,    pub content: String,}#[derive(Debug, Clone)]pub struct SyntheticLibrary {    pub dir: PathBuf,    pub model_version: i64,    pub library_schema_version: i64,    pub assets: Vec<SyntheticAsset>,    pub persons: Vec<SyntheticPerson>,    pub faces: Vec<SyntheticFace>,    /// `None` writes NO `search/psi.sqlite` — a Mac that has never run    /// analysis, which is the state every asset imports with no place in.    pub index: Option<Vec<SyntheticIndexRow>>,}impl SyntheticLibrary {    pub fn at(dir: impl Into<PathBuf>) -> SyntheticLibrary {        SyntheticLibrary {            dir: dir.into(),            model_version: 19_607,            library_schema_version: 5001,            assets: Vec::new(),            persons: Vec::new(),            faces: Vec::new(),            index: Some(Vec::new()),        }    }    /// Write it, and answer its path.    pub fn write(&self) -> PathBuf {        let database = self.dir.join("database");        std::fs::create_dir_all(database.join("search")).expect("the database directory");        std::fs::create_dir_all(self.dir.join("originals")).expect("the originals directory");        std::fs::write(            database.join("DataModelVersion.plist"),            plist_xml(&[                (                    "LibrarySchemaVersion",                    PlistValue::Integer(self.library_schema_version),                ),                ("MetaSchemaVersion", PlistValue::Integer(3)),            ]),        )        .expect("the version file");        let db = crate::test_support::open_fixture_db(&database.join("Photos.sqlite"));        db.execute_batch(SCHEMA).expect("the schema");        db.execute(            "INSERT INTO Z_METADATA (Z_VERSION, Z_UUID, Z_PLIST) VALUES (1, 'lib', ?)",            [                plist_xml(&[("PLModelVersion", PlistValue::Integer(self.model_version))])                    .into_bytes(),            ],        )        .expect("the metadata");        for asset in &self.assets {            self.write_asset(&db, asset);        }        for person in &self.persons {            db.execute(                "INSERT INTO ZPERSON (Z_PK, ZPERSONUUID, ZFULLNAME, ZDISPLAYNAME, ZFACECOUNT,                                      ZMERGETARGETPERSON, ZCONTACTMATCHINGDICTIONARY)                 VALUES (?, ?, ?, ?, 0, ?, ?)",                rusqlite::params![                    person.pk,                    person.uuid,                    person.full_name,                    person.display_name,                    person.merge_target_pk,                    person                        .contact_identifier                        .as_ref()                        .map(|id| contact_archive_xml(id).into_bytes()),                ],            )            .expect("a person");        }        for face in &self.faces {            db.execute(                "INSERT INTO ZDETECTEDFACE (ZUUID, ZASSETFORFACE, ZPERSONFORFACE, ZCENTERX, ZCENTERY,                                            ZSIZE, ZQUALITY, ZISINTRASH, ZHIDDEN)                 VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)",                rusqlite::params![                    face.uuid,                    face.asset_pk,                    face.person_pk,                    face.center_x,                    face.center_y,                    face.size,                    face.quality,                    face.is_in_trash,                    face.hidden,                ],            )            .expect("a face");        }        drop(db);        if let Some(rows) = &self.index {            self.write_index(&database.join("search").join("psi.sqlite"), rows);        }        self.dir.clone()    }    fn write_asset(&self, db: &Connection, asset: &SyntheticAsset) {        let directory = asset.directory_value();        let filename = asset.filename_value();        db.execute(            "INSERT INTO ZASSET (               Z_PK, ZUUID, ZKIND, ZKINDSUBTYPE, ZUNIFORMTYPEIDENTIFIER, ZDIRECTORY, ZFILENAME,               ZSAVEDASSETTYPE, ZDATECREATED, ZLATITUDE, ZLONGITUDE, ZWIDTH, ZHEIGHT, ZORIENTATION,               ZFAVORITE, ZHDRTYPE, ZDEPTHTYPE, ZADJUSTMENTSSTATE, ZAVALANCHEUUID,               ZISDETECTEDSCREENSHOT, ZOVERALLAESTHETICSCORE, ZCURATIONSCORE, ZTRASHEDSTATE, ZHIDDEN)             VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)",            rusqlite::params![                asset.pk,                asset.uuid,                asset.kind,                asset.kind_subtype,                asset.uti_value(),                directory,                filename,                asset.saved_asset_type,                apple_seconds(&asset.taken_at),                asset.latitude,                asset.longitude,                asset.width,                asset.height,                asset.orientation,                asset.favorite,                asset.hdr_type,                asset.depth_type,                asset.adjustments_state,                asset.avalanche_uuid,                asset.is_detected_screenshot,                asset.overall_aesthetic_score,                asset.curation_score,                asset.trashed,                asset.hidden,            ],        )        .expect("an asset");        db.execute(            "INSERT INTO ZADDITIONALASSETATTRIBUTES (Z_PK, ZASSET, ZTIMEZONEOFFSET,                                                     ZCAMERACAPTUREDEVICE, ZORIGINALFILENAME,                                                     ZSCENEANALYSISVERSION, ZTITLE)             VALUES (?, ?, ?, ?, ?, ?, ?)",            rusqlite::params![                asset.pk,                asset.pk,                asset.timezone_offset,                asset.camera_capture_device,                asset.original_filename,                asset.scene_analysis_version,                asset.title,            ],        )        .expect("the attributes");        db.execute(            "INSERT INTO ZEXTENDEDATTRIBUTES (Z_PK, ZASSET, ZCAMERAMAKE, ZCAMERAMODEL)             VALUES (?, ?, ?, ?)",            rusqlite::params![asset.pk, asset.pk, asset.camera_make, asset.camera_model],        )        .expect("the extended attributes");        if let Some(description) = &asset.long_description {            db.execute(                "INSERT INTO ZASSETDESCRIPTION (Z_PK, ZASSETATTRIBUTES, ZLONGDESCRIPTION)                 VALUES (?, ?, ?)",                rusqlite::params![asset.pk, asset.pk, description],            )            .expect("the description");        }        if let Some(bytes) = &asset.bytes {            let folder = if asset.saved_asset_type == 4 {                self.dir                    .join("scopes")                    .join("cloudsharing")                    .join("data")                    .join(&directory)            } else {                self.dir.join("originals").join(&directory)            };            std::fs::create_dir_all(&folder).expect("the originals folder");            std::fs::write(folder.join(&filename), bytes).expect("the original");        }    }    fn write_index(&self, path: &Path, rows: &[SyntheticIndexRow]) {        let psi = crate::test_support::open_fixture_db(path);        psi.execute_batch(PSI_SCHEMA).expect("the index schema");        for row in rows {            let (first, second) = psi_uuid_halves(&row.uuid).expect("a uuid");            psi.execute(                "INSERT OR IGNORE INTO assets (uuid_0, uuid_1, creationDate) VALUES (?, ?, 0)",                [first, second],            )            .expect("an index asset");            let asset_id: i64 = psi                .query_row(                    "SELECT rowid FROM assets WHERE uuid_0 = ? AND uuid_1 = ?",                    [first, second],                    |row| row.get(0),                )                .expect("the index asset's row id");            psi.execute(                "INSERT INTO groups (category, owning_groupid, content_string) VALUES (?, 0, ?)",                rusqlite::params![row.category, row.content],            )            .expect("an index group");            let group_id = psi.last_insert_rowid();            psi.execute(                "INSERT INTO ga (groupid, assetid) VALUES (?, ?)",                [group_id, asset_id],            )            .expect("the index link");        }    }}