use std::fs; use std::io::Write; use std::os::unix::fs::OpenOptionsExt; use std::path::{Path, PathBuf}; use anyhow::{Context, Result}; use directories::ProjectDirs; use serde::{Deserialize, Serialize}; use crate::subsonic::{Auth, Client}; /// Server credentials, written 0600. Either a token, md5(password + salt), /// which is not the password but is enough to log in to this server; or, for /// a server that refuses tokens, the password itself. #[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] pub struct Config { pub url: String, pub username: String, #[serde(default, skip_serializing_if = "String::is_empty")] pub salt: String, #[serde(default, skip_serializing_if = "String::is_empty")] pub token: String, #[serde(default, skip_serializing_if = "Option::is_none")] pub password: Option, } impl Config { pub fn from_client(client: &Client) -> Config { let (salt, token, password) = match client.auth() { Auth::Token { salt, token } => (salt.clone(), token.clone(), None), Auth::Password(p) => (String::new(), String::new(), Some(p.clone())), }; Config { url: client.base().to_string(), username: client.user().to_string(), salt, token, password, } } pub fn client(&self) -> Client { let auth = match &self.password { Some(p) => Auth::Password(p.clone()), None => Auth::Token { salt: self.salt.clone(), token: self.token.clone(), }, }; Client::new(&self.url, &self.username, auth) } } fn dirs() -> Option { ProjectDirs::from("", "", "remus") } fn config_path() -> Option { dirs().map(|d| d.config_dir().join("config.toml")) } pub fn cache_dir() -> Option { dirs().map(|d| d.cache_dir().to_path_buf()) } /// For state that is not configuration, such as the saved queue. Not every /// platform has a state directory, so it falls back to the data directory. pub fn state_dir() -> Option { dirs().map(|d| d.state_dir().unwrap_or(d.data_dir()).to_path_buf()) } pub fn load() -> Result> { let Some(path) = config_path() else { return Ok(None) }; match fs::read_to_string(&path) { Ok(text) => Ok(Some( toml::from_str(&text).with_context(|| format!("parsing {}", path.display()))?, )), Err(e) if e.kind() == std::io::ErrorKind::NotFound => Ok(None), Err(e) => Err(e).with_context(|| format!("reading {}", path.display())), } } pub fn save(cfg: &Config) -> Result<()> { let path = config_path().context("no config directory")?; write_atomic(&path, &toml::to_string(cfg)?)?; log::info!("saved login to {}", path.display()); Ok(()) } /// Preferences. Kept apart from the login, so logging out does not reset them. #[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)] #[serde(default)] pub struct Settings { /// Tint the UI with the colours of the playing track's cover. pub album_art_colours: bool, } fn settings_path() -> Option { dirs().map(|d| d.config_dir().join("settings.toml")) } /// The saved settings, or the defaults when there are none or they cannot be read. pub fn load_settings() -> Settings { let Some(path) = settings_path() else { return Settings::default(); }; match fs::read_to_string(&path) { Ok(text) => toml::from_str(&text).unwrap_or_else(|e| { log::warn!("ignoring {}: {e}", path.display()); Settings::default() }), Err(e) if e.kind() == std::io::ErrorKind::NotFound => Settings::default(), Err(e) => { log::warn!("reading {}: {e}", path.display()); Settings::default() } } } pub fn save_settings(s: &Settings) -> Result<()> { let path = settings_path().context("no config directory")?; write_atomic(&path, &toml::to_string(s)?) } /// Writes aside, syncs, then renames over the old file, so a power cut /// mid-save leaves either the old file or the new one, never a torn one. /// Owner-only, since the login file holds a token. pub fn write_atomic(path: &Path, text: &str) -> Result<()> { if let Some(dir) = path.parent() { fs::create_dir_all(dir)?; } let mut tmp = path.as_os_str().to_owned(); tmp.push(".tmp"); let tmp = PathBuf::from(tmp); let mut f = fs::OpenOptions::new() .write(true) .create(true) .truncate(true) .mode(0o600) .open(&tmp) .with_context(|| format!("writing {}", tmp.display()))?; f.write_all(text.as_bytes())?; f.sync_all()?; fs::rename(&tmp, path).with_context(|| format!("replacing {}", path.display()))?; if let Some(dir) = path.parent() && let Ok(d) = fs::File::open(dir) { let _ = d.sync_all(); } Ok(()) } #[cfg(test)] mod tests { use super::*; #[test] fn token_login_from_before_password_auth_still_loads() { let old = "url = \"https://h\"\nusername = \"u\"\nsalt = \"s\"\ntoken = \"t\"\n"; let cfg: Config = toml::from_str(old).unwrap(); assert_eq!(cfg.password, None); let auth = Auth::Token { salt: "s".into(), token: "t".into(), }; assert_eq!(*cfg.client().auth(), auth); } #[test] fn each_auth_method_round_trips() { let token = Auth::Token { salt: "s".into(), token: "t".into(), }; for auth in [token, Auth::Password("sesame".into())] { let cfg = Config::from_client(&Client::new("https://h", "u", auth.clone())); let text = toml::to_string(&cfg).unwrap(); let back: Config = toml::from_str(&text).unwrap(); assert_eq!(back, cfg); assert_eq!(*back.client().auth(), auth); } } #[test] fn password_login_stores_no_token_fields() { let cfg = Config::from_client(&Client::new("https://h", "u", Auth::Password("p".into()))); let text = toml::to_string(&cfg).unwrap(); assert!(!text.contains("salt") && !text.contains("token"), "{text}"); } #[test] fn settings_default_when_fields_are_missing() { let s: Settings = toml::from_str("").unwrap(); assert_eq!(s, Settings::default()); assert!(!s.album_art_colours); } #[test] fn settings_round_trip() { let s = Settings { album_art_colours: true, }; let back: Settings = toml::from_str(&toml::to_string(&s).unwrap()).unwrap(); assert_eq!(back, s); } }