//! Tool pictures as photo records. //! //! A tool's card names its picture as `{"photo": "photo:"}`: a photo //! record this database holds, drawn from bytes the way any photo is. Two //! kinds of tool carry their picture's bytes with them — the built-ins that //! ship one (`cotton_core::definitions::pictures`) and every installed package //! (its carried `pictures/`, kept one row per picture in `cotton_tool_assets`) //! — and this is //! where those bytes become the record a card can draw. //! //! The work is split where the bytes go: [`missing`] answers what this file //! still lacks, the caller (the server, which owns the object store) puts each //! picture's bytes under [`ToolPhoto::key`] and [`ToolPhoto::thumb_key`], and //! [`write_records`] then writes the rows — so a record never names bytes that //! were not stored. use base64::{engine::general_purpose::STANDARD, Engine}; use cotton_core::definitions::pictures::BUILTIN_TOOL_PICTURES; use cotton_core::media::keys; use cotton_store::protocol::derived_id::photo_record_id; use rusqlite::types::Value as SqlValue; use serde_json::{Map, Value}; use sha2::{Digest, Sha256}; use std::collections::BTreeMap; use crate::mcp::dispatch::Ctx; use crate::mcp::handlers::common::{insert_row, now_iso}; use crate::mcp::protocol::ToolFailure; /// Where the package installer keeps a package's carried pictures /// (`tool_packages`): one row per (tool, file name), its bytes as base64 — /// a core table of its own since 137, no longer a `cotton_records` row. pub const TOOL_ASSETS: &str = "cotton_tool_assets"; /// The pictures tool `tool_id`'s installed package carries, by file name, as /// the standard base64 the package's asset rows keep — empty for a package /// that carries none. pub fn package_pictures( db: &cotton_store::Driver, workspace_id: &str, tool_id: &str, ) -> Result, String> { Ok(db .all( &format!("SELECT name, bytes FROM {TOOL_ASSETS} WHERE workspace_id = ? AND tool_id = ? ORDER BY name"), &[SqlValue::Text(workspace_id.into()), SqlValue::Text(tool_id.into())], ) .map_err(|error| error.to_string())? .into_iter() .filter_map(|row| Some((row.text("name")?.to_string(), row.text("bytes")?.to_string()))) .collect()) } /// One tool picture this file names and holds no photo record for. #[derive(Debug, Clone, PartialEq, Eq)] pub struct ToolPhoto { pub sha256: String, pub ext: String, pub content_type: &'static str, pub bytes: Vec, } impl ToolPhoto { /// The photo record's id, the one a tool's `{"photo": …}` names. pub fn id(&self) -> String { photo_record_id(&self.sha256) } /// Where the bytes are stored for this file. pub fn key(&self, file: &cotton_store::file_identity::FileId) -> String { keys::photo_key(file, &self.sha256, &self.ext) } /// The grid tier a phone asks for first. A tool picture is a small /// cut-out, so the tier holds the same bytes: a JPEG thumbnail would lose /// the transparency the object is cut out of. pub fn thumb_key(&self, file: &cotton_store::file_identity::FileId) -> String { keys::photo_thumb_key(file, &self.sha256) } } /// The pictures the build itself carries, by hash: every shipped built-in /// picture, then the `objects` the app ships that built-in pictures name (PNG /// bytes the server carries). fn shipped(objects: &[&[u8]]) -> BTreeMap { let mut wanted: BTreeMap = BTreeMap::new(); for (sha, bytes) in BUILTIN_TOOL_PICTURES { if let Some(photo) = picture(&format!("{sha}.png"), bytes.to_vec()) { wanted.insert(photo.sha256.clone(), photo); } } for bytes in objects { let sha = hex::encode(Sha256::digest(bytes)); if let Some(photo) = picture(&format!("{sha}.png"), bytes.to_vec()) { wanted.entry(photo.sha256.clone()).or_insert(photo); } } wanted } /// The pictures this file's installed packages carry, by hash — each taken /// only under the hash of its own bytes ([`picture`]). fn carried_by_packages(db: &cotton_store::Driver, workspace_id: &str) -> Result, ToolFailure> { let mut wanted: BTreeMap = BTreeMap::new(); let rows = db .all( &format!("SELECT name, bytes FROM {TOOL_ASSETS} WHERE workspace_id = ? ORDER BY tool_id, name"), &[SqlValue::Text(workspace_id.into())], ) .map_err(|error| ToolFailure::new(error.to_string()))?; for row in rows { let (Some(name), Some(encoded)) = (row.text("name"), row.text("bytes")) else { continue }; let Ok(bytes) = STANDARD.decode(encoded) else { continue }; if let Some(photo) = picture(name, bytes) { wanted.entry(photo.sha256.clone()).or_insert(photo); } } Ok(wanted) } /// The photo records that ARE the build's own tool pictures, for `objects` — /// the same pictures [`missing`] seeds. The bytes never change in a running /// build, so a caller that asks every minute keeps the answer. pub fn shipped_record_ids(objects: &[&[u8]]) -> std::collections::BTreeSet { shipped(objects).values().map(ToolPhoto::id).collect() } /// The photo records that are pictures this file's installed packages carry. pub fn package_record_ids(db: &cotton_store::Driver, workspace_id: &str) -> Result, String> { Ok(carried_by_packages(db, workspace_id).map_err(|failure| failure.0)?.values().map(ToolPhoto::id).collect()) } /// The tool pictures this file has bytes for and no photo record of: every /// shipped built-in picture, the `objects` the app ships that built-in /// pictures name (PNG bytes the server carries), then every installed /// package's carried ones. pub fn missing(ctx: &Ctx<'_>, objects: &[&[u8]]) -> Result, ToolFailure> { let mut wanted = shipped(objects); for (sha, photo) in carried_by_packages(ctx.db(), ctx.workspace_id)? { wanted.entry(sha).or_insert(photo); } let mut missing = Vec::new(); for photo in wanted.into_values() { let held = ctx .db() .get( "SELECT id FROM cotton_photos WHERE workspace_id = ? AND id = ?", &[SqlValue::Text(ctx.workspace_id.into()), SqlValue::Text(photo.id())], ) .map_err(|error| ToolFailure::new(error.to_string()))? .is_some(); if !held { missing.push(photo); } } Ok(missing) } /// The photo records for pictures whose bytes the caller has stored. pub fn write_records(ctx: &mut Ctx<'_>, photos: &[ToolPhoto]) -> Result<(), ToolFailure> { for photo in photos { let patch = record_patch(ctx, photo, &format!("{}.{}", photo.sha256, photo.ext)); insert_row(ctx, "cotton_photos", &photo.id(), patch)?; } Ok(()) } /// A picture sent whole (`add_photo`), by what its bytes are: a PNG, JPEG or /// WebP, under the hash of its own bytes. Anything else is no picture. pub fn uploaded(bytes: Vec) -> Option { let (ext, content_type) = if bytes.starts_with(b"\x89PNG\r\n\x1a\n") { ("png", "image/png") } else if bytes.starts_with(&[0xFF, 0xD8, 0xFF]) { ("jpg", "image/jpeg") } else if bytes.len() > 12 && &bytes[..4] == b"RIFF" && &bytes[8..12] == b"WEBP" { ("webp", "image/webp") } else { return None; }; let sha256 = hex::encode(Sha256::digest(&bytes)); Some(ToolPhoto { sha256, ext: ext.to_string(), content_type, bytes }) } /// The photo record of a picture sent whole, whose bytes the caller has /// stored: named `file_name`, with the sender's caption when there is one. pub fn write_upload(ctx: &mut Ctx<'_>, photo: &ToolPhoto, file_name: &str, caption: Option<&str>) -> Result<(), ToolFailure> { let mut patch = record_patch(ctx, photo, file_name); if let Some(caption) = caption { patch.insert("caption".into(), Value::from(caption)); } insert_row(ctx, "cotton_photos", &photo.id(), patch) } /// One picture's photo row: where its bytes are, what they are, and when it /// arrived in this file. fn record_patch(ctx: &Ctx<'_>, photo: &ToolPhoto, file_name: &str) -> Map { let file = ctx.file.id(); let mut patch = Map::new(); patch.insert("key".into(), Value::from(photo.key(&file))); patch.insert("sha256".into(), Value::from(photo.sha256.clone())); patch.insert("content_type".into(), Value::from(photo.content_type)); patch.insert("size_bytes".into(), Value::from(photo.bytes.len())); if let Some((width, height)) = png_size(&photo.bytes) { patch.insert("width".into(), Value::from(width)); patch.insert("height".into(), Value::from(height)); } patch.insert("original_filename".into(), Value::from(file_name)); // A photo row requires when it was taken; a picture sent here was // not taken here, so it is dated when it arrived in this file. patch.insert("taken_at".into(), Value::from(now_iso(ctx))); patch } /// A carried picture by its name (`.`), when the name is its /// own bytes' hash and the bytes are a picture a card can draw. fn picture(name: &str, bytes: Vec) -> Option { let (stem, ext) = name.rsplit_once('.')?; let ext = ext.to_ascii_lowercase(); let content_type = match ext.as_str() { "png" => "image/png", "jpg" | "jpeg" => "image/jpeg", "webp" => "image/webp", _ => return None, }; let sha256 = hex::encode(Sha256::digest(&bytes)); (stem == sha256).then_some(ToolPhoto { sha256, ext, content_type, bytes }) } /// A PNG's width and height, from its header. fn png_size(bytes: &[u8]) -> Option<(u32, u32)> { if bytes.len() < 24 || &bytes[..8] != b"\x89PNG\r\n\x1a\n" { return None; } let width = u32::from_be_bytes(bytes[16..20].try_into().ok()?); let height = u32::from_be_bytes(bytes[20..24].try_into().ok()?); Some((width, height)) } #[cfg(test)] mod tests { use super::*; /// RULE: a carried picture becomes a photo record only under the hash of /// its own bytes — a name that lies would give the tool's card someone /// else's photo id, or a record whose key holds different bytes. #[test] fn a_picture_is_taken_only_under_its_own_hash() { let bytes = BUILTIN_TOOL_PICTURES[0].1.to_vec(); let sha = BUILTIN_TOOL_PICTURES[0].0; let photo = picture(&format!("{sha}.PNG"), bytes.clone()).expect("its own hash"); assert_eq!(photo.id(), format!("photo:{sha}")); assert_eq!(photo.content_type, "image/png"); assert!(png_size(&photo.bytes).is_some()); assert_eq!(picture(&format!("{}.png", "0".repeat(64)), bytes.clone()), None); assert_eq!(picture(&format!("{sha}.svg"), bytes), None); } }