Cotton code
535 lines · 21.9 KB · RustRaw
//! This device's notification preferences and the two OS-only notification//! actions.//!//! The preferences are local to one installation. The reminder engine takes//! them as an argument and the platform still owns notification scheduling;//! Rust must therefore never claim that it requested or opened an OS//! permission panel. This module owns the durable preference file and is the//! shared vocabulary for the generic device page.use std::sync::{Mutex, MutexGuard};use serde_json::{json, Map, Value};use cotton_core::rules::reminders::{    migrate_notification_prefs, NotificationCategory, NotificationPrefs,};use crate::{handle::CottonHandle, methods::MethodError, shell::client::ClientController};/// Methods owned by the local-device preferences engine.pub const METHODS: [&str; 6] = [    "device.notifications.asked",    "device.preferences.import",    "device.preferences.read",    "device.preferences.set",    "device.notifications.request",    "device.notifications.openSettings",];pub const FILE: &str = "device-preferences.json";/// Device-record columns represented by the local notification preference/// record. `notify` is the master switch; the others map one-to-one to the/// reminder engine's categories.pub const COLUMNS: [&str; 5] = [    "notify",    "notify_reminders",    "notify_events",    "notify_birthdays",    "notify_alarms",];/// Serializes read-modify-write, so two callers cannot share a temporary file.static WRITE_LOCK: Mutex<()> = Mutex::new(());/// Answers a local-device preference method. The first platform bridge imports/// its existing local value once; from then on this file is the sole source for/// the generic record page and the reminder scheduler's caller.pub fn call(handle: &CottonHandle, method: &str, request: &Value) -> Result<Value, MethodError> {    match method {        "device.preferences.import" => import(handle, request),        "device.preferences.read" => facts(&handle.client()),        "device.preferences.set" => set(handle, request),        "device.notifications.request" => Ok(platform_action("request_notifications")),        "device.notifications.asked" => asked(handle, request),        "device.notifications.openSettings" => Ok(platform_action("open_notification_settings")),        other => Err(MethodError::new(            "unknown_method",            format!("`{other}` is not a device-preferences method"),        )),    }}/// This device's notification preferences as the reminder engine takes them:/// the stored file, else every switch on and never asked — a phone that kept/// no legacy value (Android) starts there, as `migrate_notification_prefs`/// says a first install does.pub(crate) fn prefs(client: &ClientController) -> Result<NotificationPrefs, MethodError> {    Ok(migrate_notification_prefs(&stored(client)?.unwrap_or(Value::Null)))}/// `device.notifications.asked {at}` — the platform asked the OS for leave to/// notify (`request_notifications`), at `at`: the one inline ask is spent, so/// it is never answered again. A phone that kept no preferences yet starts/// from the defaults; every switch already chosen is kept.fn asked(handle: &CottonHandle, request: &Value) -> Result<Value, MethodError> {    let at = request.get("at").cloned().unwrap_or(Value::Null);    if !at.is_string() {        return Err(MethodError::new("bad_request", "device.notifications.asked takes the instant it asked, `at`"));    }    let next = {        let _guard = write_lock();        let raw = stored(&handle.client())?.unwrap_or_else(|| preferences(&NotificationPrefs::default()));        let (next, _) = apply(&raw, &json!({"patch": {"askedAt": at}}))?;        write_locked(&handle.client(), &next)?;        next    };    emit_device_data(&handle.client());    Ok(read(&next))}/// Normalise the local preference record into the device-page columns and the/// canonical value the platform store and reminder engine share.pub fn read(raw: &Value) -> Value {    let prefs = migrate_notification_prefs(raw);    json!({        "data": columns(&prefs),        "preferences": preferences(&prefs),        "local": COLUMNS,        "needs_import": false,    })}/// The local-only part of this installation's device record.  Reads of/// `records.get` use this directly so they do not need a host handle or an/// OS bridge.pub fn facts(client: &ClientController) -> Result<Value, MethodError> {    match stored(client)? {        Some(raw) => Ok(read(&raw)),        None => Ok(json!({"data": {}, "local": [], "needs_import": true})),    }}fn set(handle: &CottonHandle, request: &Value) -> Result<Value, MethodError> {    let (next, before) = {        let _guard = write_lock();        let raw = stored(&handle.client())?.ok_or_else(|| {            MethodError::new(                "needs_import",                "Import this device's existing notification preferences before changing them",            )        })?;        let (next, before) = apply(&raw, request)?;        write_locked(&handle.client(), &next)?;        (next, before)    };    emit_device_data(&handle.client());    let mut answer = read(&next);    let fields = answer        .as_object_mut()        .expect("read always returns an object");    fields.insert("changed".to_string(), json!(true));    fields.insert(        "undo".to_string(),        json!({"method":"device.preferences.set","args":{"patch":before}}),    );    Ok(answer)}/// Apply one full patch before touching the local file. Kept public to make/// the ownership rule testable without opening a client handle.pub fn apply(raw: &Value, request: &Value) -> Result<(Value, Value), MethodError> {    let patch = request        .get("patch")        .and_then(Value::as_object)        .filter(|patch| !patch.is_empty())        .ok_or_else(|| {            MethodError::new(                "bad_request",                "device.preferences.set needs a non-empty patch",            )        })?;    let mut prefs = migrate_notification_prefs(raw);    let mut before = columns(&prefs)        .as_object()        .expect("columns is an object")        .clone();    for (column, value) in patch {        match column.as_str() {            "askedAt" => {                before.insert(                    "askedAt".to_string(),                    prefs                        .asked_at                        .clone()                        .map(Value::from)                        .unwrap_or(Value::Null),                );                prefs.asked_at = match value {                    Value::Null => None,                    Value::String(asked_at)                        if chrono::DateTime::parse_from_rfc3339(asked_at).is_ok() =>                    {                        Some(asked_at.clone())                    }                    _ => {                        return Err(MethodError::new(                            "bad_request",                            "askedAt must be an RFC3339 timestamp or null",                        ));                    }                };            }            "notify" => prefs.enabled = bool_patch(column, value)?,            "notify_reminders" => set_category(                &mut prefs,                NotificationCategory::Reminders,                bool_patch(column, value)?,            ),            "notify_events" => set_category(                &mut prefs,                NotificationCategory::Events,                bool_patch(column, value)?,            ),            "notify_birthdays" => set_category(                &mut prefs,                NotificationCategory::Birthdays,                bool_patch(column, value)?,            ),            "notify_alarms" => set_category(                &mut prefs,                NotificationCategory::Alarms,                bool_patch(column, value)?,            ),            _ => {                return Err(MethodError::new(                    "bad_request",                    format!("{column} is not a local notification preference"),                ));            }        }    }    Ok((preferences(&prefs), Value::Object(before)))}fn bool_patch(column: &str, value: &Value) -> Result<bool, MethodError> {    value        .as_bool()        .ok_or_else(|| MethodError::new("bad_request", format!("{column} must be true or false")))}fn import(handle: &CottonHandle, request: &Value) -> Result<Value, MethodError> {    let candidate = request.get("preferences").ok_or_else(|| {        MethodError::new(            "bad_request",            "device.preferences.import needs the existing platform preferences",        )    })?;    if !complete_preferences(candidate) {        return Err(MethodError::new(            "bad_request",            "device.preferences.import needs enabled, every notification category, and optional askedAt",        ));    }    let (canonical, write) = {        let _guard = write_lock();        let (canonical, write) = imported(stored(&handle.client())?, candidate);        if write {            write_locked(&handle.client(), &canonical)?;        }        (canonical, write)    };    if write {        emit_device_data(&handle.client());    }    Ok(read(&canonical))}/// This file changes fields drawn on the device row. Emit only after the/// preference mutex is released: event callbacks may re-read core.pub(crate) fn emit_device_data(client: &ClientController) {    let Ok(workspace) =        client.with_file(|file| Ok::<String, String>(file.workspace_id.to_string()))    else {        return;    };    client.emit_data(&workspace, vec!["cotton_devices".to_string()], "local");}/// Resolve the one-time platform import without touching storage. An existing/// core value always wins: the bridge may migrate old state, never replace a/// choice already made through the generic record page.fn imported(existing: Option<Value>, candidate: &Value) -> (Value, bool) {    match existing {        Some(existing) => (existing, false),        None => (preferences(&migrate_notification_prefs(candidate)), true),    }}fn path(client: &ClientController) -> std::path::PathBuf {    client.layout().client_dir().join(FILE)}fn stored(client: &ClientController) -> Result<Option<Value>, MethodError> {    let path = path(client);    let bytes = match std::fs::read(&path) {        Ok(bytes) => bytes,        Err(error) if error.kind() == std::io::ErrorKind::NotFound => return Ok(None),        Err(error) => return Err(MethodError::new("unreadable", format!("{FILE}: {error}"))),    };    parse(&bytes).map(Some)}fn parse(bytes: &[u8]) -> Result<Value, MethodError> {    let value: Value = serde_json::from_slice(bytes).map_err(|error| {        MethodError::new("unreadable", format!("{FILE} is not valid JSON: {error}"))    })?;    if complete_preferences(&value) {        Ok(value)    } else {        Err(MethodError::new(            "unreadable",            format!("{FILE} does not hold complete notification preferences"),        ))    }}fn complete_preferences(value: &Value) -> bool {    value.get("enabled").and_then(Value::as_bool).is_some()        && value            .get("categories")            .and_then(Value::as_object)            .is_some_and(|categories| {                ["reminders", "events", "birthdays", "alarms"]                    .into_iter()                    .all(|category| categories.get(category).and_then(Value::as_bool).is_some())            })        && value            .get("askedAt")            .is_none_or(|asked_at| asked_at.is_string())}fn write_locked(client: &ClientController, preferences: &Value) -> Result<(), MethodError> {    let path = path(client);    if let Some(parent) = path.parent() {        std::fs::create_dir_all(parent)            .map_err(|error| MethodError::new("unwritable", format!("{FILE}: {error}")))?;    }    // The mutex serializes this process; the pid keeps a second Cotton process    // from deleting or renaming this one's temporary file.    let partial = path.with_extension(format!("json.{}.partial", std::process::id()));    // not a copy: preferences file.    std::fs::write(        &partial,        serde_json::to_vec_pretty(preferences).expect("preferences serialise"),    )    .map_err(|error| MethodError::new("unwritable", format!("{FILE}: {error}")))?;    // not a copy: preferences file.    std::fs::rename(&partial, path)        .map_err(|error| MethodError::new("unwritable", format!("{FILE}: {error}")))}fn write_lock() -> MutexGuard<'static, ()> {    WRITE_LOCK        .lock()        .unwrap_or_else(|poisoned| poisoned.into_inner())}fn set_category(prefs: &mut NotificationPrefs, category: NotificationCategory, enabled: bool) {    prefs.categories.insert(category, enabled);}fn columns(prefs: &NotificationPrefs) -> Value {    json!({        "notify": prefs.enabled,        "notify_reminders": prefs.category_enabled(NotificationCategory::Reminders),        "notify_events": prefs.category_enabled(NotificationCategory::Events),        "notify_birthdays": prefs.category_enabled(NotificationCategory::Birthdays),        "notify_alarms": prefs.category_enabled(NotificationCategory::Alarms),    })}fn preferences(prefs: &NotificationPrefs) -> Value {    let mut categories = Map::new();    for category in [        NotificationCategory::Reminders,        NotificationCategory::Events,        NotificationCategory::Birthdays,        NotificationCategory::Alarms,    ] {        categories.insert(            category.as_str().to_string(),            json!(prefs.category_enabled(category)),        );    }    let mut value = Map::new();    value.insert("enabled".to_string(), json!(prefs.enabled));    value.insert("categories".to_string(), Value::Object(categories));    if let Some(asked_at) = &prefs.asked_at {        value.insert("askedAt".to_string(), json!(asked_at));    }    Value::Object(value)}fn platform_action(action: &str) -> Value {    json!({"platform_action": action})}#[cfg(test)]mod tests {    use super::*;    /// RULE: Device notification choices remain local and use the one reminder    /// preference shape, so a generic page cannot save a switch into a synced    /// device row or silently re-enable a category it was given as off.    #[test]    fn set_normalises_and_changes_only_declared_local_preferences() {        let raw = json!({"enabled": true, "categories": {"events": false}});        let (preferences, before) = apply(            &raw,            &json!({                "patch": {"notify": false, "notify_birthdays": false}            }),        )        .unwrap();        let answer = read(&preferences);        assert_eq!(answer["data"]["notify"], false);        assert_eq!(answer["data"]["notify_events"], false);        assert_eq!(answer["data"]["notify_birthdays"], false);        assert_eq!(answer["preferences"]["categories"]["reminders"], true);        assert_eq!(before["notify"], true);        assert_eq!(answer["local"], json!(COLUMNS));        assert!(apply(&Value::Null, &json!({"patch":{"name":"not local"}})).is_err());    }    /// RULE: Permission prompts and Settings panes belong to the OS, so core    /// asks the platform to perform them and never reports an invented grant.    #[test]    fn os_notification_actions_are_explicit_requests_not_claimed_results() {        assert_eq!(            platform_action("request_notifications"),            json!({"platform_action":"request_notifications"})        );        assert_eq!(            platform_action("open_notification_settings"),            json!({"platform_action":"open_notification_settings"})        );        assert_eq!(            platform_action("choose_city"),            json!({"platform_action":"choose_city"})        );    }    /// RULE: A damaged local preference file refuses the page instead of    /// falling back to defaults, because defaults could re-enable a category    /// the person had turned off.    #[test]    fn corrupt_preferences_are_refused_not_defaulted() {        let error = parse(b"{this is not json").unwrap_err();        assert_eq!(error.code, "unreadable");        assert!(error.message.contains(FILE));        let error = parse(br#"{"enabled":true,"categories":{"events":false}}"#).unwrap_err();        assert_eq!(error.code, "unreadable");    }    /// RULE: The one-time platform import only fills an absent core file, so a    /// late UserDefaults bridge cannot overwrite a generic-page change.    #[test]    fn import_never_overwrites_existing_core_preferences() {        let existing = json!({"enabled": false, "categories": {"alarms": false}});        let (kept, wrote) = imported(Some(existing.clone()), &json!({"enabled": true}));        assert!(!wrote);        assert_eq!(kept, existing);        let (first, wrote) = imported(None, &json!({"enabled": false}));        assert!(wrote);        assert_eq!(first["enabled"], false);    }    /// RULE: The migration bridge takes Swift's complete notification wire    /// shape and preserves its one-time prompt history; a partial bridge input    /// must not manufacture defaults before the old local value is saved.    #[test]    fn import_shape_is_complete_and_read_preserves_asked_at() {        let legacy = json!({            "enabled": false,            "categories": {"reminders": true, "events": false, "birthdays": true, "alarms": false},            "askedAt": "2026-10-13T12:20:00Z"        });        assert!(complete_preferences(&legacy));        assert!(!complete_preferences(            &json!({"enabled": true, "categories": {}})        ));        let answer = read(&legacy);        assert_eq!(answer["needs_import"], false);        assert_eq!(answer["preferences"]["askedAt"], legacy["askedAt"]);    }    /// RULE: Recording the system prompt is local preference history, not a    /// switch change; it preserves every notification choice and refuses an    /// invalid instant before the caller can write the file.    #[test]    fn asked_at_patch_preserves_switches_and_undoes_the_previous_stamp() {        let raw = json!({            "enabled": false,            "categories": {"reminders": true, "events": false, "birthdays": true, "alarms": false}        });        let (next, undo) =            apply(&raw, &json!({"patch":{"askedAt":"2026-10-13T12:34:00Z"}})).unwrap();        assert_eq!(next["enabled"], false);        assert_eq!(next["categories"]["events"], false);        assert_eq!(next["askedAt"], "2026-10-13T12:34:00Z");        assert_eq!(undo["askedAt"], Value::Null);        assert!(apply(&raw, &json!({"patch":{"askedAt":"tomorrow"}})).is_err());        assert_eq!(raw["enabled"], false);        assert_eq!(raw["categories"]["events"], false);    }    /// RULE: The native file is the sole preference truth after one import;    /// actual writes preserve other switches and corrupt files refuse reads.    #[test]    fn native_preference_file_preserves_import_and_prompt_history() {        let (_dir, handle) = crate::fixture::synthetic_phone();        let run = |method, args| crate::methods::dispatch(&handle, method, &args);        let legacy = json!({"enabled":false,"categories":{"reminders":true,"events":false,"birthdays":true,"alarms":false},"askedAt":"2026-10-01T00:00:00Z"});        assert_eq!(run("device.preferences.read", json!({})).unwrap()["needs_import"], true);        assert!(run("device.preferences.set", json!({"patch":{"notify":true}})).is_err());        run("device.preferences.import", json!({"preferences":legacy})).unwrap();        run("device.preferences.import", json!({"preferences":{"enabled":true,"categories":{"reminders":false,"events":true,"birthdays":false,"alarms":true}}})).unwrap();        assert_eq!(run("device.preferences.read", json!({})).unwrap()["preferences"], legacy);        run("device.preferences.set", json!({"patch":{"notify_events":true}})).unwrap();        let changed = run("device.preferences.set", json!({"patch":{"askedAt":"2026-10-13T12:34:00Z"}})).unwrap();        assert_eq!(changed["undo"]["args"]["patch"]["askedAt"], "2026-10-01T00:00:00Z");        let current = run("device.preferences.read", json!({})).unwrap();        assert_eq!(current["data"]["notify"], false);        assert_eq!(current["data"]["notify_reminders"], true);        assert_eq!(current["data"]["notify_events"], true);        assert!(run("device.preferences.set", json!({"patch":{"askedAt":"tomorrow"}})).is_err());        let path = handle.client().layout().client_dir().join(FILE);        std::fs::write(&path, b"broken").unwrap();        assert_eq!(run("device.preferences.read", json!({})).unwrap_err().code, "unreadable");        assert!(run("device.preferences.set", json!({"patch":{"notify":true}})).is_err());        assert_eq!(std::fs::read(path).unwrap(), b"broken");    }    /// RULE (Android Todos, 12 Nov 2026): a phone that kept no preferences    /// (Android has no legacy store) reads as every switch on and never asked;    /// the platform's one ask is recorded by `device.notifications.asked`,    /// from those defaults, keeping a switch already chosen.    #[test]    fn a_phone_with_no_preferences_records_its_one_ask_from_the_defaults() {        let (_dir, handle) = crate::fixture::synthetic_phone();        let run = |method, args| crate::methods::dispatch(&handle, method, &args);        let fresh = prefs(&handle.client()).unwrap();        assert!(fresh.enabled && fresh.asked_at.is_none());        assert!(run("device.notifications.asked", json!({})).is_err());        let asked = run("device.notifications.asked", json!({"at": "2026-11-12T10:00:00Z"})).unwrap();        assert_eq!(asked["preferences"]["askedAt"], "2026-11-12T10:00:00Z");        assert_eq!(asked["data"]["notify_reminders"], true);        assert_eq!(prefs(&handle.client()).unwrap().asked_at.as_deref(), Some("2026-11-12T10:00:00Z"));        run("device.preferences.set", json!({"patch":{"notify_events":false}})).unwrap();        run("device.notifications.asked", json!({"at": "2026-11-13T10:00:00Z"})).unwrap();        assert_eq!(run("device.preferences.read", json!({})).unwrap()["data"]["notify_events"], false);    }}