Cotton code
883 lines · 44.6 KB · RustRaw
//! `calls.*` — Cotton Calling on this phone, every decision the core's//! ([`cotton_core::calling`]). The shell hands in what happened (a tap, a//! VoIP push, a room frame, the ICE state, a timer) and draws and performs//! the effects answered; the routes on the person's own object (the room's//! start, join, decline and end, the ICE servers, the push token) are asked//! here, through the door `personal.connect` holds ([`ObjectDoor`]).//!//! ```text//! calls.state         {}                                      → { call, active }//! calls.start         { person? | number? | people? | numbers?, video?, group? } → { call, effects }   (refused in_a_call, no_number, too_many, bad_group)//! calls.enter         { room, video?, group?, name? }          → { call, effects }   (a group's call going on: in late, or again)//! calls.notes         { on }                                  → { call, effects }   (Take notes: this phone starts or stops)//! calls.incoming      { room, video?, ring?, privateKey?, later? } → { call, effects, caller?, join? }   (PushKit: perform the report before returning)//! calls.join          { room }                                → { call, effects }   (after `calls.incoming {later: true}`)//! calls.answer        {}                                      → { call, effects }//! calls.decline       { busy? }                               → { call, effects }//! calls.end           {}                                      → { call, effects }//! calls.leave         {}                                      → { call, effects }   (a group: the others go on)//! calls.invite        { person? | number? | people? | numbers? } → { call, effects }//! calls.mute          { audio, video }                        → { call, effects }//! calls.speaking      { on }                                  → { call, effects }//! calls.signal        { in: <room frame> }                    → { call, effects }//!                     { out: { kind, sdp?, candidate?, mid?, mline? } }//!                     { out: { sfu: push|renegotiate|close, sdp?, tracks?, mids? } }   (a group call's SFU)//! calls.media         { state: connected|disconnected|failed } → { call, effects }//! calls.socketClosed  {}                                      → { call, effects }//! calls.stop          { room, reason }                        → { call, effects }   (a stop push)//! calls.tick          {}                                      → { call, effects }//! calls.iceServers    {}                                      → { iceServers, ttl }//! calls.pushToken     { platform: ios|android, token, topic?, sandbox? } → { ok }//! calls.history       {}                                      → { id } | { written: false }//! calls.link          { person? | people?, video? }           → { url }//! calls.openLink      { url }                                 → { people, video } | null//! ```//!//! Every `effects` list is the shell's alone, in order: the core performs//! its own asks and writes the history row itself, so neither ever reaches//! the shell. One call at a time, held for the life of the controller; the//! room credential is never answered but inside an `open_socket` effect.use serde_json::{json, Value};use cotton_core::calling::history::{self, HistoryRow};use cotton_core::calling::link;use cotton_core::calling::machine::{ring_while_busy, step, stray_stop, Call, Callee, Effect, Event, MAX_INVITEES};use cotton_core::calling::wire::{ClientFrame, EndReason, Joined, MediaState, RoomFrame, SignalKind, Started};use cotton_tools::mcp::handlers::common::insert_row;use crate::handle::CottonHandle;use crate::methods::MethodError;use crate::shell::client::ClientController;/// Every method this family answers.pub const METHODS: [&str; 24] = [    "calls.answer",    "calls.decline",    "calls.end",    "calls.enter",    "calls.history",    "calls.ack",    "calls.iceServers",    "calls.incoming",    "calls.invite",    "calls.join",    "calls.leave",    "calls.link",    "calls.media",    "calls.mute",    "calls.notes",    "calls.openLink",    "calls.pushToken",    "calls.signal",    "calls.socketClosed",    "calls.speaking",    "calls.start",    "calls.state",    "calls.stop",    "calls.tick",];/// The object's call routes.pub mod routes {    pub const START: &str = "/v1/calls";    pub const ICE: &str = "/v1/calls/ice";    /// A ring or a stop that came by push, acked as a socket's frame is (CALLS FIX 2).    pub const ACK: &str = "/v1/calls/ack";    pub const DEVICE: &str = "/v1/calls/device";    pub fn join(room: &str) -> String {        format!("/v1/calls/{room}/join")    }    pub fn decline(room: &str) -> String {        format!("/v1/calls/{room}/decline")    }    pub fn end(room: &str) -> String {        format!("/v1/calls/{room}/end")    }    pub fn invite(room: &str) -> String {        format!("/v1/calls/{room}/invite")    }    pub fn enter(room: &str) -> String {        format!("/v1/calls/{room}/enter")    }    pub fn status(room: &str) -> String {        format!("/v1/calls/{room}/status")    }}/// The VoIP topics an iPhone's push token may be filed under: Cotton Calling, Cotton Chat (calls moved into Chat,/// 19 Nov 2026) and their Devs.pub const TOPICS: [&str; 4] = ["com.cottondb.calling", "com.cottondb.calling.dev", "com.cottondb.messages", "com.cottondb.messages.dev"];/// The table a call is kept in on this phone.const CALLS: &str = "cotton_call_log";pub fn call(handle: &CottonHandle, method: &str, request: &Value) -> Result<Value, MethodError> {    let dev = handle.flavor() == cotton_core::flavor::Flavor::Dev;    over(&handle.client(), method, request, dev)}/// The same, over a named controller (the suite's phone). `dev`: links name Cotton Calling Dev.pub fn over(client: &ClientController, method: &str, request: &Value, dev: bool) -> Result<Value, MethodError> {    if matches!(method, "calls.start" | "calls.enter" | "calls.incoming" | "calls.join") {        crate::phone::call_notes::said_can(client, request);    }    match method {        "calls.state" => {            let call = client.call_slot().lock().unwrap_or_else(|p| p.into_inner()).clone();            Ok(json!({ "call": call, "active": call.is_active() }))        }        "calls.start" => start(client, request),        "calls.enter" => enter(client, request),        "calls.notes" => {            let on = request.get("on").and_then(Value::as_bool).ok_or_else(|| bad("on", "true or false"))?;            drive(client, Event::Notes { on })        }        "calls.incoming" => incoming(client, request),        "calls.join" => join(client, request),        "calls.answer" => drive(client, Event::Accept),        "calls.decline" => drive(client, if request.get("busy").and_then(Value::as_bool).unwrap_or(false) { Event::Busy } else { Event::Decline }),        "calls.end" => drive(client, Event::HangUp),        "calls.leave" => drive(client, Event::Leave),        "calls.invite" => {            let callees = callees_of(client, request)?;            drive(client, Event::Invite { callees })        }        "calls.mute" => {            let audio = request.get("audio").and_then(Value::as_bool).ok_or_else(|| bad("audio", "true or false"))?;            let video = request.get("video").and_then(Value::as_bool).ok_or_else(|| bad("video", "true or false"))?;            drive(client, Event::Mute { audio, video })        }        "calls.speaking" => {            let on = request.get("on").and_then(Value::as_bool).ok_or_else(|| bad("on", "true or false"))?;            drive(client, Event::Speaking { on })        }        "calls.signal" => signal(client, request),        "calls.media" => {            let state: MediaState = serde_json::from_value(request.get("state").cloned().unwrap_or(Value::Null)).map_err(|_| bad("state", "connected, disconnected or failed"))?;            drive(client, Event::Media(state))        }        "calls.socketClosed" => drive(client, Event::SocketClosed),        "calls.stop" => stop(client, request),        "calls.tick" => drive(client, Event::Tick),        "calls.iceServers" => door(client)?.send("GET", routes::ICE, None),        // A ring or a stop that came by push: the object is told this phone has it, as a socket's `ring_ack` tells it,        // so it pushes no more and keeps no missed call for it (CALLS FIX 2, M3).        "calls.ack" => {            let room = text(request, "room")?;            door(client)?.send("POST", routes::ACK, Some(&json!({ "room": room })))        }        "calls.pushToken" => push_token(client, request),        "calls.history" => {            let call = client.call_slot().lock().unwrap_or_else(|p| p.into_inner()).clone();            match write_history(client, &call)? {                Some(id) => Ok(json!({ "id": id })),                None => Ok(json!({ "written": false })),            }        }        "calls.link" => {            let people = words_of(request, "person", "people")?;            if people.len() > MAX_INVITEES {                return Err(too_many());            }            let people: Vec<&str> = people.iter().map(String::as_str).collect();            Ok(json!({ "url": link::build(&people, flag(request, "video"), dev) }))        }        "calls.openLink" => Ok(match link::parse(text(request, "url")?) {            Some(found) => json!({ "people": found.people, "video": found.video }),            None => Value::Null,        }),        other => Err(MethodError::new("unknown_method", format!("`{other}` is not a calls method"))),    }}fn bad(field: &str, shape: &str) -> MethodError {    MethodError::new("bad_request", format!("`{field}` is {shape}"))}fn text<'a>(request: &'a Value, field: &str) -> Result<&'a str, MethodError> {    request.get(field).and_then(Value::as_str).map(str::trim).filter(|v| !v.is_empty()).ok_or_else(|| bad(field, "required text"))}fn too_many() -> MethodError {    MethodError::new("too_many", format!("A call rings at most {MAX_INVITEES} people."))}/// One text under `one` or a list under `many`, trimmed, each once.fn words_of(request: &Value, one: &str, many: &str) -> Result<Vec<String>, MethodError> {    let mut words: Vec<String> = Vec::new();    if let Some(word) = request.get(one).and_then(Value::as_str).map(str::trim).filter(|w| !w.is_empty()) {        words.push(word.to_string());    }    if let Some(list) = request.get(many) {        let list = list.as_array().ok_or_else(|| bad(many, "a list"))?;        for word in list {            let word = word.as_str().map(str::trim).filter(|w| !w.is_empty()).ok_or_else(|| bad(many, "a list of text"))?;            if !words.iter().any(|held| held == word) {                words.push(word.to_string());            }        }    }    if words.is_empty() {        return Err(bad(one, "required"));    }    Ok(words)}/// Who a start or an invite calls: people (by their first phone in this copy) and numbers (E.164, named when this copy knows them).fn callees_of(client: &ClientController, request: &Value) -> Result<Vec<Callee>, MethodError> {    let people = if request.get("person").is_some() || request.get("people").is_some() { words_of(request, "person", "people")? } else { Vec::new() };    let numbers = if request.get("number").is_some() || request.get("numbers").is_some() { words_of(request, "number", "numbers")? } else { Vec::new() };    if people.is_empty() && numbers.is_empty() {        return Err(bad("person or number", "required"));    }    if people.len() + numbers.len() > MAX_INVITEES {        return Err(too_many());    }    let mut callees: Vec<Callee> = Vec::new();    for person in people {        let (number, name) = number_of(client, &person)?;        let number = number.ok_or_else(|| MethodError::new("no_number", "This person has no phone number to call."))?;        callees.push(Callee { number, person: Some(person), name });    }    for raw in numbers {        let number = e164(&raw).ok_or_else(|| MethodError::new("bad_number", "Use an international number starting with +."))?;        let (person, name) = person_of(client, &number);        callees.push(Callee { number, person, name });    }    let mut seen = std::collections::BTreeSet::new();    callees.retain(|callee| seen.insert(callee.number.clone()));    Ok(callees)}fn flag(request: &Value, field: &str) -> bool {    request.get(field).and_then(Value::as_bool).unwrap_or(false)}fn door(client: &ClientController) -> Result<std::sync::Arc<crate::phone::personal_object::ObjectDoor>, MethodError> {    client.object_door().ok_or_else(|| MethodError::new("not_connected", "this phone is not connected to its database yet"))}fn now_ms(client: &ClientController) -> i64 {    client.now().timestamp_millis()}fn fresh_uuid() -> String {    let mut bytes: [u8; 16] = rand::random();    bytes[6] = (bytes[6] & 0x0f) | 0x40;    bytes[8] = (bytes[8] & 0x3f) | 0x80;    let hex: String = bytes.iter().map(|b| format!("{b:02X}")).collect();    format!("{}-{}-{}-{}-{}", &hex[0..8], &hex[8..12], &hex[12..16], &hex[16..20], &hex[20..32])}/// `+` and the E.164 digits, or none.fn e164(raw: &str) -> Option<String> {    cotton_core::import::phone::normalize_phone(raw).map(|digits| format!("+{digits}"))}/// The person's first phone in this copy, and their name.fn number_of(client: &ClientController, person: &str) -> Result<(Option<String>, Option<String>), MethodError> {    let person = person.to_string();    let found = client        .read_rows("calls.person", &mut |ctx| {            let workspace = rusqlite::types::Value::Text(ctx.workspace_id.to_string());            let id = rusqlite::types::Value::Text(person.clone());            let name = ctx                .db()                .all("SELECT full_name FROM cotton_people WHERE workspace_id = ? AND id = ? AND trashed_at IS NULL", &[workspace.clone(), id.clone()])                .map_err(|e| e.to_string())?;            let phones = ctx                .db()                .all("SELECT value FROM cotton_person_handles WHERE workspace_id = ? AND person_id = ? AND kind = 'phone' AND trashed_at IS NULL ORDER BY position, created_at", &[workspace, id])                .map_err(|e| e.to_string())?;            let name = name.first().and_then(|row| crate::phone::passwords::json_row(row).get("full_name").and_then(Value::as_str).map(str::to_string));            let phone = phones.iter().find_map(|row| crate::phone::passwords::json_row(row).get("value").and_then(Value::as_str).and_then(e164));            Ok(json!({ "known": !name.is_none(), "name": name, "phone": phone }))        })        .map_err(|why| MethodError::new("unreadable", why))?;    let found = crate::authoring::own_answer(found);    if found["known"] != json!(true) {        return Err(MethodError::new("person_not_found", "Nobody with this id is kept here."));    }    Ok((found["phone"].as_str().map(str::to_string), found["name"].as_str().map(str::to_string)))}/// The person in this copy holding `number`, and their name: who(handle) (`cotton_store::protocol::who`).fn person_of(client: &ClientController, number: &str) -> (Option<String>, Option<String>) {    let Some((kind, value)) = cotton_store::protocol::who::who_key(cotton_store::protocol::person_handles::HandleKind::Phone, number, None) else {        return (None, None);    };    let found = client.read_rows("calls.caller", &mut |ctx| {        let who = cotton_store::protocol::who::who(ctx.db(), ctx.workspace_id, kind, &value).map_err(|e| e.to_string())?;        Ok(who_answer(&who))    });    match found.map(crate::authoring::own_answer) {        Ok(found) => (found["person"].as_str().map(str::to_string), found["name"].as_str().map(str::to_string)),        Err(_) => (None, None),    }}/// Who a number is, for a caller's line: the one person and their name; for a/// number several of his contacts share (a household landline), no person and/// every holder's name, never the first as if certain (PEOPLE BUILD 1b).pub(crate) fn who_answer(who: &cotton_store::protocol::who::Who) -> Value {    use cotton_store::protocol::who::Who;    match who {        Who::One(holder) => json!({ "person": holder.id, "name": holder.full_name }),        Who::Shared(holders) => json!({ "name": holders.iter().map(|h| h.full_name.as_str()).collect::<Vec<_>>().join(" & ") }),        Who::Nobody => json!({}),    }}fn start(client: &ClientController, request: &Value) -> Result<Value, MethodError> {    let video = flag(request, "video");    let callees = callees_of(client, request)?;    {        let held = client.call_slot().lock().unwrap_or_else(|p| p.into_inner());        if held.is_active() {            return Err(MethodError::new("in_a_call", "A call is already under way."));        }    }    let group = group_of(request)?;    drive(client, Event::Dial { uuid: fresh_uuid(), callees, video, group })}/// A Cotton group's id as a request names it (32 hex), or none.fn group_of(request: &Value) -> Result<Option<String>, MethodError> {    match request.get("group") {        None | Some(Value::Null) => Ok(None),        Some(Value::String(g)) if cotton_core::chat::group::is_group_id(g) => Ok(Some(g.clone())),        Some(_) => Err(bad("group", "a Cotton group's id")),    }}/// Into a group's call already going on (late, or again after leaving): no ring, the room lets a member in.fn enter(client: &ClientController, request: &Value) -> Result<Value, MethodError> {    let room = text(request, "room")?.to_string();    if !cotton_core::calling::wire::is_room_id(&room) {        return Err(bad("room", "a call's room id"));    }    {        let held = client.call_slot().lock().unwrap_or_else(|p| p.into_inner());        if held.is_active() {            return Err(MethodError::new("in_a_call", "A call is already under way."));        }    }    let name = request.get("name").and_then(Value::as_str).map(str::to_string);    drive(client, Event::Enter { room, video: flag(request, "video"), group: group_of(request)?, name })}/// A ring pushed here. `ring` is the box the person's own object sealed for/// this phone's chat key with who is calling (`{v, ring, from, video}`): with/// `privateKey` it is opened here, at once and without the network, so the/// system's call UI names the caller from the first moment (`caller`, and the/// title of `system_call_incoming`) instead of "Cotton" until joining answers./// Apple and Google carry the box and cannot read it. `later: true` answers/// before the join is asked (`join` names the room): the shell reports the/// call to CallKit, then asks `calls.join`, so a slow object never delays the/// report iOS demands inside the push.fn incoming(client: &ClientController, request: &Value) -> Result<Value, MethodError> {    let room = text(request, "room")?.to_string();    let video = flag(request, "video");    // A ring for a call that ended here (its frame and its push, a socket that opened late, a duplicate push minutes    // on): it rang once and rings no more. A push was reported to CallKit before the core was asked (`pushed`), so    // that report is ended at once; a frame reported nothing, so nothing is said (CALLS FIX 2, M1).    if let Some(reason) = ended_here(client, &room) {        let call = client.call_slot().lock().unwrap_or_else(|p| p.into_inner()).clone();        let effects = if flag(request, "pushed") { stray_stop(&room, reason) } else { Vec::new() };        return Ok(json!({ "call": call, "effects": effects }));    }    let busy_elsewhere = {        let held = client.call_slot().lock().unwrap_or_else(|p| p.into_inner());        held.is_active() && held.room.as_deref() != Some(room.as_str())    };    if busy_elsewhere {        let effects = perform(client, ring_while_busy(&room));        let call = client.call_slot().lock().unwrap_or_else(|p| p.into_inner()).clone();        return Ok(json!({ "call": call, "effects": addressed(client, effects) }));    }    let caller = match (request.get("ring").and_then(Value::as_str), request.get("privateKey").and_then(Value::as_str)) {        (Some(sealed), Some(key)) => ring_hint(client, &room, sealed, key),        _ => None,    };    let mut answer = drive_with(client, Event::Incoming { room: room.clone(), video }, flag(request, "later"))?;    // A phone rung late (its socket opened 38 s in) starts the call at the ring's own start, as the object kept it,    // not at the moment it heard it (CALLS FIX 3).    if let Some(at) = request.get("at").and_then(Value::as_i64).filter(|t| *t > 0) {        let mut slot = client.call_slot().lock().unwrap_or_else(|p| p.into_inner());        if slot.room.as_deref() == Some(room.as_str()) && slot.phase == cotton_core::calling::machine::Phase::RingingIn && at < slot.started_at {            slot.started_at = at;            answer["call"] = json!(*slot);        }    }    if let Some(caller) = caller {        let who = caller["name"].as_str().or_else(|| caller["number"].as_str()).unwrap_or_default().to_string();        // A group's ring is named by the group and who rings: "Invented Family · Asha".        let group = caller["group"].as_str().map(str::to_string);        let place = group.as_deref().and_then(|g| group_place(client, g));        let title = match &place {            Some((_, Some(group_name))) => cotton_core::messages::app::list::say(&cotton_core::messages::app::list::lines(), "app.call.group.ring", &[("group", group_name), ("name", &who)]),            _ => who.clone(),        };        {            let mut slot = client.call_slot().lock().unwrap_or_else(|p| p.into_inner());            if slot.room.as_deref() == Some(room.as_str()) && slot.number.is_none() {                slot.number = caller["number"].as_str().map(str::to_string);                slot.person = caller["person"].as_str().map(str::to_string);                slot.name = caller["name"].as_str().map(str::to_string);            }            if slot.room.as_deref() == Some(room.as_str()) && group.is_some() {                slot.group = group.clone();                slot.mode = cotton_core::calling::wire::Mode::Sfu;                if let Some((thread, group_name)) = &place {                    slot.thread = Some(thread.clone());                    if group_name.is_some() {                        slot.name = group_name.clone();                    }                }            }            answer["call"] = json!(*slot);        }        for effect in answer["effects"].as_array_mut().into_iter().flatten() {            if effect["do"] == "system_call_incoming" && !title.is_empty() {                effect["title"] = json!(title);                effect["handle"] = caller["number"].clone();            }        }        answer["caller"] = caller;    }    Ok(answer)}/// A group's conversation on this phone and its name, when it is here.pub(crate) fn group_place(client: &ClientController, group: &str) -> Option<(String, Option<String>)> {    let ns = namespace(client).ok()?;    let thread = super::chat_group::thread_id(&ns, group);    let t = thread.clone();    let found = super::cotton_chat::read(client, "calls.group", move |ctx| {        Ok(super::cotton_chat::one(ctx, "SELECT title FROM cotton_msg_threads WHERE workspace_id = ? AND id = ? AND trashed_at IS NULL", &[super::cotton_chat::ws(ctx), rusqlite::types::Value::Text(t.clone())])?.map(Value::Object).unwrap_or(Value::Null))    })    .ok()?;    found.is_object().then(|| (thread, found["title"].as_str().map(str::to_string).filter(|t| !t.is_empty())))}/// Who a ring's sealed box says is calling, as this copy knows them: `{ number, name?, person?, photo?, photoPath? }`./// None when the box does not open for this key, is not this ring's, or names no number.fn ring_hint(client: &ClientController, room: &str, sealed: &str, key: &str) -> Option<Value> {    let secret = zeroize::Zeroizing::new(cotton_core::chat::seal::key_from_text(key)?);    let opened = cotton_core::chat::seal::open(&secret, sealed)?;    let said: Value = serde_json::from_slice(&opened.payload).ok()?;    if said["ring"].as_str() != Some(room) {        return None;    }    let number = super::cotton_chat::e164(said["from"].as_str()?)?;    let (person, name) = person_of(client, &number);    let mut caller = json!({ "number": number, "name": name, "person": person });    // What kind of call it was, for a missed call's row written from a stop (CALLS FIX 1).    if said["video"].as_bool() == Some(true) {        caller["video"] = json!(true);    }    if let Some(group) = said["group"].as_str().filter(|g| cotton_core::chat::group::is_group_id(g)) {        caller["group"] = json!(group);    }    let numbers = vec![number.clone()];    let photo = super::cotton_chat::read(client, "calls.caller", move |ctx| {        let who = super::chat_calls::who(ctx, &numbers)?;        let found = who.get(&numbers[0]);        let photo = found.and_then(|w| w.photo.clone());        let path = photo.as_deref().and_then(|key| super::media::local_path_of(ctx.db(), key)).filter(|p| p.exists()).map(|p| p.to_string_lossy().to_string());        // The name Chat knows them by (a contact's), when they are none of Your people.        let name = found.map(|w| w.name.clone()).filter(|n| n != &numbers[0]);        Ok(json!({ "photo": photo, "photoPath": path, "name": name }))    })    .ok()?;    if caller["name"].is_null() {        caller["name"] = photo["name"].clone();    }    caller["photo"] = photo["photo"].clone();    caller["photoPath"] = photo["photoPath"].clone();    Some(caller)}/// The join a `calls.incoming {later}` left: asked now, outside the call's lock, then the machine stepped.fn join(client: &ClientController, request: &Value) -> Result<Value, MethodError> {    let room = text(request, "room")?.to_string();    let waiting = {        let slot = client.call_slot().lock().unwrap_or_else(|p| p.into_inner());        slot.room.as_deref() == Some(room.as_str()) && slot.phase == cotton_core::calling::machine::Phase::RingingIn && slot.credential.is_none()    };    if !waiting {        let call = client.call_slot().lock().unwrap_or_else(|p| p.into_inner()).clone();        return Ok(json!({ "call": call, "effects": [] }));    }    let event = joined(client, &room);    drive(client, event)}/// `POST /v1/calls/<room>/join`, as the event it comes to.fn joined(client: &ClientController, room: &str) -> Event {    joined_at(client, room, &routes::join(room))}/// A join or an enter (`path`), as the event it comes to.fn joined_at(client: &ClientController, _room: &str, path: &str) -> Event {    let mut body = json!({});    crate::phone::call_notes::can(client, &mut body);    match ask(client, "POST", path, Some(body)) {        Ok(answer) => match serde_json::from_value::<Joined>(answer) {            Ok(joined) => {                let (person, name) = person_of(client, &joined.from);                Event::Joined { answer: joined, person, name }            }            Err(_) => Event::JoinFailed { code: "unreadable_answer".into() },        },        Err(error) => Event::JoinFailed { code: error.code },    }}fn signal(client: &ClientController, request: &Value) -> Result<Value, MethodError> {    if let Some(frame) = request.get("in") {        let frame: RoomFrame = serde_json::from_value(frame.clone()).map_err(|_| bad("in", "a room frame"))?;        return drive(client, Event::Frame(frame));    }    let out = request.get("out").ok_or_else(|| bad("in or out", "required"))?;    // The SFU's ops (a group call): `{ out: { sfu: push|renegotiate|close, sdp?, tracks?, mids? } }`.    if let Some(op) = out.get("sfu") {        let op: cotton_core::calling::wire::SfuOp = serde_json::from_value(op.clone()).map_err(|_| bad("out.sfu", "push, pull, renegotiate or close"))?;        let sdp = out.get("sdp").and_then(Value::as_str).map(str::to_string);        let tracks = match out.get("tracks") {            Some(t) => Some(serde_json::from_value(t.clone()).map_err(|_| bad("out.tracks", "[{ mid?, member?, name, kind? }]"))?),            None => None,        };        let mids = out.get("mids").and_then(Value::as_array).map(|m| m.iter().filter_map(|x| x.as_str().map(str::to_string)).collect());        return drive(client, Event::Out(ClientFrame::Sfu { op, sdp, tracks, mids }));    }    let kind: SignalKind = serde_json::from_value(out.get("kind").cloned().unwrap_or(Value::Null)).map_err(|_| bad("out.kind", "offer, answer, ice or restart"))?;    let words = |field: &str| out.get(field).and_then(Value::as_str).map(str::to_string);    let frame = ClientFrame::Signal { kind, sdp: words("sdp"), candidate: words("candidate"), mid: words("mid"), mline: out.get("mline").and_then(Value::as_u64).map(|n| n as u32) };    match kind {        SignalKind::Ice if words("candidate").is_none() => return Err(bad("out.candidate", "required for ice")),        SignalKind::Offer | SignalKind::Answer | SignalKind::Restart if words("sdp").is_none() => return Err(bad("out.sdp", "required")),        _ => {}    }    drive(client, Event::Out(frame))}fn stop(client: &ClientController, request: &Value) -> Result<Value, MethodError> {    let room = text(request, "room")?.to_string();    let reason = EndReason::parse(text(request, "reason")?).ok_or_else(|| bad("reason", "an end reason"))?;    let here = client.call_slot().lock().unwrap_or_else(|p| p.into_inner()).room.as_deref() == Some(room.as_str());    if here && ended_here(client, &room).is_none() {        // The ring's own start, when the stop says it and this phone heard it later (CALLS FIX 3).        if let Some(at) = request.get("at").and_then(Value::as_i64).filter(|t| *t > 0) {            let mut slot = client.call_slot().lock().unwrap_or_else(|p| p.into_inner());            if slot.direction == cotton_core::calling::machine::Direction::In && slot.live_at.is_none() && at < slot.started_at {                slot.started_at = at;            }        }        return drive(client, Event::Stop { reason });    }    // A missed call this phone never heard ring: the stop names who called, sealed as the ring was, and the row is    // written as if it had rung, at the ring's own times (`at`, `ended`), once: a second telling never changes it    // (CALLS FIX 2, M2). Never for a ring answered or declined on another phone: that one writes it.    if matches!(reason, EndReason::Missed | EndReason::Cancelled) && !here && !logged(client, &room) {        if let (Some(sealed), Some(key)) = (request.get("ring").and_then(Value::as_str), request.get("privateKey").and_then(Value::as_str)) {            if let Some(caller) = ring_hint(client, &room, sealed, key) {                let now = now_ms(client);                let at = request.get("at").and_then(Value::as_i64).filter(|t| *t > 0).unwrap_or(now);                let ended = request.get("ended").and_then(Value::as_i64).filter(|t| *t >= at).unwrap_or(now.max(at));                let group = caller["group"].as_str().map(str::to_string);                let place = group.as_deref().and_then(|g| group_place(client, g));                let missed = Call {                    phase: cotton_core::calling::machine::Phase::Ended,                    direction: cotton_core::calling::machine::Direction::In,                    video: caller["video"].as_bool().unwrap_or(false),                    mode: if group.is_some() { cotton_core::calling::wire::Mode::Sfu } else { cotton_core::calling::wire::Mode::P2p },                    uuid: cotton_core::calling::machine::uuid_of_room(&room),                    room: Some(room.clone()),                    number: caller["number"].as_str().map(str::to_string),                    person: caller["person"].as_str().map(str::to_string),                    name: place.as_ref().and_then(|(_, n)| n.clone()).or_else(|| caller["name"].as_str().map(str::to_string)),                    thread: place.map(|(thread, _)| thread),                    group,                    started_at: at,                    phase_at: ended,                    ended_at: Some(ended),                    reason: Some(reason),                    ..Call::idle()                };                write_history(client, &missed)?;            }        }    }    remember_ended(client, &room, reason, now_ms(client));    let call = client.call_slot().lock().unwrap_or_else(|p| p.into_inner()).clone();    // A VoIP push was reported to CallKit before the core was asked, and is ended here at once; a frame over the chat    // socket (or a missed call told when it opened) reported nothing, and rings nothing (CALLS FIX 2, H1).    let effects = if flag(request, "pushed") { stray_stop(&room, reason) } else { Vec::new() };    Ok(json!({ "call": call, "effects": effects }))}/// How long a call that ended here is remembered: past any VoIP push still on its way for it.const ENDED_KEPT_MS: i64 = 10 * 60_000;fn remember_ended(client: &ClientController, room: &str, reason: EndReason, now: i64) {    let mut ended = client.ended_calls().lock().unwrap_or_else(|p| p.into_inner());    ended.retain(|(r, at, _)| r != room && now - at < ENDED_KEPT_MS);    ended.push((room.to_string(), now, reason));}/// Why the call in `room` ended here, when it did lately.fn ended_here(client: &ClientController, room: &str) -> Option<EndReason> {    let now = now_ms(client);    let ended = client.ended_calls().lock().unwrap_or_else(|p| p.into_inner());    ended.iter().find(|(r, at, _)| r == room && now - at < ENDED_KEPT_MS).map(|(_, _, reason)| *reason)}/// Whether this copy holds a row for the call in `room` already.fn logged(client: &ClientController, room: &str) -> bool {    let Ok(ns) = namespace(client) else { return false };    let id = cotton_core::calling::history::call_id(&ns, room);    client        .read_rows("calls.logged", &mut |ctx| {            let found = ctx.db().all(&format!("SELECT 1 FROM {CALLS} WHERE id = ?"), &[rusqlite::types::Value::Text(id.clone())]).map_err(|e| e.to_string())?;            Ok(json!(!found.is_empty()))        })        .map(|answer| crate::authoring::own_answer(answer) == json!(true))        .unwrap_or(false)}fn push_token(client: &ClientController, request: &Value) -> Result<Value, MethodError> {    let token = text(request, "token")?;    let body = match text(request, "platform")? {        "ios" => {            let token = token.to_ascii_lowercase();            if token.len() < 32 || token.len() > 200 || !token.bytes().all(|b| b.is_ascii_hexdigit()) {                return Err(bad("token", "the VoIP push token as hex"));            }            let topic = text(request, "topic")?;            if !TOPICS.contains(&topic) {                return Err(bad("topic", "Cotton Calling's bundle id"));            }            json!({ "platform": "ios", "token": token, "topic": topic, "sandbox": flag(request, "sandbox") })        }        "android" => {            // An FCM registration token: printable, no spaces, as Firebase handed it.            if token.len() < 32 || token.len() > 4096 || !token.bytes().all(|b| b.is_ascii_graphic()) {                return Err(bad("token", "the FCM registration token"));            }            json!({ "platform": "android", "token": token })        }        _ => return Err(bad("platform", "ios or android")),    };    // What this phone's shell says it speaks (`ring_ack`: it acks each ring, takes a late ring and a missed call kept    // for it), so a phone that rings by push alone is rung the new way too; a shell that says nothing is rung as before.    let mut body = body;    if let Some(can) = request.get("can").and_then(Value::as_array) {        body["can"] = json!(can.iter().filter_map(Value::as_str).collect::<Vec<_>>());    }    door(client)?.send("POST", routes::DEVICE, Some(&body))}/// One event through the machine, the core's asks performed (each answer/// fed back as its own event), the history written when the call ends:/// answered as the call and the shell's effects.fn drive(client: &ClientController, event: Event) -> Result<Value, MethodError> {    drive_with(client, event, false)}/// [`drive`], the join left for `calls.join` when `join_later`.fn drive_with(client: &ClientController, event: Event, join_later: bool) -> Result<Value, MethodError> {    let mut later: Option<String> = None;    let mut slot = client.call_slot().lock().unwrap_or_else(|p| p.into_inner());    let mut queue = std::collections::VecDeque::from([event]);    let mut shell = Vec::new();    let mut history = None;    let mut refused = None;    while let Some(event) = queue.pop_front() {        let (next, effects) = step(&slot, event, now_ms(client));        *slot = next;        for effect in effects {            match effect {                Effect::AskStart { to, video, group } => queue.push_back(match ask(client, "POST", routes::START, Some(start_body(client, &to, video, group.as_deref()))) {                    Ok(answer) => match serde_json::from_value::<Started>(answer) {                        Ok(started) => Event::Started(started),                        Err(_) => Event::StartFailed { code: "unreadable_answer".into() },                    },                    Err(error) => Event::StartFailed { code: error.code },                }),                Effect::AskJoin { room } if join_later => later = Some(room),                Effect::AskJoin { room } => queue.push_back(joined(client, &room)),                Effect::AskEnter { room } => queue.push_back(joined_at(client, &room, &routes::enter(&room))),                Effect::AskDecline { room, busy } => {                    let _ = ask(client, "POST", &routes::decline(&room), Some(json!({ "busy": busy })));                }                Effect::AskEnd { room } => {                    let _ = ask(client, "POST", &routes::end(&room), Some(json!({})));                }                // An invite the object refuses rings nobody: the roster says so when the room does.                Effect::AskInvite { room, to } => {                    let _ = ask(client, "POST", &routes::invite(&room), Some(json!({ "to": one_or_many(&to) })));                }                Effect::WriteHistory => match write_history(client, &slot) {                    Ok(written) => history = written,                    Err(error) => refused = Some(error.message),                },                other => shell.push(other),            }        }    }    // A call that ended is remembered for a push's lifetime, past the next call (CALLS FIX 2, M1).    if slot.phase == cotton_core::calling::machine::Phase::Ended {        if let Some(room) = slot.room.clone() {            if ended_here(client, &room).is_none() {                remember_ended(client, &room, slot.reason.unwrap_or(EndReason::Cancelled), now_ms(client));            }        }    }    // Members the room names by number only are named from this copy, here and in any roster drawn.    let mut named = false;    for member in slot.members.iter_mut().filter(|m| m.person.is_none() && m.name.is_none()) {        if let Some(number) = member.number.clone() {            let (person, name) = person_of(client, &number);            named |= person.is_some();            member.person = person;            member.name = name;        }    }    if named {        for effect in shell.iter_mut() {            if let Effect::ShowRoster { members } = effect {                *members = slot.members.clone();            }        }    }    let mut answer = json!({ "call": *slot, "effects": addressed(client, shell) });    // Take notes: the recording begun, grown or ended as the room now says (phone::call_notes).    let notes = crate::phone::call_notes::follow(client, &slot);    if let Some(effects) = answer["effects"].as_array_mut() {        effects.extend(notes);    }    if let Some(room) = later {        answer["join"] = json!(room);    }    if let Some(id) = history {        answer["history"] = json!(id);    }    // A row the copy would not take is said, never dropped quietly: `calls.history` writes it again.    if let Some(why) = refused {        answer["historyRefused"] = json!(why);    }    Ok(answer)}/// The asks of a list made outside the machine (`ring_while_busy`), performed; the rest answered.fn perform(client: &ClientController, effects: Vec<Effect>) -> Vec<Effect> {    effects        .into_iter()        .filter(|effect| match effect {            Effect::AskDecline { room, busy } => {                let _ = ask(client, "POST", &routes::decline(room), Some(json!({ "busy": busy })));                false            }            _ => true,        })        .collect()}/// The shell's effects as it reads them, each `open_socket` carrying the/// socket's whole address (`url`: the object's origin, `wss` where it is/// `https`, and the path) beside its path: the shell holds no origin of its/// own to put a path on. The socket is the open host's (`src/open.ts`), so/// no database prefix.fn addressed(client: &ClientController, effects: Vec<Effect>) -> Value {    let origin = client.object_door().map(|door| door.address.origin().text.clone());    let mut said = json!(effects);    for effect in said.as_array_mut().into_iter().flatten() {        if effect["do"] != "open_socket" {            continue;        }        if let (Some(origin), Some(path)) = (origin.as_deref(), effect["path"].as_str()) {            let socket = origin.strip_prefix("https://").map(|host| format!("wss://{host}")).or_else(|| origin.strip_prefix("http://").map(|host| format!("ws://{host}"))).unwrap_or_else(|| origin.to_string());            effect["url"] = json!(format!("{socket}{path}"));        }    }    said}/// `POST /v1/calls`'s body: `group` only on a group's call.fn start_body(client: &ClientController, to: &[String], video: bool, group: Option<&str>) -> Value {    let mut body = json!({ "to": one_or_many(to), "video": video });    crate::phone::call_notes::can(client, &mut body);    if let Some(group) = group {        body["group"] = json!(group);    }    body}/// `to` as the route takes it: one number, or the list.fn one_or_many(to: &[String]) -> Value {    match to {        [one] => json!(one),        many => json!(many),    }}fn ask(client: &ClientController, method: &str, path: &str, body: Option<Value>) -> Result<Value, MethodError> {    door(client)?.send(method, path, body.as_ref())}/// The namespace a call's id is made under: this database's.fn namespace(client: &ClientController) -> Result<String, MethodError> {    client.current_database().map_err(|why| MethodError::new("not_attached", why))}/// The ended call's row into this copy (it goes up sealed, as `call` is), or none when it leaves none.fn write_history(client: &ClientController, call: &Call) -> Result<Option<String>, MethodError> {    let Some(row) = history::history_row(call, &namespace(client)?) else { return Ok(None) };    let id = row.id.clone();    // Its line in its Chat conversation first, where this copy keeps Chat (Calling's does not): it is written    // once whatever happens, so a row refused below is written again by `calls.history` with the line kept.    crate::phone::chat_calls::leave_line(client, call)?;    let mut columns = columns_of(&row);    // What Chat needs to say the call and ring again (`phone::chat_calls`).    if let Some(meta) = crate::phone::chat_calls::row_meta(call) {        columns.insert("meta".into(), meta);    }    let answer = client        .write_rows("calls.history", &mut |ctx| {            // Every column the copy's table holds: the compiled ones and those            // the object's definitions laid on it at the first paint (kind,            // ended_reason, missed, who), never one it lacks.            let held: Vec<String> = ctx                .db()                .all(&format!("SELECT name FROM pragma_table_info('{CALLS}')"), &[])                .map_err(|error| error.to_string())?                .iter()                .filter_map(|column| column.text("name").map(str::to_string))                .collect();            let columns: serde_json::Map<String, Value> = columns.iter().filter(|(column, _)| held.contains(column)).map(|(column, value)| (column.clone(), value.clone())).collect();            insert_row(ctx, CALLS, &id, columns).map_err(|failure| failure.to_string())?;            Ok(json!({ "id": id }))        })        .map_err(|why| MethodError::new("write_refused", why))?;    Ok(crate::authoring::own_answer(answer)["id"].as_str().map(str::to_string))}/// The row's columns, by the `call` table's keys; the write keeps those the copy's table holds.fn columns_of(row: &HistoryRow) -> serde_json::Map<String, Value> {    let Value::Object(all) = serde_json::to_value(row).unwrap_or_default() else { return serde_json::Map::new() };    all.into_iter()        .filter(|(column, _)| column != "id")        .map(|(column, value)| match (column.as_str(), value) {            // A flag is stored as 0 or 1 (`live`, `missed`).            (_, Value::Bool(flag)) => (column, json!(i64::from(flag))),            (_, value) => (column, value),        })        .filter(|(_, value)| !value.is_null())        .collect()}#[cfg(test)]#[path = "calls_tests.rs"]mod tests;