//! The app's own small state in its data folder: the project list and account labels (never secrets). Written //! atomically (temp file, then rename) so a crash never leaves half a file. use std::fs; use std::path::{Path, PathBuf}; use serde::{Deserialize, Serialize}; use crate::accounts::Account; #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] pub struct Project { pub id: String, /// Absolute folder that holds storebound.config.ts. pub path: String, pub name: String, #[serde(default)] pub play_account: Option, #[serde(default)] pub apple_account: Option, pub added: String, } #[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)] pub struct State { #[serde(default)] pub projects: Vec, #[serde(default)] pub accounts: Vec, } pub const FILE: &str = "state.json"; pub fn load(dir: &Path) -> State { fs::read_to_string(dir.join(FILE)).ok().and_then(|s| serde_json::from_str(&s).ok()).unwrap_or_default() } pub fn save(dir: &Path, state: &State) -> Result<(), String> { fs::create_dir_all(dir).map_err(|e| e.to_string())?; let tmp: PathBuf = dir.join(format!("{FILE}.tmp")); let json = serde_json::to_string_pretty(state).map_err(|e| e.to_string())?; fs::write(&tmp, json + "\n").map_err(|e| e.to_string())?; fs::rename(&tmp, dir.join(FILE)).map_err(|e| e.to_string()) } /// Random id (hex) for projects and accounts. pub fn new_id() -> Result { let mut b = [0u8; 8]; getrandom::fill(&mut b).map_err(|e| e.to_string())?; Ok(crate::confirm::hex(&b)) } /// Current time as an RFC 3339 UTC string, without a date crate. pub fn now_iso() -> String { let secs = std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).map(|d| d.as_secs()).unwrap_or(0); iso_from_unix(secs) } pub fn iso_from_unix(secs: u64) -> String { let days = (secs / 86_400) as i64; let rem = secs % 86_400; // civil-from-days (Howard Hinnant) let z = days + 719_468; let era = z.div_euclid(146_097); let doe = z - era * 146_097; let yoe = (doe - doe / 1460 + doe / 36_524 - doe / 146_096) / 365; let y = yoe + era * 400; let doy = doe - (365 * yoe + yoe / 4 - yoe / 100); let mp = (5 * doy + 2) / 153; let d = doy - (153 * mp + 2) / 5 + 1; let m = if mp < 10 { mp + 3 } else { mp - 9 }; let y = if m <= 2 { y + 1 } else { y }; format!("{y:04}-{m:02}-{d:02}T{:02}:{:02}:{:02}Z", rem / 3600, rem % 3600 / 60, rem % 60) }