//! `object.act { act, args }` — an act at the person's own object, from the //! phone: `POST /v1/act` through the door `personal.connect` held //! ([`ObjectDoor`]), under this phone's credential, the object's answer //! handed back as it came. The credential never reaches Swift. //! //! ONLY [`ADMITTED`] acts go. A book's Start reading and Finished and a //! Goodreads export shared to the phone (`import_goodreads`) are the phone's //! OWN (`phone::book_acts`, local-first): they write its copy, signed in or //! not, and queue for the object. The rest reach the object, and a phone not //! signed in is refused [`SIGN_IN_FIRST`]: Books' Plus and a book's Find details //! (`find_book`, Open Library asked by the object; a book's details asked by //! its ISBN, else its title and author, [`details_asked`]); and the music //! kit's: a song's Find lyrics (`find_lyrics`, LRCLIB asked by the object for //! that one song) and an album's cover (`fetch_cover`, the Cover Art Archive //! then Deezer, asked by the object; iTunes, which refuses the object's //! network, the phone asks itself); and the cinemas kit's: Cinemas' Find a //! film and a film's Find details (`find_film`, TMDB asked by the object, //! whose key the phone never holds); and Downloads' Fetch a link, Cancel and //! Try again (`fetch_add`, `fetch_cancel`, `fetch_retry`: the queue the Mac //! fetches from lives in the object, and the Mac's own acts, claiming and //! landing, never go from a phone); and Cotton Meetings' queue, where a phone //! on charge is a transcriber like the Mac: `meeting_claim { id, by: phone }` //! takes a waiting recording (refused 409 `not_waiting` / `not_yours` when //! the Mac or another holds it, and the phone drops the job) and //! `meeting_failed { id, why }` gives one up. The one-time `drop_old_music` and //! `reshape_films` are never the phone's to send. Nothing a page names can //! make the phone mint a token, set a role or write a definition through //! this door. //! //! A command runs it with its `data` and bindings as one object //! (`{act: "find_book", book: ""}`): every key but `act` is the //! act's arguments. A call may instead pass them whole as `args`. //! //! An act that wrote something comes back to this phone by sync: a pass is //! asked for at once ([`ClientController::nudge_sync`]), never waited on. use serde_json::{json, Map, Value}; use cotton_client::transport::object::{bearer, routes, ObjectRefusal}; use crate::handle::CottonHandle; use crate::methods::MethodError; use crate::phone::personal_object::ObjectDoor; pub const METHODS: [&str; 1] = ["object.act"]; /// The acts the phone asks its object for; this method also takes the /// phone's own (`phone::book_acts::ACTS`), run in its copy. pub const ADMITTED: [&str; 9] = ["find_book", "find_lyrics", "fetch_cover", "find_film", "fetch_add", "fetch_cancel", "fetch_retry", "meeting_claim", "meeting_failed"]; pub fn call(handle: &CottonHandle, method: &str, request: &Value) -> Result { if method != "object.act" { return Err(MethodError::new("unknown_method", format!("`{method}` is not an object act method"))); } call_on(&handle.client(), request) } /// `object.act` on this phone's client. pub(crate) fn call_on(client: &crate::shell::client::ClientController, request: &Value) -> Result { let (name, args) = parse(request)?; // An act the phone's own copy can run runs there, signed in or not, and // its write queues for the object like any other. if crate::phone::book_acts::ACTS.contains(&name) { let answer = crate::phone::book_acts::run(client, name, &args)?; client.nudge_sync(); return Ok(answer); } // The rest ask the object, which a phone not signed in has none of. let Some(door) = client.object_door() else { let said = cotton_core::rules::shell_lines::LineSet::shipped("backup") .and_then(|lines| lines.say("acts.sign_in_first", &[])) .ok_or_else(|| MethodError::new("unreadable", "the backup set says no words for signing in first"))?; return Err(MethodError::new(SIGN_IN_FIRST, said).with_details(json!({ "act": name }))); }; let request = match name { "find_book" => details_asked(client, request, &args)?, "find_film" => film_asked(client, request, &args)?, "fetch_cover" => words_asked(client, request, &args, "fetch_cover", "music_album", "album", &["title", "artist_name", "mb_release", "mb_release_group"])?, "find_lyrics" => words_asked(client, request, &args, "find_lyrics", "song", "song", &["title", "artist_name", "album_title"])?, _ => request.clone(), }; let answer = act(&door, &request)?; client.nudge_sync(); Ok(answer) } /// A book's Find details (`find_book { book }`): asked by its ISBN where the /// book holds one, else by its title and author, as this phone's copy says /// them; the object fills only the book's empty columns. A Find a book /// (`query`) or an ISBN given goes as it is. fn details_asked(client: &crate::shell::client::ClientController, request: &Value, args: &Value) -> Result { let Some(book) = args.get("book").and_then(Value::as_str) else { return Ok(request.clone()) }; if args.get("query").is_some() || args.get("isbn").is_some() { return Ok(request.clone()); } let record = crate::phone::records::call(client, "records.get", &json!({"table": "book", "id": book}))?; let words = |column: &str| record["data"][column].as_str().map(str::trim).filter(|words| !words.is_empty()).map(str::to_string); let asked = match words("isbn") { Some(isbn) => json!({"book": book, "isbn": isbn}), None => { let title = words("title").ok_or_else(|| bad("a book with no title or ISBN has nothing to look up by"))?; let query = [Some(title), words("author")].into_iter().flatten().collect::>().join(" "); json!({"book": book, "query": query}) } }; Ok(json!({"act": "find_book", "args": asked})) } /// A film's Find details (`find_film { film }`): its title, year and TMDB id /// as this phone's copy says them go beside it, since a sealed film's words /// are not the object's to read (e2e rulings R2); the object fills only the /// film's empty columns, as a patch the phone lays. fn film_asked(client: &crate::shell::client::ClientController, request: &Value, args: &Value) -> Result { let Some(film) = args.get("film").and_then(Value::as_str) else { return Ok(request.clone()) }; let record = crate::phone::records::call(client, "records.get", &json!({"table": "film", "id": film}))?; let mut asked = json!({"film": film}); for column in ["title", "year", "tmdb_id"] { if let Some(words) = record["data"][column].as_str().map(str::trim).filter(|words| !words.is_empty()) { asked[column] = json!(words); } } Ok(json!({"act": "find_film", "args": asked})) } /// An album's Find cover (`fetch_cover { album }`) or a song's Find lyrics /// (`find_lyrics { song }`): the row's words this phone's copy holds go beside /// it, since a sealed row's words are not the object's to read (e2e rulings /// R2); the object fills only what the row leaves empty, as a patch the phone /// lays. A song names its album's title from the album it links. fn words_asked(client: &crate::shell::client::ClientController, request: &Value, args: &Value, act: &str, table: &str, by: &str, columns: &[&str]) -> Result { let Some(id) = args.get(by).and_then(Value::as_str) else { return Ok(request.clone()) }; let record = crate::phone::records::call(client, "records.get", &json!({"table": table, "id": id}))?; let mut asked = args.clone(); if !asked.is_object() { return Ok(request.clone()); } for column in columns { let mut words = record["data"][*column].as_str().map(str::trim).filter(|words| !words.is_empty()).map(str::to_string); if *column == "album_title" && words.is_none() { if let Some(album) = record["data"]["album"].as_str().filter(|album| !album.is_empty()) { let linked = crate::phone::records::call(client, "records.get", &json!({"table": "music_album", "id": album})).ok(); words = linked.and_then(|linked| linked["data"]["title"].as_str().map(str::trim).filter(|words| !words.is_empty()).map(str::to_string)); } } if let Some(words) = words { asked[*column] = json!(words); } } Ok(json!({"act": act, "args": asked})) } /// The refusal of an act at the object on a phone not signed in: the shell /// says the act's own words for it and offers Sign in. pub const SIGN_IN_FIRST: &str = "sign_in_first"; /// The act through a NAMED door: a suite drives one over a scripted exchange. pub fn act(door: &ObjectDoor, request: &Value) -> Result { let (name, args) = parse(request)?; if !ADMITTED.contains(&name) { return Err(bad(&format!("`{name}` is this phone's own act, run in its copy, never sent to its object"))); } door.address .send(door.exchange.as_ref(), "POST", routes::ACT, bearer(&door.credential), Some(&json!({"act": name, "args": args}))) .map_err(refused) .map_err(|refusal| said_plainly(name, &args, refusal)) } /// RULE (owner on Cotton Cinemas 1.0 (4), 7 Nov 2026): a refusal the /// person can do nothing about is said in the kit's words, not the object's /// (which an assistant reads): Find a film on an object holding no TMDB key, /// and a film's Find details (`find_film { film }`) in its own words, never Find /// a film's (android-finish's Cinemas walk, 25 Nov 2026). fn said_plainly(name: &str, args: &Value, refusal: MethodError) -> MethodError { match (name, refusal.code.as_str()) { ("find_film", "not_connected") => { let key = if args.get("film").is_some_and(|film| !film.is_null()) { "add.details_not_connected" } else { "add.find_not_connected" }; match cotton_core::rules::shell_lines::LineSet::shipped("cinemas").and_then(|lines| lines.say(key, &[])) { Some(line) => MethodError { message: line, ..refusal }, None => MethodError::new("unreadable", "the cinemas set says no words for Find a film unconnected"), } } _ => refusal, } } /// The act's name, admitted, and its arguments. fn parse(request: &Value) -> Result<(&str, Value), MethodError> { let object = request.as_object().ok_or_else(|| bad("object.act takes an object"))?; let name = object .get("act") .and_then(Value::as_str) .map(str::trim) .filter(|name| !name.is_empty()) .ok_or_else(|| bad("object.act names its act"))?; if !ADMITTED.contains(&name) && !crate::phone::book_acts::ACTS.contains(&name) { return Err(bad(&format!("`{name}` is not an act this phone asks its object for"))); } let args = match object.get("args") { Some(Value::Object(args)) => { if object.keys().any(|key| key != "act" && key != "args" && key != crate::phone::databases::DATABASE) { return Err(bad("object.act takes its arguments either whole as `args` or beside `act`, not both")); } Value::Object(args.clone()) } Some(_) => return Err(bad("object.act's `args` is an object")), // The database a dispatch scoped the call to is the phone's, never the act's. None => Value::Object(object.iter().filter(|(key, _)| key.as_str() != "act" && key.as_str() != crate::phone::databases::DATABASE).map(|(k, v)| (k.clone(), v.clone())).collect::>()), }; Ok((name, args)) } /// The object's refusal by its own word, its status beside it; a request that /// reached nothing is `offline`. fn refused(refusal: ObjectRefusal) -> MethodError { let code = match (refusal.status, refusal.code.as_str()) { (0, _) => "offline".to_string(), (_, code) if !code.is_empty() => code.to_string(), (status, _) => format!("http_{status}"), }; MethodError::new(&code, refusal.message).with_details(json!({ "status": refusal.status })) } fn bad(message: &str) -> MethodError { MethodError::new("bad_request", message) } #[cfg(test)] #[path = "object_acts_tests.rs"] mod tests;