//! CIRCLE GAPS 2 (28 Nov 2026): a Cinemas list someone shared with him, as his phone draws it. A shared Cinemas list//! is a shared list `cinemas-<id>` on its founder's object (`share_sheet`, `shared_list`); on a member's phone it//! stands on Cinemas home under its own line, and opens to who shared it, its titles, and Leave. Shapes://! `assets/design/shared/CONTACTS-ANSWERS.md` §10.//!//! ```text//! cinemas.home's `received` → null | { title, rows: [{ owner, id, words, detail, initials, call }] }//! cinemas.shared { owner, id } → { owner, id, title, from: { number, name }, detail, items: [{ id, title, year, kind }], unopened, leave }//! cinemas.shared.leave { owner, id } → { said } (an ask the founder's phone carries out with a new key)//! ```//!//! Home never waits on the network: `received` is the list as last read, and each home read refreshes it behind//! the answer (the next home shows what changed). Opening one reads it where it lives, now.use std::collections::HashMap;use std::sync::{Mutex, OnceLock};use serde_json::{json, Value};usecrate::handle::CottonHandle;usecrate::methods::MethodError;usecrate::shell::client::ClientController;pubconst METHODS: [&str; 2] = ["cinemas.shared", "cinemas.shared.leave"];/// The item a Cinemas list's name rides in (never a title): `{list_name}`.pub(crate) const NAME_ITEM: &str = "list-name";/// A member's ask to leave, `leave:<number>`: the founder's phone takes them off with a new key (a member cannot).pub(crate) const LEAVE_ITEM: &str = "leave:";fn say(line: &str, fills: &[(&str, &str)]) -> String { cotton_core::rules::shell_lines::LineSet::shipped("cinemas").and_then(|lines| lines.say(&format!("shared.{line}"), fills)).unwrap_or_default()}/// Each account's received lists as last read: `(owner, id, name, titles)`.fn cache() -> &'staticMutex<HashMap<String, Vec<(String, String, String, usize)>>> {static CACHE: OnceLock<Mutex<HashMap<String, Vec<(String, String, String, usize)>>>> = OnceLock::new(); CACHE.get_or_init(Default::default)}fn account(client: &ClientController) -> String { format!("{}|{}", client.layout().client_dir().display(), client.object_door().map(|d| d.credential.len()).unwrap_or(0))}fn initials(name: &str) -> String {super::contacts_groups::initials(name)}/// Home's `received` line from the copy last read (null when none), and a refresh of that copy behind it.pub(crate) fn received(client: &std::sync::Arc<ClientController>) -> Value {let key = account(client);if client.object_door().is_some() && due(&key) {let background = std::sync::Arc::clone(client);let refresh_key = key.clone(); std::thread::spawn(move || {let _ = refresh(&background, refresh_key); }); }let lists = cache().lock().ok().and_then(|held| held.get(&key).cloned()).unwrap_or_default(); received_line(client, &lists)}/// Reads every list shared with him now and keeps it for home (the background refresh; a test calls it itself).pub(crate) fn refresh_now(client: &ClientController) -> Result<(), MethodError> { refresh(client, account(client))}/// Whether home may read the lists again now: at most once a minute for each account (a refresh stamps it).fn due(key: &str) -> bool {static LAST: OnceLock<Mutex<HashMap<String, std::time::Instant>>> = OnceLock::new();letOk(mut last) = LAST.get_or_init(Default::default).lock() else { returnfalse };let now = std::time::Instant::now();if last.get(key).is_some_and(|at| now.duration_since(*at) < std::time::Duration::from_secs(60)) {returnfalse; } last.insert(key.to_string(), now);true}fn refresh(client: &ClientController, key: String) -> Result<(), MethodError> { due(&key);let lists = read_received(client)?;ifletOk(mut held) = cache().lock() { held.insert(key, lists); }Ok(())}fn received_line(client: &ClientController, lists: &[(String, String, String, usize)]) -> Value {if lists.is_empty() {returnValue::Null; }let rows: Vec<Value> = lists .iter() .map(|(owner, id, name, count)| {let from = super::your_people::named(client, owner, None).shown;let words = if name.is_empty() { say("untitled", &[("name", &from)]) } else { name.clone() }; json!({ "owner": owner, "id": id, "words": words, "detail": say("detail", &[("name", &from), ("count", &count.to_string())]), "initials": initials(&from),"call": { "method": "cinemas.shared", "request": { "owner": owner, "id": id } } }) }) .collect(); json!({ "title": say("title", &[]), "rows": rows })}/// Every Cinemas list shared with him (not his own), read where each lives.fn read_received(client: &ClientController) -> Result<Vec<(String, String, String, usize)>, MethodError> {let listed = super::shared_list::over(client, "shared.lists", &json!({}))?;let me = listed["me"].as_str().unwrap_or_default().to_string();letmut found = Vec::new();for list in listed["lists"].as_array().into_iter().flatten() {let (Some(owner), Some(id)) = (list["owner"].as_str(), list["id"].as_str()) else { continue };if owner == me || !id.starts_with("cinemas-") {continue; }letOk(read) = super::shared_list::over(client, "shared.read", &json!({ "owner": owner, "id": id })) else { continue };// Left, waiting for the founder's phone to take him off: no longer his to see.if read["items"].as_array().into_iter().flatten().any(|i| i["id"].as_str() == Some(&format!("{LEAVE_ITEM}{me}"))) {continue; }let (name, titles) = split(&read); found.push((owner.to_string(), id.to_string(), name, titles.len())); }Ok(found)}/// A read list's name and its titles (the name's own item left out).fn split(read: &Value) -> (String, Vec<Value>) {letmut name = String::new();letmut titles = Vec::new();for item in read["items"].as_array().into_iter().flatten() {if item["id"].as_str().is_some_and(|i| i.starts_with(LEAVE_ITEM)) {continue; }if item["id"] == NAME_ITEM { name = item["list_name"].as_str().unwrap_or_default().to_string(); } else { titles.push(json!({ "id": item["id"], "title": item["title"], "year": item["year"], "kind": item["kind"] })); } } (name, titles)}fn named(request: &Value) -> Result<(String, String), MethodError> {let field = |key: &str| request[key].as_str().map(str::trim).filter(|s| !s.is_empty()).map(str::to_string).ok_or_else(|| MethodError::new("bad_request", format!("`{key}` names the shared list")));let id = field("id")?;if !id.starts_with("cinemas-") {returnErr(MethodError::new("bad_request", "not a Cinemas list")); }Ok((field("owner")?, id))}pubfn call(handle: &CottonHandle, method: &str, request: &Value) -> Result<Value, MethodError> { over(&handle.client(), method, request)}pubfn over(client: &ClientController, method: &str, request: &Value) -> Result<Value, MethodError> {match method {"cinemas.shared" => open(client, request),"cinemas.shared.leave" => leave(client, request), other => Err(MethodError::new("unknown_method", format!("no method {other}"))), }}fn open(client: &ClientController, request: &Value) -> Result<Value, MethodError> {let (owner, id) = named(request)?;let read = super::shared_list::over(client, "shared.read", &json!({ "owner": owner, "id": id }))?;let (name, titles) = split(&read);let from = super::your_people::named(client, &owner, None);let title = if name.is_empty() { say("untitled", &[("name", &from.shown)]) } else { name };Ok(json!({"owner": owner, "id": id, "title": title,"from": { "number": owner, "name": from.shown },"detail": say("detail", &[("name", &from.shown), ("count", &titles.len().to_string())]),"items": titles, "unopened": read["unopened"].as_array().map(|u| u.len()).unwrap_or(0),"leave": { "words": say("leave", &[]), "red": true, "confirm": say("leave_confirm", &[("name", &from.shown)]), "call": { "method": "cinemas.shared.leave", "request": { "owner": owner, "id": id } } }, }))}fn leave(client: &ClientController, request: &Value) -> Result<Value, MethodError> {let (owner, id) = named(request)?;let listed = super::shared_list::over(client, "shared.lists", &json!({}))?;let me = listed["me"].as_str().unwrap_or_default().to_string();if me.is_empty() || me == owner {returnErr(MethodError::new("bad_request", "his own list is stopped from Share, not left")); }// A member cannot re-key the list for those who stay (he would know the new key): he asks to leave, sealed in the// list itself, and the founder's phone takes him off with a new key the next time it reads the list.super::shared_list::over(client, "shared.put", &json!({ "owner": owner, "id": id, "item": format!("{LEAVE_ITEM}{me}"), "body": { "leave": true } }))?;ifletOk(mut held) = cache().lock() {ifletSome(lists) = held.get_mut(&account(client)) { lists.retain(|(o, i, ..)| !(o == &owner && i == &id)); } }Ok(json!({ "said": say("left", &[]) }))}