//! The queue saved to disk, so a restart picks up where playback was. //! //! One file holds a queue per server, keyed by user and server address. It //! stores song ids and what is needed to draw the queue, never a stream URL: //! those carry the token or the password, and are rebuilt from the client. use std::collections::BTreeMap; use std::fs; use std::path::{Path, PathBuf}; use anyhow::Result; use serde::{Deserialize, Serialize}; use crate::config; use crate::shuffle::{Library, Mode}; use crate::subsonic::{Client, Song}; const VERSION: u32 = 1; #[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)] pub struct SavedQueue { /// In the order they play. pub songs: Vec, /// Each song's position in the order it was queued. Empty in files from /// before shuffle, which were saved in that order. #[serde(default)] pub order: Vec, #[serde(default)] pub shuffle: Mode, #[serde(default)] pub library: Option, pub current: Option, /// Seconds into the current song. pub position: f64, } #[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] pub struct SavedQueues { version: u32, servers: BTreeMap, } impl Default for SavedQueues { fn default() -> Self { SavedQueues { version: VERSION, servers: BTreeMap::new(), } } } impl SavedQueues { pub fn get(&self, client: &Client) -> Option<&SavedQueue> { self.servers.get(&key(client)) } 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 { key_of(client.base(), client.user()) } fn key_of(base: &str, user: &str) -> String { format!("{user}@{base}") } pub fn path() -> Option { config::state_dir().map(|d| d.join("queue.json")) } /// The saved queues, or none when there is no file or it cannot be read. /// A bad file is logged and left for the next save to replace. pub fn load(path: &Path) -> SavedQueues { let text = match fs::read_to_string(path) { Ok(text) => text, Err(e) if e.kind() == std::io::ErrorKind::NotFound => return SavedQueues::default(), Err(e) => { log::warn!("reading {}: {e}", path.display()); return SavedQueues::default(); } }; match serde_json::from_str::(&text) { Ok(q) if q.version == VERSION => q, Ok(q) => { log::warn!("ignoring {}: unknown version {}", path.display(), q.version); SavedQueues::default() } Err(e) => { log::warn!("ignoring {}: {e}", path.display()); SavedQueues::default() } } } pub fn save(path: &Path, queues: &SavedQueues) -> Result<()> { config::write_atomic(path, &serde_json::to_string(queues)?) } #[cfg(test)] mod tests { use super::*; use crate::subsonic::Auth; fn song(id: &str) -> Song { serde_json::from_value(serde_json::json!({ "id": id, "title": format!("Song {id}"), "artist": "A", "album": "B", "coverArt": "al-1", "duration": 200, "track": 1, })) .unwrap() } fn temp(name: &str) -> PathBuf { let dir = std::env::temp_dir().join(format!("remus-queue-{name}-{}", std::process::id())); let _ = fs::remove_dir_all(&dir); dir.join("queue.json") } #[test] fn round_trips_a_queue_per_server() { let path = temp("round-trip"); let home = Client::new("https://home", "u", Auth::Password("secret-pass".into())); let other = Client::new( "https://other", "u", Auth::Token { salt: "s".into(), token: "secret-token".into(), }, ); let mut queues = SavedQueues::default(); let a = SavedQueue { songs: vec![song("1"), song("2")], order: vec![1, 0], shuffle: Mode::Tracks, library: Some(Library { added_end: 1 }), current: Some(1), position: 93.5, }; let b = SavedQueue { songs: vec![song("9")], current: None, position: 0.0, ..SavedQueue::default() }; queues.set(&home, a.clone()); queues.set(&other, b.clone()); save(&path, &queues).unwrap(); let back = load(&path); assert_eq!(back.get(&home), Some(&a)); assert_eq!(back.get(&other), Some(&b)); let text = fs::read_to_string(&path).unwrap(); assert!(!text.contains("secret") && !text.contains("stream"), "{text}"); 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"); fs::create_dir_all(path.parent().unwrap()).unwrap(); let client = Client::new("https://h", "u", Auth::Password("p".into())); let text = r#"{"version": 1, "servers": {"u@https://h": { "songs": [{"id": "1", "title": "One"}], "current": 0, "position": 12.0}}}"#; fs::write(&path, text).unwrap(); let q = load(&path).get(&client).cloned().expect("the queue"); assert_eq!( (q.songs.len(), q.order, q.shuffle, q.library), (1, vec![], Mode::Off, None) ); assert_eq!(q.songs[0].album_id, None); let _ = fs::remove_dir_all(path.parent().unwrap()); } #[test] fn an_unreadable_file_loads_as_empty() { let path = temp("unreadable"); fs::create_dir_all(path.parent().unwrap()).unwrap(); let client = Client::new("https://h", "u", Auth::Password("p".into())); for text in ["{ not json", "{\"version\": 99, \"servers\": {}}", ""] { fs::write(&path, text).unwrap(); assert_eq!(load(&path).get(&client), None, "{text:?}"); } // A directory in its place cannot be read as a file at all. fs::remove_file(&path).unwrap(); fs::create_dir(&path).unwrap(); assert_eq!(load(&path).get(&client), None); let _ = fs::remove_dir_all(path.parent().unwrap()); } #[test] fn a_missing_file_loads_as_empty() { let path = temp("missing"); assert_eq!(load(&path), SavedQueues::default()); } }