feat: log out of or forget a saved server, and pick one on the login screen
The queue button on a server row in Settings opens a prompt with Cancel, Log out and Forget, replacing the double-press Remove. Log out keeps the address and username without credentials; Forget also deletes the server's saved queue and cover cache. The login screen lists the saved servers beside the form, and a saved login the server turns down at startup is logged out and opens the login screen prefilled. Bumps the version to 0.10.0.
This commit is contained in:
+295
-39
@@ -25,7 +25,7 @@ use crate::prompts::{self, Control, Family, Prompts};
|
||||
use crate::saved_queue::{self, SavedQueue, SavedQueues};
|
||||
use crate::shuffle::{self, Library, Mode};
|
||||
use crate::subsonic::{self, Album, Artist, Client, Playlist, SearchResult, Song};
|
||||
use crate::{Action, AppWindow, Area, Header, Hint, Item, Screen, Theme};
|
||||
use crate::{Action, AppWindow, Area, Header, Hint, Item, KnownServer, Screen, Theme};
|
||||
|
||||
thread_local! {
|
||||
static APP: RefCell<Option<App>> = const { RefCell::new(None) };
|
||||
@@ -57,6 +57,8 @@ pub fn install(ui: &AppWindow, rt: Handle) {
|
||||
ui.on_search_accepted(|q| with_app(move |app| app.run_search(q.to_string())));
|
||||
ui.on_login_submit(|| with_app(|app| app.login_submit()));
|
||||
ui.on_login_field_clicked(|i| with_app(move |app| app.set_login_focus(i)));
|
||||
ui.on_login_known_clicked(|i| with_app(move |app| app.pick_known(i.max(0) as usize)));
|
||||
ui.on_confirm_clicked(|i| with_app(move |app| app.confirm_clicked(i.max(0) as usize)));
|
||||
ui.on_layout_changed(|| with_app(|app| app.sync_items(true)));
|
||||
|
||||
with_app(|app| app.start());
|
||||
@@ -143,6 +145,33 @@ enum Setting {
|
||||
AddServer,
|
||||
}
|
||||
|
||||
/// What the server prompt in Settings offers.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
enum Choice {
|
||||
Cancel,
|
||||
LogOut,
|
||||
Forget,
|
||||
}
|
||||
|
||||
impl Choice {
|
||||
fn label(self) -> &'static str {
|
||||
match self {
|
||||
Choice::Cancel => "Cancel",
|
||||
Choice::LogOut => "Log out",
|
||||
Choice::Forget => "Forget",
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The prompt asking what to do with a saved server. Holds the server by
|
||||
/// address and username rather than index, in case the list changes under it.
|
||||
struct Confirm {
|
||||
url: String,
|
||||
username: String,
|
||||
choices: Vec<Choice>,
|
||||
sel: usize,
|
||||
}
|
||||
|
||||
/// How long the UI takes to change from one palette to the next.
|
||||
const FADE: Duration = Duration::from_millis(800);
|
||||
/// How long the now-playing cover takes to turn edge-on, the `in` animation
|
||||
@@ -255,8 +284,11 @@ pub struct App {
|
||||
/// Bumped when the player is stopped for a server switch; player events
|
||||
/// sent before that are dropped.
|
||||
player_epoch: Arc<std::sync::atomic::AtomicU64>,
|
||||
/// A server row whose remove button was pressed once, and when.
|
||||
remove_armed: Option<(usize, Instant)>,
|
||||
/// The log out or forget prompt, while it is open.
|
||||
confirm: Option<Confirm>,
|
||||
/// No page has loaded since entering a saved login. A wrong-credentials
|
||||
/// error until then means the saved login stopped working.
|
||||
checking_login: bool,
|
||||
screen: Screen,
|
||||
area: Area,
|
||||
section: usize,
|
||||
@@ -361,7 +393,8 @@ impl App {
|
||||
mpris,
|
||||
logins: Logins::default(),
|
||||
player_epoch: Arc::default(),
|
||||
remove_armed: None,
|
||||
confirm: None,
|
||||
checking_login: false,
|
||||
screen: Screen::Login,
|
||||
area: Area::Content,
|
||||
section: 0,
|
||||
@@ -495,9 +528,40 @@ impl App {
|
||||
// Adding a server from inside the app: the bottom button goes back.
|
||||
self.ui.set_login_can_cancel(self.client.is_some());
|
||||
self.ui.set_login_password_shown(false);
|
||||
let known: Vec<KnownServer> = self
|
||||
.logins
|
||||
.servers
|
||||
.iter()
|
||||
.map(|c| KnownServer {
|
||||
label: c.label().into(),
|
||||
note: if c.logged_in() { "" } else { "Logged out" }.into(),
|
||||
})
|
||||
.collect();
|
||||
self.ui.set_login_known(ModelRc::new(VecModel::from(known)));
|
||||
self.set_login_focus(0);
|
||||
}
|
||||
|
||||
/// The login form filled in with a saved server, waiting for its password.
|
||||
fn login_to(&mut self, cfg: &Config) {
|
||||
self.ui.set_login_server(cfg.url.clone().into());
|
||||
self.ui.set_login_username(cfg.username.clone().into());
|
||||
self.ui.set_login_password("".into());
|
||||
self.ui.set_login_error("".into());
|
||||
self.show_login();
|
||||
self.set_login_focus(2);
|
||||
}
|
||||
|
||||
/// A saved server picked on the login screen.
|
||||
fn pick_known(&mut self, i: usize) {
|
||||
if let Some(cfg) = self.logins.servers.get(i).cloned() {
|
||||
self.ui.set_login_server(cfg.url.into());
|
||||
self.ui.set_login_username(cfg.username.into());
|
||||
self.ui.set_login_password("".into());
|
||||
self.ui.set_login_error("".into());
|
||||
self.set_login_focus(2);
|
||||
}
|
||||
}
|
||||
|
||||
/// The login form, empty, for one more server.
|
||||
fn add_server(&mut self) {
|
||||
self.ui.set_login_server("".into());
|
||||
@@ -520,9 +584,18 @@ impl App {
|
||||
self.set_area(area);
|
||||
}
|
||||
|
||||
/// 0 to 2 are the fields and 3 and 4 the buttons. Below 0 are the saved
|
||||
/// servers in the card beside the form, from the top one at -n to the
|
||||
/// bottom one at -1, so Up from the address field reaches the list.
|
||||
fn set_login_focus(&mut self, i: i32) {
|
||||
self.login_focus = i.clamp(0, 4);
|
||||
let known = self.logins.servers.len() as i32;
|
||||
self.login_focus = i.clamp(-known, 4);
|
||||
self.ui.set_login_focus(self.login_focus);
|
||||
self.ui.set_login_known_selected(if self.login_focus < 0 {
|
||||
known + self.login_focus
|
||||
} else {
|
||||
-1
|
||||
});
|
||||
self.ui.invoke_focus_login(self.login_focus);
|
||||
self.render_hints();
|
||||
}
|
||||
@@ -531,6 +604,15 @@ impl App {
|
||||
match a {
|
||||
Action::Up | Action::SectionPrev => self.set_login_focus(self.login_focus - 1),
|
||||
Action::Down | Action::SectionNext => self.set_login_focus(self.login_focus + 1),
|
||||
// Across to the saved servers and back. A text field keeps Left
|
||||
// and Right on a keyboard for its cursor.
|
||||
Action::Left if self.login_focus >= 0 && !self.logins.servers.is_empty() => {
|
||||
self.set_login_focus(-(self.logins.servers.len() as i32))
|
||||
}
|
||||
Action::Right if self.login_focus < 0 => self.set_login_focus(0),
|
||||
Action::Activate if self.login_focus < 0 => {
|
||||
self.pick_known((self.logins.servers.len() as i32 + self.login_focus) as usize)
|
||||
}
|
||||
Action::Activate if self.login_focus < 2 => self.set_login_focus(self.login_focus + 1),
|
||||
Action::Activate if self.login_focus == 4 && self.client.is_some() => self.cancel_login(),
|
||||
Action::Activate if self.login_focus == 4 => self.action(Action::Quit),
|
||||
@@ -585,12 +667,9 @@ impl App {
|
||||
}
|
||||
|
||||
fn enter_browse(&mut self, client: Client) {
|
||||
let host = client.base().split("://").nth(1).unwrap_or(client.base()).to_string();
|
||||
self.ui
|
||||
.set_server_label(format!("{} on {}", client.user(), host).into());
|
||||
// Keyed like the saved queue, by user and full address.
|
||||
let key = sanitize(&format!("{}@{}", client.user(), client.base()));
|
||||
self.covers.dir = self.covers.root.as_ref().map(|r| r.join(key));
|
||||
.set_server_label(config::server_label(client.base(), client.user()).into());
|
||||
self.covers.dir = self.covers.root.as_ref().map(|r| r.join(cover_dir_name(&client)));
|
||||
if let Some(d) = &self.covers.dir
|
||||
&& let Err(e) = std::fs::create_dir_all(d)
|
||||
{
|
||||
@@ -598,6 +677,7 @@ impl App {
|
||||
self.covers.dir = None;
|
||||
}
|
||||
self.client = Some(client);
|
||||
self.checking_login = true;
|
||||
self.covers.generation += 1;
|
||||
self.covers.images.clear();
|
||||
self.covers.tones.clear();
|
||||
@@ -669,54 +749,195 @@ impl App {
|
||||
}
|
||||
|
||||
fn select_server(&mut self, i: usize) {
|
||||
if i == self.logins.active {
|
||||
return;
|
||||
}
|
||||
let Some(cfg) = self.logins.servers.get(i).cloned() else {
|
||||
return;
|
||||
};
|
||||
if !cfg.logged_in() {
|
||||
self.login_to(&cfg);
|
||||
return;
|
||||
}
|
||||
if i == self.logins.active {
|
||||
return;
|
||||
}
|
||||
self.logins.active = i;
|
||||
self.save_logins();
|
||||
self.switch_server(cfg.client());
|
||||
self.toast(format!("Switched to {}", cfg.label()));
|
||||
}
|
||||
|
||||
/// The first press arms, a second within a few seconds removes.
|
||||
fn remove_server(&mut self, i: usize) {
|
||||
/// Asks whether to log out of a saved server or forget it.
|
||||
fn open_server_prompt(&mut self, i: usize) {
|
||||
let Some(cfg) = self.logins.servers.get(i) else {
|
||||
return;
|
||||
};
|
||||
let (title, message, choices) = if cfg.logged_in() {
|
||||
(
|
||||
format!("Log out of {}?", cfg.label()),
|
||||
"Logging out keeps the server, so logging in again only needs the password. \
|
||||
Forgetting removes it, with its saved queue and cached covers."
|
||||
.to_string(),
|
||||
vec![Choice::Cancel, Choice::LogOut, Choice::Forget],
|
||||
)
|
||||
} else {
|
||||
(
|
||||
format!("Forget {}?", cfg.label()),
|
||||
"Removes the server, with its saved queue and cached covers.".to_string(),
|
||||
vec![Choice::Cancel, Choice::Forget],
|
||||
)
|
||||
};
|
||||
let labels: Vec<SharedString> = choices.iter().map(|c| c.label().into()).collect();
|
||||
self.ui.set_confirm_title(title.into());
|
||||
self.ui.set_confirm_message(message.into());
|
||||
self.ui.set_confirm_choices(ModelRc::new(VecModel::from(labels)));
|
||||
self.confirm = Some(Confirm {
|
||||
url: cfg.url.clone(),
|
||||
username: cfg.username.clone(),
|
||||
choices,
|
||||
sel: 0,
|
||||
});
|
||||
self.render_confirm();
|
||||
}
|
||||
|
||||
fn render_confirm(&mut self) {
|
||||
self.ui.set_confirm_shown(self.confirm.is_some());
|
||||
if let Some(c) = &self.confirm {
|
||||
self.ui.set_confirm_selected(c.sel as i32);
|
||||
}
|
||||
self.render_hints();
|
||||
}
|
||||
|
||||
/// Keys and buttons while the prompt is open. Nothing else reacts.
|
||||
fn confirm_action(&mut self, a: Action) {
|
||||
let Some(c) = &mut self.confirm else { return };
|
||||
match a {
|
||||
Action::Left | Action::Up => c.sel = c.sel.saturating_sub(1),
|
||||
Action::Right | Action::Down => c.sel = (c.sel + 1).min(c.choices.len() - 1),
|
||||
Action::Activate => return self.choose(),
|
||||
Action::Back => self.confirm = None,
|
||||
_ => return,
|
||||
}
|
||||
self.render_confirm();
|
||||
}
|
||||
|
||||
fn confirm_clicked(&mut self, i: usize) {
|
||||
if let Some(c) = &mut self.confirm
|
||||
&& i < c.choices.len()
|
||||
{
|
||||
c.sel = i;
|
||||
self.choose();
|
||||
}
|
||||
}
|
||||
|
||||
fn choose(&mut self) {
|
||||
let Some(c) = self.confirm.take() else { return };
|
||||
self.render_confirm();
|
||||
let Some(i) = self.logins.find(&c.url, &c.username) else {
|
||||
return;
|
||||
};
|
||||
match c.choices[c.sel] {
|
||||
Choice::Cancel => {}
|
||||
Choice::LogOut => self.log_out_server(i),
|
||||
Choice::Forget => self.forget_server(i),
|
||||
}
|
||||
}
|
||||
|
||||
/// Drops a server's credentials and keeps its entry, queue and covers.
|
||||
fn log_out_server(&mut self, i: usize) {
|
||||
let Some(cfg) = self.logins.servers.get(i).cloned() else {
|
||||
return;
|
||||
};
|
||||
let armed = self
|
||||
.remove_armed
|
||||
.is_some_and(|(j, at)| j == i && at.elapsed() < Duration::from_secs(4));
|
||||
if !armed {
|
||||
self.remove_armed = Some((i, Instant::now()));
|
||||
self.toast(format!("Press again to remove {}", cfg.label()));
|
||||
return;
|
||||
let was_active = cfg.logged_in() && i == self.logins.active;
|
||||
self.logins.log_out(i);
|
||||
self.save_logins();
|
||||
self.toast(format!("Logged out of {}", cfg.label()));
|
||||
if was_active {
|
||||
self.leave_server(true);
|
||||
} else {
|
||||
self.refresh_settings();
|
||||
}
|
||||
self.remove_armed = None;
|
||||
let was_active = i == self.logins.active;
|
||||
}
|
||||
|
||||
/// Removes a server, with its saved queue and cover cache.
|
||||
fn forget_server(&mut self, i: usize) {
|
||||
let Some(cfg) = self.logins.servers.get(i).cloned() else {
|
||||
return;
|
||||
};
|
||||
let was_active = cfg.logged_in() && i == self.logins.active;
|
||||
self.logins.remove(i);
|
||||
self.save_logins();
|
||||
self.toast(format!("Removed {}", cfg.label()));
|
||||
if !was_active {
|
||||
if was_active {
|
||||
self.leave_server(false);
|
||||
} else {
|
||||
self.refresh_settings();
|
||||
return;
|
||||
}
|
||||
// After leaving, which saves the queue of the server it leaves.
|
||||
self.forget_server_data(&cfg);
|
||||
self.toast(format!("Forgot {}", cfg.label()));
|
||||
}
|
||||
|
||||
fn forget_server_data(&mut self, cfg: &Config) {
|
||||
let client = cfg.client();
|
||||
if self.saved.forget(client.base(), client.user())
|
||||
&& let Some(path) = &self.saved_path
|
||||
&& let Err(e) = saved_queue::save(path, &self.saved)
|
||||
{
|
||||
log::warn!("could not save the queue: {e:#}");
|
||||
}
|
||||
if let Some(root) = &self.covers.root {
|
||||
let dir = root.join(cover_dir_name(&client));
|
||||
match std::fs::remove_dir_all(&dir) {
|
||||
Ok(()) => log::info!("removed the cover cache {}", dir.display()),
|
||||
Err(e) if e.kind() == std::io::ErrorKind::NotFound => {}
|
||||
Err(e) => log::warn!("could not remove {}: {e}", dir.display()),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The browsed server was logged out of or forgotten: browse the next
|
||||
/// logged-in one, or show the login screen when none is left.
|
||||
fn leave_server(&mut self, keep_queue: bool) {
|
||||
match self.logins.active().cloned() {
|
||||
Some(next) => self.switch_server(next.client()),
|
||||
None => {
|
||||
// Nothing left to browse: stop, keep the queue on disk.
|
||||
self.save_queue();
|
||||
self.stop_player();
|
||||
self.clear_queue();
|
||||
self.client = None;
|
||||
self.render_player();
|
||||
self.drop_client(keep_queue);
|
||||
self.add_server();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Stops browsing and playing, for the login screen.
|
||||
fn drop_client(&mut self, keep_queue: bool) {
|
||||
if keep_queue {
|
||||
self.save_queue();
|
||||
}
|
||||
self.stop_player();
|
||||
self.clear_queue();
|
||||
self.client = None;
|
||||
self.checking_login = false;
|
||||
self.render_player();
|
||||
}
|
||||
|
||||
/// The server turned down the saved login of the browsed server: log it
|
||||
/// out and ask for its password, rather than showing load errors.
|
||||
fn login_rejected(&mut self) {
|
||||
let i = self.logins.active;
|
||||
let Some(cfg) = self.logins.active().cloned() else {
|
||||
return;
|
||||
};
|
||||
log::warn!("{} turned down the saved login, logging it out", cfg.label());
|
||||
self.logins.log_out(i);
|
||||
self.save_logins();
|
||||
self.drop_client(true);
|
||||
self.login_to(&cfg);
|
||||
self.ui.set_login_error(
|
||||
format!(
|
||||
"The server did not accept the saved login for {}. Enter the password to log in again.",
|
||||
cfg.label()
|
||||
)
|
||||
.into(),
|
||||
);
|
||||
}
|
||||
|
||||
/// The section that `delta` steps away, wrapping around, so Settings is
|
||||
/// one press back from the first section.
|
||||
fn section_step(&self, delta: isize) -> usize {
|
||||
@@ -802,6 +1023,9 @@ impl App {
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
if self.confirm.is_some() {
|
||||
return self.confirm_action(a);
|
||||
}
|
||||
match self.screen {
|
||||
Screen::Login => self.login_action(a),
|
||||
Screen::Browse => self.browse_action(a),
|
||||
@@ -882,7 +1106,7 @@ impl App {
|
||||
Action::Shuffle => self.shuffle_selected(),
|
||||
Action::Back => self.back(),
|
||||
Action::Queue => match self.selected_setting() {
|
||||
Some(Setting::Server(i)) => self.remove_server(i),
|
||||
Some(Setting::Server(i)) => self.open_server_prompt(i),
|
||||
_ => self.enqueue_selected(),
|
||||
},
|
||||
Action::SectionNext => self.select_section(self.section_step(1)),
|
||||
@@ -1587,6 +1811,19 @@ impl App {
|
||||
|
||||
/// Appends a load result to the page. `done` is false while more batches follow.
|
||||
fn page_loaded(&mut self, page_id: u64, result: Result<PageData>, done: bool) {
|
||||
if self.find_page_mut(page_id).is_none() {
|
||||
return;
|
||||
}
|
||||
match &result {
|
||||
Ok(_) => self.checking_login = false,
|
||||
Err(e)
|
||||
if self.checking_login
|
||||
&& subsonic::api_error(e).is_some_and(|a| a.code == subsonic::WRONG_CREDENTIALS) =>
|
||||
{
|
||||
return self.login_rejected();
|
||||
}
|
||||
Err(_) => {}
|
||||
}
|
||||
let Some(page) = self.find_page_mut(page_id) else {
|
||||
return;
|
||||
};
|
||||
@@ -1807,9 +2044,14 @@ impl App {
|
||||
}
|
||||
};
|
||||
match self.screen {
|
||||
_ if self.confirm.is_some() => {
|
||||
h(Control::Activate, "Select");
|
||||
h(Control::Back, "Cancel");
|
||||
}
|
||||
Screen::Login => {
|
||||
let adding = self.client.is_some();
|
||||
let label = match self.login_focus {
|
||||
..0 => "Use this server",
|
||||
0 | 1 => "Next",
|
||||
4 if adding => "Cancel",
|
||||
4 => "Exit",
|
||||
@@ -1846,10 +2088,16 @@ impl App {
|
||||
Some(Target::Setting(Setting::CoverBackdrop)) => h(Control::Seek, "Adjust"),
|
||||
Some(Target::Setting(Setting::Version)) => {}
|
||||
Some(Target::Setting(Setting::Server(i))) => {
|
||||
if *i != self.logins.active {
|
||||
h(Control::Activate, "Switch");
|
||||
let logged_in = self.logins.servers.get(*i).is_some_and(Config::logged_in);
|
||||
if !logged_in {
|
||||
h(Control::Activate, "Log in");
|
||||
h(Control::Queue, "Forget");
|
||||
} else {
|
||||
if *i != self.logins.active {
|
||||
h(Control::Activate, "Switch");
|
||||
}
|
||||
h(Control::Queue, "Log out or forget");
|
||||
}
|
||||
h(Control::Queue, "Remove");
|
||||
}
|
||||
Some(Target::Setting(Setting::AddServer)) => h(Control::Activate, "Add"),
|
||||
Some(Target::Setting(_)) => h(Control::Activate, "Change"),
|
||||
@@ -2973,12 +3221,14 @@ fn settings_data(s: &Settings, logins: &Logins) -> PageData {
|
||||
.enumerate()
|
||||
.map(|(i, cfg)| Entry {
|
||||
title: cfg.label(),
|
||||
subtitle: if i == logins.active {
|
||||
subtitle: if !cfg.logged_in() {
|
||||
"Logged out".to_string()
|
||||
} else if i == logins.active {
|
||||
"Browsing now".to_string()
|
||||
} else {
|
||||
"Saved login".to_string()
|
||||
},
|
||||
detail: if i == logins.active {
|
||||
detail: if cfg.logged_in() && i == logins.active {
|
||||
"Active".to_string()
|
||||
} else {
|
||||
String::new()
|
||||
@@ -3177,6 +3427,12 @@ fn remove_unkeyed_covers(root: &Path) {
|
||||
}
|
||||
}
|
||||
|
||||
/// A server's directory under the cover cache root, keyed like the saved
|
||||
/// queue, by user and full address.
|
||||
fn cover_dir_name(client: &Client) -> String {
|
||||
sanitize(&format!("{}@{}", client.user(), client.base()))
|
||||
}
|
||||
|
||||
fn sanitize(id: &str) -> String {
|
||||
id.chars()
|
||||
.map(|c| {
|
||||
|
||||
+138
-6
@@ -11,7 +11,8 @@ 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.
|
||||
/// 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,
|
||||
@@ -39,6 +40,17 @@ impl Config {
|
||||
}
|
||||
}
|
||||
|
||||
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()),
|
||||
@@ -72,8 +84,7 @@ pub fn state_dir() -> Option<PathBuf> {
|
||||
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('/'))
|
||||
server_label(&self.url, &self.username)
|
||||
}
|
||||
|
||||
fn same_login(&self, other: &Config) -> bool {
|
||||
@@ -81,10 +92,21 @@ impl Config {
|
||||
}
|
||||
}
|
||||
|
||||
/// "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`.
|
||||
/// Index into `servers`. Points at a logged-in server whenever there is
|
||||
/// one.
|
||||
#[serde(default)]
|
||||
pub active: usize,
|
||||
/// `[[server]]` tables in the file.
|
||||
@@ -93,8 +115,22 @@ pub struct Logins {
|
||||
}
|
||||
|
||||
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)
|
||||
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<usize> {
|
||||
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,
|
||||
@@ -113,7 +149,7 @@ impl Logins {
|
||||
}
|
||||
|
||||
/// Removes a login. The active one stays the same server where it can;
|
||||
/// removing it makes the first remaining login active.
|
||||
/// removing it makes the first remaining logged-in server active.
|
||||
pub fn remove(&mut self, i: usize) {
|
||||
if i >= self.servers.len() {
|
||||
return;
|
||||
@@ -124,6 +160,16 @@ impl Logins {
|
||||
} 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();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -143,6 +189,7 @@ fn parse_logins(text: &str) -> Result<Logins> {
|
||||
if l.active >= l.servers.len() {
|
||||
l.active = 0;
|
||||
}
|
||||
l.settle_active();
|
||||
l
|
||||
}
|
||||
Stored::One(c) => Logins {
|
||||
@@ -362,6 +409,91 @@ mod tests {
|
||||
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();
|
||||
|
||||
+24
-1
@@ -57,12 +57,22 @@ impl SavedQueues {
|
||||
pub fn set(&mut self, client: &Client, queue: SavedQueue) {
|
||||
self.servers.insert(key(client), queue);
|
||||
}
|
||||
|
||||
/// Drops the queue of a forgotten server, by its address as
|
||||
/// `Client::base` gives it. Returns whether there was one.
|
||||
pub fn forget(&mut self, base: &str, user: &str) -> bool {
|
||||
self.servers.remove(&key_of(base, user)).is_some()
|
||||
}
|
||||
}
|
||||
|
||||
/// Song ids are only unique within one server, and two users of a server
|
||||
/// have their own queues.
|
||||
fn key(client: &Client) -> String {
|
||||
format!("{}@{}", client.user(), client.base())
|
||||
key_of(client.base(), client.user())
|
||||
}
|
||||
|
||||
fn key_of(base: &str, user: &str) -> String {
|
||||
format!("{user}@{base}")
|
||||
}
|
||||
|
||||
pub fn path() -> Option<PathBuf> {
|
||||
@@ -156,6 +166,19 @@ mod tests {
|
||||
let _ = fs::remove_dir_all(path.parent().unwrap());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn forgetting_a_server_drops_only_its_queue() {
|
||||
let home = Client::new("https://home", "u", Auth::Password("p".into()));
|
||||
let other = Client::new("https://other", "u", Auth::Password("p".into()));
|
||||
let mut queues = SavedQueues::default();
|
||||
queues.set(&home, SavedQueue::default());
|
||||
queues.set(&other, SavedQueue::default());
|
||||
assert!(queues.forget(home.base(), home.user()));
|
||||
assert!(!queues.forget(home.base(), home.user()));
|
||||
assert!(queues.get(&home).is_none());
|
||||
assert!(queues.get(&other).is_some());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_queue_saved_before_shuffle_loads_unshuffled() {
|
||||
let path = temp("before-shuffle");
|
||||
|
||||
Reference in New Issue
Block a user