//! Me's name and picture, carried ONE WAY to the owner's person in every //! shared database (the Me brief, piece 2; owner and architect, 11 Oct 2026). //! //! Me is the owner's person in the PERSONAL database, found by //! `cotton_workspaces.owner_person_id` and nothing else (`read.you`). In a //! shared database the owner is a member like any other, and the person that //! is them there is the one their signed member claim binds //! (`cotton_store::member_person::bound_person`) — never one found by name. //! When Me's name or picture differs from that person's, this writes Me's onto //! it. Never the other way: a shared database's row is never read back into Me. //! //! A database with no claim for the owner is passed over here; making that //! person and signing the claim is the database's founding and joining //! (`databases`, `member_actions`), not this. //! //! WHEN: at the end of each sync pass (`handle.rs`, beside the vault key's //! publish), so a change to Me, a database joined later and a pass that failed //! all catch up. What was carried where is remembered for the process, so a //! pass with nothing new opens no shared file. use std::collections::BTreeMap; use std::path::PathBuf; use std::sync::Mutex; use serde_json::{json, Map, Value}; use crate::shell::client::ClientController; use crate::shell::file::ReadFile; /// Each shared database's id, and the face (`name`, picture sha) last carried /// to it or found already there — the latch that keeps an idle pass from /// opening every shared file. static CARRIED: Mutex> = Mutex::new(BTreeMap::new()); /// What Me looks like now. struct Face { name: String, picture: Option, } /// Me's picture, by the bytes on this device: a key is one file's own and is /// refused in another, so the picture travels as its bytes and each shared /// database keys its own copy (content-addressed, so the same picture is /// copied and keyed once). struct Picture { sha: String, ext: String, path: PathBuf, } impl Face { /// What [`CARRIED`] remembers: a change to either part is a new face. fn print(&self) -> String { format!("{}\u{0}{}", self.name, self.picture.as_ref().map_or("", |picture| picture.sha.as_str())) } } /// The sha and extension an avatar key ends in (`…/{sha}.{ext}`). pub(crate) fn picture_name(key: &str) -> Option<(String, String)> { let last = key.rsplit('/').next()?; let (sha, ext) = match last.split_once('.') { Some((sha, ext)) => (sha, ext), None => (last, ""), }; (!sha.is_empty()).then(|| (sha.to_string(), ext.to_string())) } /// Me, as the personal database holds it, or `None` while no person is linked /// or Me is in the bin. A picture whose bytes are not on this device yet is /// left for a later pass. fn me(client: &ClientController) -> Result, String> { let _personal = client.name_database(None)?; let found = client.with_file(|file| { let Some(id) = super::you::owner_of(file)? else { return Ok(None); }; Ok(super::you::present_person(file, &id)?.map(|(_, name, key)| (name, key))) })?; let Some((name, key)) = found else { return Ok(None); }; let picture = match key { Some(key) => picture_on_this_device(client, &key)?, None => None, }; Ok(Some(Face { name, picture })) } /// Me's name, while Me is linked and present — what a person this device /// makes for the owner in another database is called. #[cfg(test)] pub(crate) fn me_name(client: &ClientController) -> Option { let _personal = client.name_database(None).ok()?; client .with_file(|file| { let Some(id) = super::you::owner_of(file)? else { return Ok(None); }; Ok(super::you::present_person(file, &id)?.map(|(_, name, _)| name)) }) .ok() .flatten() .filter(|name| !name.trim().is_empty()) } /// Where Me's picture's bytes are on this device — `read.mediaPath`'s own /// answer, which knows a serving Mac's store as well as a copy's ledger. fn picture_on_this_device(client: &ClientController, key: &str) -> Result, String> { let Some((sha, ext)) = picture_name(key) else { return Ok(None); }; let mut args = Map::new(); args.insert("key".to_string(), Value::from(key)); args.insert("tier".to_string(), Value::from("largest")); let answer = super::media::media_path(client, &args)?; // Only the original: a thumbnail's bytes are not the picture's sha. let original = answer.get("tier").and_then(Value::as_str) == Some("original"); Ok(answer .get("path") .and_then(Value::as_str) .filter(|_| original) .map(|path| Picture { sha, ext, path: PathBuf::from(path) })) } /// The owner's person in one shared database — the row their signed claim /// binds — with its name and its picture's sha. fn owner_row(file: &ReadFile<'_>, owner_key: &str) -> Result)>, String> { let Some(bound) = cotton_store::member_person::bound_person(file.driver, file.workspace_id, owner_key) .map_err(|error| error.to_string())? else { return Ok(None); }; let row = file .driver .get( "SELECT full_name, avatar_key FROM cotton_people WHERE workspace_id = ? AND id = ? AND archived_at IS NULL", &[ rusqlite::types::Value::Text(file.workspace_id.to_string()), rusqlite::types::Value::Text(bound.person_id.clone()), ], ) .map_err(|error| error.to_string())?; Ok(row.map(|row| { ( bound.person_id.clone(), row.text("full_name").unwrap_or_default().to_string(), row.text("avatar_key").and_then(picture_name).map(|(sha, _)| sha), ) })) } /// Carry Me's name and picture to the owner's person in every shared database /// this device holds where the owner's claim binds one. Answers the ids of the /// databases written; one database's refusal is logged and the rest go on. pub fn carry(client: &ClientController) -> Result, String> { let Some(face) = me(client)? else { return Ok(Vec::new()); }; let Ok(owner_key) = super::vault::person_public_key(client) else { return Ok(Vec::new()); }; let print = face.print(); let layout = client.layout().clone(); let mut carried = Vec::new(); for database in client.databases()? { // A database made here and not yet taken by a server is held and // writable here like any other, so it is carried to as well. if database.personal { continue; } if CARRIED.lock().map(|done| done.get(&database.id) == Some(&print)).unwrap_or(false) { continue; } match carry_into(client, &layout, &database.id, &owner_key, &face) { Ok(wrote) => { if let Ok(mut done) = CARRIED.lock() { done.insert(database.id.clone(), print.clone()); } if wrote { carried.push(database.id); } } Err(refusal) => tracing::warn!( "me: your name and picture could not be carried to database {} — {refusal}. \ The next pass asks again.", database.id ), } } Ok(carried) } /// One shared database: `Ok(true)` when it was written, `Ok(false)` when it /// already matched Me or holds no claim for the owner. fn carry_into( client: &ClientController, layout: &cotton_client::layout::Layout, database: &str, owner_key: &str, face: &Face, ) -> Result { let _named = client.name_database(Some(database))?; let Some((person_id, name, sha)) = client.with_file(|file| owner_row(file, owner_key))? else { return Ok(false); }; let rename = name != face.name; let picture = face.picture.as_ref().filter(|picture| sha.as_deref() != Some(picture.sha.as_str())); if !rename && picture.is_none() { return Ok(false); } client.write_rows("you.carryFace", &mut |ctx| { if rename { let mut patch = Map::new(); patch.insert("full_name".to_string(), Value::from(face.name.clone())); cotton_tools::mcp::handlers::common::update_row(ctx, "cotton_people", &person_id, patch) .map_err(|failure| failure.to_string())?; } if let Some(picture) = picture { let args = super::media::CaptureAvatarArgs { person_id: person_id.clone(), path: picture.path.clone(), mime: cotton_core::import::media_plan::content_type_for_extension(&picture.ext) .unwrap_or("image/jpeg") .to_string(), filename: (!picture.ext.is_empty()).then(|| format!("{}.{}", picture.sha, picture.ext)), photo_id: None, }; super::media::write_avatar(ctx, layout, &args)?; } Ok(json!({ "personId": person_id })) })?; Ok(true) } /// Forget what was carried — a test's fresh start. #[cfg(test)] pub(crate) fn forget_carried() { if let Ok(mut done) = CARRIED.lock() { done.clear(); } }