From 5dbdc04cd46f2f50712649e1a58ce577d59a7e6c Mon Sep 17 00:00:00 2001 From: Yuriy Panov Date: Mon, 16 Nov 2026 12:21:02 +0600 Subject: [PATCH] feat: My server, browse and play a Navidrome library MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Adds a "My server" sidebar item (⌘5) for Navidrome and other Subsonic-compatible servers: albums, artists, playlists, starred songs and search, with album, artist and playlist pages. Server songs share the player and queue with Yandex tracks and scrobble back to the server. - New subsonic-api crate: token auth, envelope and error parsing, and a stream plan that keeps files the player decodes and asks the server to transcode the rest to MP3. - ym_api::Track gains a Subsonic source; the player fetches, reports and scrobbles by source. Server errors never sign out of Yandex, and the Yandex client never fetches server audio or covers. - Server credentials live in the keychain; connect and disconnect from the page or Settings. - Server tracks have no likes; lyrics come from LRCLIB. --- Cargo.lock | 14 + Cargo.toml | 2 +- crates/musyx/Cargo.toml | 1 + crates/musyx/assets/icons/server.svg | 18 + crates/musyx/src/app.rs | 209 ++++- crates/musyx/src/covers.rs | 51 +- crates/musyx/src/i18n/ru.rs | 37 +- crates/musyx/src/media.rs | 7 +- crates/musyx/src/player/mod.rs | 93 +- crates/musyx/src/route.rs | 48 +- crates/musyx/src/screens/detail.rs | 20 +- crates/musyx/src/screens/mod.rs | 34 +- crates/musyx/src/screens/server.rs | 1059 +++++++++++++++++++++++ crates/musyx/src/screens/settings.rs | 8 +- crates/musyx/src/session.rs | 42 + crates/musyx/src/shortcuts.rs | 9 +- crates/musyx/src/snapshot.rs | 1 + crates/musyx/src/ui/icons.rs | 1 + crates/musyx/src/widgets/menu.rs | 54 +- crates/musyx/src/widgets/now_playing.rs | 57 +- crates/musyx/src/widgets/player_bar.rs | 37 +- crates/musyx/src/widgets/track_row.rs | 27 +- crates/subsonic-api/Cargo.toml | 21 + crates/subsonic-api/src/client.rs | 584 +++++++++++++ crates/subsonic-api/src/error.rs | 61 ++ crates/subsonic-api/src/lib.rs | 14 + crates/subsonic-api/src/models.rs | 348 ++++++++ crates/subsonic-api/tests/live.rs | 38 + crates/ym-api/src/client.rs | 7 +- crates/ym-api/src/lib.rs | 5 +- crates/ym-api/src/lrclib.rs | 4 +- crates/ym-api/src/models.rs | 145 +++- 32 files changed, 2906 insertions(+), 150 deletions(-) create mode 100644 crates/musyx/assets/icons/server.svg create mode 100644 crates/musyx/src/screens/server.rs create mode 100644 crates/subsonic-api/Cargo.toml create mode 100644 crates/subsonic-api/src/client.rs create mode 100644 crates/subsonic-api/src/error.rs create mode 100644 crates/subsonic-api/src/lib.rs create mode 100644 crates/subsonic-api/src/models.rs create mode 100644 crates/subsonic-api/tests/live.rs diff --git a/Cargo.lock b/Cargo.lock index a7c9c3c..04ca592 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -3010,6 +3010,7 @@ dependencies = [ "serde", "serde_json", "souvlaki", + "subsonic-api", "sys-locale", "tokio", "winresource", @@ -5009,6 +5010,19 @@ dependencies = [ "float-cmp", ] +[[package]] +name = "subsonic-api" +version = "0.3.2" +dependencies = [ + "md-5", + "rand 0.9.5", + "reqwest", + "serde", + "serde_json", + "thiserror 2.0.21", + "tokio", +] + [[package]] name = "subtle" version = "2.6.1" diff --git a/Cargo.toml b/Cargo.toml index 865bbd3..106251a 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -1,6 +1,6 @@ [workspace] resolver = "3" -members = ["crates/ym-api", "crates/musyx"] +members = ["crates/ym-api", "crates/subsonic-api", "crates/musyx"] [workspace.package] version = "0.3.2" diff --git a/crates/musyx/Cargo.toml b/crates/musyx/Cargo.toml index 3e0da5e..15dfb6c 100644 --- a/crates/musyx/Cargo.toml +++ b/crates/musyx/Cargo.toml @@ -8,6 +8,7 @@ publish.workspace = true [dependencies] ym-api = { path = "../ym-api" } +subsonic-api = { path = "../subsonic-api" } iced = { version = "0.14.0", features = ["svg", "image", "tokio", "advanced", "qr_code", "lazy", "canvas"] } keyring = "4.2.0" rodio = { version = "0.23.0", default-features = false, features = ["playback", "mp3", "mp4", "flac"] } diff --git a/crates/musyx/assets/icons/server.svg b/crates/musyx/assets/icons/server.svg new file mode 100644 index 0000000..78dc3c3 --- /dev/null +++ b/crates/musyx/assets/icons/server.svg @@ -0,0 +1,18 @@ + + + + + + + diff --git a/crates/musyx/src/app.rs b/crates/musyx/src/app.rs index 679e068..0ca5f9f 100644 --- a/crates/musyx/src/app.rs +++ b/crates/musyx/src/app.rs @@ -15,12 +15,13 @@ use ym_api::{ PlaylistId, PlaylistSummary, Station, Track, WaveSettings, YmClient, }; -use crate::covers::Covers; +use crate::covers::{Covers, Fetcher}; use crate::player::{self, Audio, Effect, Player}; use crate::route::{Navigator, Route}; use crate::screens::browse::{self, Discover, HomeData}; use crate::screens::collection::{Library, Liked, Tab}; use crate::screens::search::{self, Search}; +use crate::screens::server::{self, ServerScreen}; use crate::screens::wave::WaveScreen; use crate::screens::detail::{self, Page}; use crate::screens::{self, Loadable, sign_in}; @@ -63,6 +64,8 @@ pub struct App { discover: Discover, genre_playlists: HashMap>>, wave: WaveScreen, + /// The user's own music server: its connection, lists and pages. + server: ServerScreen, /// Drives the My Wave hero animation. wave_phase: f32, covers: Covers, @@ -106,6 +109,7 @@ pub enum Message { Navigate(Route), Back, Search(search::Msg), + Server(server::Msg), ToggleDrawer(Panel), CloseDrawer, ShowNowPlaying(bool), @@ -217,6 +221,7 @@ impl App { discover: Discover::default(), genre_playlists: HashMap::new(), wave: WaveScreen::default(), + server: ServerScreen::default(), wave_phase: 0.0, covers: Covers::default(), likes: LikedIds::default(), @@ -259,6 +264,8 @@ impl App { return (app, Task::batch([appearance, restore(), config.capture()])); } app.session = config.session(); + // No keychain in snapshots: My server shows its connect form. + let _ = app.server.update(server::Msg::Restored(Ok(None))); app.library.liked = Liked::loaded(config.sample_liked(), &Liked::NotLoaded); app.pages.insert(Route::Album(1), Loadable::Loaded(config.sample_album())); app.pages.insert(Route::Playlist(crate::snapshot::OWN_PLAYLIST), Loadable::Loaded(config.sample_playlist())); @@ -275,7 +282,7 @@ impl App { return (app, Task::batch([appearance, config.capture()])); } - (app, Task::batch([appearance, restore()])) + (app, Task::batch([appearance, restore(), ServerScreen::restore()])) } pub fn title(&self) -> String { @@ -556,6 +563,19 @@ impl App { } return task; } + Message::Server(msg) => { + let connected = matches!(msg, server::Msg::Checked(_, Ok(()))); + if connected || matches!(msg, server::Msg::Disconnect) { + // Another server can use the same cover ids for other pictures. + self.covers.forget_server(); + } + let task = self.server.update(msg); + let route = self.nav.current(); + if connected && route.is_server() { + return Task::batch([task, self.on_enter(route)]); + } + return task; + } Message::ToggleDrawer(panel) => { self.drawer = if self.drawer == Some(panel) { None } else { Some(panel) }; self.lyric_line = None; @@ -1001,8 +1021,13 @@ impl App { } Message::WaveTick => self.wave_phase = (self.wave_phase + 0.04) % 10_000.0, Message::CoverWanted(url) => { - let Some(client) = self.client().cloned() else { return Task::none() }; - return self.covers.want(url, &client); + let fetcher = if url.starts_with(ym_api::SUBSONIC_COVER_PREFIX) { + self.server.client().cloned().map(Fetcher::Server) + } else { + self.client().cloned().map(Fetcher::Yandex) + }; + let Some(fetcher) = fetcher else { return Task::none() }; + return self.covers.want(url, fetcher); } Message::CoverLoaded(url, bytes) => self.covers.loaded(url, bytes), Message::CoversTick => self.covers.flush(), @@ -1022,7 +1047,8 @@ impl App { Shortcut::VolumeUp => to_player(player::Msg::SetVolume(self.player.volume + shortcuts::VOLUME_STEP)), Shortcut::VolumeDown => to_player(player::Msg::SetVolume(self.player.volume - shortcuts::VOLUME_STEP)), Shortcut::ToggleLike => { - let Some(track) = self.player.track().cloned() else { return Task::none() }; + // Only Yandex tracks have a heart. + let Some(track) = self.player.track().filter(|t| t.is_yandex()).cloned() else { return Task::none() }; let liked = self.library.liked.contains(&track.id); Message::LikeTrack(track, !liked) } @@ -1171,6 +1197,9 @@ impl App { // "Yours" comes from liked albums. Task::batch([featured, self.load_tab(Tab::Albums)]) } + Route::Server | Route::ServerAlbum(_) | Route::ServerArtist(_) | Route::ServerPlaylist(_) => { + self.server.enter(route) + } Route::Album(_) | Route::Artist(_) | Route::Playlist(_) => { if self.pages.get(&route).is_some_and(|p| !p.needs_load()) { return Task::none(); @@ -1315,6 +1344,7 @@ impl App { wave: &self.wave, wave_phase: self.wave_phase, settings: &self.settings, + server: &self.server, })) .height(Fill) .style(theme::scroll); @@ -1355,28 +1385,28 @@ impl App { .into() } - /// Runs the player's requests against the API. + /// Runs the player's requests against the API: Yandex's, or the music + /// server's for tracks from there. fn run(&self, effects: Vec) -> Task { - let Some(client) = self.client() else { return Task::none() }; + let ym = self.client().cloned(); + let server = self.server.client().cloned(); + let quality = self.settings.quality; Task::batch(effects.into_iter().map(|effect| match effect { - Effect::Fetch { generation, track_id } => { - let client = client.clone(); - let quality = self.settings.quality; - Task::future(async move { fetch_audio(&client, &track_id, quality).await }) + Effect::Fetch { generation, track } => { + Task::future(fetch_audio(ym.clone(), server.clone(), track, quality)) .map(move |result| Message::Player(player::Msg::Fetched { generation, result })) } - Effect::Prefetch { track_id } => { - let client = client.clone(); - let quality = self.settings.quality; + Effect::Prefetch { track } => { + let (ym, server) = (ym.clone(), server.clone()); Task::future(async move { - let result = fetch_audio(&client, &track_id, quality).await; - (track_id, result) + let track_id = track.id.clone(); + (track_id, fetch_audio(ym, server, track, quality).await) }) .map(|(track_id, result)| Message::Player(player::Msg::Prefetched { track_id, result })) } Effect::SignedOut => Task::done(Message::SignOut), Effect::WaveFetch { station, session_id, queue } => { - let client = client.clone(); + let Some(client) = ym.clone() else { return Task::none() }; // My Wave's settings ride along as seeds when a session starts. let settings = (station == MY_WAVE).then(|| self.wave.shown()).flatten(); Task::future(async move { @@ -1389,7 +1419,7 @@ impl App { } // Feedback and reports are fire-and-forget: a lost one only blunts recommendations. Effect::WaveFeedback { session_id, event, batch_id } => { - let client = client.clone(); + let Some(client) = ym.clone() else { return Task::none() }; Task::future(async move { if let Err(e) = client.wave_feedback(&session_id, &event, batch_id.as_deref()).await { eprintln!("wave feedback {event:?} (batch {batch_id:?}): {e}"); @@ -1398,7 +1428,7 @@ impl App { .discard() } Effect::Report(report) => { - let client = client.clone(); + let Some(client) = ym.clone() else { return Task::none() }; Task::future(async move { if let Err(e) = client.report_play(&report).await { eprintln!("play report: {e}"); @@ -1406,17 +1436,59 @@ impl App { }) .discard() } + Effect::NowPlaying(track) => scrobble(server.clone(), &track, false), + Effect::Scrobble(track) => scrobble(server.clone(), &track, true), })) } } -async fn fetch_audio(client: &YmClient, track_id: &str, quality: Quality) -> Result { - let stream = match quality { - Quality::Lossless => client.lossless_stream(track_id).await?, - _ => client.stream(track_id, quality.max_kbps()).await?, +/// Tells the music server what's playing (`submission: false`) or what was played. +fn scrobble(server: Option, track: &Track, submission: bool) -> Task { + let (Some(server), Some(song)) = (server, track.subsonic()) else { return Task::none() }; + let song_id = song.song_id.clone(); + Task::future(async move { + if let Err(e) = server.scrobble(&song_id, submission).await { + eprintln!("scrobble {song_id} ({submission}): {e}"); + } + }) + .discard() +} + +async fn fetch_audio( + ym: Option, + server: Option, + track: Track, + quality: Quality, +) -> Result { + let Some(song) = track.subsonic() else { + let client = ym.ok_or_else(|| Error::Network("not signed in".into()))?; + let stream = match quality { + Quality::Lossless => client.lossless_stream(&track.id).await?, + _ => client.stream(&track.id, quality.max_kbps()).await?, + }; + let bytes = client.fetch(&stream).await?; + return Ok(Audio { stream, bytes }); }; - let bytes = client.fetch(&stream).await?; - Ok(Audio { stream, bytes }) + let server = server.ok_or_else(|| Error::Api("no music server connected".into()))?; + let plan = subsonic_api::StreamPlan::for_song(&song.suffix, song.bit_rate, quality.max_kbps(), quality == Quality::Lossless); + let audio = server.stream(&song.song_id, plan).await.map_err(server_error)?; + let stream = ym_api::Stream { + urls: Vec::new(), + codec: audio.codec.to_owned(), + bitrate_kbps: audio.bitrate_kbps, + preview: false, + key: None, + }; + Ok(Audio { stream, bytes: audio.bytes.into() }) +} + +/// A music-server failure in the player's terms. Never `Unauthorized`: that +/// would sign the user out of Yandex over a problem with another service. +fn server_error(e: subsonic_api::Error) -> Error { + match e { + subsonic_api::Error::Network(m) => Error::Network(m), + other => Error::Api(format!("music server: {other}")), + } } /// `MUSYX_TRACE=1` logs every message except the frequent background ones. @@ -1663,6 +1735,93 @@ mod tests { assert!(!app.likes.clips.contains(&1)); } + fn server_track(id: &str) -> Track { + let song = ym_api::SubsonicSong { + song_id: id.into(), + album_id: Some("al1".into()), + album_title: Some("A".into()), + artist_id: None, + cover_art: Some("al-al1".into()), + suffix: "mp3".into(), + bit_rate: 320, + }; + Track::from_subsonic(format!("S{id}"), Some("Kino".into()), std::time::Duration::from_secs(100), song) + } + + fn connected(app: &mut App) { + let config = subsonic_api::Config { url: "http://10.0.0.2:4533".into(), username: "yp".into(), password: "pw".into() }; + let _ = app.update(Message::Server(server::Msg::Restored(Ok(Some(config))))); + } + + #[test] + fn my_server_shows_the_connect_form_until_a_server_is_set_up() { + let mut app = signed_in(); + let _ = app.update(Message::Server(server::Msg::Restored(Ok(None)))); + let _ = app.update(Message::Navigate(Route::Server)); + { + let mut ui = iced_test::simulator(app.view()); + assert!(ui.find("Server address").is_ok()); + assert!(ui.find("Connect").is_ok()); + } + + connected(&mut app); + let mut ui = iced_test::simulator(app.view()); + assert!(ui.find("Server address").is_err(), "connected: the library shows instead"); + assert!(ui.find("yp on 10.0.0.2:4533").is_ok()); + } + + #[test] + fn server_albums_open_their_page() { + let mut app = signed_in(); + connected(&mut app); + let _ = app.update(Message::Navigate(Route::Server)); + let album = subsonic_api::AlbumSummary { + id: "al1".into(), + name: "Gruppa krovi".into(), + artist: Some("Kino".into()), + artist_id: Some("ar1".into()), + cover_art: None, + song_count: 11, + duration: std::time::Duration::from_secs(2400), + year: Some(1988), + }; + let epoch = app.server.epoch(); + let _ = app.update(Message::Server(server::Msg::AlbumsLoaded { + epoch, + sort: subsonic_api::AlbumSort::Newest, + offset: 0, + result: Ok(vec![album]), + })); + let messages = click_in_window(&app, "Gruppa krovi"); + let route = Route::ServerAlbum(crate::route::Sid::of("al1")); + assert_eq!(messages, [format!("{:?}", Message::Navigate(route))]); + let _ = app.update(Message::Navigate(route)); + assert_eq!(app.nav.current(), route); + assert_eq!(app.title(), "Album · Musyx"); + } + + #[test] + fn server_tracks_have_no_heart_and_like_shortcuts_skip_them() { + let mut app = signed_in(); + let _ = app.update(Message::PlayTracks { tracks: vec![server_track("s1")].into(), start: 0, shuffle: false }); + let _ = app.update(Message::Shortcut(Shortcut::ToggleLike)); + assert!(app.toast.is_none(), "nothing was liked"); + let messages = click_in_window(&app, "Ss1"); + assert!(!messages.iter().any(|m| m.starts_with("LikeTrack")), "{messages:?}"); + } + + #[test] + fn music_server_failures_never_sign_out_of_yandex() { + let rejected = server_error(subsonic_api::Error::Unauthorized("Wrong username or password".into())); + assert!(matches!(rejected, Error::Api(_)), "{rejected:?}"); + assert!(matches!(server_error(subsonic_api::Error::Network("down".into())), Error::Network(_))); + let no_server = tokio::runtime::Builder::new_current_thread() + .build() + .unwrap() + .block_on(fetch_audio(None, None, server_track("s1"), Quality::Best)); + assert!(matches!(no_server, Err(Error::Api(_)))); + } + #[test] fn similar_tracks_replace_the_queue_and_say_so() { let mut app = signed_in(); diff --git a/crates/musyx/src/covers.rs b/crates/musyx/src/covers.rs index 79075e9..39afe9d 100644 --- a/crates/musyx/src/covers.rs +++ b/crates/musyx/src/covers.rs @@ -27,6 +27,36 @@ const PARALLEL: usize = 8; /// Side of the Now Playing backdrop in pixels; it is stretched over the window. const BACKDROP: u32 = 32; +/// Who downloads a cover: Yandex for its own URLs, the music server for +/// `subsonic://cover/…` ones. Yandex's client sends its token with every +/// request, so it must never fetch a server URL. +#[derive(Clone)] +pub enum Fetcher { + Yandex(YmClient), + Server(subsonic_api::Client), +} + +impl Fetcher { + /// The cache file name. Server covers include the host, since another + /// server can reuse the same cover id for a different picture. + fn file_name(&self, url: &str) -> String { + match self { + Fetcher::Yandex(_) => file_name(url), + Fetcher::Server(client) => file_name(&format!("{}|{url}", client.host())), + } + } + + async fn fetch(&self, url: &str) -> Result, String> { + match self { + Fetcher::Yandex(client) => client.image(url).await.map_err(|e| e.to_string()), + Fetcher::Server(client) => { + let (id, size) = ym_api::parse_subsonic_cover(url).ok_or("not a server cover")?; + client.cover_art(id, size).await.map_err(|e| e.to_string()) + } + } + } +} + pub struct Covers { images: HashMap, pending: HashSet, @@ -92,14 +122,14 @@ impl Covers { } /// Starts fetching `url` unless it is known, in flight, or failed before. - pub fn want(&mut self, url: String, client: &YmClient) -> Task { + pub fn want(&mut self, url: String, fetcher: Fetcher) -> Task { if self.images.contains_key(&url) || self.pending.contains(&url) || self.failed.contains(&url) { return Task::none(); } self.pending.insert(url.clone()); - let (client, dir, gate) = (client.clone(), self.dir.clone(), self.gate.clone()); + let (dir, gate) = (self.dir.clone(), self.gate.clone()); Task::future(async move { - let bytes = load(&client, &url, dir, &gate).await; + let bytes = load(&fetcher, &url, dir, &gate).await; Message::CoverLoaded(url, bytes) }) } @@ -117,6 +147,15 @@ impl Covers { }) } + /// Drops server covers held in memory, after switching servers. + pub fn forget_server(&mut self) { + let theirs = |url: &String| url.starts_with(ym_api::SUBSONIC_COVER_PREFIX); + self.images.retain(|url, _| !theirs(url)); + self.failed.retain(|url| !theirs(url)); + self.backdrops.retain(|url, _| !theirs(url)); + self.version += 1; + } + pub fn loaded(&mut self, url: String, bytes: Option>) { self.pending.remove(&url); match bytes { @@ -131,8 +170,8 @@ impl Covers { } } -async fn load(client: &YmClient, url: &str, dir: Option, gate: &Semaphore) -> Option> { - let path = dir.as_ref().map(|d| d.join(file_name(url))); +async fn load(fetcher: &Fetcher, url: &str, dir: Option, gate: &Semaphore) -> Option> { + let path = dir.as_ref().map(|d| d.join(fetcher.file_name(url))); if let Some(path) = &path && let Ok(bytes) = tokio::fs::read(path).await { @@ -140,7 +179,7 @@ async fn load(client: &YmClient, url: &str, dir: Option, gate: &Semapho } let _permit = gate.acquire().await.ok()?; - let bytes = match client.image(url).await { + let bytes = match fetcher.fetch(url).await { Ok(bytes) if !bytes.is_empty() => bytes, Ok(_) => return None, Err(e) => { diff --git a/crates/musyx/src/i18n/ru.rs b/crates/musyx/src/i18n/ru.rs index 661f34e..58e96a9 100644 --- a/crates/musyx/src/i18n/ru.rs +++ b/crates/musyx/src/i18n/ru.rs @@ -20,7 +20,7 @@ pub fn get(english: &str) -> Option<&'static str> { "Open or close Now Playing" => "Открыть или закрыть «Сейчас играет»", "Go back" => "Назад", "Close a menu or panel" => "Закрыть меню или панель", - "Home, My Wave, Search, Collection, Podcasts" => "Главная, Моя волна, Поиск, Коллекция, Подкасты", + "Home, My Wave, Search, Collection, My server, Podcasts" => "Главная, Моя волна, Поиск, Коллекция, Мой сервер, Подкасты", "Album" => "Альбом", "Artist" => "Исполнитель", "Playlist" => "Плейлист", @@ -375,6 +375,41 @@ pub fn get(english: &str) -> Option<&'static str> { "Moved" => "Перемещено", "Couldn't move the track. Try again." => "Не удалось переместить трек. Попробуйте ещё раз.", + // My server (Navidrome and other Subsonic servers) + "My server" => "Мой сервер", + "Checking your server…" => "Проверяем сервер…", + "Connect your Navidrome or another Subsonic-compatible server to browse and play your own music here." => "Подключите Navidrome или другой Subsonic-совместимый сервер, чтобы слушать здесь свою музыку.", + "Browse and play a Navidrome or other Subsonic-compatible server under My server. The password is kept in the system keychain." => "Слушайте музыку с Navidrome или другого Subsonic-совместимого сервера в разделе «Мой сервер». Пароль хранится в системной связке ключей.", + "Server address" => "Адрес сервера", + "Username" => "Имя пользователя", + "Password" => "Пароль", + "Connect" => "Подключить", + "Connecting…" => "Подключаемся…", + "Disconnect" => "Отключить", + "Connected to {} as {}." => "Подключено к {} как {}.", + "{} on {}" => "{} на {}", + "Enter the server address and your username." => "Введите адрес сервера и имя пользователя.", + "That doesn't look like a server address. Try something like music.example.com." => "Это не похоже на адрес сервера. Попробуйте, например, music.example.com.", + "Couldn't reach the server. Check the address and your connection." => "Не удалось связаться с сервером. Проверьте адрес и подключение к интернету.", + "That address didn't answer like a music server. Check it and try again." => "По этому адресу не отвечает музыкальный сервер. Проверьте адрес и попробуйте ещё раз.", + "The server didn't accept that username and password." => "Сервер не принял имя пользователя и пароль.", + "The server no longer accepts your sign-in. Disconnect it in Settings and connect again." => "Сервер больше не принимает ваш вход. Отключите его в настройках и подключите снова.", + "Search your server" => "Поиск на сервере", + "Clear" => "Очистить", + "Recently added" => "Недавно добавленные", + "A–Z" => "А–Я", + "Starred" => "Избранное", + "your starred songs" => "избранные треки", + "The server has no albums yet." => "На сервере пока нет альбомов.", + "The server has no artists yet." => "На сервере пока нет исполнителей.", + "No playlists yet. Playlists you make on the server show up here." => "Плейлистов пока нет. Плейлисты, созданные на сервере, появятся здесь.", + "No starred songs yet. Star songs on the server and they show up here." => "Избранных треков пока нет. Отметьте треки звёздочкой на сервере, и они появятся здесь.", + "Nothing on your server matches that." => "На сервере ничего не нашлось.", + "This album isn't on your server any more." => "Этого альбома больше нет на сервере.", + "This artist isn't on your server any more." => "Этого исполнителя больше нет на сервере.", + "This playlist isn't on your server any more." => "Этого плейлиста больше нет на сервере.", + "Connect your server under My server to see this page." => "Подключите сервер в разделе «Мой сервер», чтобы открыть эту страницу.", + // Units "{} h {} min" => "{} ч {} мин", "{} min" => "{} мин", diff --git a/crates/musyx/src/media.rs b/crates/musyx/src/media.rs index 4251f5e..c7e7c7e 100644 --- a/crates/musyx/src/media.rs +++ b/crates/musyx/src/media.rs @@ -101,12 +101,13 @@ impl Media { if new_track { let title = track.full_title(); let artist = track.artist_line(); - let album = track.album.as_ref().map(|a| a.title.clone()); - let cover = track.cover_url(covers::LARGE); + let album = track.album_title(); + // Server covers are app-internal URLs the system can't open. + let cover = track.cover_url(covers::LARGE).filter(|url| url.starts_with("http")); let _ = controls.set_metadata(MediaMetadata { title: Some(&title), artist: Some(&artist), - album: album.as_deref(), + album, cover_url: cover.as_deref(), duration: Some(track.duration), }); diff --git a/crates/musyx/src/player/mod.rs b/crates/musyx/src/player/mod.rs index 2bca8d1..ba52dd2 100644 --- a/crates/musyx/src/player/mod.rs +++ b/crates/musyx/src/player/mod.rs @@ -75,14 +75,25 @@ pub enum Msg { /// Work the app has to do on the player's behalf. #[derive(Debug, Clone, PartialEq, Eq)] pub enum Effect { - Fetch { generation: u64, track_id: String }, - Prefetch { track_id: String }, + /// Download `track`'s audio from wherever it lives. + Fetch { generation: u64, track: Track }, + Prefetch { track: Track }, /// The token stopped working mid-session. SignedOut, /// Start a session (`session_id: None`) or continue one; `queue` is recent `full_id`s. WaveFetch { station: String, session_id: Option, queue: Vec }, WaveFeedback { session_id: String, event: WaveEvent, batch_id: Option }, + /// A finished or abandoned listen of a Yandex track. Report(PlayReport), + /// A track from a music server started: set it as "now playing" there. + NowPlaying(Track), + /// A music-server track was played long enough to count as a play. + Scrobble(Track), +} + +/// The usual scrobbling rule: half the track, or four minutes of a long one. +pub fn counts_as_play(played: Duration, length: Duration) -> bool { + !length.is_zero() && played >= (length / 2).min(Duration::from_secs(240)) } /// A station being played, endlessly topped up. @@ -381,8 +392,11 @@ impl Player { self.status = Status::Playing; self.skips = 0; let mut effects = Vec::new(); - if let Some((id, full_id)) = self.track().map(|t| (t.id.clone(), t.full_id())) { - if let Some(wave) = &self.wave + if let Some(track) = self.track().cloned() { + let (id, full_id) = (track.id.clone(), track.full_id()); + if !track.is_yandex() { + effects.push(Effect::NowPlaying(track)); + } else if let Some(wave) = &self.wave && let Some(session_id) = wave.session_id.clone() { effects.push(Effect::WaveFeedback { @@ -455,6 +469,10 @@ impl Player { let Some(id) = self.started.take() else { return vec![] }; let Some(track) = self.track().filter(|t| t.id == id) else { return vec![] }; let played = if finished { self.duration } else { self.position.min(self.duration) }; + // Server tracks are reported to their server, never to Yandex or its stations. + if !track.is_yandex() { + return if counts_as_play(played, self.duration) { vec![Effect::Scrobble(track.clone())] } else { vec![] }; + } let mut effects = vec![Effect::Report(PlayReport { track_id: id.clone(), album_id: track.album.as_ref().map(|a| a.id), @@ -575,7 +593,7 @@ impl Player { None => { self.status = Status::Loading; self.current = None; - vec![Effect::Fetch { generation: self.generation, track_id: track.id }] + vec![Effect::Fetch { generation: self.generation, track }] } } } @@ -610,7 +628,7 @@ impl Player { return vec![]; } self.prefetched = None; - vec![Effect::Prefetch { track_id: next.id.clone() }] + vec![Effect::Prefetch { track: next.clone() }] } fn skip_unplayable(&mut self) -> Vec { @@ -667,14 +685,14 @@ mod tests { let mut p = Player::default(); let tracks: Arc<[Track]> = vec![track("a", 10), track("b", 20)].into(); let effects = p.update(Msg::Play { tracks, start: 0, shuffle: None }); - assert!(effects.contains(&Effect::Fetch { generation: 1, track_id: "a".into() }), "{effects:?}"); + assert!(effects.contains(&Effect::Fetch { generation: 1, track: track("a", 10) }), "{effects:?}"); assert_eq!(effects.iter().filter(|e| matches!(e, Effect::Fetch { .. })).count(), 1); assert_eq!(p.status(), Status::Loading); assert!(p.update(Msg::Fetched { generation: 1, result: Ok(audio()) }).is_empty()); let effects = p.update(Msg::Engine(Event::Loaded { generation: 1, duration: None })); assert_eq!(p.status(), Status::Playing); assert_eq!(p.duration(), Duration::from_secs(10)); - assert_eq!(effects, vec![Effect::Prefetch { track_id: "b".into() }]); + assert_eq!(effects, vec![Effect::Prefetch { track: track("b", 20) }]); } #[test] @@ -861,7 +879,7 @@ mod tests { assert_eq!(p.status(), Status::Loading, "a wave doesn't end"); let batch = WaveBatch { session_id: Some("s1".into()), tracks: vec![track("w9", 50)], batch_id: Some("b2".into()) }; let effects = p.update(Msg::WaveBatch { station: "user:onyourwave".into(), result: Ok(batch) }); - assert!(matches!(effects.first(), Some(Effect::Fetch { track_id, .. }) if track_id == "w9")); + assert!(matches!(effects.first(), Some(Effect::Fetch { track, .. }) if track.id == "w9")); } #[test] @@ -901,7 +919,7 @@ mod tests { let mut empty = Player::default(); let effects = empty.update(Msg::Append(track("solo", 5))); - assert!(effects.iter().any(|e| matches!(e, Effect::Fetch { track_id, .. } if track_id == "solo"))); + assert!(effects.iter().any(|e| matches!(e, Effect::Fetch { track, .. } if track.id == "solo"))); } #[test] @@ -909,7 +927,7 @@ mod tests { let mut p = playing(3, 0); p.update(Msg::Prefetched { track_id: "1".into(), result: Ok(audio()) }); let effects = p.update(Msg::PlayNext(track("n", 5))); - assert!(effects.contains(&Effect::Prefetch { track_id: "n".into() }), "{effects:?}"); + assert!(effects.iter().any(|e| matches!(e, Effect::Prefetch { track } if track.id == "n")), "{effects:?}"); let generation = p.generation; let effects = p.update(Msg::Engine(Event::Ended { generation })); assert_eq!(p.track().unwrap().id, "n", "{effects:?}"); @@ -952,4 +970,57 @@ mod tests { assert!(!p.muted); assert_eq!(p.volume, 0.5); } + + fn server_track(id: &str, secs: u64) -> Track { + let song = ym_api::SubsonicSong { + song_id: id.into(), + album_id: None, + album_title: None, + artist_id: None, + cover_art: None, + suffix: "mp3".into(), + bit_rate: 320, + }; + Track::from_subsonic(format!("S{id}"), None, Duration::from_secs(secs), song) + } + + #[test] + fn server_tracks_in_a_wave_report_to_their_server_only() { + let mut p = wave_with(3); + loaded(&mut p); + p.update(Msg::PlayNext(server_track("s1", 100))); + let effects = p.update(Msg::Next); + assert!(effects.iter().any(|e| matches!(e, Effect::Fetch { track, .. } if track.id == "sub-s1")), "{effects:?}"); + let generation = p.generation; + p.update(Msg::Fetched { generation, result: Ok(audio()) }); + let effects = loaded(&mut p); + assert!(effects.iter().any(|e| matches!(e, Effect::NowPlaying(t) if t.id == "sub-s1")), "{effects:?}"); + assert!(!effects.iter().any(|e| matches!(e, Effect::WaveFeedback { .. })), "{effects:?}"); + + let generation = p.generation; + p.update(Msg::Engine(Event::Position { generation, position: Duration::from_secs(30) })); + let effects = p.update(Msg::Next); + assert!( + !effects.iter().any(|e| matches!(e, Effect::Report(_) | Effect::WaveFeedback { .. } | Effect::Scrobble(_))), + "30 of 100 seconds: nothing to report anywhere: {effects:?}" + ); + } + + #[test] + fn server_tracks_scrobble_after_half_or_four_minutes() { + let mut p = Player::default(); + let tracks: Arc<[Track]> = vec![server_track("a", 100), server_track("b", 100)].into(); + let effects = p.update(Msg::Play { tracks, start: 0, shuffle: None }); + let generation = fetch_generation(&effects).unwrap(); + p.update(Msg::Fetched { generation, result: Ok(audio()) }); + loaded(&mut p); + p.update(Msg::Engine(Event::Position { generation, position: Duration::from_secs(60) })); + let effects = p.update(Msg::Next); + assert!(effects.iter().any(|e| matches!(e, Effect::Scrobble(t) if t.id == "sub-a")), "{effects:?}"); + assert!(!effects.iter().any(|e| matches!(e, Effect::Report(_)))); + + assert!(counts_as_play(Duration::from_secs(240), Duration::from_secs(3600))); + assert!(!counts_as_play(Duration::from_secs(239), Duration::from_secs(3600))); + assert!(!counts_as_play(Duration::ZERO, Duration::ZERO)); + } } diff --git a/crates/musyx/src/route.rs b/crates/musyx/src/route.rs index ee56f7a..d9b778b 100644 --- a/crates/musyx/src/route.rs +++ b/crates/musyx/src/route.rs @@ -6,12 +6,26 @@ use ym_api::PlaylistId; use crate::ui::icons::Icon; +/// A music-server id (album, artist, playlist) as a `Copy` handle, so routes +/// to server pages stay `Copy`. The server screen maps it back to the id. +#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] +pub struct Sid(pub u64); + +impl Sid { + /// 64-bit FNV-1a of the id; equal ids give equal handles. + pub fn of(id: &str) -> Sid { + Sid(id.bytes().fold(0xcbf2_9ce4_8422_2325_u64, |h, b| (h ^ u64::from(b)).wrapping_mul(0x0100_0000_01b3))) + } +} + #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] pub enum Route { Home, Wave, Search, Collection, + /// The user's own music server (Navidrome or another Subsonic server). + Server, Podcasts, Settings, Album(i64), @@ -20,12 +34,15 @@ pub enum Route { Chart, /// Index into the app's flattened genre list. Genre(usize), + ServerAlbum(Sid), + ServerArtist(Sid), + ServerPlaylist(Sid), } impl Route { /// Sidebar order. - pub const NAV: [Route; 5] = - [Route::Home, Route::Wave, Route::Search, Route::Collection, Route::Podcasts]; + pub const NAV: [Route; 6] = + [Route::Home, Route::Wave, Route::Search, Route::Collection, Route::Server, Route::Podcasts]; pub fn label(self) -> &'static str { match self { @@ -33,27 +50,34 @@ impl Route { Route::Wave => tr("My Wave"), Route::Search => tr("Search"), Route::Collection => tr("Collection"), + Route::Server => tr("My server"), Route::Podcasts => tr("Podcasts"), Route::Settings => tr("Settings"), - Route::Album(_) => tr("Album"), - Route::Artist(_) => tr("Artist"), - Route::Playlist(_) => tr("Playlist"), + Route::Album(_) | Route::ServerAlbum(_) => tr("Album"), + Route::Artist(_) | Route::ServerArtist(_) => tr("Artist"), + Route::Playlist(_) | Route::ServerPlaylist(_) => tr("Playlist"), Route::Chart => tr("Chart"), Route::Genre(_) => tr("Genre"), } } + /// My server and its album, artist and playlist pages. + pub fn is_server(self) -> bool { + matches!(self, Route::Server | Route::ServerAlbum(_) | Route::ServerArtist(_) | Route::ServerPlaylist(_)) + } + pub fn icon(self) -> Icon { match self { Route::Home => Icon::Home, Route::Wave => Icon::Wave, Route::Search => Icon::Search, Route::Collection => Icon::Library, + Route::Server => Icon::Server, Route::Podcasts => Icon::Podcast, Route::Settings => Icon::Settings, - Route::Album(_) => Icon::Disc, - Route::Artist(_) => Icon::Wave, - Route::Playlist(_) => Icon::Queue, + Route::Album(_) | Route::ServerAlbum(_) => Icon::Disc, + Route::Artist(_) | Route::ServerArtist(_) => Icon::Wave, + Route::Playlist(_) | Route::ServerPlaylist(_) => Icon::Queue, Route::Chart => Icon::Chart, Route::Genre(_) => Icon::Library, } @@ -125,6 +149,14 @@ mod tests { assert!(!nav.can_go_back()); } + #[test] + fn server_ids_become_stable_route_handles() { + assert_eq!(Sid::of("al-1"), Sid::of("al-1")); + assert_ne!(Sid::of("al-1"), Sid::of("al-2")); + assert_ne!(Route::ServerAlbum(Sid::of("x")), Route::ServerArtist(Sid::of("x"))); + assert_eq!(Route::NAV[4], Route::Server, "My server sits after Collection"); + } + #[test] fn history_is_bounded() { let mut nav = Navigator::new(Route::Home); diff --git a/crates/musyx/src/screens/detail.rs b/crates/musyx/src/screens/detail.rs index a2504d0..4374570 100644 --- a/crates/musyx/src/screens/detail.rs +++ b/crates/musyx/src/screens/detail.rs @@ -88,18 +88,18 @@ fn not_found_or_retry<'a>(env: Env<'a>, e: &'a Error, what: What, route: Route) status(env.t, LoadState::Failed(e), what.retry, Message::Navigate(route)) } -struct Head<'a> { - cover: Option, - hues: (f32, f32), - round: bool, - kind: String, - title: String, - by: Option>, - meta: String, - actions: Vec>, +pub(crate) struct Head<'a> { + pub cover: Option, + pub hues: (f32, f32), + pub round: bool, + pub kind: String, + pub title: String, + pub by: Option>, + pub meta: String, + pub actions: Vec>, } -fn head<'a>(env: Env<'a>, h: Head<'a>) -> Element<'a, Message> { +pub(crate) fn head<'a>(env: Env<'a>, h: Head<'a>) -> Element<'a, Message> { let t = env.t; let size_px = 200.0; let corner = if h.round { size_px / 2.0 } else { theme::radius::COVER }; diff --git a/crates/musyx/src/screens/mod.rs b/crates/musyx/src/screens/mod.rs index de134ad..65b12ff 100644 --- a/crates/musyx/src/screens/mod.rs +++ b/crates/musyx/src/screens/mod.rs @@ -4,6 +4,7 @@ pub mod browse; pub mod collection; pub mod detail; pub mod search; +pub mod server; pub mod settings; pub mod sign_in; pub mod wave; @@ -24,16 +25,17 @@ use crate::widgets::track_list::Env; use crate::i18n::{tr, trf}; /// Something fetched from the API: not asked for yet, on its way, here, or failed. +/// `E` is the API's error type: Yandex's, or the music server's. #[derive(Debug, Default)] -pub enum Loadable { +pub enum Loadable { #[default] NotLoaded, Loading, Loaded(T), - Failed(Error), + Failed(E), } -impl Loadable { +impl Loadable { pub fn get(&self) -> Option<&T> { match self { Loadable::Loaded(v) => Some(v), @@ -46,19 +48,21 @@ impl Loadable { matches!(self, Loadable::NotLoaded | Loadable::Failed(_)) } + pub fn from_result(result: Result) -> Self { + match result { + Ok(v) => Loadable::Loaded(v), + Err(e) => Loadable::Failed(e), + } + } +} + +impl Loadable { pub fn state(&self) -> collection::LoadState<'_> { match self { Loadable::Failed(e) => collection::LoadState::Failed(e), _ => collection::LoadState::Loading, } } - - pub fn from_result(result: Result) -> Self { - match result { - Ok(v) => Loadable::Loaded(v), - Err(e) => Loadable::Failed(e), - } - } } /// Everything a routed screen may need from app state. @@ -75,10 +79,12 @@ pub struct Ctx<'a> { pub wave: &'a wave::WaveScreen, pub wave_phase: f32, pub settings: &'a crate::store::Settings, + pub server: &'a server::ServerScreen, } pub fn view<'a>(ctx: Ctx<'a>) -> Element<'a, Message> { - let Ctx { env, route, search, me, library, pages, discover, genre_playlists, player, wave, wave_phase, settings } = ctx; + let Ctx { env, route, search, me, library, pages, discover, genre_playlists, player, wave, wave_phase, settings, server } = + ctx; let t = env.t; let content: Column<'a, Message> = match route { Route::Home => { @@ -102,8 +108,12 @@ pub fn view<'a>(ctx: Ctx<'a>) -> Element<'a, Message> { Route::Album(_) | Route::Artist(_) | Route::Playlist(_) => { column![detail::view(env, route, pages.get(&route).unwrap_or(&Loadable::Loading))] } + Route::Server => column![server::view(env, server)], + Route::ServerAlbum(_) | Route::ServerArtist(_) | Route::ServerPlaylist(_) => { + column![server::page(env, server, route)] + } Route::Podcasts => column![browse::podcasts(env, discover, &library.albums)], - Route::Settings => column![settings::view(t, settings, account_card(t, me))], + Route::Settings => column![settings::view(t, settings, account_card(t, me), server::settings_section(t, server))], }; content diff --git a/crates/musyx/src/screens/server.rs b/crates/musyx/src/screens/server.rs new file mode 100644 index 0000000..019ee7c --- /dev/null +++ b/crates/musyx/src/screens/server.rs @@ -0,0 +1,1059 @@ +//! My server: the user's own library on a Subsonic-compatible server such as +//! Navidrome. It stands apart from the Yandex session: its own client, its own +//! sign-in (kept in the keychain) and its own error type, so nothing that goes +//! wrong here can sign the user out of Yandex. + +use std::collections::HashMap; +use std::sync::Arc; + +use iced::widget::{Row, button, column, container, row, space, text_input}; +use iced::{Alignment, Element, Fill, Task}; +use subsonic_api::{ + AlbumSort, AlbumSummary, ArtistSummary, Client, Config, Error, PlaylistSummary, SearchResults, Song, +}; +use ym_api::{SubsonicSong, Track, hash_str, hues_for, subsonic_cover_url}; + +use super::Loadable; +use super::collection::play_bar; +use super::detail::{Head, head}; +use crate::app::Message; +use crate::covers::{self, Covers}; +use crate::i18n::{tr, trf}; +use crate::route::{Route, Sid}; +use crate::session; +use crate::ui::theme::{self, Tokens, size}; +use crate::ui::{counted, duration_words, line, para, tracks_word}; +use crate::widgets::card::{self, Card}; +use crate::widgets::track_list::{self, Env}; +use crate::widgets::track_row::Columns; + +/// Albums asked for at a time. +const PAGE: usize = 60; + +type Load = Loadable; + +#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)] +pub enum Tab { + #[default] + Albums, + Artists, + Playlists, + Starred, +} + +impl Tab { + const ALL: [Tab; 4] = [Tab::Albums, Tab::Artists, Tab::Playlists, Tab::Starred]; + + fn label(self) -> &'static str { + match self { + Tab::Albums => tr("Albums"), + Tab::Artists => tr("Artists"), + Tab::Playlists => tr("Playlists"), + Tab::Starred => tr("Starred"), + } + } +} + +#[derive(Debug, Default)] +pub enum Conn { + /// Reading the keychain at startup. + #[default] + Restoring, + /// Nothing stored, or disconnected. + Unconfigured, + Ready(Client), +} + +/// The connect form. The password is only held until the server accepts it. +#[derive(Debug, Clone, Default)] +pub struct Form { + pub url: String, + pub username: String, + pub password: String, + pub busy: bool, + pub error: Option<&'static str>, +} + +#[derive(Debug)] +pub enum Page { + Album { info: AlbumSummary, tracks: Arc<[Track]> }, + Artist { info: ArtistSummary, albums: Vec }, + Playlist { info: PlaylistSummary, tracks: Arc<[Track]> }, +} + +/// A page as the server sent it, before its songs become tracks. +#[derive(Debug, Clone)] +pub enum Fetched { + Album(subsonic_api::Album), + Artist(subsonic_api::Artist), + Playlist(subsonic_api::Playlist), +} + +#[derive(Debug)] +pub struct Found { + artists: Vec, + albums: Vec, + songs: Arc<[Track]>, +} + +#[derive(Debug, Default)] +pub struct ServerScreen { + conn: Conn, + pub form: Form, + tab: Tab, + sort: AlbumSort, + albums: Load>, + /// The last page of albums was full, so there may be more. + more: bool, + loading_more: bool, + artists: Load>, + playlists: Load>, + starred: Load>, + query: String, + /// The query searched and what it found; `None` shows the tabs. + results: Option<(String, Load)>, + pages: HashMap>, + /// The server ids behind route handles, learned as lists arrive. + ids: HashMap, + /// Bumped whenever the connection changes, so late replies from the old one are dropped. + epoch: u64, +} + +#[derive(Debug, Clone)] +pub enum Msg { + Restored(Result, String>), + Url(String), + Username(String), + Password(String), + Connect, + Checked(Config, Result<(), Error>), + Saved(Result<(), String>), + Disconnect, + Tab(Tab), + Sort(AlbumSort), + LoadMore, + Retry, + AlbumsLoaded { epoch: u64, sort: AlbumSort, offset: usize, result: Result, Error> }, + ArtistsLoaded(u64, Result, Error>), + PlaylistsLoaded(u64, Result, Error>), + StarredLoaded(u64, Result, Error>), + Query(String), + Search, + ClearSearch, + Found(u64, String, Result), + PageLoaded(u64, Route, Result), +} + +fn send(msg: Msg) -> Message { + Message::Server(msg) +} + +impl ServerScreen { + /// Reads the stored server from the keychain. + pub fn restore() -> Task { + Task::future(session::server::load()).map(|r| send(Msg::Restored(r))) + } + + /// The current connection's generation, for tests that feed replies in. + #[cfg(test)] + pub fn epoch(&self) -> u64 { + self.epoch + } + + pub fn client(&self) -> Option<&Client> { + match &self.conn { + Conn::Ready(client) => Some(client), + _ => None, + } + } + + /// Forgets everything loaded from the server, keeping the connection. + fn reset_data(&mut self) { + let (conn, form, tab, sort, epoch) = + (std::mem::take(&mut self.conn), std::mem::take(&mut self.form), self.tab, self.sort, self.epoch); + *self = ServerScreen { conn, form, tab, sort, epoch: epoch + 1, ..ServerScreen::default() }; + } + + fn remember(&mut self, id: &str) -> Sid { + let sid = Sid::of(id); + self.ids.entry(sid).or_insert_with(|| id.to_owned()); + sid + } + + fn remember_albums(&mut self, albums: &[AlbumSummary]) { + for a in albums { + self.remember(&a.id); + if let Some(artist) = &a.artist_id { + self.remember(artist); + } + } + } + + /// A server song as a track the player and lists understand. + fn track(&mut self, song: Song) -> Track { + for id in [&song.album_id, &song.artist_id].into_iter().flatten() { + self.remember(id); + } + Track::from_subsonic( + song.title, + song.artist, + song.duration, + SubsonicSong { + song_id: song.id, + album_id: song.album_id, + album_title: song.album, + artist_id: song.artist_id, + cover_art: song.cover_art, + suffix: song.suffix, + bit_rate: song.bit_rate, + }, + ) + } + + fn tracks(&mut self, songs: Vec) -> Arc<[Track]> { + songs.into_iter().map(|s| self.track(s)).collect() + } + + /// Loads what a route shows on first visit, and retries after a failure. + pub fn enter(&mut self, route: Route) -> Task { + let Some(client) = self.client().cloned() else { return Task::none() }; + let id = match route { + Route::Server => return self.load_tab(), + Route::ServerAlbum(sid) | Route::ServerArtist(sid) | Route::ServerPlaylist(sid) => { + if self.pages.get(&route).is_some_and(|p| !p.needs_load()) { + return Task::none(); + } + match self.ids.get(&sid) { + Some(id) => id.clone(), + None => { + self.pages.insert(route, Loadable::Failed(Error::NotFound("unknown id".into()))); + return Task::none(); + } + } + } + _ => return Task::none(), + }; + self.pages.insert(route, Loadable::Loading); + let epoch = self.epoch; + Task::future(async move { + let result = match route { + Route::ServerAlbum(_) => client.album(&id).await.map(Fetched::Album), + Route::ServerArtist(_) => client.artist(&id).await.map(Fetched::Artist), + _ => client.playlist(&id).await.map(Fetched::Playlist), + }; + send(Msg::PageLoaded(epoch, route, result)) + }) + } + + fn load_tab(&mut self) -> Task { + let Some(client) = self.client().cloned() else { return Task::none() }; + let epoch = self.epoch; + match self.tab { + Tab::Albums if self.albums.needs_load() => { + self.albums = Loadable::Loading; + let sort = self.sort; + Task::future(async move { + let result = client.albums(sort, 0, PAGE).await; + send(Msg::AlbumsLoaded { epoch, sort, offset: 0, result }) + }) + } + Tab::Artists if self.artists.needs_load() => { + self.artists = Loadable::Loading; + Task::future(async move { send(Msg::ArtistsLoaded(epoch, client.artists().await)) }) + } + Tab::Playlists if self.playlists.needs_load() => { + self.playlists = Loadable::Loading; + Task::future(async move { send(Msg::PlaylistsLoaded(epoch, client.playlists().await)) }) + } + Tab::Starred if self.starred.needs_load() => { + self.starred = Loadable::Loading; + Task::future(async move { send(Msg::StarredLoaded(epoch, client.starred().await)) }) + } + _ => Task::none(), + } + } + + pub fn update(&mut self, msg: Msg) -> Task { + match msg { + Msg::Restored(result) => { + let config = result.unwrap_or_else(|e| { + eprintln!("keychain (server): {e}"); + None + }); + self.conn = Conn::Unconfigured; + if let Some(config) = config { + self.form.url = config.url.clone(); + self.form.username = config.username.clone(); + match Client::new(&config) { + Ok(client) => self.conn = Conn::Ready(client), + Err(e) => eprintln!("stored server: {e}"), + } + } + } + Msg::Url(url) => self.form.url = url, + Msg::Username(name) => self.form.username = name, + Msg::Password(password) => self.form.password = password, + Msg::Connect => { + if self.form.busy { + return Task::none(); + } + let config = Config { + url: self.form.url.trim().to_owned(), + username: self.form.username.trim().to_owned(), + password: self.form.password.clone(), + }; + if config.url.is_empty() || config.username.is_empty() { + self.form.error = Some(tr("Enter the server address and your username.")); + return Task::none(); + } + let client = match Client::new(&config) { + Ok(client) => client, + Err(e) => { + self.form.error = Some(connect_error(&e)); + return Task::none(); + } + }; + self.form.busy = true; + self.form.error = None; + return Task::future(async move { + let result = client.ping().await; + send(Msg::Checked(config, result)) + }); + } + Msg::Checked(config, result) => { + self.form.busy = false; + let client = result.and_then(|()| Client::new(&config)); + match client { + Ok(client) => { + self.conn = Conn::Ready(client); + self.form.password.clear(); + self.form.error = None; + self.reset_data(); + return Task::future(session::server::save(config)).map(|r| send(Msg::Saved(r))); + } + Err(e) => { + eprintln!("server sign-in: {e}"); + self.form.error = Some(connect_error(&e)); + } + } + } + // The connection works this session either way; it just won't be remembered. + Msg::Saved(Err(e)) => eprintln!("keychain (server): {e}"), + Msg::Saved(Ok(())) => {} + Msg::Disconnect => { + self.conn = Conn::Unconfigured; + self.form.password.clear(); + self.form.error = None; + self.reset_data(); + return Task::future(async { + if let Err(e) = session::server::clear().await { + eprintln!("keychain (server): {e}"); + } + }) + .discard(); + } + Msg::Tab(tab) => { + self.tab = tab; + return self.load_tab(); + } + Msg::Sort(sort) if sort != self.sort => { + self.sort = sort; + self.albums = Loadable::NotLoaded; + self.more = false; + self.loading_more = false; + return self.load_tab(); + } + Msg::Sort(_) => {} + Msg::Retry => return self.load_tab(), + Msg::LoadMore => { + let (Some(client), Loadable::Loaded(albums)) = (self.client().cloned(), &self.albums) else { + return Task::none(); + }; + if self.loading_more || !self.more { + return Task::none(); + } + self.loading_more = true; + let (epoch, sort, offset) = (self.epoch, self.sort, albums.len()); + return Task::future(async move { + let result = client.albums(sort, offset, PAGE).await; + send(Msg::AlbumsLoaded { epoch, sort, offset, result }) + }); + } + Msg::AlbumsLoaded { epoch, sort, offset, result } => { + if epoch != self.epoch || sort != self.sort { + return Task::none(); + } + self.loading_more = false; + match result { + Ok(page) => { + self.more = page.len() == PAGE; + self.remember_albums(&page); + match &mut self.albums { + Loadable::Loaded(albums) if offset > 0 => albums.extend(page), + _ => self.albums = Loadable::Loaded(page), + } + } + Err(e) => { + eprintln!("server albums: {e}"); + // A failed "more" keeps what's shown; the button stays to try again. + if offset == 0 { + self.albums = Loadable::Failed(e); + } + } + } + } + Msg::ArtistsLoaded(epoch, result) if epoch == self.epoch => { + if let Ok(artists) = &result { + for a in artists { + self.remember(&a.id); + } + } + self.artists = loaded("server artists", result); + } + Msg::PlaylistsLoaded(epoch, result) if epoch == self.epoch => { + if let Ok(playlists) = &result { + for p in playlists { + self.remember(&p.id); + } + } + self.playlists = loaded("server playlists", result); + } + Msg::StarredLoaded(epoch, result) if epoch == self.epoch => { + let result = result.map(|songs| self.tracks(songs)); + self.starred = loaded("server starred", result); + } + Msg::ArtistsLoaded(..) | Msg::PlaylistsLoaded(..) | Msg::StarredLoaded(..) => {} + Msg::Query(query) => { + if query.trim().is_empty() { + self.results = None; + } + self.query = query; + } + Msg::Search => { + let query = self.query.trim().to_owned(); + let Some(client) = self.client().cloned() else { return Task::none() }; + if query.is_empty() { + self.results = None; + return Task::none(); + } + self.results = Some((query.clone(), Loadable::Loading)); + let epoch = self.epoch; + return Task::future(async move { + let result = client.search(&query).await; + send(Msg::Found(epoch, query, result)) + }); + } + Msg::ClearSearch => { + self.query.clear(); + self.results = None; + } + Msg::Found(epoch, query, result) => { + if epoch != self.epoch || self.results.as_ref().is_none_or(|(q, _)| *q != query) { + return Task::none(); + } + let found = result.map(|r| { + self.remember_albums(&r.albums); + for a in &r.artists { + self.remember(&a.id); + } + Found { artists: r.artists, albums: r.albums, songs: self.tracks(r.songs) } + }); + self.results = Some((query, loaded("server search", found))); + } + Msg::PageLoaded(epoch, route, result) => { + if epoch != self.epoch { + return Task::none(); + } + let page = result.map(|fetched| match fetched { + Fetched::Album(a) => { + if let Some(artist) = &a.info.artist_id { + self.remember(artist); + } + Page::Album { info: a.info, tracks: self.tracks(a.songs) } + } + Fetched::Artist(a) => { + self.remember_albums(&a.albums); + Page::Artist { info: a.info, albums: a.albums } + } + Fetched::Playlist(p) => Page::Playlist { info: p.info, tracks: self.tracks(p.songs) }, + }); + self.pages.insert(route, loaded("server page", page)); + } + } + Task::none() + } +} + +fn loaded(what: &str, result: Result) -> Load { + if let Err(e) = &result { + eprintln!("{what}: {e}"); + } + Loadable::from_result(result) +} + +fn connect_error(e: &Error) -> &'static str { + match e { + Error::Unauthorized(_) => tr("The server didn't accept that username and password."), + Error::InvalidUrl(_) => tr("That doesn't look like a server address. Try something like music.example.com."), + Error::Network(_) => tr("Couldn't reach the server. Check the address and your connection."), + Error::NotFound(_) | Error::Api(_) => tr("That address didn't answer like a music server. Check it and try again."), + } +} + +// ---- Views --------------------------------------------------------------- + +pub fn view<'a>(env: Env<'a>, s: &'a ServerScreen) -> Element<'a, Message> { + let t = env.t; + let title = line(tr("My server"), theme::DISPLAY, size::DISPLAY_S, t.fg); + let client = match &s.conn { + Conn::Restoring => return column![title, para(tr("Checking your server…"), size::BODY, t.muted)].spacing(24).into(), + Conn::Unconfigured => { + return column![ + title, + container(para( + tr("Connect your Navidrome or another Subsonic-compatible server to browse and play your own music here."), + size::BODY, + t.muted, + )) + .max_width(560), + connect_form(t, &s.form), + ] + .spacing(24) + .into(); + } + Conn::Ready(client) => client, + }; + + let head = row![ + title, + space::horizontal(), + line(trf("{} on {}", &[&client.username(), &client.host()]), theme::BODY, size::META, t.muted), + ] + .align_y(Alignment::Center); + + let search = text_input(tr("Search your server"), &s.query) + .on_input(|q| send(Msg::Query(q))) + .on_submit(send(Msg::Search)) + .font(theme::BODY) + .size(size::BODY) + .padding([10, 16]) + .width(420) + .style(theme::search_field); + let search = match &s.results { + Some(_) => row![ + search, + button(line(tr("Clear"), theme::MEDIUM, size::BODY, t.fg)) + .padding([9, 14]) + .style(theme::ghost) + .on_press(send(Msg::ClearSearch)), + ] + .spacing(8) + .align_y(Alignment::Center), + None => row![search], + }; + + let body = match &s.results { + Some((_, found)) => results(env, found), + None => column![Row::with_children(Tab::ALL.map(|tab| tab_button(t, tab, s))).spacing(4), tab_body(env, s)] + .spacing(24) + .into(), + }; + + column![head, search, body].spacing(24).width(Fill).into() +} + +fn tab_button<'a>(t: &'static Tokens, tab: Tab, s: &ServerScreen) -> Element<'a, Message> { + let on = s.tab == tab; + let count = match tab { + Tab::Albums => None, // Paged, so the count would only be what's loaded. + Tab::Artists => s.artists.get().map(Vec::len), + Tab::Playlists => s.playlists.get().map(Vec::len), + Tab::Starred => s.starred.get().map(|t| t.len()), + }; + let mut label = row![line(tab.label(), theme::MEDIUM, size::BODY, if on { t.fg } else { t.muted })] + .spacing(6) + .align_y(Alignment::Center); + if let Some(n) = count { + label = label.push(line(n.to_string(), theme::BODY, size::SMALL, t.muted)); + } + button( + column![label, container(space()).width(Fill).height(2).style(theme::tab_underline(on))] + .spacing(7) + .width(iced::Shrink), + ) + .padding([6, 10]) + .style(theme::tab(on)) + .on_press(send(Msg::Tab(tab))) + .into() +} + +fn tab_body<'a>(env: Env<'a>, s: &'a ServerScreen) -> Element<'a, Message> { + let t = env.t; + let retry = send(Msg::Retry); + match s.tab { + Tab::Albums => { + let sort = |label: &'static str, sort: AlbumSort| { + let on = s.sort == sort; + button(line(label, theme::MEDIUM, 13.5, if on { t.accent_ink } else { t.fg })) + .padding([7, 13]) + .style(theme::chip(on)) + .on_press_maybe((!on).then_some(send(Msg::Sort(sort)))) + }; + let chips = row![ + sort(tr("Recently added"), AlbumSort::Newest), + sort(tr("A–Z"), AlbumSort::AlphabeticalByName), + ] + .spacing(6); + let list = match &s.albums { + Loadable::Loaded(albums) if albums.is_empty() => empty(t, tr("The server has no albums yet.")), + Loadable::Loaded(albums) => { + let more = s.more.then(|| { + button(line( + if s.loading_more { tr("Loading…") } else { tr("Show more") }, + theme::MEDIUM, + size::BODY, + t.fg, + )) + .padding([9, 16]) + .style(theme::ghost) + .on_press_maybe((!s.loading_more).then_some(send(Msg::LoadMore))) + }); + column![card::grid(albums.iter().map(|a| album_card(t, env.covers, a)))] + .push(more) + .spacing(20) + .into() + } + other => status(t, other, tr("your albums"), retry), + }; + column![chips, list].spacing(20).into() + } + Tab::Artists => match &s.artists { + Loadable::Loaded(artists) if artists.is_empty() => empty(t, tr("The server has no artists yet.")), + Loadable::Loaded(artists) => card::grid(artists.iter().map(|a| artist_card(t, env.covers, a))), + other => status(t, other, tr("your artists"), retry), + }, + Tab::Playlists => match &s.playlists { + Loadable::Loaded(lists) if lists.is_empty() => { + empty(t, tr("No playlists yet. Playlists you make on the server show up here.")) + } + Loadable::Loaded(lists) => card::grid(lists.iter().map(|p| playlist_card(t, env.covers, p))), + other => status(t, other, tr("your playlists"), retry), + }, + Tab::Starred => match &s.starred { + Loadable::Loaded(tracks) if tracks.is_empty() => { + empty(t, tr("No starred songs yet. Star songs on the server and they show up here.")) + } + Loadable::Loaded(tracks) => track_section(env, tracks, Columns::FULL), + other => status(t, other, tr("your starred songs"), retry), + }, + } +} + +fn results<'a>(env: Env<'a>, found: &'a Load) -> Element<'a, Message> { + let t = env.t; + let found = match found { + Loadable::Loaded(found) => found, + other => return status(t, other, tr("the results"), send(Msg::Search)), + }; + if found.artists.is_empty() && found.albums.is_empty() && found.songs.is_empty() { + return empty(t, tr("Nothing on your server matches that.")); + } + let mut sections = column![].spacing(28); + if !found.artists.is_empty() { + sections = sections.push(section(t, tr("Artists"), card::grid(found.artists.iter().map(|a| artist_card(t, env.covers, a))))); + } + if !found.albums.is_empty() { + sections = sections.push(section(t, tr("Albums"), card::grid(found.albums.iter().map(|a| album_card(t, env.covers, a))))); + } + if !found.songs.is_empty() { + sections = sections.push(section(t, tr("Tracks"), track_list::view(env, &found.songs, Columns::FULL))); + } + sections.into() +} + +fn section<'a>(t: &'static Tokens, heading: &'a str, body: Element<'a, Message>) -> Element<'a, Message> { + column![line(heading, theme::SEMIBOLD, size::SECTION, t.fg), body].spacing(14).into() +} + +/// Play and Shuffle over a track list. +fn track_section<'a>(env: Env<'a>, tracks: &Arc<[Track]>, columns: Columns) -> Element<'a, Message> { + let total = tracks.iter().map(|t| t.duration).sum(); + column![ + play_bar(env.t, format!("{} · {}", tracks_word(tracks.len()), duration_words(total)), tracks), + track_list::view(env, tracks, columns), + ] + .spacing(22) + .into() +} + +fn cover(id: Option<&str>) -> Option { + id.map(|c| subsonic_cover_url(c, covers::LARGE)) +} + +fn album_card<'a>(t: &'static Tokens, covers: &Covers, a: &AlbumSummary) -> Element<'a, Message> { + card::view( + t, + covers, + Card { + title: a.name.clone(), + subtitle: a.subtitle(), + cover: cover(a.cover_art.as_deref()), + hues: hues_for(hash_str(&a.id)), + round: false, + on_press: Message::Navigate(Route::ServerAlbum(Sid::of(&a.id))), + menu: None, + }, + ) +} + +fn albums_word(n: u32) -> String { + counted(i64::from(n), ["album", "albums"], ["альбом", "альбома", "альбомов"]) +} + +fn artist_card<'a>(t: &'static Tokens, covers: &Covers, a: &ArtistSummary) -> Element<'a, Message> { + card::view( + t, + covers, + Card { + title: a.name.clone(), + subtitle: if a.album_count > 0 { albums_word(a.album_count) } else { tr("Artist").to_owned() }, + cover: cover(a.cover_art.as_deref()), + hues: hues_for(hash_str(&a.id)), + round: true, + on_press: Message::Navigate(Route::ServerArtist(Sid::of(&a.id))), + menu: None, + }, + ) +} + +fn playlist_card<'a>(t: &'static Tokens, covers: &Covers, p: &PlaylistSummary) -> Element<'a, Message> { + card::view( + t, + covers, + Card { + title: p.name.clone(), + subtitle: tracks_word(p.song_count as usize), + cover: cover(p.cover_art.as_deref()), + hues: hues_for(hash_str(&p.id)), + round: false, + on_press: Message::Navigate(Route::ServerPlaylist(Sid::of(&p.id))), + menu: None, + }, + ) +} + +/// An album, artist or playlist page. +pub fn page<'a>(env: Env<'a>, s: &'a ServerScreen, route: Route) -> Element<'a, Message> { + let t = env.t; + let (loading, gone, what) = match route { + Route::ServerAlbum(_) => (tr("Loading the album…"), tr("This album isn't on your server any more."), tr("the album")), + Route::ServerArtist(_) => (tr("Loading the artist…"), tr("This artist isn't on your server any more."), tr("the artist")), + _ => (tr("Loading the playlist…"), tr("This playlist isn't on your server any more."), tr("the playlist")), + }; + if s.client().is_none() { + return para(tr("Connect your server under My server to see this page."), size::BODY, t.muted).into(); + } + match s.pages.get(&route) { + Some(Loadable::Loaded(Page::Album { info, tracks })) => album_page(env, info, tracks), + Some(Loadable::Loaded(Page::Artist { info, albums })) => artist_page(env, info, albums), + Some(Loadable::Loaded(Page::Playlist { info, tracks })) => playlist_page(env, info, tracks), + Some(Loadable::Failed(Error::NotFound(_))) => para(gone, size::BODY, t.muted).into(), + Some(failed @ Loadable::Failed(_)) => status(t, failed, what, Message::Navigate(route)), + _ => para(loading, size::BODY, t.muted).into(), + } +} + +fn length(tracks: &[Track]) -> String { + format!("{} · {}", tracks_word(tracks.len()), duration_words(tracks.iter().map(|t| t.duration).sum())) +} + +fn album_page<'a>(env: Env<'a>, info: &'a AlbumSummary, tracks: &'a Arc<[Track]>) -> Element<'a, Message> { + let t = env.t; + let by: Option> = info.artist.as_ref().map(|name| { + let label = line(name.as_str(), theme::MEDIUM, size::BODY, t.fg); + match &info.artist_id { + Some(id) => button(label) + .padding(0) + .style(theme::tab(true)) + .on_press(Message::Navigate(Route::ServerArtist(Sid::of(id)))) + .into(), + None => label.into(), + } + }); + column![ + head(env, Head { + cover: cover(info.cover_art.as_deref()), + hues: hues_for(hash_str(&info.id)), + round: false, + kind: match info.year { + Some(year) => format!("{} · {year}", tr("Album")), + None => tr("Album").to_owned(), + }, + title: info.name.clone(), + by, + meta: length(tracks), + actions: vec![], + }), + play_bar(t, String::new(), tracks), + track_list::view(env, tracks, Columns::ALBUM_PAGE), + ] + .spacing(28) + .into() +} + +fn artist_page<'a>(env: Env<'a>, info: &'a ArtistSummary, albums: &'a [AlbumSummary]) -> Element<'a, Message> { + let t = env.t; + let count = u32::try_from(albums.len()).unwrap_or(u32::MAX); + column![ + head(env, Head { + cover: cover(info.cover_art.as_deref()), + hues: hues_for(hash_str(&info.id)), + round: true, + kind: tr("Artist").to_owned(), + title: info.name.clone(), + by: None, + meta: albums_word(count), + actions: vec![], + }), + section(t, tr("Albums"), card::grid(albums.iter().map(|a| album_card(t, env.covers, a)))), + ] + .spacing(28) + .into() +} + +fn playlist_page<'a>(env: Env<'a>, info: &'a PlaylistSummary, tracks: &'a Arc<[Track]>) -> Element<'a, Message> { + let t = env.t; + column![ + head(env, Head { + cover: cover(info.cover_art.as_deref()), + hues: hues_for(hash_str(&info.id)), + round: false, + kind: tr("Playlist").to_owned(), + title: info.name.clone(), + by: info.owner.as_ref().map(|o| line(o.as_str(), theme::MEDIUM, size::BODY, t.fg).into()), + meta: length(tracks), + actions: vec![], + }), + track_section(env, tracks, Columns::FULL), + ] + .spacing(28) + .into() +} + +/// Loading text, or a failure with a retry button. +fn status<'a, T>(t: &'static Tokens, state: &Load, what: &str, retry: Message) -> Element<'a, Message> { + let Loadable::Failed(e) = state else { + return para(trf("Loading {}…", &[&what]), size::BODY, t.muted).into(); + }; + let text = match e { + Error::Network(_) => trf("Couldn't load {}. Check your connection and try again.", &[&what]), + Error::Unauthorized(_) => tr("The server no longer accepts your sign-in. Disconnect it in Settings and connect again.").to_owned(), + _ => trf("Couldn't load {}. Try again in a moment.", &[&what]), + }; + column![ + para(text, size::BODY, t.muted), + button(line(tr("Try again"), theme::SEMIBOLD, size::BODY, t.accent_ink)) + .padding([11, 18]) + .style(theme::primary) + .on_press(retry), + ] + .spacing(16) + .into() +} + +fn empty<'a>(t: &'static Tokens, text: &'static str) -> Element<'a, Message> { + para(text, size::BODY, t.muted).into() +} + +/// Address, username and password, as on the My server page and in Settings. +pub fn connect_form<'a>(t: &'static Tokens, form: &'a Form) -> Element<'a, Message> { + let can = !form.busy && !form.url.trim().is_empty() && !form.username.trim().is_empty(); + let submit = can.then_some(send(Msg::Connect)); + let field = |label: &'static str, placeholder: &'static str, value: &'a str, on: fn(String) -> Msg, secure: bool| { + column![ + line(label, theme::MEDIUM, size::META, t.muted), + text_input(placeholder, value) + .on_input(move |v| send(on(v))) + .on_submit_maybe(submit.clone()) + .secure(secure) + .font(theme::BODY) + .size(size::BODY) + .padding([10, 14]) + .width(Fill) + .style(theme::search_field), + ] + .spacing(6) + }; + let connect = button(line( + if form.busy { tr("Connecting…") } else { tr("Connect") }, + theme::SEMIBOLD, + size::BODY, + t.accent_ink, + )) + .padding([11, 18]) + .style(theme::primary) + .on_press_maybe(submit.clone()); + + column![ + field(tr("Server address"), "music.example.com", &form.url, Msg::Url, false), + field(tr("Username"), "", &form.username, Msg::Username, false), + field(tr("Password"), "", &form.password, Msg::Password, true), + row![connect].push(form.error.map(|e| para(e, size::META, t.like))).spacing(14).align_y(Alignment::Center), + ] + .spacing(14) + .max_width(420) + .into() +} + +/// The My server card in Settings. +pub fn settings_section<'a>(t: &'static Tokens, s: &'a ServerScreen) -> Element<'a, Message> { + match &s.conn { + Conn::Restoring => para(tr("Checking your server…"), size::META, t.muted).into(), + Conn::Unconfigured => column![ + para( + tr("Browse and play a Navidrome or other Subsonic-compatible server under My server. The password is kept in the system keychain."), + size::META, + t.muted, + ), + connect_form(t, &s.form), + ] + .spacing(14) + .into(), + Conn::Ready(client) => row![ + para(trf("Connected to {} as {}.", &[&client.host(), &client.username()]), size::BODY, t.fg).width(Fill), + button(line(tr("Disconnect"), theme::MEDIUM, size::BODY, t.fg)) + .padding([9, 16]) + .style(theme::ghost) + .on_press(send(Msg::Disconnect)), + ] + .spacing(12) + .align_y(Alignment::Center) + .into(), + } +} + +#[cfg(test)] +mod tests { + use super::*; + + fn ready() -> ServerScreen { + let config = Config { url: "http://10.0.0.2:4533".into(), username: "yp".into(), password: "pw".into() }; + let mut s = ServerScreen::default(); + let _ = s.update(Msg::Restored(Ok(Some(config)))); + s + } + + fn album(id: &str) -> AlbumSummary { + AlbumSummary { + id: id.into(), + name: format!("Album {id}"), + artist: Some("Kino".into()), + artist_id: Some("ar1".into()), + cover_art: None, + song_count: 1, + duration: std::time::Duration::from_secs(60), + year: None, + } + } + + #[test] + fn stored_config_restores_a_connection_without_the_password_in_the_form() { + let s = ready(); + assert_eq!(s.client().map(Client::host).as_deref(), Some("10.0.0.2:4533")); + assert_eq!((s.form.url.as_str(), s.form.username.as_str(), s.form.password.as_str()), ("http://10.0.0.2:4533", "yp", "")); + let mut none = ServerScreen::default(); + let _ = none.update(Msg::Restored(Ok(None))); + assert!(none.client().is_none() && matches!(none.conn, Conn::Unconfigured)); + } + + #[test] + fn loaded_lists_make_their_routes_resolvable() { + let mut s = ready(); + let epoch = s.epoch; + let _ = s.update(Msg::AlbumsLoaded { epoch, sort: AlbumSort::Newest, offset: 0, result: Ok(vec![album("a1")]) }); + assert_eq!(s.ids.get(&Sid::of("a1")).map(String::as_str), Some("a1")); + assert_eq!(s.ids.get(&Sid::of("ar1")).map(String::as_str), Some("ar1"), "the album's artist too"); + assert!(!s.more, "a short page is the last"); + let task = s.enter(Route::ServerAlbum(Sid::of("a1"))); + assert!(matches!(s.pages.get(&Route::ServerAlbum(Sid::of("a1"))), Some(Loadable::Loading))); + drop(task); + let _ = s.enter(Route::ServerAlbum(Sid::of("never-seen"))); + assert!(matches!(s.pages.get(&Route::ServerAlbum(Sid::of("never-seen"))), Some(Loadable::Failed(Error::NotFound(_))))); + } + + #[test] + fn replies_from_a_previous_connection_or_sort_are_dropped() { + let mut s = ready(); + let old = s.epoch; + let _ = s.update(Msg::Disconnect); + assert!(s.client().is_none()); + let _ = s.update(Msg::AlbumsLoaded { epoch: old, sort: AlbumSort::Newest, offset: 0, result: Ok(vec![album("a1")]) }); + assert!(matches!(s.albums, Loadable::NotLoaded)); + + let mut s = ready(); + let _ = s.update(Msg::Sort(AlbumSort::AlphabeticalByName)); + let epoch = s.epoch; + let _ = s.update(Msg::AlbumsLoaded { epoch, sort: AlbumSort::Newest, offset: 0, result: Ok(vec![album("a1")]) }); + assert!(matches!(s.albums, Loadable::Loading), "the A–Z list is still coming"); + } + + #[test] + fn more_albums_append_and_a_failed_page_keeps_the_list() { + let mut s = ready(); + let epoch = s.epoch; + let full: Vec<_> = (0..PAGE).map(|i| album(&i.to_string())).collect(); + let _ = s.update(Msg::AlbumsLoaded { epoch, sort: AlbumSort::Newest, offset: 0, result: Ok(full) }); + assert!(s.more); + let _ = s.update(Msg::LoadMore); + assert!(s.loading_more); + let _ = s.update(Msg::AlbumsLoaded { epoch, sort: AlbumSort::Newest, offset: PAGE, result: Err(Error::Network("x".into())) }); + assert_eq!(s.albums.get().map(Vec::len), Some(PAGE)); + assert!(!s.loading_more); + let _ = s.update(Msg::AlbumsLoaded { epoch, sort: AlbumSort::Newest, offset: PAGE, result: Ok(vec![album("last")]) }); + assert_eq!(s.albums.get().map(Vec::len), Some(PAGE + 1)); + assert!(!s.more); + } + + #[test] + fn songs_become_server_tracks() { + let mut s = ready(); + let song = Song { + id: "s1".into(), + title: "Kukushka".into(), + artist: Some("Kino".into()), + artist_id: Some("ar1".into()), + album: Some("Chorny Albom".into()), + album_id: Some("al1".into()), + duration: std::time::Duration::from_secs(402), + track: Some(3), + disc: None, + cover_art: Some("al-al1".into()), + suffix: "flac".into(), + bit_rate: 1000, + }; + let track = s.track(song); + assert_eq!(track.id, "sub-s1"); + assert_eq!(track.album_title(), Some("Chorny Albom")); + assert_eq!(track.subsonic().map(|s| s.song_id.as_str()), Some("s1")); + assert!(s.ids.contains_key(&Sid::of("al1")) && s.ids.contains_key(&Sid::of("ar1"))); + } + + #[test] + fn connect_needs_an_address_and_a_name() { + let mut s = ServerScreen::default(); + let _ = s.update(Msg::Restored(Ok(None))); + let _ = s.update(Msg::Connect); + assert!(s.form.error.is_some() && !s.form.busy); + let _ = s.update(Msg::Url("ftp://nope".into())); + let _ = s.update(Msg::Username("yp".into())); + let _ = s.update(Msg::Connect); + assert!(!s.form.busy, "a bad address never leaves the form"); + let _ = s.update(Msg::Url("music.example.com".into())); + let _ = s.update(Msg::Connect); + assert!(s.form.busy && s.form.error.is_none()); + let config = Config { url: "music.example.com".into(), username: "yp".into(), password: String::new() }; + let _ = s.update(Msg::Checked(config, Err(Error::Unauthorized("no".into())))); + assert!(!s.form.busy && s.client().is_none()); + assert_eq!(s.form.error, Some(tr("The server didn't accept that username and password."))); + } +} diff --git a/crates/musyx/src/screens/settings.rs b/crates/musyx/src/screens/settings.rs index 1975519..cf035fd 100644 --- a/crates/musyx/src/screens/settings.rs +++ b/crates/musyx/src/screens/settings.rs @@ -9,7 +9,12 @@ use crate::ui::theme::{self, Tokens, size}; use crate::ui::{line, para}; use crate::i18n::{tr, trf}; -pub fn view<'a>(t: &'static Tokens, settings: &Settings, account: Element<'a, Message>) -> Element<'a, Message> { +pub fn view<'a>( + t: &'static Tokens, + settings: &Settings, + account: Element<'a, Message>, + server: Element<'a, Message>, +) -> Element<'a, Message> { let quality = Row::with_children(Quality::ALL.map(|q| chip(t, q.label(), q == settings.quality, Message::SetQuality(q)))) .spacing(6); let appearance = @@ -23,6 +28,7 @@ pub fn view<'a>(t: &'static Tokens, settings: &Settings, account: Element<'a, Me line(tr("Settings"), theme::DISPLAY, size::DISPLAY_S, t.fg), account, section(t, tr("Streaming quality"), column![quality, para(settings.quality.detail(), size::META, t.muted)].spacing(10).into()), + section(t, tr("My server"), server), section(t, tr("Appearance"), appearance.into()), section(t, tr("Language"), language.into()), section( diff --git a/crates/musyx/src/session.rs b/crates/musyx/src/session.rs index 20a4bc1..61b9b66 100644 --- a/crates/musyx/src/session.rs +++ b/crates/musyx/src/session.rs @@ -109,3 +109,45 @@ async fn forget(reason: Error) -> Restored { } Restored::SignedOut } + +/// The music server's address and sign-in, kept in the keychain next to the +/// Yandex credentials (the password is a secret like the token). +pub mod server { + use subsonic_api::Config; + + use super::blocking; + + const ACCOUNT: &str = "subsonic"; + + fn entry() -> Result { + keyring::Entry::new(super::SERVICE, ACCOUNT).map_err(|e| e.to_string()) + } + + pub async fn load() -> Result, String> { + blocking(|| { + let raw = match entry()?.get_password() { + Ok(raw) => raw, + Err(keyring::Error::NoEntry) => return Ok(None), + Err(e) => return Err(e.to_string()), + }; + Ok(serde_json::from_str(&raw).ok()) + }) + .await + } + + pub async fn save(config: Config) -> Result<(), String> { + blocking(move || { + let json = serde_json::to_string(&config).map_err(|e| e.to_string())?; + entry()?.set_password(&json).map_err(|e| e.to_string()) + }) + .await + } + + pub async fn clear() -> Result<(), String> { + blocking(|| match entry()?.delete_credential() { + Ok(()) | Err(keyring::Error::NoEntry) => Ok(()), + Err(e) => Err(e.to_string()), + }) + .await + } +} diff --git a/crates/musyx/src/shortcuts.rs b/crates/musyx/src/shortcuts.rs index 8ba6333..205eef5 100644 --- a/crates/musyx/src/shortcuts.rs +++ b/crates/musyx/src/shortcuts.rs @@ -97,7 +97,7 @@ pub fn from_key(key: &Key, physical: Physical, mods: Modifiers, repeat: bool) -> 'p' => S::NowPlaying, '[' => S::Back, ',' => S::Go(Route::Settings), - '1'..='5' => S::Go(Route::NAV[c as usize - '1' as usize]), + '1'..='6' => S::Go(Route::NAV[c as usize - '1' as usize]), _ => return None, }) } @@ -134,7 +134,7 @@ pub fn help() -> Vec<(&'static str, Vec)> { (tr("Search"), vec![with(cmd, "F"), "/".to_owned()]), (tr("Go back"), vec![with(cmd, "["), with(alt, "←")]), (tr("Close a menu or panel"), vec!["Esc".to_owned()]), - (tr("Home, My Wave, Search, Collection, Podcasts"), vec![format!("{cmd}1 … {cmd}5")]), + (tr("Home, My Wave, Search, Collection, My server, Podcasts"), vec![format!("{cmd}1 … {cmd}6")]), (tr("Settings"), vec![with(cmd, ",")]), ] } @@ -198,8 +198,9 @@ mod tests { #[test] fn number_keys_open_the_sidebar_sections() { assert_eq!(press(ch("1"), Code::Digit1, Modifiers::COMMAND), Some(Shortcut::Go(Route::Home))); - assert_eq!(press(ch("5"), Code::Digit5, Modifiers::COMMAND), Some(Shortcut::Go(Route::Podcasts))); - assert_eq!(press(ch("6"), Code::Digit6, Modifiers::COMMAND), None); + assert_eq!(press(ch("5"), Code::Digit5, Modifiers::COMMAND), Some(Shortcut::Go(Route::Server))); + assert_eq!(press(ch("6"), Code::Digit6, Modifiers::COMMAND), Some(Shortcut::Go(Route::Podcasts))); + assert_eq!(press(ch("7"), Code::Digit7, Modifiers::COMMAND), None); assert_eq!(press(ch(","), Code::Comma, Modifiers::COMMAND), Some(Shortcut::Go(Route::Settings))); } diff --git a/crates/musyx/src/snapshot.rs b/crates/musyx/src/snapshot.rs index 505a08c..990203f 100644 --- a/crates/musyx/src/snapshot.rs +++ b/crates/musyx/src/snapshot.rs @@ -60,6 +60,7 @@ impl Config { "wave" => Route::Wave, "search" => Route::Search, "collection" => Route::Collection, + "server" => Route::Server, "podcasts" => Route::Podcasts, "settings" => Route::Settings, "album" => Route::Album(1), diff --git a/crates/musyx/src/ui/icons.rs b/crates/musyx/src/ui/icons.rs index 8fbb35a..7100fe3 100644 --- a/crates/musyx/src/ui/icons.rs +++ b/crates/musyx/src/ui/icons.rs @@ -33,6 +33,7 @@ icons! { Wave => "audio-lines", Search => "search", Library => "library", + Server => "server", Podcast => "podcast", Plus => "plus", LogOut => "log-out", diff --git a/crates/musyx/src/widgets/menu.rs b/crates/musyx/src/widgets/menu.rs index 480182b..544b3bd 100644 --- a/crates/musyx/src/widgets/menu.rs +++ b/crates/musyx/src/widgets/menu.rs @@ -8,7 +8,7 @@ use ym_api::{AlbumSummary, ArtistSummary, PlaylistId, PlaylistSummary, Track}; use crate::app::Message; use crate::i18n::{tr, trf}; -use crate::route::Route; +use crate::route::{Route, Sid}; use crate::ui::icons::{Icon, icon}; use crate::ui::line; use crate::ui::theme::{self, Tokens, radius, size}; @@ -138,6 +138,9 @@ pub fn groups(target: &Target, ctx: &Ctx<'_>) -> Vec> { } fn track_groups(track: &Track, from: Source, ctx: &Ctx<'_>) -> Vec> { + if let Some(song) = track.subsonic() { + return server_track_groups(track, song, from, ctx); + } let playable = |e: Entry| if track.available { e } else { Entry { action: Action::Disabled, ..e } }; let queue_group = match from { Source::Queue { pos } => vec![ @@ -193,6 +196,37 @@ fn track_groups(track: &Track, from: Source, ctx: &Ctx<'_>) -> Vec> { groups } +/// A song from the music server: queueing and its album and artist there. +/// Likes, playlists and recommendations are Yandex's and don't apply. +fn server_track_groups(track: &Track, song: &ym_api::SubsonicSong, from: Source, ctx: &Ctx<'_>) -> Vec> { + let queue_group = match from { + Source::Queue { pos } => vec![ + entry(Icon::Play, tr("Play now"), Message::Player(crate::player::Msg::JumpTo(pos))), + entry(Icon::Next, tr("Play next"), Message::PlayNext(track.clone())), + entry(Icon::Close, tr("Remove from queue"), Message::Player(crate::player::Msg::Remove { pos, id: track.id.clone() })), + ], + _ => vec![ + if ctx.playing { + entry(Icon::Next, tr("Next track"), Message::SkipFromMenu) + } else { + entry(Icon::Next, tr("Play next"), Message::PlayNext(track.clone())) + }, + entry(Icon::Queue, tr("Add to queue"), Message::AddToQueue(track.clone())), + ], + }; + let mut go = Vec::new(); + if let Some(album) = &song.album_id { + go.push(entry(Icon::Disc, tr("Go to album"), Message::Navigate(Route::ServerAlbum(Sid::of(album))))); + } + if let (Some(artist), Some(name)) = (&song.artist_id, track.artists.first()) { + let label = trf("Go to {}", &[&shorten(&name.name)]); + go.push(entry(Icon::Artist, label, Message::Navigate(Route::ServerArtist(Sid::of(artist))))); + } + let mut groups = vec![queue_group, go]; + groups.retain(|g| !g.is_empty()); + groups +} + fn play_group(route: Route) -> Vec { vec![ entry(Icon::Play, tr("Play"), Message::PlayRoute { route, shuffle: false }), @@ -466,6 +500,24 @@ mod tests { groups(&Target::Track { track: track(r#","available":false"#), from: Source::List { playlist: None } }, &ctx()) } + #[test] + fn server_tracks_only_queue_and_link_to_their_server_pages() { + let song = ym_api::SubsonicSong { + song_id: "s1".into(), + album_id: Some("al1".into()), + album_title: Some("A".into()), + artist_id: Some("ar1".into()), + cover_art: None, + suffix: "mp3".into(), + bit_rate: 320, + }; + let t = Track::from_subsonic("T".into(), Some("Kino".into()), std::time::Duration::from_secs(60), song); + let groups = groups(&Target::Track { track: t, from: Source::List { playlist: None } }, &ctx()); + assert_eq!(labels(&groups), [vec!["Play next", "Add to queue"], vec!["Go to album", "Go to Kino"]]); + assert!(matches!(&groups[1][0].action, + Action::Send(m) if matches!(&**m, Message::Navigate(Route::ServerAlbum(sid)) if *sid == Sid::of("al1")))); + } + #[test] fn long_artist_names_are_shortened_and_at_most_three_listed() { let names: Vec = (0..5).map(|i| format!(r#"{{"id":{i},"name":"Очень длинное имя исполнителя номер {i}"}}"#)).collect(); diff --git a/crates/musyx/src/widgets/now_playing.rs b/crates/musyx/src/widgets/now_playing.rs index 0853263..7025ce0 100644 --- a/crates/musyx/src/widgets/now_playing.rs +++ b/crates/musyx/src/widgets/now_playing.rs @@ -113,8 +113,8 @@ fn info<'a>( info = info .push(text(track.full_title()).font(theme::DISPLAY).size(size::DISPLAY_M).color(t.fg).line_height(1.2)) .push(line(track.artist_line(), theme::SEMIBOLD, size::SECTION, t.fg)); - if let Some(album) = track.album.as_ref().filter(|a| !a.title.is_empty()) { - info = info.push(line(album.title.as_str(), theme::BODY, size::BODY, t.muted)); + if let Some(album) = track.album_title() { + info = info.push(line(album, theme::BODY, size::BODY, t.muted)); } if let Some(notice) = &p.notice && matches!(p.status(), Status::Loading | Status::Paused) @@ -207,13 +207,13 @@ fn controls<'a>( .spacing(10) .align_y(Alignment::Center); - let heart = button(icon( - if liked { Icon::HeartFilled } else { Icon::Heart }, - if liked { t.like } else { t.muted }, - )) - .padding(8) - .style(theme::icon_button(None)) - .on_press(Message::LikeTrack(track.clone(), !liked)); + // Only Yandex tracks can be liked. + let heart = track.is_yandex().then(|| { + button(icon(if liked { Icon::HeartFilled } else { Icon::Heart }, if liked { t.like } else { t.muted })) + .padding(8) + .style(theme::icon_button(None)) + .on_press(Message::LikeTrack(track.clone(), !liked)) + }); // The anchor takes the click and reports where the button is, so the menu hangs under it. let target = Target::Track { track: track.clone(), from: Source::PlayerBar }; @@ -238,25 +238,26 @@ fn controls<'a>( }; let volume = if p.muted { 0.0 } else { p.volume }; - row![ - transport, - space().width(Fill), - heart, - more, - pill(Icon::Queue, Panel::Queue, tr("Queue")), - pill(Icon::Lyrics, Panel::Lyrics, tr("Lyrics")), - button(icon(if p.muted { Icon::Muted } else { Icon::Volume }, t.muted)) - .padding(8) - .style(theme::icon_button(None)) - .on_press(send(Msg::ToggleMute)), - slider(0.0..=1.0, volume, |v| Message::Player(Msg::SetVolume(v))) - .step(0.01_f32) - .width(if narrow { 72 } else { 110 }) - .style(theme::volume_bar), - ] - .spacing(8) - .align_y(Alignment::Center) - .into() + row![transport, space().width(Fill)] + .push(heart) + .push(more) + .push(pill(Icon::Queue, Panel::Queue, tr("Queue"))) + .push(pill(Icon::Lyrics, Panel::Lyrics, tr("Lyrics"))) + .push( + button(icon(if p.muted { Icon::Muted } else { Icon::Volume }, t.muted)) + .padding(8) + .style(theme::icon_button(None)) + .on_press(send(Msg::ToggleMute)), + ) + .push( + slider(0.0..=1.0, volume, |v| Message::Player(Msg::SetVolume(v))) + .step(0.01_f32) + .width(if narrow { 72 } else { 110 }) + .style(theme::volume_bar), + ) + .spacing(8) + .align_y(Alignment::Center) + .into() } /// The cover's blurred copy stretched over the window, washed with the ground. Until the diff --git a/crates/musyx/src/widgets/player_bar.rs b/crates/musyx/src/widgets/player_bar.rs index bc66634..c1bc90e 100644 --- a/crates/musyx/src/widgets/player_bar.rs +++ b/crates/musyx/src/widgets/player_bar.rs @@ -88,24 +88,25 @@ fn now_playing<'a>(t: &'static Tokens, p: &'a Player, liked: bool, covers: &Cove .on_press(|_| Message::ShowNowPlaying(true)) .on_right_press(move |at| Message::OpenMenu(Box::new(Menu::new(target.clone(), Anchor::Point(at))))); - row![ - about, - button(icon( - if liked { Icon::HeartFilled } else { Icon::Heart }, - if liked { t.like } else { t.muted }, - )) - .padding(8) - .style(theme::icon_button(None)) - .on_press(Message::LikeTrack(track.clone(), !liked)), - button(icon(Icon::Dislike, t.muted)) - .padding(8) - .style(theme::icon_button(None)) - .on_press(Message::DislikeTrack(track.clone(), true)), - ] - .spacing(12) - .align_y(Alignment::Center) - .clip(true) - .into() + // Likes and dislikes are Yandex's; tracks from the music server have neither. + let yandex = track.is_yandex(); + row![about] + .push(yandex.then(|| { + button(icon(if liked { Icon::HeartFilled } else { Icon::Heart }, if liked { t.like } else { t.muted })) + .padding(8) + .style(theme::icon_button(None)) + .on_press(Message::LikeTrack(track.clone(), !liked)) + })) + .push(yandex.then(|| { + button(icon(Icon::Dislike, t.muted)) + .padding(8) + .style(theme::icon_button(None)) + .on_press(Message::DislikeTrack(track.clone(), true)) + })) + .spacing(12) + .align_y(Alignment::Center) + .clip(true) + .into() } fn transport<'a>(t: &'static Tokens, p: &'a Player) -> Element<'a, Message> { diff --git a/crates/musyx/src/widgets/track_row.rs b/crates/musyx/src/widgets/track_row.rs index 700f7cb..f8d5881 100644 --- a/crates/musyx/src/widgets/track_row.rs +++ b/crates/musyx/src/widgets/track_row.rs @@ -36,6 +36,8 @@ impl Columns { } const GRIP: f32 = 20.0; +/// The heart button's width: an icon and its padding. +const LIKE_SLOT: f32 = theme::shell::ICON + 16.0; pub struct Row<'a> { pub index: usize, @@ -102,7 +104,7 @@ pub fn view(t: &'static Tokens, r: Row<'_>) -> Element<'static, Message> { if r.columns.album { content = content.push( container(line( - track.album.as_ref().map(|a| a.title.clone()).unwrap_or_default(), + track.album_title().unwrap_or_default().to_owned(), theme::BODY, size::META, t.muted, @@ -111,16 +113,21 @@ pub fn view(t: &'static Tokens, r: Row<'_>) -> Element<'static, Message> { .clip(true), ); } + // Server tracks can't be liked; an empty slot keeps the columns lined up. + let heart: Element<'static, Message> = if track.is_yandex() { + button(icon( + if r.liked { Icon::HeartFilled } else { Icon::Heart }, + if r.liked { t.like } else { t.muted.scale_alpha(0.35) }, + )) + .padding(8) + .style(theme::icon_button(None)) + .on_press(r.on_like) + .into() + } else { + space().width(LIKE_SLOT).into() + }; content = content - .push( - button(icon( - if r.liked { Icon::HeartFilled } else { Icon::Heart }, - if r.liked { t.like } else { t.muted.scale_alpha(0.35) }, - )) - .padding(8) - .style(theme::icon_button(None)) - .on_press(r.on_like), - ) + .push(heart) .push( container(line(clock(track.duration.as_secs_f32()), theme::BODY, size::META, t.muted)) .width(52) diff --git a/crates/subsonic-api/Cargo.toml b/crates/subsonic-api/Cargo.toml new file mode 100644 index 0000000..a2bb049 --- /dev/null +++ b/crates/subsonic-api/Cargo.toml @@ -0,0 +1,21 @@ +[package] +name = "subsonic-api" +description = "Client for Subsonic-compatible music servers such as Navidrome" +version.workspace = true +edition.workspace = true +license.workspace = true +publish.workspace = true + +[dependencies] +reqwest = { version = "0.12", default-features = false, features = ["json", "rustls-tls"] } +serde = { version = "1", features = ["derive"] } +serde_json = "1" +thiserror = "2" +md-5 = "0.10" +rand = "0.9" + +[dev-dependencies] +tokio = { version = "1", features = ["macros", "rt-multi-thread"] } + +[lints] +workspace = true diff --git a/crates/subsonic-api/src/client.rs b/crates/subsonic-api/src/client.rs new file mode 100644 index 0000000..811ce25 --- /dev/null +++ b/crates/subsonic-api/src/client.rs @@ -0,0 +1,584 @@ +//! Requests, authentication and the `subsonic-response` envelope. + +use std::time::{Duration, SystemTime, UNIX_EPOCH}; + +use md5::{Digest, Md5}; +use rand::Rng; +use rand::distr::Alphanumeric; +use reqwest::Url; +use serde::de::DeserializeOwned; +use serde::{Deserialize, Serialize}; + +use crate::models::{ + self, Album, AlbumSummary, Artist, ArtistSummary, Playlist, PlaylistSummary, RawAlbum, RawArtist, + RawIndex, RawMixed, RawPlaylist, SearchResults, Song, +}; +use crate::{Error, Result}; + +/// The REST version Musyx speaks. 1.13 added token auth; 1.16.1 is what Navidrome reports. +const API_VERSION: &str = "1.16.1"; +const CLIENT_NAME: &str = "musyx"; +const API_TIMEOUT: Duration = Duration::from_secs(30); +/// Whole files are downloaded before playback; a long FLAC on a slow link takes a while. +const STREAM_TIMEOUT: Duration = Duration::from_secs(300); + +/// What the user types to connect. Stored in the system keychain as JSON. +#[derive(Clone, PartialEq, Eq, Serialize, Deserialize)] +pub struct Config { + pub url: String, + pub username: String, + pub password: String, +} + +/// The password stays out of logs. +impl std::fmt::Debug for Config { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + f.debug_struct("Config").field("url", &self.url).field("username", &self.username).finish_non_exhaustive() + } +} + +impl Config { + /// The server's `/rest/` base. Accepts what people paste: no scheme + /// (`music.example.com` means https), trailing slashes, or the web UI's + /// own address (`…/app/#/album/…`). + pub fn rest_base(&self) -> Result { + let raw = self.url.trim(); + if raw.is_empty() { + return Err(Error::InvalidUrl("empty".into())); + } + let with_scheme = if raw.contains("://") { raw.to_owned() } else { format!("https://{raw}") }; + let mut url = Url::parse(&with_scheme).map_err(|e| Error::InvalidUrl(e.to_string()))?; + if !matches!(url.scheme(), "http" | "https") || url.host_str().is_none() { + return Err(Error::InvalidUrl(format!("unsupported address {raw}"))); + } + url.set_query(None); + url.set_fragment(None); + let mut path = format!("{}/", url.path().trim_end_matches('/')); + // Everything from a pasted API path (`/rest/ping`) or the web UI (`/app/`) on. + for marker in ["/rest/", "/app/"] { + if let Some(i) = path.find(marker) { + path.truncate(i + 1); + } + } + let path = path.trim_end_matches('/'); + url.set_path(&format!("{path}/rest/")); + Ok(url) + } +} + +/// How to ask for a song's audio: the file as stored, when the player decodes +/// it and it fits the quality cap, or an MP3 the server transcodes. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub struct StreamPlan { + pub transcode: bool, + /// The cap sent as `maxBitRate`; also the label's bitrate when transcoding. + pub max_kbps: Option, + /// "mp3", "flac" or "aac-mp4", the codec names the player's decoder expects. + pub codec: &'static str, + pub bitrate_kbps: u32, +} + +impl StreamPlan { + /// `max_kbps: None` means no cap; `lossless` lets FLAC through untouched. + pub fn for_song(suffix: &str, bit_rate: u32, max_kbps: Option, lossless: bool) -> Self { + // Unknown bitrates only pass when there's no cap to break. + let fits = max_kbps.is_none_or(|cap| bit_rate != 0 && bit_rate <= cap); + let raw = |codec, bitrate_kbps| StreamPlan { transcode: false, max_kbps: None, codec, bitrate_kbps }; + match suffix { + "flac" if lossless => raw("flac", 0), + "mp3" if fits => raw("mp3", bit_rate), + "m4a" | "mp4" if fits => raw("aac-mp4", bit_rate), + _ => { + let cap = max_kbps.unwrap_or(320).min(320); + StreamPlan { transcode: true, max_kbps: Some(cap), codec: "mp3", bitrate_kbps: cap } + } + } + } +} + +/// A downloaded song, ready for the decoder. +#[derive(Clone)] +pub struct Audio { + pub bytes: Vec, + pub codec: &'static str, + pub bitrate_kbps: u32, +} + +impl std::fmt::Debug for Audio { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + f.debug_struct("Audio") + .field("codec", &self.codec) + .field("bitrate_kbps", &self.bitrate_kbps) + .field("bytes", &self.bytes.len()) + .finish() + } +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)] +pub enum AlbumSort { + /// Recently added to the library. + #[default] + Newest, + AlphabeticalByName, +} + +impl AlbumSort { + fn param(self) -> &'static str { + match self { + AlbumSort::Newest => "newest", + AlbumSort::AlphabeticalByName => "alphabeticalByName", + } + } +} + +/// A signed-in connection. Cheap to clone: the HTTP pool is shared. +#[derive(Clone)] +pub struct Client { + http: reqwest::Client, + base: Url, + username: String, + password: String, +} + +impl std::fmt::Debug for Client { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + f.debug_struct("Client").field("base", &self.base.as_str()).field("username", &self.username).finish_non_exhaustive() + } +} + +impl PartialEq for Client { + fn eq(&self, other: &Self) -> bool { + self.base == other.base && self.username == other.username && self.password == other.password + } +} + +impl Client { + /// Builds the client; nothing is sent until the first call (see [`Client::ping`]). + pub fn new(config: &Config) -> Result { + let base = config.rest_base()?; + let http = reqwest::Client::builder() + .connect_timeout(Duration::from_secs(10)) + .user_agent(concat!("musyx/", env!("CARGO_PKG_VERSION"))) + .build() + .map_err(|e| Error::Network(e.to_string()))?; + Ok(Self { http, base, username: config.username.trim().to_owned(), password: config.password.clone() }) + } + + pub fn username(&self) -> &str { + &self.username + } + + /// `music.example.com` or `10.0.0.2:4533`, for display. + pub fn host(&self) -> String { + let host = self.base.host_str().unwrap_or_default(); + match self.base.port() { + Some(port) => format!("{host}:{port}"), + None => host.to_owned(), + } + } + + fn url(&self, method: &str, params: &[(&str, &str)]) -> Url { + let salt: String = rand::rng().sample_iter(Alphanumeric).take(12).map(char::from).collect(); + self.url_with_salt(method, params, &salt) + } + + /// Token auth: `t = md5(password + salt)`, so the password never travels. + fn url_with_salt(&self, method: &str, params: &[(&str, &str)], salt: &str) -> Url { + let mut url = self.base.join(method).expect("method names are plain path segments"); + url.query_pairs_mut() + .append_pair("u", &self.username) + .append_pair("t", &token(&self.password, salt)) + .append_pair("s", salt) + .append_pair("v", API_VERSION) + .append_pair("c", CLIENT_NAME) + .append_pair("f", "json") + .extend_pairs(params); + url + } + + async fn call(&self, method: &str, params: &[(&str, &str)]) -> Result { + let body = self + .http + .get(self.url(method, params)) + .timeout(API_TIMEOUT) + .send() + .await? + .error_for_status()? + .text() + .await?; + unwrap_envelope(&body) + } + + /// Endpoints that answer with a file, or with an error envelope. + async fn bytes(&self, method: &str, params: &[(&str, &str)], timeout: Duration) -> Result> { + let reply = self.http.get(self.url(method, params)).timeout(timeout).send().await?.error_for_status()?; + let is_envelope = reply + .headers() + .get(reqwest::header::CONTENT_TYPE) + .and_then(|v| v.to_str().ok()) + .is_some_and(|ct| ct.contains("json") || ct.contains("xml")); + let body = reply.bytes().await?; + if is_envelope { + let text = String::from_utf8_lossy(&body); + unwrap_envelope::(&text)?; + return Err(Error::Api(format!("{method} answered with a message instead of a file"))); + } + Ok(body.to_vec()) + } + + /// Checks the address and the credentials. + pub async fn ping(&self) -> Result<()> { + self.call::("ping", &[]).await.map(drop) + } + + pub async fn albums(&self, sort: AlbumSort, offset: usize, size: usize) -> Result> { + let (offset, size) = (offset.to_string(), size.to_string()); + let reply: AlbumListReply = self + .call("getAlbumList2", &[("type", sort.param()), ("offset", &offset), ("size", &size)]) + .await?; + Ok(reply.resolve()) + } + + pub async fn album(&self, id: &str) -> Result { + let reply: AlbumReply = self.call("getAlbum", &[("id", id)]).await?; + reply.resolve() + } + + pub async fn artists(&self) -> Result> { + let reply: ArtistsReply = self.call("getArtists", &[]).await?; + Ok(reply.resolve()) + } + + pub async fn artist(&self, id: &str) -> Result { + let reply: ArtistReply = self.call("getArtist", &[("id", id)]).await?; + reply.resolve() + } + + pub async fn playlists(&self) -> Result> { + let reply: PlaylistsReply = self.call("getPlaylists", &[]).await?; + Ok(reply.resolve()) + } + + pub async fn playlist(&self, id: &str) -> Result { + let reply: PlaylistReply = self.call("getPlaylist", &[("id", id)]).await?; + reply.resolve() + } + + /// Starred songs, newest first as the server orders them. + pub async fn starred(&self) -> Result> { + let reply: StarredReply = self.call("getStarred2", &[]).await?; + Ok(reply.starred.resolve().songs) + } + + pub async fn search(&self, query: &str) -> Result { + let reply: SearchReply = self + .call( + "search3", + &[("query", query.trim()), ("artistCount", "12"), ("albumCount", "24"), ("songCount", "60")], + ) + .await?; + Ok(reply.result.resolve()) + } + + /// Cover image bytes at about `size` pixels square. + pub async fn cover_art(&self, id: &str, size: u32) -> Result> { + self.bytes("getCoverArt", &[("id", id), ("size", &size.to_string())], API_TIMEOUT).await + } + + /// Downloads a whole song as `plan` says. + pub async fn stream(&self, song_id: &str, plan: StreamPlan) -> Result