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. Neither means logged /// out: the server and username are kept for logging in again. #[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 logged_in(&self) -> bool { self.password.is_some() || !self.token.is_empty() } /// Drops the credentials, keeping the server and username. pub fn log_out(&mut self) { self.salt.clear(); self.token.clear(); self.password = None; } 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()) } impl Config { /// Names the server and user, as the sidebar shows them. pub fn label(&self) -> String { server_label(&self.url, &self.username) } fn same_login(&self, other: &Config) -> bool { self.url == other.url && self.username == other.username } } /// "user on host". The scheme is left out for https only, so an http and an /// https login to the same host can be told apart. pub fn server_label(url: &str, username: &str) -> String { let host = match url.split_once("://") { Some(("https", rest)) => rest, _ => url, }; format!("{} on {}", username, host.trim_end_matches('/')) } /// Every saved login, and which one is browsed. #[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)] pub struct Logins { /// Index into `servers`. Points at a logged-in server whenever there is /// one. #[serde(default)] pub active: usize, /// `[[server]]` tables in the file. #[serde(rename = "server", default)] pub servers: Vec, } impl Logins { /// The server being browsed, or none when every saved one is logged out. pub fn active(&self) -> Option<&Config> { self.servers.get(self.active).filter(|c| c.logged_in()) } /// Moves `active` off a server that is gone or logged out, to the first /// logged-in one. fn settle_active(&mut self) { if self.active().is_none() { self.active = self.servers.iter().position(Config::logged_in).unwrap_or(0); } } /// The saved entry for this server and user, logged in or not. pub fn find(&self, url: &str, username: &str) -> Option { self.servers.iter().position(|s| s.url == url && s.username == username) } /// Adds a login, or refreshes the saved one for the same server and user, /// and makes it the active one. pub fn add(&mut self, cfg: Config) { match self.servers.iter().position(|s| s.same_login(&cfg)) { Some(i) => { self.servers[i] = cfg; self.active = i; } None => { self.servers.push(cfg); self.active = self.servers.len() - 1; } } } /// Removes a login. The active one stays the same server where it can; /// removing it makes the first remaining logged-in server active. pub fn remove(&mut self, i: usize) { if i >= self.servers.len() { return; } self.servers.remove(i); if i < self.active { self.active -= 1; } else if i == self.active { self.active = 0; } self.settle_active(); } /// Logs out of a server, keeping its entry. Logging out of the active one /// makes the first logged-in server active. pub fn log_out(&mut self, i: usize) { if let Some(s) = self.servers.get_mut(i) { s.log_out(); self.settle_active(); } } } /// The single login of earlier versions, or the list. Tried in that order: /// every field of the list has a default, so it would take an old file as an /// empty list, while the old shape needs `url` and `username` at the top. #[derive(Deserialize)] #[serde(untagged)] enum Stored { One(Config), List(Logins), } fn parse_logins(text: &str) -> Result { Ok(match toml::from_str::(text)? { Stored::List(mut l) => { if l.active >= l.servers.len() { l.active = 0; } l.settle_active(); l } Stored::One(c) => Logins { active: 0, servers: vec![c], }, }) } pub fn load() -> Result { let Some(path) = config_path() else { return Ok(Logins::default()); }; match fs::read_to_string(&path) { Ok(text) => parse_logins(&text).with_context(|| format!("parsing {}", path.display())), Err(e) if e.kind() == std::io::ErrorKind::NotFound => Ok(Logins::default()), Err(e) => Err(e).with_context(|| format!("reading {}", path.display())), } } pub fn save(logins: &Logins) -> Result<()> { let path = config_path().context("no config directory")?; write_atomic(&path, &toml::to_string(logins)?)?; log::info!("saved {} login(s) to {}", logins.servers.len(), path.display()); Ok(()) } /// Preferences. Kept apart from the login, so logging out does not reset them. #[derive(Debug, Clone, 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, /// How strongly the cover shows behind the now-playing screen, 0 to 100. pub cover_backdrop: u8, /// Playback volume, 0 to 100. Only remus's own stream, not the system's. pub volume: u8, /// Muted, keeping `volume` for when it is unmuted. pub muted: bool, /// The bar with the button hints and the version. The login screen shows /// it regardless. pub show_hint_bar: bool, } /// The cover backdrop strength that looks like it did before it was a setting. pub const COVER_BACKDROP_DEFAULT: u8 = 30; impl Default for Settings { fn default() -> Self { Settings { album_art_colours: false, cover_backdrop: COVER_BACKDROP_DEFAULT, volume: 100, muted: false, show_hint_bar: true, } } } 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}"); } fn login(url: &str, user: &str, auth: Auth) -> Config { Config::from_client(&Client::new(url, user, auth)) } #[test] fn a_single_login_file_loads_as_the_only_login() { let old = "url = \"https://h\"\nusername = \"u\"\nsalt = \"s\"\ntoken = \"t\"\n"; let l = parse_logins(old).unwrap(); assert_eq!(l.servers.len(), 1); assert_eq!(l.active, 0); assert_eq!(l.active().unwrap().username, "u"); let old = "url = \"https://h\"\nusername = \"u\"\npassword = \"p\"\n"; let l = parse_logins(old).unwrap(); assert_eq!(*l.active().unwrap().client().auth(), Auth::Password("p".into())); } #[test] fn the_login_list_round_trips_with_both_auth_methods() { let mut l = Logins::default(); l.add(login( "https://a", "u", Auth::Token { salt: "s".into(), token: "t".into(), }, )); l.add(login("https://b", "v", Auth::Password("p".into()))); let text = toml::to_string(&l).unwrap(); assert!(text.contains("[[server]]"), "{text}"); let back = parse_logins(&text).unwrap(); assert_eq!(back, l); assert_eq!(back.active, 1); } #[test] fn adding_the_same_login_again_replaces_it() { let mut l = Logins::default(); l.add(login("https://a", "u", Auth::Password("old".into()))); l.add(login("https://b", "u", Auth::Password("p".into()))); l.add(login("https://a", "u", Auth::Password("new".into()))); assert_eq!(l.servers.len(), 2); assert_eq!(l.active, 0); assert_eq!(*l.servers[0].client().auth(), Auth::Password("new".into())); } #[test] fn removing_keeps_the_active_server_where_it_can() { let mut l = Logins::default(); for host in ["https://a", "https://b", "https://c"] { l.add(login(host, "u", Auth::Password("p".into()))); } l.active = 2; l.remove(0); assert_eq!(l.active().unwrap().url, "https://c"); l.remove(1); assert_eq!(l.active().unwrap().url, "https://b"); l.remove(0); assert!(l.active().is_none()); } #[test] fn an_out_of_range_active_index_falls_back_to_the_first() { let text = "active = 5\n[[server]]\nurl = \"https://a\"\nusername = \"u\"\npassword = \"p\"\n"; assert_eq!(parse_logins(text).unwrap().active, 0); } #[test] fn a_logged_out_login_keeps_its_server_and_round_trips() { let mut l = Logins::default(); l.add(login( "https://a", "u", Auth::Token { salt: "s".into(), token: "t".into(), }, )); l.add(login("https://b", "v", Auth::Password("p".into()))); l.log_out(0); l.log_out(1); let text = toml::to_string(&l).unwrap(); assert!( !text.contains("salt") && !text.contains("token") && !text.contains("password"), "{text}" ); let back = parse_logins(&text).unwrap(); assert_eq!(back, l); assert_eq!(back.servers.len(), 2); assert!(back.servers.iter().all(|s| !s.logged_in())); assert_eq!(back.servers[1].url, "https://b"); assert_eq!(back.servers[1].username, "v"); assert!(back.active().is_none()); } #[test] fn the_active_login_skips_logged_out_servers() { let mut l = Logins::default(); for host in ["https://a", "https://b", "https://c"] { l.add(login(host, "u", Auth::Password("p".into()))); } l.active = 0; l.log_out(1); assert_eq!(l.active().unwrap().url, "https://a"); l.log_out(0); assert_eq!(l.active().unwrap().url, "https://c"); l.log_out(2); assert!(l.active().is_none()); // Logging in again reuses the entry and makes it active. l.add(login("https://b", "u", Auth::Password("p".into()))); assert_eq!(l.servers.len(), 3); assert_eq!(l.active().unwrap().url, "https://b"); } #[test] fn a_saved_active_index_on_a_logged_out_server_moves_to_a_logged_in_one() { let text = "active = 0\n[[server]]\nurl = \"https://a\"\nusername = \"u\"\n\ [[server]]\nurl = \"https://b\"\nusername = \"u\"\npassword = \"p\"\n"; let l = parse_logins(text).unwrap(); assert_eq!(l.active, 1); assert_eq!(l.active().unwrap().url, "https://b"); } #[test] fn removing_the_active_login_skips_logged_out_servers() { let mut l = Logins::default(); for host in ["https://a", "https://b", "https://c"] { l.add(login(host, "u", Auth::Password("p".into()))); } l.log_out(0); l.active = 1; l.remove(1); assert_eq!(l.active().unwrap().url, "https://c"); } #[test] fn a_login_list_from_v0_8_0_loads_logged_in() { let text = "active = 1\n\ [[server]]\nurl = \"https://a\"\nusername = \"u\"\nsalt = \"s\"\ntoken = \"t\"\n\ [[server]]\nurl = \"https://b\"\nusername = \"v\"\npassword = \"p\"\n"; let l = parse_logins(text).unwrap(); assert_eq!(l.servers.len(), 2); assert!(l.servers.iter().all(Config::logged_in)); assert_eq!(l.active().unwrap().url, "https://b"); } #[test] fn labels_tell_http_and_https_apart() { assert_eq!(server_label("https://h/", "u"), "u on h"); assert_eq!(server_label("http://h", "u"), "u on http://h"); } #[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); assert_eq!(s.cover_backdrop, COVER_BACKDROP_DEFAULT); assert_eq!(s.volume, 100); assert!(!s.muted); assert!(s.show_hint_bar); } #[test] fn settings_from_before_the_backdrop_load_its_default() { let s: Settings = toml::from_str("album_art_colours = true\n").unwrap(); assert!(s.album_art_colours); assert_eq!(s.cover_backdrop, COVER_BACKDROP_DEFAULT); assert!(s.show_hint_bar); } #[test] fn settings_round_trip() { let s = Settings { album_art_colours: true, cover_backdrop: 70, volume: 35, muted: true, show_hint_bar: false, }; let back: Settings = toml::from_str(&toml::to_string(&s).unwrap()).unwrap(); assert_eq!(back, s); } }