Files
Remus/src/config.rs
T
Ansho Rei d4de15acd8 feat: keep several logins and switch between them
config.toml now holds a list of [[server]] logins and the active one.
The single-login file of earlier versions loads as the only entry.

Settings lists the servers first: confirm switches, the queue button
pressed twice removes, and Add server opens the login form, which can
now be cancelled. Removing the last login returns to the login screen.

A switch saves the queue of the server being left, stops the player and
restores the other server's saved queue paused. Player events sent
before the stop are dropped by an epoch, and cover loads started for the
old server by a generation, so nothing of one server shows on the other.
Covers are cached on disk per server, keyed like the saved queue.

The shoulder triggers wrap around the sections, which puts Settings one
press from the first section.
2026-11-04 18:23:30 +01:00

397 lines
13 KiB
Rust

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<String>,
}
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> {
ProjectDirs::from("", "", "remus")
}
fn config_path() -> Option<PathBuf> {
dirs().map(|d| d.config_dir().join("config.toml"))
}
pub fn cache_dir() -> Option<PathBuf> {
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<PathBuf> {
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 {
let host = self.url.split("://").nth(1).unwrap_or(&self.url);
format!("{} on {}", self.username, host.trim_end_matches('/'))
}
fn same_login(&self, other: &Config) -> bool {
self.url == other.url && self.username == other.username
}
}
/// Every saved login, and which one is browsed.
#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
pub struct Logins {
/// Index into `servers`.
#[serde(default)]
pub active: usize,
/// `[[server]]` tables in the file.
#[serde(rename = "server", default)]
pub servers: Vec<Config>,
}
impl Logins {
pub fn active(&self) -> Option<&Config> {
self.servers.get(self.active)
}
/// 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 login 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;
}
}
}
/// 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<Logins> {
Ok(match toml::from_str::<Stored>(text)? {
Stored::List(mut l) => {
if l.active >= l.servers.len() {
l.active = 0;
}
l
}
Stored::One(c) => Logins {
active: 0,
servers: vec![c],
},
})
}
pub fn load() -> Result<Logins> {
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<PathBuf> {
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 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);
}
}