//! WHAT THE PERSON IS TOLD, AND WHEN A BACKUP IS DUE. Pure over what the phone knows (its platform, its key store) //! and what the backup's state file says; every word is the `backup` line set's. //! //! - Which apps back up, and what they count ([`counted`]): an app with a database of its own that works before //! sign-in. Comms needs an account (backup there is sync); Data and Post have nothing of their own to restore. //! - The You row and the Backup page ([`row`], [`page`]): on or off, the last backup, which key the person has //! ([`key_line`]), the trouble and its act. //! - When a backup is due ([`due`]). //! - What a restore would change, counted first ([`restore_ask`]), and every refusal in words ([`refusal_said`]). use std::collections::BTreeMap; use serde::{Deserialize, Serialize}; use serde_json::{json, Value}; use super::file::Refusal; use crate::rules::shell_lines::{number, resolve}; const SET: &str = "backup"; /// What Google keeps of an app (25 MB), less a margin for the rules and Google's own count. pub const GOOGLE_CAP: u64 = 24 * 1024 * 1024; /// A backup after changes waits this long after the last one (seconds). pub const AFTER_CHANGES: i64 = 15 * 60; /// Undo restore keeps what was on the phone this long (seconds). pub const ASIDE_FOR: i64 = 30 * 24 * 60 * 60; /// One kind of thing an app counts: the SQL table it lives in, what narrows it to the person's own things (beside the /// bin's columns, which the counter adds where the table has them), and the noun it is counted in (`counts.*`). #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub struct Counted { pub table: &'static str, pub only: &'static str, pub noun: &'static str, } const fn counted_as(table: &'static str, only: &'static str, noun: &'static str) -> Counted { Counted { table, only, noun } } /// The apps that back up, by kit id, each with what it counts. Built-in tables keep their own names (`cotton_notes`, /// which holds journal days too, hence `kind = 'note'`); a package's table is `cotton_`. pub const APPS: &[(&str, &[Counted])] = &[ ("notes", &[counted_as("cotton_notes", "kind = 'note'", "notes")]), ("days", &[counted_as("cotton_events", "", "events"), counted_as("cotton_todos", "", "todos")]), ("story", &[counted_as("cotton_story_story", "", "scripts"), counted_as("cotton_story_scene", "", "scenes")]), ("keys", &[counted_as("cotton_secrets", "", "secrets")]), ("sites", &[counted_as("cotton_site", "", "sites")]), ]; /// What `kit` counts, or None when it does not back up. pub fn counted(kit: &str) -> Option<&'static [Counted]> { APPS.iter().find(|(id, _)| *id == kit).map(|(_, tables)| *tables) } /// The phone the person is on. #[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] #[serde(rename_all = "lowercase")] pub enum Platform { Ios, Android, } impl Platform { pub fn parse(word: &str) -> Option { match word { "ios" | "iphone" => Some(Platform::Ios), "android" => Some(Platform::Android), _ => None, } } fn id(self) -> &'static str { match self { Platform::Ios => "ios", Platform::Android => "android", } } } /// What the phone's key store can do with the backup code, as only the phone knows. #[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Deserialize)] pub struct Store { /// The key store holds this app's backup code. #[serde(default)] pub held: bool, /// Android: Block Store's end-to-end encryption is available (a screen lock), so the code goes to the cloud. /// iPhone: never known (an app cannot ask whether iCloud Keychain is on). #[serde(default)] pub cloud: Option, /// Android: the phone is too old for Google's cloud restore of the key (below Android 12, Pixels below 9). #[serde(default)] pub old: bool, } /// Why the last backup is not where it should be. #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] #[serde(rename_all = "snake_case", tag = "kind")] pub enum Trouble { /// iCloud (or iCloud Drive for this app) is off. IcloudOff, /// The person's iCloud or Google storage is full. Full, /// The file is over what Google keeps; the last one that fitted stays. TooBig, /// The folder the person picked is gone or no longer granted. FolderGone, /// Anything else, with the phone's own sentence. Failed { why: String }, } impl Trouble { fn id(&self) -> &'static str { match self { Trouble::IcloudOff => "icloud_off", Trouble::Full => "full", Trouble::TooBig => "too_big", Trouble::FolderGone => "folder_gone", Trouble::Failed { .. } => "failed", } } } /// One backup that landed. #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] pub struct Last { /// RFC 3339. pub at: String, pub bytes: u64, /// `icloud`, `google`, `folder`, `files` (saved by hand). pub place: String, } /// What the backup's state file keeps, beside the copy. Counts and times only, nothing personal. #[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)] pub struct State { #[serde(default)] pub on: bool, /// The person said they saved the recovery code (never assumed). #[serde(default)] pub code_saved: bool, #[serde(default)] pub last: Option, #[serde(default)] pub trouble: Option, /// The folder the person picked (Android), as the picker names it. #[serde(default)] pub folder: Option, /// The last restore, while Undo restore can bring back what was there: RFC 3339 of when, and the aside's name. #[serde(default)] pub restored: Option, /// Earlier restores' asides, still named until their 30 days pass (a folder the state does not name is never /// pruned: ABSENCE 1, 26 Nov 2026). #[serde(default, skip_serializing_if = "Vec::is_empty")] pub earlier: Vec, /// Aside folders found on disk when backup settings were started again (`backup.reset`): listed, never pruned /// (ABSENCE 4, item F). #[serde(default, skip_serializing_if = "Vec::is_empty")] pub listed: Vec, /// Days this phone has counted, at most one a calendar day it was used (ABSENCE 4, item G): an aside goes only /// after 30 counted days, so a clock set forward counts one day, not the jump. #[serde(default)] pub days: u32, /// The calendar day last counted (YYYY-MM-DD). #[serde(default, skip_serializing_if = "Option::is_none")] pub day: Option, } #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] pub struct Restored { pub at: String, /// Seconds since the epoch, for the 30 days. pub at_s: i64, pub aside: String, /// The phone's day count when it was set aside ([`State::days`]); none for one named before the count, which /// starts counting at the next look. #[serde(default, skip_serializing_if = "Option::is_none")] pub day_at: Option, } /// Days an aside is kept, counted as [`State::days`]. pub const ASIDE_DAYS: u32 = 30; fn say(line: &str, fills: &[(&str, &str)]) -> String { resolve(SET, line, &[], fills).unwrap_or_default() } /// Bytes as a person reads them. pub fn size_said(bytes: u64) -> String { const MB: f64 = 1024.0 * 1024.0; if bytes < 1024 * 1024 { format!("{} KB", (bytes as f64 / 1024.0).ceil().max(1.0) as u64) } else if bytes < 100 * 1024 * 1024 { format!("{:.1} MB", bytes as f64 / MB) } else { format!("{} MB", (bytes as f64 / MB).round() as u64) } } /// Whether a file of `bytes` goes into Google's Auto Backup. pub fn fits_google(bytes: u64) -> bool { bytes <= GOOGLE_CAP } /// The You row for an app of kit `kit`: only an app that backs up, only signed out. `when` is the last backup said /// for a glance ("9:53", "3 Nov"). pub fn row(kit: &str, signed_in: bool, platform: Platform, state: &State, when: Option<&str>) -> Option { if signed_in || counted(kit).is_none() { return None; } let line = if !state.on { say("row.off", &[]) } else if let Some(trouble) = &state.trouble { match trouble { Trouble::Full => say("row.trouble_full", &[("storage", &say(&format!("storage.{}", platform.id()), &[]))]), Trouble::IcloudOff => say("row.trouble_off", &[]), Trouble::TooBig => say("row.trouble_too_big", &[]), Trouble::FolderGone => say("row.trouble_folder", &[]), Trouble::Failed { .. } => on_line(when), } } else { on_line(when) }; Some(json!({"id": "backup", "label": say("row.label", &[]), "line": line, "group": "keep", "trouble": state.on && state.trouble.is_some()})) } fn on_line(when: Option<&str>) -> String { match when { Some(when) => say("row.on", &[("when", when)]), None => say("row.on_never", &[]), } } /// Which key the person has, as the page says it (`key.*`). pub fn key_line(platform: Platform, store: Store, code_saved: bool) -> &'static str { match platform { Platform::Ios if store.held && code_saved => "key.ios_both", Platform::Ios if store.held => "key.ios_store", Platform::Android if store.held && store.cloud == Some(true) && !store.old && code_saved => "key.android_both", Platform::Android if store.held && store.cloud == Some(true) && !store.old => "key.android_store", _ if code_saved => "key.code_only", Platform::Android if store.cloud == Some(false) => "key.android_no_lock", Platform::Android if store.old => "key.android_old", _ => "key.neither", } } /// The Backup page, whole. `app` is the name on the icon; `when` the last backup said in full ("9:53", "3 Nov"). pub fn page(app: &str, platform: Platform, state: &State, store: Store, when: Option<&str>) -> Value { let p = platform.id(); let place = say(&format!("places.{p}"), &[]); let storage = say(&format!("storage.{p}"), &[]); let last = state.last.as_ref().map(|last| say("page.last", &[("when", when.unwrap_or(&last.at)), ("size", &size_said(last.bytes))])); let key = key_line(platform, store, state.code_saved); let trouble = state.trouble.as_ref().filter(|_| state.on).map(|trouble| { let when = when.unwrap_or_default(); let line = match trouble { Trouble::Full if state.last.is_none() => say("trouble.full_never", &[("storage", &storage), ("app", app)]), Trouble::Failed { why } => say("trouble.failed", &[("why", why)]), other => say(&format!("trouble.{}", other.id()), &[("app", app), ("storage", &storage), ("when", when)]), }; let act = match trouble { Trouble::IcloudOff => Some(("save_to_files", say("page.save_to_files", &[]))), Trouble::TooBig => Some(("choose_folder", say("page.folder_choose", &[]))), Trouble::FolderGone => Some(("choose_folder", say("page.folder_choose", &[]))), _ => None, }; let mut block = json!({"id": trouble.id(), "line": line}); if let Some((id, label)) = act { block["act"] = json!({"id": id, "label": label}); } block }); let mut answer = json!({ "title": say("page.title", &[]), "on": state.on, "toggle": say(&format!("page.toggle_{p}"), &[]), "lead": say(&format!("page.lead_{p}"), &[("app", app)]), "last": last.unwrap_or_else(|| say("page.never", &[])), "now": say("page.now", &[]), "backing_up": say("page.backing_up", &[]), "made": say("page.made", &[]), "key": { "title": say("key.title", &[]), "id": key.trim_start_matches("key."), "line": say(key, &[]), "show": say("key.show", &[]), "use_other": say("key.use_other", &[]), "keeps": store.held, "code_saved": state.code_saved, }, "restore": {"label": say("page.restore", &[]), "choose_file": say("page.choose_file", &[])}, "place": place, }); if let Some(trouble) = trouble { answer["trouble"] = trouble; } if platform == Platform::Android { if let Some(folder) = &state.folder { answer["folder"] = json!({"line": say("page.folder", &[("folder", folder)]), "change": say("page.folder_change", &[])}); } else { answer["files_left_out"] = json!(say("page.files_left_out", &[])); } } if let Some(restored) = &state.restored { answer["undo"] = json!({"label": say("restore.undo", &[]), "since": restored.at}); } answer } /// The recovery code's page: the code in its groups, and the words around it. pub fn code_page(app: &str, code: &str) -> Value { json!({ "title": say("code.title", &[]), "code": code, "groups": code.split('-').collect::>(), "line": say("code.line", &[("app", app)]), "copy": say("code.copy", &[]), "copied": say("code.copied", &[]), "save_passwords": say("code.save_passwords", &[]), "saved": say("code.saved", &[]), }) } /// Whether a backup is due now: on, signed out, the copy changed since the last backup, and the last one is at least /// [`AFTER_CHANGES`] old (`by_hand` skips both). Times in seconds since the epoch. pub fn due(state: &State, signed_in: bool, changed_s: Option, last_s: Option, now_s: i64, by_hand: bool) -> bool { if !state.on || signed_in { return false; } if by_hand { return true; } match (changed_s, last_s) { (_, None) => true, (Some(changed), Some(last)) => changed > last && now_s - last >= AFTER_CHANGES, (None, Some(_)) => false, } } /// Counts said as a person reads them: "3 scripts, 41 scenes", "nothing yet". Only the kit's own nouns, in its order, /// then the photos and files when there are any. pub fn counts_said(kit: &str, counts: &BTreeMap) -> String { let mut parts: Vec = counted(kit) .unwrap_or_default() .iter() .filter_map(|c| counts.get(c.noun).filter(|n| **n > 0).map(|n| say(&format!("counts.{}", c.noun), &[("n", &number(*n as i64))]))) .collect(); if let Some(files) = counts.get("files").filter(|n| **n > 0) { parts.push(say("counts.files", &[("n", &number(*files as i64))])); } if parts.is_empty() { say("restore.nothing", &[]) } else { parts.join(", ") } } /// Whether a copy holds anything a person made, by its counts. pub fn holds_anything(counts: &BTreeMap) -> bool { counts.values().any(|n| *n > 0) } /// What a restore would change, counted first: a fresh phone is asked to restore; one that holds anything is asked to /// replace it, with both counts and Undo's promise. `device` is the manifest's (`ios`, `android`). pub fn restore_ask(app: &str, kit: &str, here: &BTreeMap, there: &BTreeMap, when: &str, device: &str) -> Value { let device = match device { "ios" | "android" => say(&format!("devices.{device}"), &[]), _ => say("devices.unknown", &[]), }; let there_said = counts_said(kit, there); if holds_anything(here) { json!({ "fresh": false, "title": say("restore.replace_title", &[]), "line": say("restore.replace_line", &[("here", &counts_said(kit, here)), ("there", &there_said), ("when", when)]), "yes": say("restore.replace_yes", &[]), "no": say("restore.replace_no", &[]), "here": here, "there": there, }) } else { json!({ "fresh": true, "title": say("restore.fresh_title", &[("app", app)]), "line": say("restore.fresh_line", &[("when", when), ("device", &device), ("there", &there_said)]), "yes": say("restore.fresh_yes", &[]), "no": say("restore.fresh_no", &[]), "here": here, "there": there, }) } } /// What a restore said once it was done. pub fn restored_said(kit: &str, there: &BTreeMap, when: &str) -> String { say("restore.done", &[("there", &counts_said(kit, there)), ("when", when)]) } /// A refusal in words. `app` is the name on the icon, `file` the file name this app makes; `names` turns another /// app's kit id into the name on its icon. pub fn refusal_said(refusal: &Refusal, app: &str, file: &str, names: &dyn Fn(&str) -> String) -> Value { let line = match refusal { Refusal::OtherApp(other) => say("refused.other_app", &[("other", &names(other)), ("app", app)]), Refusal::Io(why) => say("refused.io", &[("why", why)]), other => say(&format!("refused.{}", other.code()), &[("app", app), ("file", file)]), }; let mut answer = json!({"code": refusal.code(), "said": line}); if matches!(refusal, Refusal::OtherKey | Refusal::CodeTyped(_)) { answer["ask_code"] = json!({ "title": say("code.type_title", &[]), "line": say("code.type_line", &[]), "open": say("code.open", &[]), }); } answer } /// The file name an app's backup takes: the name on its icon, without the stop iPhone keeps on some. pub fn file_name(app: &str) -> String { let name: String = app.trim_end_matches('.').chars().filter(|c| c.is_alphanumeric() || *c == ' ').collect(); format!("{}.cottonbackup", if name.trim().is_empty() { "Cotton" } else { name.trim() }) } #[cfg(test)] #[path = "plan_tests.rs"] mod tests;