Cotton code
176 lines · 8.5 KB · RustRaw
//! `chat.storage {}`, `chat.storage.free { thread, expected }` — STORAGE BY//! CHAT (the owner's iPhone, Comms build 23, 23 Nov 2026, item 4): what each//! chat keeps on this phone, largest first, and a way to free one chat.//!//! ```json//! chat.storage {} → { "title", "none"?,//!   "chats": [{ "thread", "name", "picture", "bytes", "said",//!               "parts": [{ "id": "photos|videos|voice|files", "label", "bytes", "said" }],//!               "free": { "label", "bytes", "line", "ask"?, "ask_body"?, "confirm"? } }] }//! chat.storage.free { thread, expected } → { "freed_bytes", "said" }   (refused storage_changed)//! ```//!//! - **Measured, never guessed** (shared/DECISIONS.md "Storage"): a chat's//!   bytes are the files on this phone under its folder in the person's own//!   media (`{file}/messages/{thread}/`, where every chat file is kept://!   `chat_files::keep`, the sender's own copy, an import's), each read from//!   the disk; a ledger entry whose file is not here counts nothing. They are//!   what Storage's Photos and files holds, split by chat. Thumbnails stay in//!   Other, as Storage counts them; a preview lives in its message (Your data).//! - **The kinds** come from each file's type: a picture is Photos, a video//!   Videos, a sound Voice messages, anything else Files. A kind with nothing//!   in it is left out, so a chat lists only what it holds.//! - **Largest first**, then by name. A chat that keeps nothing is not listed;//!   when none keeps anything, `none` says so.//! - **Free this chat** is Free up space over this chat's folder alone//!   (`shell_settings::free_within`): only what is safely in the person's//!   account goes (`FREEABLE`), never a preview, never a file not synced yet,//!   and each comes back when it is opened. Its amount is said before it is//!   asked, and a chat whose files changed since is refused, as Free up space is.use std::collections::HashMap;use serde_json::{json, Value};use cotton_core::messages::app::list::{self, say};use crate::methods::shell_settings::{self, size_said, FREEABLE};use crate::methods::MethodError;use crate::shell::client::ClientController;/// The kinds a chat's breakdown says, in this order.pub const KINDS: [&str; 4] = ["photos", "videos", "voice", "files"];/// The kind a file of `content_type` counts as.pub fn kind_of(content_type: &str) -> &'static str {    let content_type = content_type.to_ascii_lowercase();    if content_type.starts_with("image/") {        "photos"    } else if content_type.starts_with("video/") {        "videos"    } else if content_type.starts_with("audio/") {        "voice"    } else {        "files"    }}/// What one chat keeps on this phone, measured.#[derive(Debug, Clone, Default, PartialEq, Eq)]pub struct ChatKept {    /// By kind, in [`KINDS`]' order.    pub kinds: [u64; 4],    /// Of them, what Free this chat may take (as the ledger says, as Free up space counts it).    pub freeable: u64,}impl ChatKept {    pub fn total(&self) -> u64 {        self.kinds.iter().sum()    }}/// The folder every file of the person's chats is kept under on this phone's copy.fn messages_prefix(client: &ClientController) -> Result<String, MethodError> {    client.with_file(|file| Ok(format!("{}/messages/", file.identity.id()))).map_err(|why| MethodError::new("not_ready", why))}/// Every chat's files on this phone, measured from the disk, by thread.pub fn measured(client: &ClientController) -> Result<HashMap<String, ChatKept>, MethodError> {    let prefix = messages_prefix(client)?;    let sql = format!(        "SELECT key, content_type, local_path, size_bytes, CASE WHEN {FREEABLE} THEN 1 ELSE 0 END AS free \           FROM _media WHERE local_path IS NOT NULL AND state <> 'delete_pending' AND COALESCE(tier, '') <> 'thumb' \            AND substr(key, 1, length(?1)) = ?1"    );    let found: Vec<(String, String, String, u64, bool)> = client        .with_file(|file| {            Ok(file                .driver                .all(&sql, &[rusqlite::types::Value::Text(prefix.clone())])                .map_err(|error| error.to_string())?                .iter()                .map(|row| {                    (                        row.text("key").unwrap_or_default().to_string(),                        row.text("content_type").unwrap_or_default().to_string(),                        row.text("local_path").unwrap_or_default().to_string(),                        u64::try_from(row.int("size_bytes").unwrap_or(0)).unwrap_or(0),                        row.int("free") == Some(1),                    )                })                .collect())        })        .map_err(|why| MethodError::new("unreadable", why))?;    let mut out: HashMap<String, ChatKept> = HashMap::new();    for (key, content_type, path, ledger, free) in found {        let Some(thread) = key[prefix.len()..].split('/').next().filter(|thread| !thread.is_empty()) else { continue };        // Measured: what the disk holds. A file the ledger names but the phone no longer has counts nothing.        let Ok(meta) = std::fs::metadata(&path) else { continue };        if !meta.is_file() {            continue;        }        let chat = out.entry(thread.to_string()).or_default();        let at = KINDS.iter().position(|kind| *kind == kind_of(&content_type)).unwrap_or(3);        chat.kinds[at] += meta.len();        if free {            chat.freeable += ledger;        }    }    Ok(out)}pub(crate) fn call(client: &ClientController, method: &str, request: &Value) -> Result<Value, MethodError> {    match method {        "chat.storage" => storage(client),        "chat.storage.free" => free(client, request),        other => Err(MethodError::new("unknown_method", format!("`{other}` is not a storage method"))),    }}fn storage(client: &ClientController) -> Result<Value, MethodError> {    let lines = list::lines();    let line = |id: &str, fills: &[(&str, &str)]| say(&lines, &format!("app.you.storage_chat.{id}"), fills);    let measured = measured(client)?;    let named = super::chat_app::named(client)?;    // A chat no longer in the list (deleted) is no chat a person can open: not listed.    let mut chats: Vec<(&String, &ChatKept, &(String, Value))> =        measured.iter().filter(|(_, kept)| kept.total() > 0).filter_map(|(thread, kept)| named.get(thread).map(|name| (thread, kept, name))).collect();    chats.sort_by(|a, b| b.1.total().cmp(&a.1.total()).then_with(|| a.2 .0.to_lowercase().cmp(&b.2 .0.to_lowercase())).then_with(|| a.0.cmp(b.0)));    let chats: Vec<Value> = chats        .into_iter()        .map(|(thread, kept, (name, picture))| {            let parts: Vec<Value> = KINDS                .iter()                .zip(kept.kinds)                .filter(|(_, bytes)| *bytes > 0)                .map(|(kind, bytes)| json!({ "id": kind, "label": line(kind, &[]), "bytes": bytes, "said": size_said(bytes) }))                .collect();            let freed = size_said(kept.freeable);            let mut free = json!({ "label": line("free", &[]), "bytes": kept.freeable });            if kept.freeable > 0 {                free["line"] = json!(line("free_line", &[("size", &freed)]));                free["ask"] = json!(line("free_ask", &[("size", &freed)]));                free["ask_body"] = json!(line("free_ask_body", &[]));                free["confirm"] = json!(line("free_confirm", &[]));            } else {                free["line"] = json!(line("free_none", &[]));            }            json!({ "thread": thread, "name": name, "picture": picture, "bytes": kept.total(), "said": size_said(kept.total()), "parts": parts, "free": free })        })        .collect();    let mut answer = json!({ "title": say(&lines, "app.you.storage_chats", &[]), "chats": chats });    if answer["chats"].as_array().is_some_and(Vec::is_empty) {        answer["none"] = json!(say(&lines, "app.you.storage_chats_none", &[]));    }    Ok(answer)}fn free(client: &ClientController, request: &Value) -> Result<Value, MethodError> {    let thread = request["thread"].as_str().filter(|t| !t.is_empty() && !t.contains('/')).ok_or_else(|| MethodError::new("bad_request", "chat.storage.free takes the chat, `thread`"))?;    let expected = request["expected"].as_u64().ok_or_else(|| MethodError::new("bad_request", "chat.storage.free takes the bytes the person agreed to free, `expected`"))?;    let within = format!("{}{thread}/", messages_prefix(client)?);    shell_settings::free_within(client, expected, Some(&within))}// Tests: chat_storage_tests.rs, a part of chat_app_tests (its invented chats).