//! The photos engine through the generic verbs — photos, videos, albums, and //! the engine's four VIEWS (`cotton_core::definitions::VIEW_TABLES`): the one //! library (`media`), an album's pictures (`album_item`), the duplicate pairs //! (`duplicate`) and where a picture was seen (`sighting`). //! //! READS. A photo, a video and an album are kinds with tables of their own, so //! they read through `builtin` like every other kind; what their engine adds //! beside the stored columns is here — the albums a picture is in, an album's //! print and how many pictures it holds ([`picture_extras`], //! [`album_extras`]) — and so are their `where` keys, each an entry in //! `builtin::NARROWINGS` ([`in_album`], [`addable_to`]). A VIEW has no table: //! each is one constant SELECT over the engine's own tables ([`view_sql`]), //! read through [`list_view`] and [`read_view`], which narrow, search, order //! and count it in SQL. Every column name that reaches that SQL is a declared //! column of the shipped view, checked and quoted; every value is bound. //! //! What a list leaves out unless a `where` asks: the library leaves out the //! pictures the owner agreed are copies (the grid's own rule — a copy is //! filtered, never deleted), and the duplicates are the OPEN pairs. A read by //! id answers every row, so a write's before and after can always be read. //! //! WRITES go through the tools that already write each table, called by the //! adapters in `builtin`: `update_photo` / `update_video` (a caption, a review //! note), `remove_photo` / `remove_video` (the picture and its bytes, which no //! undo can bring back), `update_album` (a name, a cover, a picture added or //! taken out), `decide_album` (keep, not this, bring it back) and //! `decide_duplicate`. A sighting is read only. use std::collections::BTreeMap; use cotton_core::definitions::{is_device_answered_column, TableDefinition}; use cotton_core::records::{Changed, Condition, Data, RecordError, WhereClause, WhereRefusal}; use cotton_store::driver::Row; use cotton_store::protocol::derived_id::media_album_item_id; use rusqlite::types::Value as SqlValue; use serde_json::{json, Map, Value}; use sha2::{Digest, Sha256}; use super::builtin::call; use super::{refuse, sql_err, sql_value, Page, Stored}; use crate::mcp::dispatch::Ctx; use crate::mcp::handlers::common::{text, Valid}; use crate::mcp::handlers::media_tools::is_media_id; use crate::mcp::handlers::{albums, media_analysis, photos, videos}; use crate::mcp::protocol::ToolFailure; use crate::mcp::read_db::Filter; // ── the views ─────────────────────────────────────────────────────────────── /// The photos engine's views, by id — this module's share of `VIEW_TABLES`. pub const MEDIA_VIEWS: [&str; 4] = ["media", "album_item", "duplicate", "sighting"]; /// Is this definition one of the photos engine's views? pub fn is_view(definition: &TableDefinition) -> bool { definition.has_engine() && MEDIA_VIEWS.contains(&definition.id.as_str()) } /// The workspace, bound ONCE as a one-row table every view reads it from, so /// the `?`s that follow a view's SELECT are numbered in the order written. const WORKSPACE: &str = "ws(id) AS (SELECT ?)"; /// One picture of either kind in the library: a film's print is its poster. /// A picture in the bin is deleted, waiting: no view here shows it. const MEDIA_SQL: &str = "SELECT p.id AS id, 'photo' AS kind, p.key AS key, p.caption AS caption, \ p.taken_at AS taken_at, p.place_name AS place_name, p.summary AS summary, NULL AS duration_ms, \ p.size_bytes AS size_bytes, p.place_city AS place_city, p.camera_make AS camera_make, \ p.camera_model AS camera_model, p.favourite AS favourite, p.created_at AS created_at, p.updated_at AS updated_at \ FROM cotton_photos p WHERE p.workspace_id = (SELECT id FROM ws) AND p.trashed_at IS NULL \ UNION ALL \ SELECT v.id, 'video', v.poster_key, v.caption, v.taken_at, v.place_name, v.summary, \ v.duration_ms, v.size_bytes, v.place_city, v.camera_make, v.camera_model, v.favourite, v.created_at, v.updated_at \ FROM cotton_videos v WHERE v.workspace_id = (SELECT id FROM ws) AND v.trashed_at IS NULL"; /// One picture in one album, its print and words beside it. const ALBUM_ITEM_SQL: &str = "SELECT i.id AS id, i.album_id AS album_id, i.record_id AS record_id, \ i.record_kind AS record_kind, i.added_by AS added_by, i.sort_at AS sort_at, i.origin_handle AS origin_handle, \ i.record_kind AS kind, CASE i.record_kind WHEN 'video' THEN v.poster_key ELSE p.key END AS key, \ COALESCE(p.caption, v.caption) AS caption, COALESCE(p.taken_at, v.taken_at, i.sort_at) AS taken_at, \ v.duration_ms AS duration_ms, i.created_at AS created_at, i.updated_at AS updated_at \ FROM cotton_media_album_items i \ LEFT JOIN cotton_photos p ON i.record_kind = 'photo' AND p.id = i.record_id \ LEFT JOIN cotton_videos v ON i.record_kind = 'video' AND v.id = i.record_id \ WHERE i.workspace_id = (SELECT id FROM ws) AND p.trashed_at IS NULL AND v.trashed_at IS NULL"; /// One proposed pair, both prints and what the facts are made of. A pair is /// two photos or two films (`record_kind`, and both ids carry its prefix), so /// each side reads from the one library — a film's print is its poster. const DUPLICATE_SQL: &str = "SELECT d.id AS id, d.record_kind AS record_kind, d.keep_id AS keep_id, d.copy_id AS copy_id, \ COALESCE(kp.key, kv.poster_key) AS keep_key, COALESCE(cp.key, cv.poster_key) AS copy_key, \ d.distance AS distance, d.method AS method, \ d.state AS state, d.decided_at AS decided_at, d.created_at AS created_at, d.updated_at AS updated_at, \ COALESCE(kp.id, kv.id) AS keep_found, COALESCE(kp.width, kv.width) AS keep_width, \ COALESCE(kp.height, kv.height) AS keep_height, \ COALESCE(kp.size_bytes, kv.size_bytes) AS keep_size, COALESCE(kp.favourite, kv.favourite) AS keep_favourite, \ COALESCE(cp.id, cv.id) AS copy_found, COALESCE(cp.width, cv.width) AS copy_width, \ COALESCE(cp.height, cv.height) AS copy_height, \ COALESCE(cp.size_bytes, cv.size_bytes) AS copy_size, COALESCE(cp.favourite, cv.favourite) AS copy_favourite \ FROM cotton_media_duplicates d \ LEFT JOIN cotton_photos kp ON kp.id = d.keep_id AND kp.workspace_id = d.workspace_id \ LEFT JOIN cotton_videos kv ON kv.id = d.keep_id AND kv.workspace_id = d.workspace_id \ LEFT JOIN cotton_photos cp ON cp.id = d.copy_id AND cp.workspace_id = d.workspace_id \ LEFT JOIN cotton_videos cv ON cv.id = d.copy_id AND cv.workspace_id = d.workspace_id \ WHERE d.workspace_id = (SELECT id FROM ws) \ AND kp.trashed_at IS NULL AND kv.trashed_at IS NULL AND cp.trashed_at IS NULL AND cv.trashed_at IS NULL"; /// One place a picture was seen, with its chat's name. const SIGHTING_SQL: &str = "SELECT s.id AS id, \ CASE s.record_kind WHEN 'photo' THEN s.record_id END AS photo_id, \ CASE s.record_kind WHEN 'video' THEN s.record_id END AS video_id, \ s.record_kind AS record_kind, s.record_id AS record_id, s.source AS source, s.source_id AS source_id, \ s.key AS key, s.thread_id AS thread_id, t.title AS thread_name, s.seen_at AS seen_at, \ s.created_at AS created_at, s.updated_at AS updated_at \ FROM cotton_media_sightings s LEFT JOIN cotton_msg_threads t ON t.id = s.thread_id \ WHERE s.workspace_id = (SELECT id FROM ws) AND s.record_id NOT IN (SELECT id FROM cotton_photos WHERE trashed_at IS NOT NULL UNION ALL SELECT id FROM cotton_videos WHERE trashed_at IS NOT NULL)"; /// What a view reads, and how its list is ordered. struct View { sql: &'static str, /// Declared columns filled outside the SELECT (a duplicate's facts or /// a picture's links), so scalar SQL `where` cannot name them. worded: &'static [&'static str], order: &'static str, } fn view_sql(id: &str) -> Option { Some(match id { "media" => View { sql: MEDIA_SQL, // These links are filled beside each picture, not selected by the // union. Refuse scalar SQL filtering rather than letting SQLite // read a quoted missing column as a string literal. worded: &["albums", "people"], order: "taken_at IS NULL, taken_at DESC, id", }, "album_item" => View { sql: ALBUM_ITEM_SQL, worded: &[], // An album reads in the order its moment unfolded (`get_album`). // A picture is in many albums, so the item's own id ends the tie. order: "taken_at IS NULL, taken_at ASC, record_id, id", }, "duplicate" => View { sql: DUPLICATE_SQL, worded: &["keep_facts", "copy_facts"], // Grouped by the picture to keep, closest copy first // (`list_duplicates`). order: "keep_id, distance, copy_id", }, "sighting" => View { sql: SIGHTING_SQL, worded: &[], // Oldest first, as a picture's page lists where it was seen. order: "seen_at IS NULL, seen_at ASC, id", }, _ => return None, }) } /// A declared column of the view, as SQL — the key checked to be one of the /// definition's own (`parse_where` has already refused any other) and quoted. /// A column only a phone answers (the library's `on_phone`, /// `DEVICE_ANSWERED_COLUMNS`) is no fact of the object's, so it is refused in /// words as the columns filled beside each row are. fn view_column(definition: &TableDefinition, view: &View, key: &str) -> Valid { let plain = !key.is_empty() && key .bytes() .all(|byte| byte.is_ascii_lowercase() || byte.is_ascii_digit() || byte == b'_'); if definition.column(key).is_none() || !plain || view.worded.contains(&key) || is_device_answered_column(&definition.id, key) { return Err(refuse(RecordError::CannotNarrow { plural: definition.plural.clone(), column: key.to_string(), })); } // Qualified by the view: a declared column its SELECT does not answer is // then SQLite's "no such column", never a quoted name read as a string // literal that silently narrows to nothing. Ok(format!("v.\"{key}\"")) } /// One `where` entry over a view, appended to `sql`. fn view_where( definition: &TableDefinition, view: &View, clause: &WhereClause, sql: &mut String, params: &mut Vec, zone: &cotton_core::records::Zone, ) -> Valid<()> { let column = view_column(definition, view, &clause.column)?; match &clause.condition { Condition::Is(value) => { sql.push_str(&format!(" AND {column} = ?")); params.push(sql_value(value)); } Condition::OneOf(values) => { let holes = vec!["?"; values.len()].join(", "); sql.push_str(&format!(" AND {column} IN ({holes})")); params.extend(values.iter().map(sql_value)); } Condition::Present(present) => { let test = if *present { "<>" } else { "=" }; sql.push_str(&format!(" AND COALESCE({column}, '') {test} ''")); } Condition::NoneOf(values) => { // NULLIF: a record holding nothing holds no value, and SQL's NULL // NOT IN answers no row — so blanks stay out. let holes = vec!["?"; values.len()].join(", "); sql.push_str(&format!(" AND NULLIF({column}, '') NOT IN ({holes})")); params.extend(values.iter().map(sql_value)); } Condition::Month(month) => { sql.push_str(&format!(" AND {}", super::yearly_dates::in_month(&column, *month))); } Condition::WithinDays(days) => { sql.push_str(&format!(" AND {}", super::within_days(&column, *days))); } Condition::On(day) => { sql.push_str(&format!(" AND {}", super::on_day(&column, *day, zone))); } Condition::Bound(_) => { sql.push_str(" AND "); sql.push_str(&super::condition_sql(&column, &clause.condition, params, zone)); } } Ok(()) } /// The rows a view's LIST leaves out unless a `where` names the column that /// decides it: the library's agreed copies, and the duplicates already /// answered. fn list_defaults(id: &str, clauses: &[WhereClause], sql: &mut String) { let names = |column: &str| clauses.iter().any(|clause| clause.column == column); match id { "media" => sql.push_str( " AND NOT (kind = 'photo' AND EXISTS (SELECT 1 FROM cotton_media_duplicates d \ WHERE d.workspace_id = (SELECT id FROM ws) AND d.copy_id = v.id \ AND d.state = 'confirmed'))", ), "duplicate" if !names("state") => sql.push_str(" AND state = 'open'"), _ => {} } } /// One page of a view's records, and how many the whole list holds. #[allow(clippy::too_many_arguments)] pub fn list_view( ctx: &Ctx<'_>, definition: &TableDefinition, project: Option<&str>, query_text: Option<&str>, clauses: &[WhereClause], offset: i64, limit: i64, ) -> Valid { let view = view_sql(&definition.id).ok_or_else(|| super::read_only(definition))?; let mut sql = String::from(" FROM v WHERE 1"); let mut params = vec![SqlValue::Text(ctx.workspace_id.to_string())]; list_defaults(&definition.id, clauses, &mut sql); let zone = crate::mcp::handlers::common::where_zone(ctx)?; for clause in clauses { view_where(definition, &view, clause, &mut sql, &mut params, &zone)?; } if let Some(project) = project { if definition.id != "media" { return Err(ToolFailure::new(format!( "{} are not filed in projects", definition.plural ))); } sql.push_str( " AND EXISTS (SELECT 1 FROM cotton_project_links l WHERE l.record_id = v.id \ AND l.record_kind = v.kind AND l.project_id = ?)", ); params.push(SqlValue::Text(project.to_string())); } if let Some(words) = query_text { // Every word somewhere in what the picture says: its caption or its // description (the definition's `search`). let columns: Vec = definition .search .iter() .flatten() .map(|key| view_column(definition, &view, key)) .collect::>()?; if columns.is_empty() { sql.push_str(" AND 0"); } for word in words.split_whitespace() { let any: Vec = columns .iter() .map(|column| format!("instr(lower(COALESCE({column}, '')), lower(?)) > 0")) .collect(); if !any.is_empty() { sql.push_str(&format!(" AND ({})", any.join(" OR "))); params.extend(columns.iter().map(|_| SqlValue::Text(word.to_string()))); } } } let with = format!("WITH {WORKSPACE}, v AS ({})", view.sql); let db = ctx.read.driver(); let total = db .get(&format!("{with} SELECT COUNT(*) AS n{sql}"), ¶ms) .map_err(sql_err)? .and_then(|row| row.int("n")) .unwrap_or(0); let mut page_params = params; page_params.push(SqlValue::Integer(limit + 1)); page_params.push(SqlValue::Integer(offset)); let rows = db .all( &format!("{with} SELECT *{sql} ORDER BY {} LIMIT ? OFFSET ?", view.order), &page_params, ) .map_err(sql_err)?; let mut records: Vec = rows.iter().map(|row| view_record(definition, row)).collect(); let more = records.len() as i64 > limit; records.truncate(limit as usize); Ok(Page { records, more, total, }) } /// One row of a view by its id — every row, whatever its list leaves out. pub fn read_view(ctx: &Ctx<'_>, definition: &TableDefinition, id: &str) -> Valid> { let view = view_sql(&definition.id).ok_or_else(|| super::read_only(definition))?; let row = ctx .read .driver() .get( &format!( "WITH {WORKSPACE}, v AS ({}) SELECT * FROM v WHERE id = ?", view.sql ), &[ SqlValue::Text(ctx.workspace_id.to_string()), SqlValue::Text(id.to_string()), ], ) .map_err(sql_err)?; Ok(row.map(|row| view_record(definition, &row))) } fn json_of(value: &SqlValue) -> Value { match value { SqlValue::Null | SqlValue::Blob(_) => Value::Null, SqlValue::Integer(number) => Value::from(*number), SqlValue::Real(number) => serde_json::Number::from_f64(*number).map_or(Value::Null, Value::Number), SqlValue::Text(words) => Value::from(words.clone()), } } /// A view row as a record: its declared columns, nulls left out. fn view_record(definition: &TableDefinition, row: &Row) -> Stored { let columns: BTreeMap<&str, Value> = row .columns() .iter() .map(|(name, value)| (name.as_str(), json_of(value))) .collect(); let mut data = Data::new(); for column in &definition.columns { if let Some(value) = columns.get(column.key.as_str()).filter(|value| !value.is_null()) { // A yes-or-no column reads as one: SQLite holds a favourite as 0 or 1. let value = match value.as_i64() { Some(number) if column.column_type == cotton_core::definitions::ColumnType::Bool => Value::Bool(number != 0), _ => value.clone(), }; data.insert(column.key.clone(), value); } } if definition.id == "duplicate" { for side in ["keep", "copy"] { if let Some(facts) = side_facts(&columns, side) { data.insert(format!("{side}_facts"), Value::from(facts)); } } } let words = |name: &str| columns.get(name).and_then(Value::as_str).map(str::to_string); Stored { id: words("id").unwrap_or_default(), data, created_at: words("created_at"), updated_at: words("updated_at"), deleted_at: None, byline: None, } } /// One side of a pair in words, read off the columns the view selected for it. fn side_facts(columns: &BTreeMap<&str, Value>, side: &str) -> Option { let get = |name: &str| columns.get(format!("{side}_{name}").as_str()); get("found").filter(|found| !found.is_null())?; picture_facts( get("width").and_then(Value::as_i64), get("height").and_then(Value::as_i64), get("size").and_then(Value::as_i64), get("favourite").and_then(Value::as_i64) == Some(1), ) } /// What a duplicate pair says under one picture: "4032 × 3024 · 2.1 MB · /// Favourite" — the dimensions only when both are known, the size only when /// one was recorded, and nothing at all when there is nothing to say. pub fn picture_facts( width: Option, height: Option, size_bytes: Option, favourite: bool, ) -> Option { let mut parts: Vec = Vec::new(); if let (Some(width), Some(height)) = (width, height) { parts.push(format!("{width} × {height}")); } if let Some(size) = size_label(size_bytes) { parts.push(size); } if favourite { parts.push("Favourite".to_string()); } (!parts.is_empty()).then(|| parts.join(" · ")) } /// "812 B" · "44 KB" · "3.2 MB" · "412 MB" · "2.4 GB" — the app's own /// `MediaBytes.sizeLabel`, rung for rung: nothing for no size or zero, a /// decimal under ten of a unit, the rung crossed where the LABEL would read /// 1024. pub fn size_label(bytes: Option) -> Option { let bytes = bytes.filter(|bytes| *bytes > 0)?; if bytes < 1024 { return Some(format!("{bytes} B")); } let kb = bytes as f64 / 1024.0; if kb < 1024.0 { return Some(format!("{} KB", kb.round() as i64)); } let mb = kb / 1024.0; if mb.round() < 1024.0 { return Some(if mb < 10.0 { format!("{mb:.1} MB") } else { format!("{} MB", mb.round() as i64) }); } let gb = mb / 1024.0; Some(if gb < 10.0 { format!("{gb:.1} GB") } else { format!("{} GB", gb.round() as i64) }) } // ── what the engine adds to a photo, a video and an album ─────────────────── /// The albums a picture is in — a link holding several, newest album first, /// a dismissed album left out (it is no album the owner keeps). pub fn picture_extras(ctx: &Ctx<'_>, row: &Map, data: &mut Data) -> Valid<()> { let id = text(row, "id").unwrap_or_default(); let albums: Vec = ctx .read .driver() .all( "SELECT a.id FROM cotton_media_album_items i \ JOIN cotton_media_albums a ON a.id = i.album_id \ WHERE i.workspace_id = ? AND i.record_id = ? AND a.state <> 'dismissed' \ ORDER BY a.starts_at DESC, a.id", &[ SqlValue::Text(ctx.workspace_id.to_string()), SqlValue::Text(id.clone()), ], ) .map_err(sql_err)? .iter() .filter_map(|row| row.text("id").map(Value::from)) .collect(); if !albums.is_empty() { data.insert("albums".into(), Value::Array(albums)); } // Who is in the picture: the people the owner confirmed on its faces // (`cotton_media_faces.person_id`), each once — never a suggestion. let mut people: Vec = Vec::new(); for row in ctx .read .driver() .all( "SELECT DISTINCT person_id FROM cotton_media_faces \ WHERE workspace_id = ? AND record_id = ? AND person_id IS NOT NULL \ ORDER BY person_id", &[ SqlValue::Text(ctx.workspace_id.to_string()), SqlValue::Text(id.clone()), ], ) .map_err(sql_err)? { if let Some(person) = row.text("person_id") { people.push(Value::from(person)); } } if !people.is_empty() { data.insert("people".into(), Value::Array(people)); } Ok(()) } const PHOTO_WITH_SOMEONE: &str = "EXISTS (SELECT 1 FROM cotton_media_faces f \ WHERE f.record_id = cotton_photos.id AND f.person_id IS NOT NULL)"; const PHOTO_WITH_NOBODY: &str = "NOT EXISTS (SELECT 1 FROM cotton_media_faces f \ WHERE f.record_id = cotton_photos.id AND f.person_id IS NOT NULL)"; const VIDEO_WITH_SOMEONE: &str = "EXISTS (SELECT 1 FROM cotton_media_faces f \ WHERE f.record_id = cotton_videos.id AND f.person_id IS NOT NULL)"; const VIDEO_WITH_NOBODY: &str = "NOT EXISTS (SELECT 1 FROM cotton_media_faces f \ WHERE f.record_id = cotton_videos.id AND f.person_id IS NOT NULL)"; /// `where {people}` on photos and videos: pictures this person (or any of /// these) was confirmed in, or pictures with anyone confirmed at all /// (`present`) — the same faces [`picture_extras`] answers `people` from, so /// a person's page lists exactly the pictures whose page names them. pub fn with_person( ctx: &Ctx<'_>, definition: &TableDefinition, condition: &Condition, ) -> Valid> { let wanted: Vec = match condition { Condition::Is(value) => value.as_str().map(str::to_string).into_iter().collect(), Condition::OneOf(values) => values .iter() .filter_map(Value::as_str) .map(str::to_string) .collect(), Condition::Present(present) => { let video = definition.id == "video"; return Ok(vec![Filter::Static(match (video, *present) { (false, true) => PHOTO_WITH_SOMEONE, (false, false) => PHOTO_WITH_NOBODY, (true, true) => VIDEO_WITH_SOMEONE, (true, false) => VIDEO_WITH_NOBODY, })]); } Condition::NoneOf(_) | Condition::Month(_) | Condition::WithinDays(_) | Condition::Bound(_) | Condition::On(_) => unreachable!("narrow refuses not, month, within_days and bounds before a table's own narrowing"), }; let mut pictured: Vec = Vec::new(); for person in &wanted { for row in ctx .read .driver() .all( "SELECT DISTINCT record_id FROM cotton_media_faces \ WHERE workspace_id = ? AND person_id = ? AND record_kind = ?", &[ SqlValue::Text(ctx.workspace_id.to_string()), SqlValue::Text(person.clone()), SqlValue::Text(definition.id.clone()), ], ) .map_err(sql_err)? { if let Some(id) = row.text("record_id") { pictured.push(SqlValue::Text(id.to_string())); } } } Ok(vec![Filter::In("id".into(), pictured)]) } /// An album's print — its cover picture (a film's poster) and that picture's /// size — and how many pictures it holds. pub fn album_extras(ctx: &Ctx<'_>, row: &Map, data: &mut Data) -> Valid<()> { let id = text(row, "id").unwrap_or_default(); let db = ctx.read.driver(); let workspace = SqlValue::Text(ctx.workspace_id.to_string()); let members = db .get( "SELECT COUNT(*) AS n FROM cotton_media_album_items WHERE workspace_id = ? AND album_id = ? \ AND record_id NOT IN (SELECT id FROM cotton_photos WHERE trashed_at IS NOT NULL UNION ALL SELECT id FROM cotton_videos WHERE trashed_at IS NOT NULL)", &[workspace.clone(), SqlValue::Text(id)], ) .map_err(sql_err)? .and_then(|row| row.int("n")) .unwrap_or(0); data.insert("member_count".into(), Value::from(members)); let Some(cover) = text(row, "cover_id") else { return Ok(()); }; let print = db .get( "SELECT key, width, height FROM cotton_photos WHERE workspace_id = ? AND id = ? AND trashed_at IS NULL \ UNION ALL \ SELECT poster_key, width, height FROM cotton_videos WHERE workspace_id = ? AND id = ? AND trashed_at IS NULL", &[ workspace.clone(), SqlValue::Text(cover.clone()), workspace, SqlValue::Text(cover), ], ) .map_err(sql_err)?; if let Some(print) = print { for (column, key) in [("key", "cover_key"), ("width", "cover_width"), ("height", "cover_height")] { let value = match print.columns().iter().find(|(name, _)| name == column) { Some((_, value)) => json_of(value), None => Value::Null, }; if !value.is_null() { data.insert(key.into(), value); } } } Ok(()) } // ── where, through the engine ─────────────────────────────────────────────── /// A picture in an album the owner has not dismissed — `albums` holding /// something, as [`picture_extras`] answers it. const PHOTO_IN_AN_ALBUM: &str = "EXISTS (SELECT 1 FROM cotton_media_album_items i \ JOIN cotton_media_albums a ON a.id = i.album_id \ WHERE i.record_id = cotton_photos.id AND a.state <> 'dismissed')"; const VIDEO_IN_AN_ALBUM: &str = "EXISTS (SELECT 1 FROM cotton_media_album_items i \ JOIN cotton_media_albums a ON a.id = i.album_id \ WHERE i.record_id = cotton_videos.id AND a.state <> 'dismissed')"; /// `where {albums}` on photos and videos: in this album (or any of these), or /// in some album at all (`present`). A link holding several matches when it /// holds the one asked for — and a dismissed album is no album the picture is /// in, as [`picture_extras`] answers `albums`, so naming one matches nothing. pub fn in_album( ctx: &Ctx<'_>, definition: &TableDefinition, condition: &Condition, ) -> Valid> { let video = definition.id == "video"; let wanted: Vec = match condition { Condition::Is(value) => value.as_str().map(str::to_string).into_iter().collect(), Condition::OneOf(values) => values .iter() .filter_map(Value::as_str) .map(str::to_string) .collect(), Condition::Present(present) => { let fragment = if video { VIDEO_IN_AN_ALBUM } else { PHOTO_IN_AN_ALBUM }; return Ok(vec![if *present { Filter::Static(fragment) } else { Filter::Static(if video { "NOT EXISTS (SELECT 1 FROM cotton_media_album_items i \ JOIN cotton_media_albums a ON a.id = i.album_id \ WHERE i.record_id = cotton_videos.id AND a.state <> 'dismissed')" } else { "NOT EXISTS (SELECT 1 FROM cotton_media_album_items i \ JOIN cotton_media_albums a ON a.id = i.album_id \ WHERE i.record_id = cotton_photos.id AND a.state <> 'dismissed')" }) }]); } Condition::NoneOf(_) | Condition::Month(_) | Condition::WithinDays(_) | Condition::Bound(_) | Condition::On(_) => unreachable!("narrow refuses not, month, within_days and bounds before a table's own narrowing"), }; let mut members: Vec = Vec::new(); for album in &wanted { for row in ctx .read .driver() .all( "SELECT i.record_id FROM cotton_media_album_items i \ JOIN cotton_media_albums a ON a.id = i.album_id \ WHERE i.workspace_id = ? AND i.album_id = ? AND i.record_kind = ? \ AND a.state <> 'dismissed'", &[ SqlValue::Text(ctx.workspace_id.to_string()), SqlValue::Text(album.clone()), SqlValue::Text(definition.id.clone()), ], ) .map_err(sql_err)? { if let Some(id) = row.text("record_id") { members.push(SqlValue::Text(id.to_string())); } } } Ok(vec![Filter::In("id".into(), members)]) } /// The SQL twin of `cotton_core::rules::media::albums::album_admits_by_hand` /// over a `cotton_photos` row: not a picture of information, and no /// `screenshot` among its subtypes. A `subtypes` that is not a JSON list holds /// none, as `string_list_of` reads it. const PHOTO_ADMITTED_BY_HAND: &str = "COALESCE(is_utility, 0) <> 1 AND NOT (CASE WHEN \ json_valid(subtypes) AND json_type(subtypes) = 'array' THEN EXISTS (SELECT 1 FROM \ json_each(subtypes) AS st WHERE st.value = 'screenshot') ELSE 0 END)"; /// `where {addable_to: }` on photos: the photos that album can still /// take by hand — not in it already, and admitted (no screenshot, no picture /// of information). An album that is not there is refused, so a stale picker /// never offers the whole library to an album that cannot take it. pub fn addable_to( ctx: &Ctx<'_>, definition: &TableDefinition, condition: &Condition, ) -> Valid> { let Condition::Is(Value::String(album)) = condition else { return Err(refuse(RecordError::BadWhere { column: "addable_to".into(), reason: WhereRefusal::AddableToOneAlbum, })); }; let db = ctx.read.driver(); let workspace = SqlValue::Text(ctx.workspace_id.to_string()); let state = db .get( "SELECT state FROM cotton_media_albums WHERE workspace_id = ? AND id = ?", &[workspace.clone(), SqlValue::Text(album.clone())], ) .map_err(sql_err)?; match state.as_ref().and_then(|row| row.text("state")) { None => { return Err(ToolFailure::new(format!( "there is no album {album:?} to add {} to", definition.plural.to_lowercase() ))) } Some("dismissed") => { return Err(ToolFailure::new(format!( "{album} is dismissed — bring it back before adding to it" ))) } Some(_) => {} } let held: Vec = db .all( "SELECT record_id FROM cotton_media_album_items WHERE workspace_id = ? AND album_id = ?", &[workspace, SqlValue::Text(album.clone())], ) .map_err(sql_err)? .iter() .filter_map(|row| row.text("record_id").map(|id| SqlValue::Text(id.to_string()))) .collect(); Ok(vec![ Filter::NotIn("id".into(), held), Filter::Static(PHOTO_ADMITTED_BY_HAND), ]) } // ── the adapters' writers ─────────────────────────────────────────────────── /// `update_record` on a photo or a video: `caption` (null clears it) and /// `review_note` (null is Keep — the note, its author and its moment go /// together; words set a suggestion under the writer's byline) and /// `favourite` (the owner's star: Cotton Photos marks one, and the Mac /// imports Apple Photos' own), through `update_photo` / `update_video`. pub fn picture_update( ctx: &mut Ctx<'_>, definition: &TableDefinition, id: &str, patch: &Data, ) -> Valid<()> { let mut args = Map::new(); args.insert("id".into(), Value::from(id)); for (key, value) in patch { match key.as_str() { "caption" => { args.insert("caption".into(), value.clone()); } "review_note" => { args.insert("reviewNote".into(), value.clone()); } "favourite" => { args.insert("favourite".into(), value.clone()); } other => { return Err(ToolFailure::new(format!( "{} cannot set {other:?} through the generic verbs; Cotton sets it itself", definition.plural ))) } } } let (name, handler): (&str, super::builtin::Handler) = if definition.id == "video" { ("update_video", videos::update_video) } else { ("update_photo", photos::update_photo) }; call(ctx, definition, name, handler, Value::Object(args)).map(|_| ()) } /// `delete_record` on a photo, a video or the library: the picture goes to /// the bin with its file, through `remove_photo` / `remove_video` — which the /// id's own prefix names. pub fn picture_remove(ctx: &mut Ctx<'_>, definition: &TableDefinition, id: &str) -> Valid<()> { let (name, handler): (&str, super::builtin::Handler) = if is_media_id(id, "video") { ("remove_video", videos::remove_video) } else { ("remove_photo", photos::remove_photo) }; call(ctx, definition, name, handler, json!({ "id": id })).map(|_| ()) } /// The Undo of [`picture_remove`]: out of the bin, on the table the id's own /// prefix names. pub fn picture_untrash(ctx: &mut Ctx<'_>, _definition: &TableDefinition, id: &str) -> Valid<()> { let table = if is_media_id(id, "video") { "cotton_videos" } else { "cotton_photos" }; crate::mcp::handlers::media_tools::set_media_trashed(ctx, table, id, false) } /// `update_record` on the library refuses, but for the star: a picture is /// changed on its own table, and a favourite marked on the library's print /// (Cotton Photos' Recent, Favourites and Videos read the library) is the /// picture's own, so it goes to `update_photo` / `update_video` by the id's /// prefix. pub fn library_update( ctx: &mut Ctx<'_>, definition: &TableDefinition, id: &str, patch: &Data, ) -> Valid<()> { if let Some(favourite) = patch.get("favourite").filter(|_| patch.len() == 1) { let (name, handler): (&str, super::builtin::Handler) = if is_media_id(id, "video") { ("update_video", videos::update_video) } else { ("update_photo", photos::update_photo) }; return call(ctx, definition, name, handler, json!({ "id": id, "favourite": favourite })).map(|_| ()); } Err(ToolFailure::new(format!( "{} are read here; change a picture through its own table — update_record on \"photo\" \ or \"video\" with the same id", definition.plural ))) } /// The decision `decide_album` takes for the state an album should be in. fn album_decision(state: &str) -> Option<&'static str> { match state { "kept" => Some("keep"), "dismissed" => Some("dismiss"), "open" => Some("open"), _ => None, } } /// `update_record` on an album: `title` and `cover_id` (one of its own /// pictures) through `update_album`, which keeps an open suggestion it /// renames; `state` through `decide_album` — kept, dismissed, or open again. /// A dismissed album is brought back BEFORE it is renamed, and anything else /// renamed before it is decided, so one patch can do both in either /// direction. `@title_by` — who named it — comes only from the undo of a /// rename (no patch can name a key that is not a column), and goes back with /// the old name through `albums::put_back_naming`. pub fn album_update( ctx: &mut Ctx<'_>, definition: &TableDefinition, id: &str, patch: &Data, ) -> Valid<()> { let mut edit = Map::new(); let mut wanted: Option = None; let mut named_by: Option = None; for (key, value) in patch { match (key.as_str(), value.as_str()) { (TITLE_BY, Some(by)) => { named_by = Some(by.to_string()); } ("title" | "cover_id", None) => { return Err(ToolFailure::new(format!( "{} cannot clear {key:?}", definition.plural ))) } ("title", Some(title)) => { edit.insert("title".into(), Value::from(title)); } ("cover_id", Some(cover)) => { edit.insert("coverId".into(), Value::from(cover)); } ("state", Some(state)) if album_decision(state).is_some() => { wanted = Some(state.to_string()); } ("state", _) => { return Err(ToolFailure::new(format!( "{} take state \"open\", \"kept\" or \"dismissed\"", definition.plural ))) } (other, _) => { return Err(ToolFailure::new(format!( "{} cannot set {other:?} through the generic verbs; Cotton sets it itself", definition.plural ))) } } } let current = |ctx: &Ctx<'_>| -> Valid> { Ok(ctx .read .driver() .get( "SELECT state FROM cotton_media_albums WHERE workspace_id = ? AND id = ?", &[ SqlValue::Text(ctx.workspace_id.to_string()), SqlValue::Text(id.to_string()), ], ) .map_err(sql_err)? .and_then(|row| row.text("state").map(str::to_string))) }; let decide = |ctx: &mut Ctx<'_>, state: &str| -> Valid<()> { let decision = album_decision(state).unwrap_or("open"); call( ctx, definition, "decide_album", albums::decide_album, json!({ "id": id, "decision": decision }), ) .map(|_| ()) }; if current(ctx)?.as_deref() == Some("dismissed") && !edit.is_empty() { if let Some(state) = wanted.take() { decide(ctx, &state)?; } } if named_by.is_some() && !edit.contains_key("title") { return Err(ToolFailure::new( "who named an album goes back only with the name it gave", )); } if !edit.is_empty() { edit.insert("id".into(), Value::from(id)); call(ctx, definition, "update_album", albums::update_album, Value::Object(edit))?; } if let Some(by) = named_by.filter(|by| by != "user") { albums::put_back_naming(ctx, id, &by)?; } if let Some(state) = wanted { if current(ctx)?.as_deref() != Some(state.as_str()) { decide(ctx, &state)?; } } Ok(()) } // ── what a write changes beside the record (`records::BESIDE`) ────────────── /// Who named an album — `update_album` makes it `user` on a rename. pub const TITLE_BY: &str = "@title_by"; /// The album a picture is put in or taken out of, WHOLE ([`album_snapshot`]): /// `update_album` keeps an open suggestion it changes and re-picks a cover it /// takes out, so the change says what the album was and what it became. pub const ALBUM: &str = "@album"; /// What an album's undo compares to say "unchanged since", and what it puts /// back: its state, decision, name, who named it, cover and bounds, which /// pictures it holds — and two stamps that move on ANY write. `version` is /// the row's `_hlc`, which every write of the album row bumps (its own tools, /// the nightly pass, another device's), even within one millisecond; `items` /// digests each picture's item with its own `_hlc`, so a picture taken out /// and put back, or added by the pass, reads as a change too. const SNAPSHOT_COLUMNS: [&str; 8] = [ "state", "decided_at", "title", "title_by", "cover_id", "starts_at", "ends_at", "_hlc", ]; /// The fields an undo must leave as they WERE — everything but the stamps, /// which any write moves. const RESTORED: [&str; 8] = [ "state", "decided_at", "title", "title_by", "cover_id", "starts_at", "ends_at", "members", ]; /// The whole album, as [`ALBUM`] holds it, or `None` when there is none. fn album_snapshot(ctx: &Ctx<'_>, album: &str) -> Valid> { let db = ctx.read.driver(); let workspace = SqlValue::Text(ctx.workspace_id.to_string()); let Some(row) = db .get( &format!( "SELECT {} FROM cotton_media_albums WHERE workspace_id = ? AND id = ?", SNAPSHOT_COLUMNS.join(", ") ), &[workspace.clone(), SqlValue::Text(album.to_string())], ) .map_err(sql_err)? else { return Ok(None); }; let mut out = Map::new(); for column in SNAPSHOT_COLUMNS { let key = if column == "_hlc" { "version" } else { column }; out.insert(key.into(), row.text(column).map_or(Value::Null, Value::from)); } let items = db .all( "SELECT record_id, _hlc FROM cotton_media_album_items \ WHERE workspace_id = ? AND album_id = ? ORDER BY record_id", &[workspace, SqlValue::Text(album.to_string())], ) .map_err(sql_err)?; let members: Vec = items .iter() .filter_map(|item| item.text("record_id").map(Value::from)) .collect(); let stamped: Vec = items .iter() .map(|item| { format!( "{} {}", item.text("record_id").unwrap_or_default(), item.text("_hlc").unwrap_or_default() ) }) .collect(); out.insert("members".into(), Value::Array(members)); out.insert( "items".into(), Value::from(hex::encode(Sha256::digest(stamped.join("\n").as_bytes()))), ); Ok(Some(Value::Object(out))) } /// An album's own state a write to it can move beside its columns: who named /// it. pub fn album_beside(ctx: &Ctx<'_>, id: &str) -> Valid { let mut out = Data::new(); let row = ctx .read .driver() .get( "SELECT title_by FROM cotton_media_albums WHERE workspace_id = ? AND id = ?", &[ SqlValue::Text(ctx.workspace_id.to_string()), SqlValue::Text(id.to_string()), ], ) .map_err(sql_err)?; if let Some(row) = row { out.insert( TITLE_BY.into(), row.text("title_by").map_or(Value::Null, Value::from), ); } Ok(out) } /// What putting a picture in an album, or taking it out, moves beside the /// picture: the album, whole. pub fn album_item_beside(ctx: &Ctx<'_>, item: &Data) -> Valid { let mut out = Data::new(); if let Some(album) = item.get("album_id").and_then(Value::as_str) { if let Some(snapshot) = album_snapshot(ctx, album)? { out.insert(ALBUM.into(), snapshot); } } Ok(out) } /// The undo of putting a picture in an album: take it out, and put the album /// back as it WAS — an open suggestion the putting-in kept is open again, /// through `decide_album`. Refused, with nothing left written, unless the /// album is wholly as the putting-in left it (its stamps say no write of any /// kind has touched it or its pictures since), and unless taking the picture /// out leaves the album exactly as it was before. pub fn album_item_uncreate( ctx: &mut Ctx<'_>, definition: &TableDefinition, id: &str, item: &Data, beside: &Data, ) -> Valid<()> { let album = item .get("album_id") .and_then(Value::as_str) .map(str::to_string) .ok_or_else(|| ToolFailure::new("this picture names no album to leave"))?; let changed_since = |why: &str| { refuse(RecordError::ChangedSince { what: Changed::Said(format!("album {album} ({why})")), }) }; let moved = beside.get(ALBUM).ok_or_else(|| { ToolFailure::new("this change does not say what it did to the album, so it cannot be undone") })?; let (Some(was), Some(left)) = (moved.get("was"), moved.get("now")) else { return Err(ToolFailure::new("this change does not say what the album was")); }; if album_snapshot(ctx, &album)?.as_ref() != Some(left) { return Err(changed_since("it was changed after the picture went in")); } album_item_remove(ctx, definition, id)?; let state_was = was.get("state").and_then(Value::as_str).unwrap_or_default(); let state_now = album_snapshot(ctx, &album)? .and_then(|now| now.get("state").and_then(Value::as_str).map(str::to_string)); if state_now.as_deref() != Some(state_was) { let decision = album_decision(state_was).ok_or_else(|| { ToolFailure::new(format!("an album cannot be put back to {state_was:?}")) })?; super::builtin::permit_tool(ctx, definition, "decide_album")?; call( ctx, definition, "decide_album", albums::decide_album, json!({ "id": album, "decision": decision }), )?; } let after = album_snapshot(ctx, &album)?.unwrap_or(Value::Null); if let Some(field) = RESTORED.iter().find(|field| after.get(**field) != was.get(**field)) { // The engine could not put the album back exactly — refused, and the // transaction around the undo drops what was written. return Err(ToolFailure::new(format!( "this change cannot be undone: taking the picture out would leave album {album}'s \ {field} other than it was before" ))); } Ok(()) } /// `create_record` on an album's pictures: `{album_id, record_id}` (and the /// picture's `kind`, which must agree) puts one picture in through /// `update_album`; one already there, or one the album cannot take by hand /// (a screenshot, a picture of information), is refused. pub fn album_item_create( ctx: &mut Ctx<'_>, definition: &TableDefinition, values: &Data, ) -> Valid { let words = |key: &str| values.get(key).and_then(Value::as_str).map(str::trim); for key in values.keys() { if !matches!(key.as_str(), "album_id" | "record_id" | "kind") { return Err(ToolFailure::new(format!( "{} take an album_id and a record_id; {key:?} is the picture's own", definition.plural ))); } } let (Some(album), Some(record)) = (words("album_id"), words("record_id")) else { return Err(ToolFailure::new( "album_id and record_id are required: the album, and the photo or video to put in it", )); }; let kind = if is_media_id(record, "video") { "video" } else if is_media_id(record, "photo") { "photo" } else { return Err(ToolFailure::new( "record_id must be a photo's or a video's id — \"photo:\" or \"video:\" then its \ content hash", )); }; if words("kind").is_some_and(|said| said != kind) { return Err(ToolFailure::new(format!("{record} is a {kind}, so kind is {kind:?}"))); } let id = media_album_item_id(album, record); if read_view(ctx, definition, &id)?.is_some() { return Err(ToolFailure::new(format!("{record} is already in {album}"))); } call( ctx, definition, "update_album", albums::update_album, json!({ "id": album, "add": [record] }), )?; Ok(id) } /// `update_record` on an album's picture refuses: it is put in or taken out. pub fn album_item_update( _ctx: &mut Ctx<'_>, definition: &TableDefinition, _id: &str, _patch: &Data, ) -> Valid<()> { Err(ToolFailure::new(format!( "{} are put in an album or taken out of it, never changed", definition.plural ))) } /// `delete_record` on an album's picture takes it out of the album through /// `update_album`; the picture stays in Photos. pub fn album_item_remove(ctx: &mut Ctx<'_>, definition: &TableDefinition, id: &str) -> Valid<()> { let item = read_view(ctx, definition, id)?.ok_or_else(|| { ToolFailure::new(cotton_core::records::receipt::no_longer_here(definition)) })?; let field = |key: &str| item.data.get(key).and_then(Value::as_str).map(str::to_string); let (Some(album), Some(record)) = (field("album_id"), field("record_id")) else { return Err(ToolFailure::new("this picture names no album to leave")); }; call( ctx, definition, "update_album", albums::update_album, json!({ "id": album, "remove": [record] }), ) .map(|_| ()) } /// `update_record` on a duplicate pair: `state` — `confirmed` (keep this one, /// the other is a copy), `dismissed` (they are different) or `open` (take the /// answer back) — through `decide_duplicate`, which deletes nothing. pub fn duplicate_update( ctx: &mut Ctx<'_>, definition: &TableDefinition, id: &str, patch: &Data, ) -> Valid<()> { let mut state: Option<&str> = None; for (key, value) in patch { match (key.as_str(), value.as_str()) { ("state", Some(wanted)) if media_analysis::MEDIA_DUPLICATE_STATES.contains(&wanted) => { state = Some(wanted); } ("state", _) => { return Err(ToolFailure::new(format!( "{} take state \"confirmed\", \"dismissed\" or \"open\"", definition.plural ))) } // When a pair was decided follows its state: decide_duplicate // stamps it, or clears it for "open". A change carries it beside // the state, so its undo puts back both. ("decided_at", _) if patch.contains_key("state") => {} (other, _) => { return Err(ToolFailure::new(format!( "{} are answered by their state; {other:?} is the Mac's to say", definition.plural ))) } } } let Some(state) = state else { return Err(ToolFailure::new("state is the one thing a pair is answered by")); }; call( ctx, definition, "decide_duplicate", media_analysis::decide_duplicate, json!({ "id": id, "state": state }), ) .map(|_| ()) } /// Every EXISTING tool a generic READ of a view stands in for, so a run that /// refuses a tool by name is never read round: the library is the photo and /// video lists, an album's pictures the album reads, the duplicates /// `list_duplicates`, a sighting a picture's own page — and a photo or a video /// answers the albums it is in, which `list_albums` would. pub fn tools_read(tool: &str, table: &str) -> Vec<&'static str> { if !matches!(tool, "list_records" | "get_record_by_table") { return Vec::new(); } match table { "media" => vec!["list_photos", "get_photo", "list_videos", "get_video"], "album_item" => vec!["list_albums", "get_album"], "duplicate" => vec!["list_duplicates"], "sighting" => vec!["get_photo", "get_video"], "photo" | "video" => vec!["list_albums"], _ => Vec::new(), } } #[cfg(test)] mod tests { use super::*; /// RULE: A picture's size reads as the app's own label does — nothing for none or zero, bytes, whole kilobytes, a decimal under ten megabytes or gigabytes, and the rung crossed where the label would read 1024. #[test] fn a_size_reads_rung_for_rung_as_the_app_says_it() { let cases: [(Option, Option<&str>); 13] = [ (None, None), (Some(0), None), (Some(-5), None), (Some(812), Some("812 B")), (Some(1023), Some("1023 B")), (Some(1024), Some("1 KB")), (Some(45_000), Some("44 KB")), (Some(1024 * 1023 + 600), Some("1024 KB")), (Some(3_355_443), Some("3.2 MB")), (Some(12 * 1024 * 1024), Some("12 MB")), (Some(1024 * 1024 * 1024 - 1), Some("1.0 GB")), (Some(2_576_980_378), Some("2.4 GB")), (Some(20 * 1024 * 1024 * 1024), Some("20 GB")), ]; for (bytes, wanted) in cases { assert_eq!(size_label(bytes).as_deref(), wanted, "{bytes:?}"); } } /// RULE: A duplicate pair's facts say the dimensions only when both are known, the size only when one was recorded, a favourite by name, and nothing when there is nothing to say. #[test] fn a_pairs_facts_say_only_what_is_known() { assert_eq!( picture_facts(Some(4032), Some(3024), Some(2_202_009), true).as_deref(), Some("4032 × 3024 · 2.1 MB · Favourite") ); assert_eq!( picture_facts(Some(1920), None, Some(812_000), false).as_deref(), Some("793 KB") ); assert_eq!(picture_facts(None, None, Some(0), true).as_deref(), Some("Favourite")); assert_eq!(picture_facts(None, Some(3), None, false), None); } /// RULE: Every view the photos engine answers is one of the shipped view tables, with SQL of its own, and every view table a definition ships as the engine's has its SQL here. #[test] fn every_media_view_has_its_sql_and_is_a_shipped_view() { for id in MEDIA_VIEWS { assert!(cotton_core::definitions::VIEW_TABLES.contains(&id), "{id}"); assert!(view_sql(id).is_some(), "{id}"); } for definition in cotton_core::definitions::builtin_table_definitions() { if cotton_core::definitions::VIEW_TABLES.contains(&definition.id.as_str()) && definition.engine.as_deref() == Some("media") { assert!(MEDIA_VIEWS.contains(&definition.id.as_str()), "{}", definition.id); let view = view_sql(&definition.id).unwrap(); for key in view.worded { assert!(definition.column(key).is_some(), "{}.{key}", definition.id); } } } } #[test] fn an_album_state_names_its_decision() { assert_eq!(album_decision("kept"), Some("keep")); assert_eq!(album_decision("dismissed"), Some("dismiss")); assert_eq!(album_decision("open"), Some("open")); assert_eq!(album_decision("lost"), None); } }