285 lines · 10.3 KB · RustRaw
//! The reader: the Photos library, page by page.//!//! **Filesystem-only** (design M7). There is no `PHPhotoLibrary` call anywhere//! in this tree, so there is no authorization prompt to raise and no framework//! answer to cache. What stands in the way is Full Disk Access, and a refusal//! to `stat` inside the library is read as the STATE it is — the panel draws a//! button that opens the right pane of System Settings, and nothing here//! retries in a loop against a decision only the person can make.//!//! **Copy before you read.** Photos holds its own databases open and writes to//! them continuously, so a page is read out of a copy this process made//! ([`copy_library_database`]), which also refuses a schema band this reader//! has not been measured against. The copy is discarded when the pass ends,//! whether it ended well or badly.//!//! **The reader decides nothing about the person's file.** It emits pages; the//! applier turns them into rows, because only the applier holds the replica —//! the same split calls and messages already have. What travels with a page is//! everything the applier would otherwise have to re-open the library to learn://! each asset's place reading, its faces, and the cluster each face names with//! Apple's merge chain already followed.use std::collections::BTreeMap;use std::path::{Path, PathBuf};use super::super::super::{ count, Emit, IngestBatch, IngestNotes, IngestSource, IngestWork, ReadOutcome, SourceCursor, SourceId, SourceStatus, Triggers,};use super::apple::contact_identifier_from_plist_xml;use super::library::{ copy_library_database, default_library_path, library_presence, plist_to_xml, LibraryCopy, LibraryPresence, LibraryReader,};use super::{PhotoAsset, PhotoCluster, PhotoWork};use crate::Layout;/// How many assets one page carries.////// Smaller than the message readers' pages on purpose: a page of assets is a/// page of file copies and digests, and a batch that took minutes to apply/// would leave the progress bar still between updates.pub const ASSETS_PER_BATCH: i64 = 100;/// Where inside `client/snapshots/` the copies live.const SNAPSHOT_DIR: &str = "photos-library";const NO_LIBRARY: &str = "there is no Photos library at this path, so there is nothing here to import";const NO_ACCESS: &str = "this Mac has not given Cotton Full Disk Access, \so the Photos library cannot be read";/// The Apple Photos library, as a source.#[derive(Debug)]pub struct PhotosSource { layout: Layout, library_path: PathBuf,}impl PhotosSource { /// The library where Photos keeps it, unless [`PhotosSource::at_path`] says /// otherwise. pub fn new(layout: Layout, home: &Path) -> PhotosSource { let library_path = default_library_path(home); PhotosSource { layout, library_path, } } pub fn at_path(mut self, path: impl Into<PathBuf>) -> PhotosSource { self.library_path = path.into(); self } pub fn path(&self) -> &Path { &self.library_path } fn snapshot_dir(&self) -> PathBuf { self.layout.snapshots_dir().join(SNAPSHOT_DIR) } /// Copy the databases out of the library and open the copies. fn open(&self) -> Result<(LibraryCopy, LibraryReader), String> { let copy = copy_library_database(&self.library_path, &self.snapshot_dir())?; match LibraryReader::open(©) { Ok(reader) => Ok((copy, reader)), Err(reason) => { copy.discard(); Err(reason) } } } /// Every cluster the faces on this page name, with Apple's merge chain /// followed and the matched Contacts card read out of its archive. /// /// Read ONCE per page rather than once per face: a page of a hundred family /// pictures names the same handful of people over and over, and unarchiving /// a plist per face would be the slowest thing in the pass. fn clusters_for( &self, reader: &LibraryReader, assets: &[PhotoAsset], notes: &mut IngestNotes, ) -> Result<BTreeMap<String, PhotoCluster>, String> { let wanted: std::collections::BTreeSet<i64> = assets .iter() .flat_map(|asset| asset.faces.iter()) .filter_map(|face| face.person_pk) .collect(); if wanted.is_empty() { return Ok(BTreeMap::new()); } let people = reader.people()?; let mut clusters: BTreeMap<String, PhotoCluster> = BTreeMap::new(); for pk in wanted { // A face naming a cluster the people table does not carry is a // COUNT, never a guess: the alternative is inventing somebody. let Some(person) = people.get(&pk) else { count(notes, "read:photosClusterMissing", 1); continue; }; if clusters.contains_key(&person.uuid) { continue; } let contact_identifier = self.contact_of(reader, person.pk, notes)?; clusters.insert( person.uuid.clone(), PhotoCluster { person: person.clone(), contact_identifier, }, ); } Ok(clusters) } /// The Contacts card Photos matched to a cluster, out of its archived /// plist. fn contact_of( &self, reader: &LibraryReader, person_pk: i64, notes: &mut IngestNotes, ) -> Result<Option<String>, String> { let Some(archive) = reader.contact_archive(person_pk)? else { return Ok(None); }; // A plist this reader cannot turn into XML is a cluster with no contact, // which is the ordinary state of most of them — not a failed run. let Ok(xml) = plist_to_xml(&archive, &self.snapshot_dir()) else { count(notes, "read:photosContactUnreadable", 1); return Ok(None); }; Ok(contact_identifier_from_plist_xml(&xml)) } /// One page, with each asset's place reading and faces alongside it. fn page(&self, reader: &LibraryReader, from: i64) -> Result<Vec<PhotoAsset>, String> { let rows = reader.assets_after(from, ASSETS_PER_BATCH)?; let mut assets = Vec::with_capacity(rows.len()); for row in rows { let place = reader.place_for(&row.uuid)?; let faces = reader.faces_for(row.pk)?; assets.push(PhotoAsset { row, place, faces, sha256: None, }); } Ok(assets) }}impl IngestSource for PhotosSource { fn id(&self) -> SourceId { SourceId::Photos } fn probe(&self) -> SourceStatus { match library_presence(&self.library_path) { LibraryPresence::Missing => return SourceStatus::not_found(NO_LIBRARY), LibraryPresence::NoAccess => return SourceStatus::no_permission(NO_ACCESS), LibraryPresence::Found => {} } // Counting means copying, which is the only way to ask a database // another process is writing to. The copy is discarded either way. let (copy, reader) = match self.open() { Ok(opened) => opened, Err(reason) => return SourceStatus::error(reason), }; let counted = reader.count_assets(); drop(reader); copy.discard(); match counted { Ok(total) => SourceStatus::ready(total), Err(reason) => SourceStatus::error(reason), } } fn read(&self, cursor: Option<&str>, emit: Emit<'_>) -> Result<ReadOutcome, String> { let mut notes = IngestNotes::new(); // A cursor that will not parse is no cursor at all: re-reading is free // — identity is the asset's uuid — and guessing a position is not. let mut from = cursor .and_then(|value| value.trim().parse::<i64>().ok()) .filter(|value| *value >= 0) .unwrap_or(0); let (copy, reader) = self.open()?; let outcome = self.drain(&reader, &mut from, &mut notes, emit); drop(reader); // The copies go whether the pass finished or not: they are a whole // Photos database, and one left behind per failed run fills the disk. copy.discard(); outcome?; Ok(ReadOutcome { cursor: from.to_string(), notes, }) } fn triggers(&self) -> Triggers { Triggers { // The library's own database directory. Photos writes there on // every import, every edit and every analysis pass. watch: vec![self.library_path.join("database")], // Photos writes constantly, so the watch fires often and the floor // is generous: an hour between passes over a library nothing // changed in is not a person waiting. every_ms: 60 * 60 * 1000, } }}impl PhotosSource { /// Page until the library runs out, emitting as it goes. /// /// Separated from [`IngestSource::read`] so the copy is discarded on EVERY /// path out — a `?` in the middle of the loop included. fn drain( &self, reader: &LibraryReader, from: &mut i64, notes: &mut IngestNotes, emit: Emit<'_>, ) -> Result<(), String> { loop { let assets = self.page(reader, *from)?; if assets.is_empty() { break; } let read = assets.len() as i64; for asset in &assets { *from = (*from).max(asset.row.pk); } count(notes, "read:photos", read); let clusters = self.clusters_for(reader, &assets, notes)?; emit(IngestBatch { work: IngestWork::Photos(Box::new(PhotoWork { library_path: self.library_path.clone(), assets, clusters, })), read, // The cursor rides the batch: a page that has been written is a // page that need never be copied and hashed again. cursor: Some(SourceCursor::from(from.to_string())), })?; if read < ASSETS_PER_BATCH { break; } } Ok(()) }}#[cfg(test)]#[path = "source_tests.rs"]mod tests;