871 lines · 47.4 KB · RustRaw
//! THE ONE SHARE SHEET (PEOPLE-DESIGN d.1, d.2 mock-ups 4 and 5; 28 Nov 2026): every app shares//! through the same methods, with its own `app` and `thing`; the answers are CONTACTS-ANSWERS.md section 10.//!//! ```text//! share.sheet { app, thing } → { title, suggested, people, roles, until, link?, foot, go }//! share.plan { app, thing, people, role, until? } → { lines, go, error }//! share.do { app, thing, people, role, until?, … } → { said, with } | { error }//! share.with { app, thing } → { title, rows, more }//! share.role { app, thing, person, role } → as share.with, with said//! share.stop { app, thing, person } → as share.with, with said//! share.by_person { person } → { mine: [rows], theirs: [rows] }//! ```//!//! People are the Circle (`circle::members`): those both accepted first, then those still waiting (`can` false, said//! why). Nothing is ever picked for him; assistants are never among them. `people` in a request names each person by//! their contact id or their number.//!//! TWO WAYS UNDERNEATH (C3), one adapter per app, here in the core://! - **Albums** (`albums`, a space): `thing` is `{kind: "album", space, album}` for a shared album, or//! `{kind: "album", name}` for a new one (founded with the people picked). The roster has owner and members and//! every member may add, so Albums offers one role, "See and add". A link for people not on Cotton is the album's//! own (`albums.shared.link.make`). Stop takes a member off with a new key (`albums.shared.rekey`), the owner only.//! - **Secrets** (`secrets`, a box): `thing` is `{kind: "secret", id}`. A copy goes only to someone whose safety number//! was compared; See it or See and copy; until a day, a week, a month, until taken back, or a date. Stop takes it//! back (`secrets.take`). Every other field of `share.do`'s request (the vault's own proof) is handed on as it came.//! - **Days** (`days`, a box per guest): `thing` is `{kind: "event", id}`. Days shares one event, not a calendar: the//! people picked join its guest list (`days.change`) and the invitation goes sealed to each phone at once//! (`days.invitations`), where they answer it. One role, Invited. Stop takes them off the list; the next pass tells//! them it is off. `timezone` in the request is the phone's zone (Days's own change reads it), UTC when absent.//! - **Cinemas** (`cinemas`, a shared list, `shared.*`): `thing` is `{kind: "list", id}`, one of his film lists. The//! first share founds the shared list `cinemas-<id>` with the people picked and every title on it (title, year,//! kind; never the file); a later share adds the people. A title put on the list or taken off it afterwards//! follows to the members on its own (`list_changed`, after `groups.update`). One role, See the list. Stop takes a person off with a new key (`shared.remove`), the founder only.//! - **Words** and **Sites** answer a plain not-yet line until spaces exist (coordinator, 28 Nov 2026).use std::ops::Deref;use std::sync::Arc;use serde_json::{json, Value};use super::circle::{self, Member};use super::cotton_chat::{e164, text};use crate::handle::CottonHandle;use crate::methods::MethodError;use crate::shell::client::ClientController;use cotton_core::rules::shell_lines::resolve;/// Every method this family answers.pub const METHODS: [&str; 7] = ["share.by_person", "share.do", "share.plan", "share.role", "share.sheet", "share.stop", "share.with"];fn say(line: &str, fills: &[(&str, &str)]) -> String { resolve("share", line, &[], fills).unwrap_or_default()}pub fn call(handle: &CottonHandle, method: &str, request: &Value) -> Result<Value, MethodError> { over(handle, method, request)}/// The phone a sheet works on: its client, and the handle another app's own methods are called through (Days).pub struct Here<'a> { handle: &'a CottonHandle, client: Arc<ClientController>,}impl Deref for Here<'_> { type Target = ClientController; fn deref(&self) -> &ClientController { &self.client }}pub fn over(handle: &CottonHandle, method: &str, request: &Value) -> Result<Value, MethodError> { let here = Here { handle, client: handle.client() }; let client = &here; if client.object_door().is_none() { return Ok(json!({ "signedOut": { "title": say("signed_out.title", &[]), "message": say("signed_out.message", &[]) } })); } if method == "share.by_person" { return by_person(client, request); } let app = match App::of(request) { Ok(a) => a, Err(e) => return Ok(json!({ "error": e.message })), }; let answered = match method { "share.sheet" => sheet(client, &app), "share.plan" => plan(client, &app, request), "share.do" => run(client, &app, request), "share.with" => with(client, &app), "share.role" => role(client, &app, request), "share.stop" => stop(client, &app, request), other => return Err(MethodError::new("unknown_method", format!("no method {other}"))), }; // A refusal is said in words on the sheet, never thrown at the shell. Ok(answered.unwrap_or_else(|e| json!({ "error": e.message })))}// ── the adapters ────────────────────────────────────────────────────────enum App { /// A shared album (`space`, `album`), or a new one to found (`name`). Albums { space: Option<String>, album: Option<String>, name: Option<String> }, Secrets { id: String }, /// One event in Days, shared by inviting. Days { id: String }, /// One of his film lists in Cinemas, shared as a shared list. Cinemas { id: String },}impl App { fn of(request: &Value) -> Result<App, MethodError> { let thing = &request["thing"]; let s = |k: &str| thing[k].as_str().map(str::to_string).filter(|v| !v.is_empty()); match (request["app"].as_str(), thing["kind"].as_str()) { (Some("albums"), Some("album")) => { let (space, album, name) = (s("space"), s("album"), s("name")); if space.is_none() && name.is_none() { return Err(MethodError::new("bad_request", say("errors.no_album", &[]))); } Ok(App::Albums { space, album, name }) } (Some("secrets"), Some("secret")) => Ok(App::Secrets { id: s("id").ok_or_else(|| MethodError::new("bad_request", say("errors.no_secret", &[])))? }), (Some("cinemas"), Some("list")) => Ok(App::Cinemas { id: s("id").ok_or_else(|| MethodError::new("bad_request", say("errors.no_list", &[])))? }), (Some(app @ ("words" | "sites")), _) => Err(MethodError::new("not_yet", say("errors.not_yet", &[("app", &say(&format!("apps.{app}"), &[]))]))), (Some("days"), Some("event")) => Ok(App::Days { id: s("id").ok_or_else(|| MethodError::new("bad_request", say("errors.no_event", &[])))? }), _ => Err(MethodError::new("no_sheet", say("errors.no_sheet", &[]))), } } fn name(&self) -> &'static str { match self { App::Albums { .. } => "albums", App::Secrets { .. } => "secrets", App::Days { .. } => "days", App::Cinemas { .. } => "cinemas", } } fn thing(&self) -> Value { match self { App::Albums { space, album, name } => json!({ "kind": "album", "space": space, "album": album, "name": name }), App::Secrets { id } => json!({ "kind": "secret", "id": id }), App::Days { id } => json!({ "kind": "event", "id": id }), App::Cinemas { id } => json!({ "kind": "list", "id": id }), } }}fn albums(client: &ClientController, method: &str, request: Value) -> Result<Value, MethodError> { super::albums_shared::call(client, method, &request)}fn secrets(client: &ClientController, method: &str, request: Value) -> Result<Value, MethodError> { super::secrets_app::call(client, method, &request)}fn days(client: &Here<'_>, method: &str, request: Value) -> Result<Value, MethodError> { super::days::call(client.handle, method, &request)}/// One of an event's people as the sheet needs them.struct Guest { key: String, number: Option<String>, name: Option<String>, on_cotton: bool, organizer: bool, line: Option<String>,}/// An event's title and its people still on it (an occurrence carries its series' people), read in one go.fn event_of(client: &ClientController, id: &str) -> Result<(String, Vec<Guest>), MethodError> { let read = super::cotton_chat::read(client, "share.days", |ctx| { let t = |v: &str| rusqlite::types::Value::Text(v.to_string()); let found = super::cotton_chat::rows(ctx, "SELECT title, series_id FROM cotton_events WHERE id = ?1 AND trashed_at IS NULL", &[t(id)])?; let Some(event) = found.into_iter().next() else { return Ok(Value::Null) }; let mut owner = id.to_string(); let own = super::days_people::guests(ctx, id).map_err(|e| e.message)?; if own.is_empty() { if let Some(series) = event.get("series_id").and_then(Value::as_str) { owner = series.to_string(); } } let people: Vec<Value> = super::days_people::guests(ctx, &owner) .map_err(|e| e.message)? .into_iter() .filter(|g| !g.removed) .map(|g| json!({ "key": g.key(), "number": g.phone, "name": g.name, "shown": g.shown(), "cotton": g.via == super::days_people::Via::Cotton, "organizer": g.organizer, "sent": g.sent, "response": g.response })) .collect(); Ok(json!({ "title": event.get("title"), "people": people })) })?; if read.is_null() { return Err(MethodError::new("gone", say("errors.no_event", &[]))); } let guests = read["people"] .as_array() .into_iter() .flatten() .map(|g| { let answered = match g["response"].as_str() { Some("accepted") => Some("with.going"), Some("declined") => Some("with.not_going"), Some("tentative") => Some("with.maybe"), _ if !g["sent"].is_null() => Some("with.invited"), _ => Some("with.to_invite"), }; Guest { key: g["key"].as_str().unwrap_or_default().to_string(), number: g["number"].as_str().and_then(e164), name: g["name"].as_str().map(str::to_string).or_else(|| g["shown"].as_str().map(str::to_string)), on_cotton: g["cotton"] == true, organizer: g["organizer"] == true, line: answered.map(|l| say(l, &[])), } }) .collect(); Ok((read["title"].as_str().unwrap_or_default().to_string(), guests))}/// The shared list a Cinemas list goes out as (the object takes letters, digits, `-` and `_`, at most 64).fn cinemas_list(id: &str) -> String { let clean: String = id.chars().filter(|c| c.is_ascii_alphanumeric() || *c == '-' || *c == '_').take(55).collect(); format!("cinemas-{clean}")}/// A film list's name and its titles, each `(film id, {title, year, kind})`, in his order.fn film_list(client: &ClientController, id: &str) -> Result<(String, Vec<(String, Value)>), MethodError> { use cotton_tools::mcp::handlers::tables::groups; let read = super::cotton_chat::read(client, "share.cinemas", |ctx| { let Some((data, None)) = groups::group_of(ctx.read.driver(), id)? else { return Ok(Value::Null) }; if data.get("table").and_then(Value::as_str) != Some(super::films::FILM_TABLE) { return Ok(Value::Null); } let mut films = Vec::new(); for film in groups::members_of(&data) { let t = rusqlite::types::Value::Text(film.clone()); if let Some(row) = super::songs::rows_where(ctx, super::films::FILM_TABLE, "title, year, kind", "id = ?", &[t])?.into_iter().next() { films.push(json!({ "id": film, "body": { "title": row.get("title"), "year": row.get("year"), "kind": row.get("kind") } })); } } Ok(json!({ "name": groups::name_of(&data), "films": films })) })?; if read.is_null() { return Err(MethodError::new("gone", say("errors.no_list", &[]))); } let films = read["films"].as_array().into_iter().flatten().map(|f| (f["id"].as_str().unwrap_or_default().to_string(), f["body"].clone())).collect(); Ok((read["name"].as_str().unwrap_or_default().to_string(), films))}/// The shared list as it stands where it lives: `(me, owner, members, item ids)`; `None` before it was first shared.fn list_state(client: &ClientController, id: &str) -> Result<Option<(String, String, Vec<String>, Vec<String>)>, MethodError> { let path = format!("/v1/shared/list?id={}", cinemas_list(id)); match super::cotton_chat::ask(client, "GET", &path, None) { Ok(answer) => { let keys = |v: &Value| v.as_object().map(|o| o.keys().cloned().collect::<Vec<_>>()).unwrap_or_default(); Ok(Some((answer["me"].as_str().unwrap_or_default().to_string(), answer["owner"].as_str().unwrap_or_default().to_string(), keys(&answer["state"]["membership"]["members"]), keys(&answer["state"]["items"])))) } Err(refusal) if refusal.code == "no_list" => Ok(None), Err(refusal) => Err(super::cotton_chat::refused(refusal)), }}/// A Cinemas list he changed (`groups.update`): when it is shared, its members' copy follows — titles put on it go/// to them, titles taken off leave — without sharing again. A list never shared, or no network now, sends nothing:/// the next change or share sends everything still owed, as the list is compared whole each time.pub fn list_changed(handle: &CottonHandle, request: &Value) { let client = handle.client(); let Some(id) = request["id"].as_str() else { return }; if client.object_door().is_none() { return; } if let Err(why) = follow_list(&client, id) { tracing::warn!(id, code = why.code, "share: a shared Cinemas list did not follow its change this time ({})", why.message); }}fn follow_list(client: &ClientController, id: &str) -> Result<(), MethodError> { // Only a film list goes out as a shared list; any other group is not one (and costs no request). let (list_name, films) = match film_list(client, id) { Ok(found) => found, Err(_) => return Ok(()), }; let Some((me, owner, _, items)) = list_state(client, id)?.map(|state| honour_leaves(client, id, state)).transpose()? else { return Ok(()) }; if me != owner { return Ok(()); } let list = cinemas_list(id); for (film, body) in films.iter().filter(|(f, _)| !items.contains(f)) { lists(client, "shared.put", json!({ "id": list, "item": film, "body": body }))?; } for item in items.iter().filter(|i| i.as_str() != super::cinemas_shared::NAME_ITEM && !i.starts_with(super::cinemas_shared::LEAVE_ITEM) && !films.iter().any(|(f, _)| f == *i)) { lists(client, "shared.take", json!({ "id": list, "item": item }))?; } // Its name rides beside the titles (a rename follows too), so a member's phone can say it. lists(client, "shared.put", json!({ "id": list, "item": super::cinemas_shared::NAME_ITEM, "body": { "list_name": list_name } }))?; Ok(())}/// On the founder's phone: each member who asked to leave (a `leave:<number>` item, posted by `cinemas.shared.leave`,/// since a member cannot re-key a list for those who stay) is taken off with a new key and the ask taken away. Costs/// no request when nobody asked; answers the list as it stands after.fn honour_leaves(client: &ClientController, id: &str, state: (String, String, Vec<String>, Vec<String>)) -> Result<(String, String, Vec<String>, Vec<String>), MethodError> { let (me, owner, members, items) = &state; let asks: Vec<String> = items.iter().filter(|i| i.starts_with(super::cinemas_shared::LEAVE_ITEM)).cloned().collect(); if me != owner || asks.is_empty() { return Ok(state); } let list = cinemas_list(id); for ask in &asks { let number = &ask[super::cinemas_shared::LEAVE_ITEM.len()..]; if members.iter().any(|m| m == number) && number != me { lists(client, "shared.remove", json!({ "id": list, "number": number }))?; } lists(client, "shared.take", json!({ "id": list, "item": ask }))?; } Ok(list_state(client, id)?.unwrap_or(state))}fn lists(client: &ClientController, method: &str, request: Value) -> Result<Value, MethodError> { super::shared_list::over(client, method, &request)}/// Days's own change with the event's whole list of people, then the pass that sends what they are owed now.fn days_people(client: &Here<'_>, id: &str, people: Vec<Value>, request: &Value) -> Result<(), MethodError> { let zone = request["timezone"].as_str().filter(|z| !z.is_empty()).unwrap_or("UTC"); days(client, "days.change", json!({ "table": "event", "id": id, "people": people, "timezone": zone }))?; days(client, "days.invitations", json!({}))?; Ok(())}/// What the thing is called, for the sheet's title.fn thing_name(client: &Here<'_>, app: &App) -> Result<String, MethodError> { match app { App::Albums { space: Some(space), album, name } => { let read = albums(client, "albums.shared.read", json!({ "space": space }))?; let found = read["albums"].as_array().into_iter().flatten().find(|a| album.as_deref().is_none_or(|id| a["id"].as_str() == Some(id))).and_then(|a| a["name"].as_str()).map(str::to_string); Ok(found.or_else(|| name.clone()).unwrap_or_default()) } App::Albums { name, .. } => Ok(name.clone().unwrap_or_default()), App::Secrets { id } => { let held = secrets(client, "secrets.holders", json!({ "id": id }))?; Ok(held["holders"].as_array().and_then(|h| h.first()).and_then(|h| h["secret"].as_str()).map(str::to_string).unwrap_or_else(|| secret_title(client, id))) } App::Days { id } => Ok(event_of(client, id)?.0), App::Cinemas { id } => Ok(film_list(client, id)?.0), }}/// A secret's name through Secrets' own plan (its words: `Share "Netflix"` → `Netflix`).fn secret_title(client: &Here<'_>, id: &str) -> String { let plan = secrets(client, "secrets.share.plan", json!({ "id": id })).unwrap_or(Value::Null); let title = plan["title"].as_str().unwrap_or_default(); title.split('"').nth(1).or_else(|| title.split('\u{201c}').nth(1).and_then(|t| t.split('\u{201d}').next())).unwrap_or(title).to_string()}/// The numbers that already have the thing.fn holders(client: &Here<'_>, app: &App) -> Result<Vec<String>, MethodError> { Ok(match app { App::Albums { space: Some(space), .. } => { let read = albums(client, "albums.shared.read", json!({ "space": space }))?; read["members"].as_array().into_iter().flatten().filter(|m| m["you"] != true).filter_map(|m| m["number"].as_str().and_then(e164)).collect() } App::Albums { .. } => Vec::new(), App::Secrets { id } => { let held = secrets(client, "secrets.holders", json!({ "id": id }))?; held["holders"].as_array().into_iter().flatten().filter(|h| h["state"] == "holds").filter_map(|h| h["number"].as_str().and_then(e164)).collect() } App::Days { id } => event_of(client, id)?.1.into_iter().filter(|g| g.on_cotton && !g.organizer).filter_map(|g| g.number).collect(), App::Cinemas { id } => match list_state(client, id)? { Some((me, _, members, _)) => members.into_iter().filter(|n| n != &me).collect(), None => Vec::new(), }, })}/// Whether a member can be given this app's thing now, and the line that says why not.fn can(app: &App, m: &Member) -> (bool, Option<String>, Option<Value>) { let first = m.name.split_whitespace().next().unwrap_or(&m.name).to_string(); if !m.accepted { return (false, Some(say("detail.waiting", &[("name", &first)])), None); } match app { App::Secrets { .. } if !m.checked => ( false, Some(say("detail.not_checked", &[("name", &first)])), Some(json!({ "method": "circle.check", "request": match &m.person { Some(p) => json!({ "person": p }), None => json!({ "number": m.number }) } })), ), _ => (true, m.checked.then(|| say("detail.checked", &[])), None), }}fn roles(app: &App) -> Value { match app { App::Albums { .. } => json!([{ "id": "add", "words": say("roles.add", &[]), "on": true }]), App::Secrets { .. } => json!([{ "id": "see", "words": say("roles.see", &[]), "on": false }, { "id": "copy", "words": say("roles.copy", &[]), "on": true }]), App::Days { .. } => json!([{ "id": "invite", "words": say("roles.invite", &[]), "on": true }]), App::Cinemas { .. } => json!([{ "id": "see", "words": say("roles.see_list", &[]), "on": true }]), }}fn default_role(app: &App) -> &'static str { match app { App::Albums { .. } => "add", App::Secrets { .. } => "copy", App::Days { .. } => "invite", App::Cinemas { .. } => "see", }}// ── the sheet ───────────────────────────────────────────────────────────fn sheet(client: &Here<'_>, app: &App) -> Result<Value, MethodError> { let name = thing_name(client, app)?; let has = holders(client, app)?; let people: Vec<Value> = circle::members(client) .iter() .map(|m| { let (ok, detail, call) = can(app, m); let mut row = json!({ "person": m.person, "number": m.number, "words": m.name, "initials": circle::initials_of(&m.name), "on": false, "has": has.contains(&m.number), "detail": detail, "can": ok }); if let Some(call) = call { row["call"] = call; } row }) .collect(); let until = matches!(app, App::Secrets { .. }).then(|| { json!(cotton_core::keys::share::UNTIL_CHOICES.iter().map(|id| json!({ "id": id, "words": say(&format!("until.{id}"), &[]), "on": *id == "week" })).chain(std::iter::once(json!({ "id": "date", "words": say("until.date", &[]), "on": false }))).collect::<Vec<_>>()) }); let link = match app { App::Albums { space: Some(_), album: Some(_), .. } => json!({ "words": say("link.words", &[]), "detail": say("link.detail", &[]) }), _ => Value::Null, }; let mut answer = json!({ "title": say("title", &[("name", &name)]), "suggested": [], "people": people, "roles": roles(app), "until": until, "foot": say(&format!("foot.{}", app.name()), &[]), "go": { "words": say("go.none", &[]), "call": { "method": "share.do", "request": { "app": app.name(), "thing": app.thing(), "people": [], "role": default_role(app) } } }, }); if !link.is_null() { answer["link"] = link; } if answer["people"].as_array().is_some_and(Vec::is_empty) { answer["empty"] = json!({ "title": say("empty.title", &[]), "message": say("empty.message", &[]), "call": { "method": "circle.add.page", "request": {} } }); } Ok(answer)}/// The Circle members a request picks (by contact id or number), each checked against what this app allows.fn picked(client: &Here<'_>, app: &App, request: &Value) -> Result<Vec<Member>, MethodError> { let wanted: Vec<&str> = request["people"].as_array().into_iter().flatten().filter_map(Value::as_str).collect(); if wanted.is_empty() { return Err(MethodError::new("bad_request", say("errors.none_picked", &[]))); } let members = circle::members(client); let mut out = Vec::new(); for w in wanted { let found = members.iter().find(|m| m.person.as_deref() == Some(w) || Some(m.number.clone()) == e164(w)).cloned(); let m = found.ok_or_else(|| MethodError::new("not_in_circle", say("errors.not_in_circle", &[])))?; let (ok, detail, _) = can(app, &m); if !ok { return Err(MethodError::new("cannot", detail.unwrap_or_default())); } if !out.iter().any(|o: &Member| o.number == m.number) { out.push(m); } } Ok(out)}/// "Asha", "Asha and Ravi", "Asha, Ravi and Lata".fn names(people: &[Member]) -> String { let firsts: Vec<String> = people.iter().map(|m| m.name.split_whitespace().next().unwrap_or(&m.name).to_string()).collect(); match firsts.as_slice() { [] => String::new(), [one] => one.clone(), [rest @ .., last] => format!("{} {} {last}", rest.join(", "), say("and", &[])), }}fn go_words(people: &[Member]) -> String { match people { [] => say("go.none", &[]), [one] => say("go.one", &[("name", one.name.split_whitespace().next().unwrap_or(&one.name))]), many => say("go.many", &[("n", &many.len().to_string())]), }}fn plan(client: &Here<'_>, app: &App, request: &Value) -> Result<Value, MethodError> { let people = picked(client, app, request)?; let who = names(&people); let mut lines = vec![say(&format!("plan.{}", app.name()), &[("names", &who)])]; if let App::Secrets { .. } = app { lines.push(say("plan.secrets_until", &[("until", &say(&format!("until.{}", request["until"].as_str().unwrap_or("week")), &[]))])); } let mut go_request = request.clone(); if let Some(o) = go_request.as_object_mut() { o.remove("method"); } Ok(json!({ "lines": lines, "go": { "words": go_words(&people), "call": { "method": "share.do", "request": go_request } }, "error": null }))}fn run(client: &Here<'_>, app: &App, request: &Value) -> Result<Value, MethodError> { let people = picked(client, app, request)?; let numbers: Vec<String> = people.iter().map(|m| m.number.clone()).collect(); let app_now = match app { App::Albums { space: Some(space), album, .. } => { albums(client, "albums.shared.members.add", json!({ "space": space, "numbers": numbers }))?; App::Albums { space: Some(space.clone()), album: album.clone(), name: None } } App::Albums { name, .. } => { let name = name.clone().unwrap_or_default(); let founded = albums(client, "albums.shared.found", json!({ "members": numbers, "name": name }))?; App::Albums { space: founded["space"].as_str().map(str::to_string), album: founded["album"].as_str().map(str::to_string), name: Some(name) } } App::Secrets { id } => { if request["role"].as_str().is_some_and(|r| r != "see" && r != "copy") { return Err(MethodError::new("bad_request", say("errors.role", &[]))); } for number in &numbers { let mut one = request.clone(); if let Some(o) = one.as_object_mut() { for k in ["app", "thing", "people", "role"] { o.remove(k); } o.insert("id".into(), json!(id)); o.insert("number".into(), json!(number)); o.insert("may".into(), json!(request["role"].as_str().unwrap_or("copy"))); o.entry("until").or_insert(json!("week")); } secrets(client, "secrets.share", one)?; } App::Secrets { id: id.clone() } } App::Days { id } => { if request["role"].as_str().is_some_and(|r| r != "invite") { return Err(MethodError::new("bad_request", say("errors.days_one_role", &[]))); } // They are in the Circle, so on Cotton: Days sends them the invitation as a box, never an email. let mut heard = super::days_people::Heard::of(client).connected.unwrap_or_default(); for m in &people { if !heard.iter().any(|(n, _)| n == &m.number) { heard.push((m.number.clone(), Some(m.name.clone()))); } } super::days_people::Heard::connected(client, heard); let (_, guests) = event_of(client, id)?; let mut list: Vec<Value> = guests.iter().filter(|g| !g.organizer).map(|g| json!({ "key": g.key, "name": g.name })).collect(); list.extend(people.iter().map(|m| json!({ "number": m.number, "name": m.name }))); days_people(client, id, list, request)?; App::Days { id: id.clone() } } App::Cinemas { id } => { if request["role"].as_str().is_some_and(|r| r != "see") { return Err(MethodError::new("bad_request", say("errors.cinemas_one_role", &[]))); } let (list_name, films) = film_list(client, id)?; let list = cinemas_list(id); match list_state(client, id)? { None => { let mut items: Vec<Value> = films.iter().map(|(film, body)| json!({ "item": film, "body": body })).collect(); items.push(json!({ "item": super::cinemas_shared::NAME_ITEM, "body": { "list_name": list_name } })); lists(client, "shared.found", json!({ "id": list, "members": numbers, "items": items }))?; } Some((me, owner, members, items)) => { if me != owner { return Err(MethodError::new("not_owner", say("errors.not_list_owner", &[]))); } for number in numbers.iter().filter(|n| !members.contains(n)) { lists(client, "shared.add", json!({ "id": list, "number": number }))?; } for (film, body) in films.iter().filter(|(f, _)| !items.contains(f)) { lists(client, "shared.put", json!({ "id": list, "item": film, "body": body }))?; } if !items.iter().any(|i| i == super::cinemas_shared::NAME_ITEM) { lists(client, "shared.put", json!({ "id": list, "item": super::cinemas_shared::NAME_ITEM, "body": { "list_name": list_name } }))?; } } } App::Cinemas { id: id.clone() } } }; let with = with(client, &app_now)?; let said = say("said.shared", &[("names", &names(&people))]); // A new album's answer names the space it founded (`thing`), so the shell goes on to add its photos there. Ok(json!({ "said": said, "thing": app_now.thing(), "with": with }))}// ── shared with ─────────────────────────────────────────────────────────fn with(client: &Here<'_>, app: &App) -> Result<Value, MethodError> { let name = thing_name(client, app)?; let stop_call = |who: &str| json!({ "method": "share.stop", "request": { "app": app.name(), "thing": app.thing(), "person": who } }); let mut rows = Vec::new(); match app { App::Albums { space: Some(space), album, .. } => { let read = albums(client, "albums.shared.read", json!({ "space": space }))?; let me_owner = read["owner"] == read["me"]; for m in read["members"].as_array().into_iter().flatten() { if m["you"] == true { rows.insert(0, json!({ "person": null, "words": say("with.you", &[]), "initials": say("with.you_initials", &[]), "detail": say(if m["role"] == "owner" { "with.made" } else { "with.member" }, &[]) })); continue; } let number = m["number"].as_str().and_then(e164); let (person, words) = match &number { Some(n) => circle::name_for(client, n), None => (None, say("with.unknown", &[])), }; let mut detail = say(if m["role"] == "owner" { "with.made" } else { "with.can_add" }, &[]); if m["trust"] == "verified" { detail = format!("{detail} · {}", say("detail.checked", &[])); } if person.is_none() && number.is_some() { detail = format!("{detail} · {}", say("with.not_in_contacts", &[])); } let mut row = json!({ "person": person, "number": number, "words": words, "initials": circle::initials_of(&words), "detail": detail }); if me_owner && m["role"] != "owner" { if let Some(n) = &number { row["acts"] = json!([{ "id": "stop", "words": say("with.stop", &[]), "red": true, "call": stop_call(n) }]); } } rows.push(row); } for l in read["links"].as_array().into_iter().flatten().filter(|l| album.is_none() || l["album"] == json!(album)) { rows.push(json!({ "person": null, "words": say("with.link", &[]), "detail": null, "acts": [{ "id": "stop", "words": say("with.link_stop", &[]), "red": true, "call": { "method": "albums.shared.link.stop", "request": { "space": space, "link": l["link"] } } }] })); } } App::Albums { .. } => {} App::Secrets { id } => { rows.push(json!({ "person": null, "words": say("with.you", &[]), "initials": say("with.you_initials", &[]), "detail": say("with.yours", &[]) })); let held = secrets(client, "secrets.holders", json!({ "id": id }))?; for h in held["holders"].as_array().into_iter().flatten() { let Some(number) = h["number"].as_str().and_then(e164) else { continue }; let (person, words) = circle::name_for(client, &number); let mut row = json!({ "person": person, "number": number, "words": words, "initials": circle::initials_of(&words), "detail": h["line"] }); if h["state"] == "holds" { row["acts"] = json!([{ "id": "stop", "words": say("with.take_back", &[]), "red": true, "call": stop_call(&number) }]); } rows.push(row); } } App::Days { id } => { rows.push(json!({ "person": null, "words": say("with.you", &[]), "initials": say("with.you_initials", &[]), "detail": say("with.yours", &[]) })); for g in event_of(client, id)?.1.into_iter().filter(|g| !g.organizer) { let (person, words) = match &g.number { Some(n) => { let (person, named) = circle::name_for(client, n); (person, if named.is_empty() { g.name.clone().unwrap_or_default() } else { named }) } None => (None, g.name.clone().unwrap_or_default()), }; let mut row = json!({ "person": person, "number": g.number, "words": words, "initials": circle::initials_of(&words), "detail": g.line }); // A guest Days reaches another way (an email through Google) is taken off in Days itself. if let (Some(n), true) = (&g.number, g.on_cotton) { row["acts"] = json!([{ "id": "stop", "words": say("with.uninvite", &[]), "red": true, "call": stop_call(n) }]); } rows.push(row); } } App::Cinemas { id } => { if let Some((me, owner, members, _)) = list_state(client, id)?.map(|state| honour_leaves(client, id, state)).transpose()? { rows.push(json!({ "person": null, "words": say("with.you", &[]), "initials": say("with.you_initials", &[]), "detail": say(if me == owner { "with.made" } else { "with.member_list" }, &[]) })); for number in members.into_iter().filter(|n| n != &me) { let (person, words) = circle::name_for(client, &number); let detail = say(if number == owner { "with.made" } else { "with.sees_list" }, &[]); let mut row = json!({ "person": person, "number": number, "words": words, "initials": circle::initials_of(&words), "detail": detail }); if me == owner { row["acts"] = json!([{ "id": "stop", "words": say("with.stop", &[]), "red": true, "call": stop_call(&number) }]); } rows.push(row); } } else { rows.push(json!({ "person": null, "words": say("with.you", &[]), "initials": say("with.you_initials", &[]), "detail": say("with.yours", &[]) })); } } } // Everyone but You: the people, and a link when there is one. let shared = rows.len().saturating_sub(1); Ok(json!({ "title": say("with.title", &[("name", &name), ("n", &shared.to_string())]), "rows": rows, "more": { "words": say("with.more", &[]), "call": { "method": "share.sheet", "request": { "app": app.name(), "thing": app.thing() } } }, }))}/// The number a `person` field names: a number as it is, or the contact's number that has the thing.fn person_number(client: &Here<'_>, app: &App, request: &Value) -> Result<String, MethodError> { let who = text(request, "person")?; if let Some(n) = e164(who) { return Ok(n); } let has = holders(client, app)?; circle::numbers_of(client, who).into_iter().find(|n| has.contains(n)).ok_or_else(|| MethodError::new("not_shared", say("errors.not_shared", &[])))}fn role(client: &Here<'_>, app: &App, request: &Value) -> Result<Value, MethodError> { match app { App::Albums { .. } => Err(MethodError::new("one_role", say("errors.albums_one_role", &[]))), App::Days { .. } => Err(MethodError::new("one_role", say("errors.days_one_role", &[]))), App::Cinemas { .. } => Err(MethodError::new("one_role", say("errors.cinemas_one_role", &[]))), App::Secrets { id } => { // A box's role is fixed in what was sealed: a new one goes, the old is taken back. let number = person_number(client, app, request)?; let may = text(request, "role")?; if may != "see" && may != "copy" { return Err(MethodError::new("bad_request", say("errors.role", &[]))); } secrets(client, "secrets.take", json!({ "id": id, "numbers": [number] }))?; secrets(client, "secrets.share", json!({ "id": id, "number": number, "may": may, "until": request["until"].as_str().unwrap_or("week") }))?; let mut answer = with(client, app)?; answer["said"] = json!(say("said.role", &[])); Ok(answer) } }}fn stop(client: &Here<'_>, app: &App, request: &Value) -> Result<Value, MethodError> { let number = person_number(client, app, request)?; match app { App::Albums { space: Some(space), .. } => { let read = albums(client, "albums.shared.read", json!({ "space": space }))?; if read["owner"] != read["me"] { return Err(MethodError::new("not_owner", say("errors.not_owner", &[]))); } let member = read["members"].as_array().into_iter().flatten().find(|m| m["number"].as_str().and_then(e164).as_deref() == Some(number.as_str())).and_then(|m| m["member"].as_str()).map(str::to_string); let member = member.ok_or_else(|| MethodError::new("not_shared", say("errors.not_shared", &[])))?; albums(client, "albums.shared.rekey", json!({ "space": space, "remove": [member] }))?; } App::Albums { .. } => return Err(MethodError::new("not_shared", say("errors.not_shared", &[]))), App::Secrets { id } => { secrets(client, "secrets.take", json!({ "id": id, "numbers": [number] }))?; } App::Days { id } => { let (_, guests) = event_of(client, id)?; let list: Vec<Value> = guests.iter().filter(|g| !g.organizer && g.number.as_deref() != Some(number.as_str())).map(|g| json!({ "key": g.key, "name": g.name })).collect(); days_people(client, id, list, request)?; } App::Cinemas { id } => { let Some((me, owner, _, _)) = list_state(client, id)? else { return Err(MethodError::new("not_shared", say("errors.not_shared", &[]))) }; if me != owner { return Err(MethodError::new("not_owner", say("errors.not_list_owner", &[]))); } lists(client, "shared.remove", json!({ "id": cinemas_list(id), "number": number }))?; } } let (_, name) = circle::name_for(client, &number); let mut answer = with(client, app)?; answer["said"] = json!(say("said.stopped", &[("name", name.split_whitespace().next().unwrap_or(&name))])); Ok(answer)}// ── by person ───────────────────────────────────────────────────────────/// What I share with a person and what they share with me, across apps (`contacts.person`'s `shared`).fn by_person(client: &Here<'_>, request: &Value) -> Result<Value, MethodError> { let who = text(request, "person")?; let numbers: Vec<String> = match e164(who) { Some(n) => vec![n], None => circle::numbers_of(client, who), }; let (mut mine, mut theirs) = (Vec::new(), Vec::new()); if numbers.is_empty() { return Ok(json!({ "mine": mine, "theirs": theirs })); } // Albums: every space this account is in, read once each; mine when I own it, theirs when they do. if let Ok(spaces) = albums(client, "albums.shared.spaces", json!({})) { for s in spaces["spaces"].as_array().into_iter().flatten() { let Some(space) = s["space"].as_str() else { continue }; let Ok(read) = albums(client, "albums.shared.read", json!({ "space": space })) else { continue }; let theirs_here = read["members"].as_array().into_iter().flatten().find(|m| m["you"] != true && m["number"].as_str().and_then(e164).is_some_and(|n| numbers.contains(&n))); let Some(them) = theirs_here else { continue }; for a in read["albums"].as_array().into_iter().flatten() { let title = a["name"].as_str().unwrap_or_default(); let open = json!({ "app": "albums", "space": space, "album": a["id"] }); if read["owner"] == read["me"] { mine.push(json!({ "app": "albums", "words": say("apps.albums", &[]), "detail": format!("{title} · {}", say("with.can_add", &[]).to_lowercase()), "open": open })); } else if them["role"] == "owner" { theirs.push(json!({ "app": "albums", "words": say("apps.albums", &[]), "detail": title, "open": open })); } } } } // Secrets: the boxes I gave them (still held) and those they gave me. // AUDIT D: read from the shares by number (`secrets.held` names holders by first name, so none ever showed here). if let Ok(held) = super::secrets_app::held_by(client, &numbers) { for h in held { mine.push(json!({ "app": "secrets", "words": say("apps.secrets", &[]), "detail": h.title, "open": { "app": "secrets", "id": h.secret_id } })); } } if let Ok(inbox) = secrets(client, "secrets.inbox", json!({})) { for row in inbox["rows"].as_array().into_iter().flatten() { if row["from"].as_str().and_then(e164).is_some_and(|n| numbers.contains(&n)) { theirs.push(json!({ "app": "secrets", "words": say("apps.secrets", &[]), "detail": row["title"], "open": { "app": "secrets", "share": row["share"] } })); } } } // Days: events he made with them on the guest list by Cotton (mine), and invitations they sent him (theirs). if let Ok(events) = events_with(client, &numbers) { for (id, title, theirs_here) in events { let row = json!({ "app": "days", "words": say("apps.days", &[]), "detail": title, "open": { "app": "days", "id": id } }); if theirs_here { theirs.push(row) } else { mine.push(row) } } } // Cinemas: his film lists they see (mine), and lists they shared with him (theirs). Words and Sites share // nothing yet, so they show nothing here. if let Ok(listed) = lists(client, "shared.lists", json!({})) { let me = listed["me"].as_str().unwrap_or_default().to_string(); 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 }; let Some(group) = id.strip_prefix("cinemas-") else { continue }; let open = json!({ "app": "cinemas", "owner": owner, "id": id }); if owner == me { let Ok(Some((_, _, members, _))) = list_state(client, group) else { continue }; if !members.iter().filter_map(|m| e164(m)).any(|m| numbers.contains(&m)) { continue; } let name = film_list(client, group).map(|(name, _)| name).unwrap_or_default(); mine.push(json!({ "app": "cinemas", "words": say("apps.cinemas", &[]), "detail": format!("{name} · {}", say("with.sees_list", &[]).to_lowercase()), "open": { "app": "cinemas", "list": group } })); } else if e164(owner).is_some_and(|n| numbers.contains(&n)) { let name = lists(client, "shared.read", json!({ "owner": owner, "id": id })) .ok() .and_then(|read| read["items"].as_array().and_then(|items| items.iter().find(|i| i["id"] == super::cinemas_shared::NAME_ITEM).and_then(|i| i["list_name"].as_str().map(str::to_string)))) .unwrap_or_default(); theirs.push(json!({ "app": "cinemas", "words": say("apps.cinemas", &[]), "detail": name, "open": open })); } } } Ok(json!({ "mine": mine, "theirs": theirs }))}/// Events with one of `numbers` on them by Cotton: `(event, title, theirs)`, theirs when that number organised it/// (an invitation received), else his own event with them on the guest list. Never a binned event or one taken off.fn events_with(client: &ClientController, numbers: &[String]) -> Result<Vec<(String, String, bool)>, MethodError> { let numbers = numbers.to_vec(); let read = super::cotton_chat::read(client, "share.by_person.days", move |ctx| { let mut found = Vec::new(); let rows = super::cotton_chat::rows( ctx, "SELECT e.id AS id, e.title AS title, g.phone AS phone, coalesce(g.role, '') AS role, \ EXISTS (SELECT 1 FROM cotton_event_attendees o WHERE o.event_id = e.id AND o.role = 'organizer') AS invited \ FROM cotton_event_attendees g JOIN cotton_events e ON e.id = g.event_id \ WHERE g.via = 'cotton' AND g.removed_at IS NULL AND g.phone IS NOT NULL AND e.trashed_at IS NULL ORDER BY e.starts_at DESC", &[], )?; for row in rows { let Some(phone) = row.get("phone").and_then(Value::as_str).and_then(e164) else { continue }; if !numbers.contains(&phone) { continue; } let organiser = row.get("role").and_then(Value::as_str) == Some("organizer"); let invited = row.get("invited").and_then(Value::as_i64).unwrap_or(0) != 0; if invited && !organiser { continue; } found.push(json!([row.get("id"), row.get("title").and_then(Value::as_str).unwrap_or_default(), organiser])); } Ok(Value::from(found)) })?; Ok(read .as_array() .into_iter() .flatten() .filter_map(|r| Some((r[0].as_str()?.to_string(), r[1].as_str().unwrap_or_default().to_string(), r[2].as_bool().unwrap_or(false)))) .collect())}#[cfg(test)]#[path = "share_sheet_tests.rs"]mod tests;