Cotton code
116 lines · 4.5 KB · RustRaw
//! A finished call's row in the `call` table, as the DEVICE writes it: the//! Worker writes no call row. The table is sealed, so the row goes up sealed//! like any other write of it.//!//! One row per room and side: its id is made from (namespace, `cotton`,//! room) as every call log id is (`cotton-mac/src/calls.rs` `call_id`), so//! two of the callee's devices that both saw a ring end unanswered land one//! row. A device whose ring another device answered or declined writes//! nothing: that device writes the call.use serde::{Deserialize, Serialize};use super::machine::{Call, Direction, Phase};use super::wire::{MemberState, Mode};use super::wire::EndReason;/// `call.source` and `call.provider` of a Cotton call.pub const COTTON: &str = "cotton";/// The row's columns, by the `call` table's keys.#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]pub struct HistoryRow {    pub id: String,    pub source: String,    pub external_id: String,    pub provider: String,    pub direction: String,    pub outcome: String,    pub started_at: String,    pub duration_s: i64,    pub handle: Option<String>,    pub person_id: Option<String>,    pub kind: String,    pub ended_at: String,    pub ended_reason: String,    /// An incoming call that rang and nobody here answered: the one clear    /// flag Calling's Missed view reads (direction and outcome are sealed).    pub missed: bool,    pub live: bool,    /// A group call: everyone else in it (not this device), by number, comma separated.    pub who: Option<String>,}/// The call log id of `room` under `namespace`.pub fn call_id(namespace: &str, room: &str) -> String {    cotton_rules::ids::derived_id("cotton_call_log", &[namespace, COTTON, room])}/// Whether this device writes the ended `call`: not when another device of/// the callee's took the ring.pub fn writes(call: &Call) -> bool {    !(call.direction == Direction::In && matches!(call.reason, Some(EndReason::AnsweredElsewhere | EndReason::DeclinedElsewhere)))}/// What happened, in the `call` table's four words.pub fn outcome(call: &Call) -> &'static str {    use EndReason as R;    if call.live_at.is_some() {        return "answered";    }    match (call.direction, call.reason) {        (Direction::Out, Some(R::Cancelled | R::HungUp)) => "cancelled",        (Direction::Out, Some(R::NoAnswer | R::Declined | R::Busy | R::RemoteHungUp)) => "missed",        (_, Some(R::Failed | R::Lost | R::TooManyCalls | R::UnreachableNetwork)) | (Direction::Out, _) => "failed",        (Direction::In, _) => "missed",    }}pub fn iso(ms: i64) -> String {    chrono::DateTime::from_timestamp_millis(ms).unwrap_or_default().to_rfc3339_opts(chrono::SecondsFormat::Millis, true)}/// The row an ended call leaves, or none: the call is not over, has no room,/// or another device writes it.pub fn history_row(call: &Call, namespace: &str) -> Option<HistoryRow> {    if call.phase != Phase::Ended || !writes(call) {        return None;    }    let room = call.room.as_deref()?;    let ended = call.ended_at.unwrap_or(call.phase_at);    Some(HistoryRow {        id: call_id(namespace, room),        source: COTTON.into(),        external_id: room.to_string(),        provider: COTTON.into(),        direction: match call.direction {            Direction::In => "in",            Direction::Out => "out",        }        .into(),        outcome: outcome(call).into(),        started_at: iso(call.started_at),        duration_s: call.duration_s(ended),        handle: call.number.clone(),        // A group call is nobody's in particular: its people are `who`.        person_id: if call.mode == Mode::Sfu { None } else { call.person.clone() },        kind: if call.video { "video" } else { "audio" }.into(),        ended_at: iso(ended),        ended_reason: call.reason.map(EndReason::as_str).unwrap_or("failed").into(),        // A ring declined here was seen, not missed.        missed: call.direction == Direction::In && call.live_at.is_none() && matches!(call.reason, Some(EndReason::Missed | EndReason::Cancelled | EndReason::NoAnswer)),        live: true,        who: (call.mode == Mode::Sfu).then(|| {            call.members                .iter()                .filter(|m| !matches!(m.state, MemberState::Ringing) && Some(&m.id) != call.me.as_ref())                .filter_map(|m| m.number.clone())                .collect::<Vec<_>>()                .join(", ")        }),    })}#[cfg(test)]#[path = "history_tests.rs"]mod tests;