//! The Apple Photos library on disk: finding it, copying its database, reading //! the copy. //! //! Photos holds the live `Photos.sqlite` open, so it is NEVER opened in place — //! `Photos.sqlite`, `-wal` and `-shm` are copied together into the client's //! snapshot directory (osxphotos does exactly this) and opened read-only from //! there; the same for `search/psi.sqlite`. Everything below is READ; the //! library is never written, locked or changed. //! //! The band check is here too, because it is the first thing the copy answers //! and the reason the copy exists: a library this reader has not been tested on //! is refused with the numbers in the sentence, before a single asset is read. //! //! **No PhotoKit** (design M7): there is no authorization prompt to ask for, //! and what stands in the way is Full Disk Access — a state, not an error. use std::collections::{HashMap, HashSet}; use std::path::{Path, PathBuf}; use rusqlite::{Connection, OptionalExtension}; use super::apple::{ check_band, library_schema_version_from_plist_xml, model_version_from_plist_xml, place_from_index_rows, psi_uuid_halves, AppleAssetRow, AppleFaceRow, ApplePersonRow, PlaceReading, }; use crate::ingest::snapshot::{copy_for_read, open_readonly}; /// Where Photos keeps the library unless the person moved it. pub fn default_library_path(home: &Path) -> PathBuf { home.join("Pictures").join("Photos Library.photoslibrary") } /// Is there a library, and may this process read inside it? #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub enum LibraryPresence { Found, Missing, /// The folder is there and this process may not read inside it — Full Disk /// Access, which cannot be asked for programmatically. NoAccess, } /// Ask the filesystem, and read a refusal as the state it is. pub fn library_presence(path: &Path) -> LibraryPresence { if !path.exists() { return LibraryPresence::Missing; } match std::fs::metadata(path.join("database").join("Photos.sqlite")) { Ok(_) => LibraryPresence::Found, Err(error) => match error.kind() { std::io::ErrorKind::NotFound => LibraryPresence::Missing, std::io::ErrorKind::PermissionDenied => LibraryPresence::NoAccess, // macOS answers a TCC denial as `Operation not permitted` (EPERM), // which Rust does NOT map to `PermissionDenied`. _ if error.raw_os_error() == Some(1) => LibraryPresence::NoAccess, _ => LibraryPresence::NoAccess, }, } } /// The copies, and the version pair that decided they could be read. #[derive(Debug)] pub struct LibraryCopy { /// The directory holding the copies. Removing it is [`LibraryCopy::discard`]. pub dir: PathBuf, pub photos_db: PathBuf, /// `None` when the library has no search index yet. pub psi_db: Option, pub model_version: i64, pub library_schema_version: i64, /// Which Photos the band check recognised. pub photos: &'static str, } impl LibraryCopy { /// Remove the copies. Idempotent, and never a failure: a copy left behind /// costs disk, and refusing to finish a run over it would cost the run. pub fn discard(&self) { let _ = std::fs::remove_dir_all(&self.dir); } } /// Copy the database files out of the library and read the version pair. /// /// Refuses a band this reader has not been tested on — with the sentence the /// panel shows — AFTER removing the copies. Guessing across a band is how a /// person's faces end up on the wrong pictures. pub fn copy_library_database(library_path: &Path, into: &Path) -> Result { let _ = std::fs::remove_dir_all(into); std::fs::create_dir_all(into).map_err(|error| format!("the copy directory: {error}"))?; let copied = copy_and_read(library_path, into); match copied { Ok(copy) => Ok(copy), Err(reason) => { let _ = std::fs::remove_dir_all(into); Err(reason) } } } fn copy_and_read(library_path: &Path, into: &Path) -> Result { let (photos_db, psi_db, model_version, library_schema_version) = copy_versions(library_path, into)?; let photos = check_band(model_version, library_schema_version)?; Ok(LibraryCopy { dir: into.to_path_buf(), photos_db, psi_db, model_version, library_schema_version, photos, }) } /// Copy the database files into `into` and read the version pair, with no /// band check: the copies, then the versions. fn copy_versions(library_path: &Path, into: &Path) -> Result<(PathBuf, Option, i64, i64), String> { let database = library_path.join("database"); let photos_db = into.join("Photos.sqlite"); copy_for_read(&database.join("Photos.sqlite"), &photos_db) .map_err(|error| format!("the Photos database could not be copied: {error}"))?; let psi_source = database.join("search").join("psi.sqlite"); let psi_db = if psi_source.exists() { let target = into.join("psi.sqlite"); copy_for_read(&psi_source, &target) .map_err(|error| format!("the search index could not be copied: {error}"))?; Some(target) } else { None }; let schema_plist = std::fs::read(database.join("DataModelVersion.plist")) .map_err(|error| format!("the library's version file could not be read: {error}"))?; let library_schema_version = library_schema_version_from_plist_xml(&plist_to_xml(&schema_plist, into)?); let model_version = read_model_version(&photos_db, into)?; let (Some(model_version), Some(library_schema_version)) = (model_version, library_schema_version) else { return Err( "This Photos library does not say which version of Photos wrote it, so \ Cotton cannot read it safely. Nothing was imported." .to_string(), ); }; Ok((photos_db, psi_db, model_version, library_schema_version)) } /// What a library measures as, for admitting a new band: its version pair, /// whether the band table already admits it, and whether each statement the /// reader runs prepares against it (`Err` names the missing table or column). /// Counts only; no row of the person's is read out. #[derive(Debug)] pub struct Measured { pub model_version: i64, pub library_schema_version: i64, pub admitted: Result<&'static str, String>, pub statements: Vec<(&'static str, Result<(), String>)>, pub assets: Option, pub has_search_index: bool, } /// Measure the library at `library_path` on copies in `into`, removed after. pub fn measure_library(library_path: &Path, into: &Path) -> Result { let _ = std::fs::remove_dir_all(into); std::fs::create_dir_all(into).map_err(|error| format!("the copy directory: {error}"))?; let measured = measure_copies(library_path, into); let _ = std::fs::remove_dir_all(into); measured } fn measure_copies(library_path: &Path, into: &Path) -> Result { let (photos_db, psi_db, model_version, library_schema_version) = copy_versions(library_path, into)?; let photos = open_readonly(&photos_db).map_err(|error| format!("the copied Photos database would not open: {error}"))?; let prepares = |db: &Connection, sql: &str| db.prepare(sql).map(|_| ()).map_err(|error| error.to_string()); let mut statements = vec![ ("assets", prepares(&photos, ASSET_SELECT)), ("asset count", prepares(&photos, ASSET_COUNT)), ("faces", prepares(&photos, FACES_SELECT)), ("people", prepares(&photos, PEOPLE_SELECT)), ("contact match", prepares(&photos, CONTACT_ARCHIVE_SELECT)), ]; if let Some(psi) = &psi_db { let psi = open_readonly(psi).map_err(|error| format!("the copied search index would not open: {error}"))?; statements.push(("search index", prepares(&psi, PSI_SELECT))); } let assets = photos.query_row(ASSET_COUNT, [], |row| row.get(0)).ok(); Ok(Measured { model_version, library_schema_version, admitted: check_band(model_version, library_schema_version), statements, assets, has_search_index: psi_db.is_some(), }) } /// `PLModelVersion` out of `Z_METADATA.Z_PLIST` on the COPY. fn read_model_version(photos_db: &Path, dir: &Path) -> Result, String> { let db = open_readonly(photos_db) .map_err(|error| format!("the copied Photos database would not open: {error}"))?; let plist: Option> = db .query_row( "SELECT Z_PLIST AS plist FROM Z_METADATA LIMIT 1", [], |row| row.get(0), ) .optional() .map_err(|error| format!("the library's metadata could not be read: {error}"))?; let Some(plist) = plist else { return Ok(None); }; Ok(model_version_from_plist_xml(&plist_to_xml(&plist, dir)?)) } /// A plist as XML. /// /// `plutil` is the ONE tool every Mac has that reads a binary plist; a /// hand-written bplist reader for two integers is a parser nobody would want to /// maintain. A plist that is ALREADY XML passes through untouched — which is /// what lets this reader's tests run where there is no `plutil`, and a real /// library writes binary plists and takes the Mac path. /// /// The conversion goes through a FILE rather than a pipe: a pipe is only /// sometimes reliable for a binary plist, and the temp directory is already /// there. pub fn plist_to_xml(bytes: &[u8], scratch: &Path) -> Result { if let Some(text) = as_xml_plist(bytes) { return Ok(text); } let path = scratch.join("metadata.plist"); std::fs::write(&path, bytes) .map_err(|error| format!("the plist could not be written for conversion: {error}"))?; let result = std::process::Command::new("plutil") .args(["-convert", "xml1", "-o", "-"]) .arg(&path) .output() .map_err(|error| { format!("plutil is not available here (this reader runs on macOS): {error}") })?; if !result.status.success() { let stderr = String::from_utf8_lossy(&result.stderr).trim().to_string(); let reason = if stderr.is_empty() { format!("exit {:?}", result.status.code()) } else { stderr }; return Err(format!("plutil could not read the plist: {reason}")); } Ok(String::from_utf8_lossy(&result.stdout).to_string()) } /// Already XML? The first 64 bytes decide, past a byte-order mark and any /// leading whitespace. pub fn as_xml_plist(bytes: &[u8]) -> Option { let head = String::from_utf8_lossy(&bytes[..bytes.len().min(64)]); let head = head.trim_start_matches('\u{feff}').trim_start(); if head.starts_with(", } impl std::fmt::Debug for LibraryReader { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { f.debug_struct("LibraryReader") .field("index", &self.psi.is_some()) .finish() } } impl LibraryReader { pub fn open(copy: &LibraryCopy) -> Result { let photos = open_readonly(©.photos_db) .map_err(|error| format!("the copied Photos database would not open: {error}"))?; let psi = match ©.psi_db { Some(path) => Some( open_readonly(path) .map_err(|error| format!("the copied search index would not open: {error}"))?, ), None => None, }; Ok(LibraryReader { photos, psi }) } pub fn count_assets(&self) -> Result { self.photos .query_row(ASSET_COUNT, [], |row| row.get(0)) .map_err(|error| format!("the assets could not be counted: {error}")) } /// One page, in key order. `Z_PK` ascending is the page cursor, and it is an /// OPTIMISATION: identity is the asset's uuid, so a re-read writes nothing /// twice. pub fn assets_after(&self, pk: i64, limit: i64) -> Result, String> { let sql = format!("{ASSET_SELECT} AND a.Z_PK > ? ORDER BY a.Z_PK LIMIT ?"); let mut statement = self .photos .prepare(&sql) .map_err(|error| format!("the asset page: {error}"))?; let rows = statement .query_map([pk, limit], |row| { Ok(AppleAssetRow { pk: row.get("pk")?, uuid: row.get::<_, Option>("uuid")?.unwrap_or_default(), kind: row.get::<_, Option>("kind")?.unwrap_or_default(), kind_subtype: row.get("kindSubtype")?, uti: row.get("uti")?, directory: row.get("directory")?, filename: row.get("filename")?, saved_asset_type: row.get("savedAssetType")?, date_created: row.get("dateCreated")?, timezone_offset: row.get("timezoneOffset")?, latitude: row.get("latitude")?, longitude: row.get("longitude")?, width: row.get("width")?, height: row.get("height")?, orientation: row.get("orientation")?, favorite: row.get("favorite")?, hdr_type: row.get("hdrType")?, depth_type: row.get("depthType")?, adjustments_state: row.get("adjustmentsState")?, avalanche_uuid: row.get("avalancheUuid")?, is_detected_screenshot: row.get("isDetectedScreenshot")?, camera_capture_device: row.get("cameraCaptureDevice")?, camera_make: row.get("cameraMake")?, camera_model: row.get("cameraModel")?, original_filename: row.get("originalFilename")?, overall_aesthetic_score: row.get("overallAestheticScore")?, curation_score: row.get("curationScore")?, scene_analysis_version: row.get("sceneAnalysisVersion")?, title: row.get("title")?, long_description: row.get("longDescription")?, }) }) .map_err(|error| format!("the asset page: {error}"))?; rows.collect::>>() .map_err(|error| format!("an asset row: {error}")) } pub fn faces_for(&self, asset_pk: i64) -> Result, String> { let mut statement = self .photos .prepare(FACES_SELECT) .map_err(|error| format!("the faces: {error}"))?; let rows = statement .query_map([asset_pk], |row| { Ok(AppleFaceRow { uuid: row.get::<_, Option>("uuid")?.unwrap_or_default(), asset_pk: row.get::<_, Option>("assetPk")?.unwrap_or_default(), center_x: row.get::<_, Option>("centerX")?.unwrap_or_default(), center_y: row.get::<_, Option>("centerY")?.unwrap_or_default(), size: row.get::<_, Option>("size")?.unwrap_or_default(), quality: row.get("quality")?, person_pk: row.get("personPk")?, person_uuid: row.get("personUuid")?, is_in_trash: row.get("isInTrash")?, hidden: row.get("hidden")?, }) }) .map_err(|error| format!("the faces: {error}"))?; rows.collect::>>() .map_err(|error| format!("a face row: {error}")) } /// Every cluster, keyed by its ORIGINAL primary key and valued with the one /// it was merged into. /// /// Photos merges clusters by pointing one at another rather than by /// rewriting the faces, so a face still names the cluster it was found in — /// and following the chain here is what stops one person becoming two. /// The walk carries a `seen` set: a cycle in Apple's own table would /// otherwise be an infinite loop inside an import. pub fn people(&self) -> Result, String> { let mut statement = self .photos .prepare(PEOPLE_SELECT) .map_err(|error| format!("the people: {error}"))?; let rows = statement .query_map([], |row| { Ok(ApplePersonRow { pk: row.get::<_, Option>("pk")?.unwrap_or_default(), uuid: row.get::<_, Option>("uuid")?.unwrap_or_default(), full_name: row.get("fullName")?, display_name: row.get("displayName")?, face_count: row.get("faceCount")?, merge_target_pk: row.get("mergeTargetPk")?, }) }) .map_err(|error| format!("the people: {error}"))? .collect::>>() .map_err(|error| format!("a person row: {error}"))?; let by_pk: HashMap = rows.iter().map(|row| (row.pk, row.clone())).collect(); let mut resolved = HashMap::new(); for row in &rows { let mut target = row.clone(); let mut seen: HashSet = HashSet::new(); while let Some(next_pk) = target.merge_target_pk { if !seen.insert(target.pk) { break; } match by_pk.get(&next_pk) { Some(next) => target = next.clone(), None => break, } } resolved.insert(row.pk, target); } Ok(resolved) } /// The keyed archive `ZCONTACTMATCHINGDICTIONARY` holds, when there is one. pub fn contact_archive(&self, person_pk: i64) -> Result>, String> { self.photos .query_row(CONTACT_ARCHIVE_SELECT, [person_pk], |row| { row.get::<_, Option>>(0) }) .optional() .map(Option::flatten) .map_err(|error| format!("the contact archive: {error}")) } /// What the search index says about one asset. /// /// Empty on a Mac with no index, and empty for an asset the index has not /// reached — both of which are ordinary. pub fn place_for(&self, uuid: &str) -> Result { let Some(psi) = &self.psi else { return Ok(PlaceReading::default()); }; let Some((first, second)) = psi_uuid_halves(uuid) else { return Ok(PlaceReading::default()); }; let mut statement = psi .prepare(PSI_SELECT) .map_err(|error| format!("the search index: {error}"))?; let rows = statement .query_map([first, second], |row| { Ok(( row.get::<_, Option>("category")?.unwrap_or_default(), row.get::<_, Option>("content")?.unwrap_or_default(), )) }) .map_err(|error| format!("the search index: {error}"))? .collect::>>() .map_err(|error| format!("a search index row: {error}"))?; Ok(place_from_index_rows(&rows)) } } #[cfg(test)] #[path = "library_tests.rs"] mod tests;