Cotton code
138 lines · 5.0 KB · RustRaw
//! The Calls view: the imported call history, one ordered list.use cotton_store::driver::{Driver, Row};use cotton_store::error::Result;use cotton_store::soft_refs::soft_value;use rusqlite::types::Value as SqlValue;use serde_json::{json, Map, Value};use std::collections::BTreeMap;fn map(row: &Row) -> Map<String, Value> {    row.columns()        .iter()        .map(|(key, value)| {            (                key.clone(),                match value {                    SqlValue::Null | SqlValue::Blob(_) => Value::Null,                    SqlValue::Text(value) => json!(value),                    SqlValue::Integer(value) => json!(value),                    SqlValue::Real(value) => json!(value),                },            )        })        .collect()}fn text<'a>(row: &'a Map<String, Value>, key: &str) -> Option<&'a str> {    row.get(key).and_then(Value::as_str)}/// Whether `person` is the person a call was resolved to.pub fn has_person(row: &Map<String, Value>, person: &str) -> bool {    text(row, "person_id") == Some(person)}/// The person a call was resolved to, when it was.pub fn people_on(row: &Map<String, Value>) -> Vec<&str> {    text(row, "person_id").into_iter().collect()}/// A call's person, DERIVED as it is read (PEOPLE BUILD 1b): its chat contact's person (who(handle); nobody for a/// number several contacts share), or, for a call with no contact, who its handle names; a call with neither keeps/// the person it was linked to, while that person is living. Never the person stored/// when the call was imported, so a number that moved, or a shared landline, answers as every screen does.fn call_person_sql(db: &Driver) -> String {    use cotton_store::protocol::who::{contact_person_sql, person_of_handle_sql, shared_held};    let shared = shared_held(db);    format!(        "(CASE WHEN EXISTS (SELECT 1 FROM cotton_msg_contacts k WHERE k.id = c.contact_id) THEN (SELECT {by_contact} FROM cotton_msg_contacts k WHERE k.id = c.contact_id) \          WHEN coalesce(c.handle, '') <> '' THEN {by_handle} \          ELSE {by_hand} END)",        by_hand = soft_value("c.person_id", "cotton_people"),        by_contact = contact_person_sql(shared, "k"),        by_handle = person_of_handle_sql(shared, "c.workspace_id", "(CASE WHEN c.handle LIKE '%@%' THEN 'email' ELSE 'phone' END)", "c.handle"),    )}/// A person's recent calls are narrowed before the shared view loads their facts.pub fn read_calls_for_person(    db: &Driver,    workspace: &str,    person: &str,) -> Result<Vec<Map<String, Value>>> {    let params = [        SqlValue::Text(workspace.into()),        SqlValue::Text(person.into()),    ];    let ids = db        .all(            &format!("SELECT c.id FROM cotton_call_log c WHERE c.workspace_id=? AND {}=?", call_person_sql(db)),            &params,        )?        .into_iter()        .filter_map(|row| row.text("id").map(str::to_string))        .collect::<Vec<_>>();    read_calls_for_ids(db, workspace, &ids)}/// Every call, before filtering or paging.pub fn read_calls(db: &Driver, workspace: &str) -> Result<Vec<Map<String, Value>>> {    read_selected(db, workspace, None)}/// Linked surfaces read only named records, rather than scanning a person's history.pub fn read_calls_for_ids(    db: &Driver,    workspace: &str,    ids: &[String],) -> Result<Vec<Map<String, Value>>> {    read_selected(db, workspace, Some(ids))}fn select(    db: &Driver,    sql: &str,    workspace: &str,    column: &str,    ids: Option<&[String]>,) -> Result<Vec<Row>> {    match ids {        None => db.all(sql, &[SqlValue::Text(workspace.into())]),        Some(ids) => {            let mut found = Vec::new();            for batch in ids.chunks(400) {                let query = format!(                    "{sql} AND {column} IN ({})",                    vec!["?"; batch.len()].join(",")                );                let mut params = vec![SqlValue::Text(workspace.into())];                params.extend(batch.iter().cloned().map(SqlValue::Text));                found.extend(db.all(&query, &params)?);            }            Ok(found)        }    }}fn read_selected(    db: &Driver,    workspace: &str,    only: Option<&[String]>,) -> Result<Vec<Map<String, Value>>> {    let mut found = BTreeMap::new();    for row in select(        db,        &format!("SELECT c.*, {} AS person_id, {} AS contact_id FROM cotton_call_log c WHERE c.workspace_id=?", call_person_sql(db), soft_value("c.contact_id", "cotton_msg_contacts")),        workspace,        "id",        only,    )? {        found.insert(row.text("id").unwrap_or_default().to_string(), map(&row));    }    let mut found = found.into_values().collect::<Vec<_>>();    let instant = |row: &Map<String, Value>| {        text(row, "started_at").and_then(|s| chrono::DateTime::parse_from_rfc3339(s).ok())    };    found.sort_by(|a, b| {        instant(b)            .cmp(&instant(a))            .then_with(|| text(a, "id").cmp(&text(b, "id")))    });    Ok(found)}#[cfg(test)]#[path = "reader_tests.rs"]mod tests;