//! 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::subsonic::{Client, Song}; const VERSION: u32 = 1; #[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)] pub struct SavedQueue { pub songs: Vec, 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); } } /// 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()) } 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")], current: Some(1), position: 93.5, }; let b = SavedQueue { songs: vec![song("9")], current: None, position: 0.0, }; 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 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()); } }