From 3b934df8ccace908867544e016f938c99e210d1a Mon Sep 17 00:00:00 2001 From: Yuriy Panov Date: Thu, 15 Oct 2026 14:51:51 +0600 Subject: [PATCH] feat: cover art cache, Collection tabs, and album, artist and playlist pages - ym-api: album/artist/playlist summaries and pages, liked albums and artists, own and liked playlists (batch-resolved from like ids), playlist tracks with missing ones looked up, image download - Cover cache: fetched when a cover nears the viewport (sensor), at most eight at once, kept in memory and on disk; arrivals are batched every 150 ms so cached lists rebuild once per batch - Collection tabs for liked tracks, albums, artists and playlists, each loading on first visit with a retry on failure - Album, Artist and Playlist routes with cover headers, Play/Shuffle and track lists; pages cached per session; sidebar lists playlists - Shared lazy track list keyed on contents, playing track, likes and cover version; card grid that wraps --- Cargo.lock | 38 +++ crates/musyx/Cargo.toml | 3 +- crates/musyx/src/app.rs | 290 +++++++++++++++------ crates/musyx/src/covers.rs | 181 +++++++++++++ crates/musyx/src/main.rs | 1 + crates/musyx/src/route.rs | 11 + crates/musyx/src/screens/collection.rs | 346 +++++++++++++++++++------ crates/musyx/src/screens/detail.rs | 229 ++++++++++++++++ crates/musyx/src/screens/mod.rs | 58 ++++- crates/musyx/src/snapshot.rs | 23 ++ crates/musyx/src/ui/mod.rs | 40 +++ crates/musyx/src/widgets/card.rs | 48 ++++ crates/musyx/src/widgets/drawer.rs | 10 +- crates/musyx/src/widgets/mod.rs | 2 + crates/musyx/src/widgets/player_bar.rs | 16 +- crates/musyx/src/widgets/sidebar.rs | 55 +++- crates/musyx/src/widgets/track_list.rs | 70 +++++ crates/musyx/src/widgets/track_row.rs | 141 ++++++---- crates/ym-api/src/client.rs | 100 +++++++ crates/ym-api/src/lib.rs | 5 + crates/ym-api/src/library.rs | 329 +++++++++++++++++++++++ crates/ym-api/src/models.rs | 24 +- 22 files changed, 1773 insertions(+), 247 deletions(-) create mode 100644 crates/musyx/src/covers.rs create mode 100644 crates/musyx/src/screens/detail.rs create mode 100644 crates/musyx/src/widgets/card.rs create mode 100644 crates/musyx/src/widgets/track_list.rs create mode 100644 crates/ym-api/src/library.rs diff --git a/Cargo.lock b/Cargo.lock index 6a5600d..b679fde 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1090,6 +1090,27 @@ dependencies = [ "ctutils", ] +[[package]] +name = "directories" +version = "6.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "16f5094c54661b38d03bd7e50df373292118db60b585c08a411c6d840017fe7d" +dependencies = [ + "dirs-sys", +] + +[[package]] +name = "dirs-sys" +version = "0.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e01a3366d27ee9890022452ee61b2b63a67e6f13f58900b651ff5665f0bb1fab" +dependencies = [ + "libc", + "option-ext", + "redox_users", + "windows-sys 0.61.2", +] + [[package]] name = "dispatch" version = "0.2.0" @@ -2860,6 +2881,7 @@ dependencies = [ name = "musyx" version = "0.1.0" dependencies = [ + "directories", "iced", "keyring", "open", @@ -3496,6 +3518,12 @@ dependencies = [ "libc", ] +[[package]] +name = "option-ext" +version = "0.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "04744f49eae99ab78e0d5c0b603ab218f515ea8cfe5a456d7629ad883a3b6e7d" + [[package]] name = "orbclient" version = "0.3.55" @@ -4138,6 +4166,16 @@ dependencies = [ "bitflags 2.13.2", ] +[[package]] +name = "redox_users" +version = "0.5.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "60dc65c0ff1a7ae1294b0c67b9f14baf70b644404010370171787bfac1038fc0" +dependencies = [ + "libredox", + "thiserror 2.0.21", +] + [[package]] name = "regex" version = "1.13.1" diff --git a/crates/musyx/Cargo.toml b/crates/musyx/Cargo.toml index 7c4c57a..fb4eee0 100644 --- a/crates/musyx/Cargo.toml +++ b/crates/musyx/Cargo.toml @@ -14,7 +14,8 @@ rodio = { version = "0.23.0", default-features = false, features = ["playback", rand = "0.9" open = "5.4.4" serde_json = "1" -tokio = { version = "1", features = ["time", "rt"] } +tokio = { version = "1", features = ["time", "rt", "fs", "sync"] } +directories = "6.0.0" png = { version = "0.18.1", optional = true } [features] diff --git a/crates/musyx/src/app.rs b/crates/musyx/src/app.rs index c5e4713..40f095b 100644 --- a/crates/musyx/src/app.rs +++ b/crates/musyx/src/app.rs @@ -1,19 +1,25 @@ //! Application state, messages and the window layout. +use std::collections::HashMap; +use std::sync::Arc; + use iced::theme::Mode; use iced::widget::{column, container, row, scrollable, space}; use iced::{Element, Fill, Subscription, Task, Theme}; use ym_api::auth::Credentials; -use ym_api::{Account, Error, YmClient}; +use ym_api::{Account, AlbumSummary, ArtistSummary, Error, LibraryPlaylists, Track, YmClient}; +use crate::covers::Covers; use crate::player::{self, Audio, Effect, Player}; use crate::route::{Navigator, Route}; -use crate::screens::collection::Liked; -use crate::screens::{self, sign_in}; +use crate::screens::collection::{Library, Liked, Tab}; +use crate::screens::detail::{self, Page}; +use crate::screens::{self, Loadable, sign_in}; use crate::session::{self, Restored}; use crate::ui::theme::{self, shell}; use crate::widgets::drawer::{self, Panel}; use crate::widgets::player_bar; +use crate::widgets::track_list::Env; use crate::widgets::{sidebar, topbar}; /// Where sign-in stands. Everything but `SignedIn` takes the whole window. @@ -36,7 +42,10 @@ pub struct App { search: String, drawer: Option, player: Player, - liked: Liked, + library: Library, + /// Album, artist and playlist pages visited this session. + pages: HashMap>, + covers: Covers, } #[derive(Debug, Clone)] @@ -56,9 +65,18 @@ pub enum Message { ToggleDrawer(Panel), CloseDrawer, Player(player::Msg), + PlayTracks { tracks: Arc<[Track]>, start: usize, shuffle: bool }, LoadLiked, - LikedLoaded(Result, Error>), - PlayLiked { start: usize, shuffle: bool }, + LikedLoaded(Result, Error>), + CollectionTab(Tab), + LoadLibrary(Tab), + AlbumsLoaded(Result, Error>), + ArtistsLoaded(Result, Error>), + PlaylistsLoaded(Result), + PageLoaded(Route, Result), + CoverWanted(String), + CoverLoaded(String, Option>), + CoversTick, } impl App { @@ -71,7 +89,9 @@ impl App { search: String::new(), drawer: None, player: Player::default(), - liked: Liked::NotLoaded, + library: Library::default(), + pages: HashMap::new(), + covers: Covers::default(), }; let appearance = iced::system::theme().map(Message::ThemeChanged); @@ -79,7 +99,8 @@ impl App { if let Some(config) = crate::snapshot::Config::from_env() { let mut app = app; app.session = config.session(); - app.liked = Liked::loaded(config.sample_liked(), &Liked::NotLoaded); + app.library.liked = Liked::loaded(config.sample_liked(), &Liked::NotLoaded); + app.pages.insert(Route::Album(1), Loadable::Loaded(config.sample_album())); if let Some(route) = config.route { app.nav = Navigator::new(route); } @@ -110,14 +131,35 @@ impl App { pub fn subscription(&self) -> Subscription { let appearance = iced::system::theme_changes().map(Message::ThemeChanged); let audio = player::engine::subscription().map(|e| Message::Player(player::Msg::Engine(e))); - match &self.session { - Session::SignedOut(sign_in) => Subscription::batch([ - appearance, - audio, - sign_in.subscription().map(Message::SignIn), - ]), - _ => Subscription::batch([appearance, audio]), + let mut subs = vec![appearance, audio]; + if let Session::SignedOut(sign_in) = &self.session { + subs.push(sign_in.subscription().map(Message::SignIn)); } + // Show arriving covers in batches instead of rebuilding lists for each one. + if self.covers.dirty() { + subs.push(iced::time::every(std::time::Duration::from_millis(150)).map(|_| Message::CoversTick)); + } + Subscription::batch(subs) + } + + fn client(&self) -> Option<&YmClient> { + match &self.session { + Session::SignedIn { client, .. } => Some(client), + _ => None, + } + } + + /// A rejected token ends the session; anything else is logged and shown by the caller. + fn failed(&mut self, what: &str, e: &Error) -> Option> { + eprintln!("{what}: {e}"); + matches!(e, Error::Unauthorized(_)).then(|| self.update(Message::SignOut)) + } + + fn signed_in(&mut self, client: YmClient, account: Account) -> Task { + self.nav = Navigator::new(Route::Home); + self.session = Session::SignedIn { client, account }; + // Liked tracks drive the hearts; playlists fill the sidebar. + Task::batch([self.update(Message::LoadLiked), self.update(Message::LoadLibrary(Tab::Playlists))]) } pub fn update(&mut self, message: Message) -> Task { @@ -129,14 +171,11 @@ impl App { self.session = Session::Restoring; return restore(); } - Message::Restored(restored) => { - self.session = match restored { - Restored::SignedIn(client, account) => Session::SignedIn { client, account }, - Restored::SignedOut => Session::SignedOut(Box::default()), - Restored::Unreachable => Session::Unreachable, - }; - return self.update(Message::LoadLiked); + Message::Restored(Restored::SignedIn(client, account)) => { + return self.signed_in(client, account); } + Message::Restored(Restored::SignedOut) => self.session = Session::SignedOut(Box::default()), + Message::Restored(Restored::Unreachable) => self.session = Session::Unreachable, Message::SignIn(msg) => { let Session::SignedOut(sign_in) = &mut self.session else { return Task::none(); @@ -150,11 +189,7 @@ impl App { } } } - Message::Connected(Ok((client, account))) => { - self.nav = Navigator::new(Route::Home); - self.session = Session::SignedIn { client, account }; - return self.update(Message::LoadLiked); - } + Message::Connected(Ok((client, account))) => return self.signed_in(client, account), Message::Connected(Err(e)) => { eprintln!("sign-in: {e}"); let pasted = matches!(self.session, Session::Connecting { pasted: true }); @@ -178,31 +213,27 @@ impl App { self.nav = Navigator::new(Route::Home); self.drawer = None; self.player.reset(); - self.liked = Liked::NotLoaded; + self.library = Library::default(); + self.pages.clear(); } Message::Navigate(route) => { self.nav.go(route); - if route == Route::Collection && matches!(self.liked, Liked::Failed(_)) { - return self.update(Message::LoadLiked); - } - // Settings shows the subscription, which can change outside the app. - if let (Route::Settings, Session::SignedIn { client, .. }) = (route, &self.session) { - let client = client.clone(); - return Task::future(async move { client.account().await }) - .map(Message::AccountRefreshed); - } + return self.on_enter(route); } Message::AccountRefreshed(Ok(fresh)) => { if let Session::SignedIn { account, .. } = &mut self.session { *account = fresh; } } - Message::AccountRefreshed(Err(Error::Unauthorized(e))) => { - eprintln!("token rejected: {e}"); - return self.update(Message::SignOut); + Message::AccountRefreshed(Err(e)) => { + if let Some(task) = self.failed("account refresh", &e) { + return task; + } + } + Message::Back => { + self.nav.back(); + return self.on_enter(self.nav.current()); } - Message::AccountRefreshed(Err(e)) => eprintln!("account refresh: {e}"), - Message::Back => self.nav.back(), Message::SearchChanged(query) => self.search = query, Message::SearchSubmitted => self.nav.go(Route::Search), Message::ToggleDrawer(panel) => { @@ -213,37 +244,140 @@ impl App { let effects = self.player.update(msg); return self.run(effects); } + Message::PlayTracks { tracks, start, shuffle } => { + return self.update(Message::Player(player::Msg::Play { + tracks, + start, + shuffle: shuffle.then_some(true), + })); + } Message::LoadLiked => { - let Session::SignedIn { client, .. } = &self.session else { return Task::none() }; - if matches!(self.liked, Liked::Loading) { + let Some(client) = self.client().cloned() else { return Task::none() }; + if matches!(self.library.liked, Liked::Loading) { return Task::none(); } - self.liked = Liked::Loading; - let client = client.clone(); + self.library.liked = Liked::Loading; return Task::future(async move { client.liked_tracks().await }).map(Message::LikedLoaded); } - Message::LikedLoaded(Ok(tracks)) => self.liked = Liked::loaded(tracks, &self.liked), - Message::LikedLoaded(Err(Error::Unauthorized(e))) => { - eprintln!("token rejected: {e}"); - return self.update(Message::SignOut); + Message::LikedLoaded(Ok(tracks)) => { + self.library.liked = Liked::loaded(tracks, &self.library.liked); } Message::LikedLoaded(Err(e)) => { - eprintln!("liked tracks: {e}"); - self.liked = Liked::Failed(e); - } - Message::PlayLiked { start, shuffle } => { - if let Some(tracks) = self.liked.tracks().cloned() { - return self.update(Message::Player(player::Msg::Play { - tracks, - start, - shuffle: shuffle.then_some(true), - })); + if let Some(task) = self.failed("liked tracks", &e) { + return task; } + self.library.liked = Liked::Failed(e); } + Message::CollectionTab(tab) => { + self.library.tab = tab; + return self.load_tab(tab); + } + Message::LoadLibrary(tab) => { + return match tab { + Tab::Tracks => self.update(Message::LoadLiked), + _ => self.force_load_tab(tab), + }; + } + Message::AlbumsLoaded(result) => { + if let Err(e) = &result + && let Some(task) = self.failed("liked albums", e) + { + return task; + } + self.library.albums = Loadable::from_result(result); + } + Message::ArtistsLoaded(result) => { + if let Err(e) = &result + && let Some(task) = self.failed("liked artists", e) + { + return task; + } + self.library.artists = Loadable::from_result(result); + } + Message::PlaylistsLoaded(result) => { + if let Err(e) = &result + && let Some(task) = self.failed("playlists", e) + { + return task; + } + self.library.playlists = Loadable::from_result(result); + } + Message::PageLoaded(route, result) => { + if let Err(e) = &result + && let Some(task) = self.failed("page", e) + { + return task; + } + self.pages.insert(route, Loadable::from_result(result)); + } + Message::CoverWanted(url) => { + let Some(client) = self.client().cloned() else { return Task::none() }; + return self.covers.want(url, &client); + } + Message::CoverLoaded(url, bytes) => self.covers.loaded(url, bytes), + Message::CoversTick => self.covers.flush(), } Task::none() } + /// Loads what a route shows on first visit, and retries after a failure. + fn on_enter(&mut self, route: Route) -> Task { + match route { + Route::Collection => { + let retry_liked = matches!(self.library.liked, Liked::Failed(_)); + let tab = self.load_tab(self.library.tab); + if retry_liked { Task::batch([tab, self.update(Message::LoadLiked)]) } else { tab } + } + // Settings shows the subscription, which can change outside the app. + Route::Settings => match self.client().cloned() { + Some(client) => { + Task::future(async move { client.account().await }).map(Message::AccountRefreshed) + } + None => Task::none(), + }, + Route::Album(_) | Route::Artist(_) | Route::Playlist(_) => { + if self.pages.get(&route).is_some_and(|p| !p.needs_load()) { + return Task::none(); + } + let Some(task) = self.client().and_then(|c| detail::load(c, route)) else { + return Task::none(); + }; + self.pages.insert(route, Loadable::Loading); + task + } + _ => Task::none(), + } + } + + fn load_tab(&mut self, tab: Tab) -> Task { + let needed = match tab { + Tab::Tracks => matches!(self.library.liked, Liked::NotLoaded), + Tab::Albums => self.library.albums.needs_load(), + Tab::Artists => self.library.artists.needs_load(), + Tab::Playlists => self.library.playlists.needs_load(), + }; + if needed { self.update(Message::LoadLibrary(tab)) } else { Task::none() } + } + + fn force_load_tab(&mut self, tab: Tab) -> Task { + let Some(client) = self.client().cloned() else { return Task::none() }; + match tab { + Tab::Tracks => Task::none(), + Tab::Albums => { + self.library.albums = Loadable::Loading; + Task::future(async move { client.liked_albums().await }).map(Message::AlbumsLoaded) + } + Tab::Artists => { + self.library.artists = Loadable::Loading; + Task::future(async move { client.liked_artists().await }).map(Message::ArtistsLoaded) + } + Tab::Playlists => { + self.library.playlists = Loadable::Loading; + Task::future(async move { client.library_playlists().await }).map(Message::PlaylistsLoaded) + } + } + } + pub fn view(&self) -> Element<'_, Message> { let t = theme::tokens(&self.theme); let page = match &self.session { @@ -258,27 +392,38 @@ impl App { fn shell<'a>(&'a self, t: &'static theme::Tokens, account: &'a Account) -> Element<'a, Message> { let route = self.nav.current(); + let env = Env { + t, + covers: &self.covers, + liked: &self.library.liked, + playing: self.player.track().map(|tr| tr.id.as_str()), + }; let content = column![ topbar::view(t, self.nav.can_go_back(), &self.search), scrollable(screens::view(screens::Ctx { - t, + env, route, query: &self.search, me: account, - liked: &self.liked, - playing: self.player.track().map(|tr| tr.id.as_str()), + library: &self.library, + pages: &self.pages, })) - .height(Fill) - .style(theme::scroll), + .height(Fill) + .style(theme::scroll), ] .width(Fill) .height(Fill); - let mut body = row![sidebar::view(t, route, account), vline(), content].height(Fill); + let mut body = row![ + sidebar::view(t, route, account, self.library.playlists.get(), &self.covers), + vline(), + content, + ] + .height(Fill); if let Some(panel) = self.drawer { - body = body.push(vline()).push(drawer::view(t, panel, &self.player)); + body = body.push(vline()).push(drawer::view(t, panel, &self.player, &self.covers)); } let window = column![ @@ -287,21 +432,20 @@ impl App { container(player_bar::view( t, &self.player, - self.player.track().is_some_and(|tr| self.liked.contains(&tr.id)), + self.player.track().is_some_and(|tr| self.library.liked.contains(&tr.id)), self.drawer, + &self.covers, )) - .height(shell::PLAYER) - .style(theme::panel), + .height(shell::PLAYER) + .style(theme::panel), ]; container(window).width(Fill).height(Fill).style(theme::app).into() } -} -impl App { /// Runs the player's requests against the API. fn run(&self, effects: Vec) -> Task { - let Session::SignedIn { client, .. } = &self.session else { return Task::none() }; + let Some(client) = self.client() else { return Task::none() }; Task::batch(effects.into_iter().map(|effect| match effect { Effect::Fetch { generation, track_id } => { let client = client.clone(); diff --git a/crates/musyx/src/covers.rs b/crates/musyx/src/covers.rs new file mode 100644 index 0000000..875ed1b --- /dev/null +++ b/crates/musyx/src/covers.rs @@ -0,0 +1,181 @@ +//! Cover art: fetched when a cover scrolls into view, kept in memory for the +//! session and on disk across sessions. +//! +//! Views never wait for images. A missing cover renders its placeholder inside +//! a `sensor`, and showing it sends [`Message::CoverWanted`]. + +use std::collections::{HashMap, HashSet}; +use std::path::PathBuf; +use std::sync::Arc; + +use iced::widget::{container, image, sensor, space}; +use iced::{Element, Task}; +use tokio::sync::Semaphore; +use ym_api::YmClient; + +use crate::app::Message; +use crate::ui::theme; + +/// Pixel sizes requested from Yandex. Rows and the player bar use `SMALL`, +/// cards and page headers `LARGE`; both cover 2× displays. +pub const SMALL: u32 = 100; +pub const LARGE: u32 = 400; + +/// Downloads in flight at once. +const PARALLEL: usize = 8; + +pub struct Covers { + images: HashMap, + pending: HashSet, + failed: HashSet, + /// Bumped (debounced) when images arrive, so cached lists rebuild. + version: u64, + dirty: bool, + dir: Option, + gate: Arc, +} + +impl Default for Covers { + fn default() -> Self { + let dir = directories::ProjectDirs::from("", "", "Musyx").map(|d| d.cache_dir().join("covers")); + Self { + images: HashMap::new(), + pending: HashSet::new(), + failed: HashSet::new(), + version: 0, + dirty: false, + dir, + gate: Arc::new(Semaphore::new(PARALLEL)), + } + } +} + +impl Covers { + pub fn get(&self, url: &str) -> Option { + self.images.get(url).cloned() + } + + pub fn version(&self) -> u64 { + self.version + } + + /// Whether arrivals are waiting to be shown; the app ticks [`Covers::flush`] meanwhile. + pub fn dirty(&self) -> bool { + self.dirty + } + + pub fn flush(&mut self) { + if self.dirty { + self.version += 1; + self.dirty = false; + } + } + + /// Starts fetching `url` unless it is known, in flight, or failed before. + pub fn want(&mut self, url: String, client: &YmClient) -> 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()); + Task::future(async move { + let bytes = load(&client, &url, dir, &gate).await; + Message::CoverLoaded(url, bytes) + }) + } + + pub fn loaded(&mut self, url: String, bytes: Option>) { + self.pending.remove(&url); + match bytes { + Some(bytes) => { + self.images.insert(url, image::Handle::from_bytes(bytes.to_vec())); + self.dirty = true; + } + None => { + self.failed.insert(url); + } + } + } +} + +async fn load(client: &YmClient, url: &str, dir: Option, gate: &Semaphore) -> Option> { + let path = dir.as_ref().map(|d| d.join(file_name(url))); + if let Some(path) = &path + && let Ok(bytes) = tokio::fs::read(path).await + { + return Some(bytes.into()); + } + + let _permit = gate.acquire().await.ok()?; + let bytes = match client.image(url).await { + Ok(bytes) if !bytes.is_empty() => bytes, + Ok(_) => return None, + Err(e) => { + eprintln!("cover {url}: {e}"); + return None; + } + }; + if let (Some(dir), Some(path)) = (&dir, &path) { + // A failed cache write only costs a re-download next time. + let _ = tokio::fs::create_dir_all(dir).await; + let _ = tokio::fs::write(path, &bytes).await; + } + Some(bytes.into()) +} + +/// A stable, filesystem-safe name for a URL (64-bit FNV-1a). +fn file_name(url: &str) -> String { + let hash = url.bytes().fold(0xcbf2_9ce4_8422_2325_u64, |h, b| (h ^ u64::from(b)).wrapping_mul(0x0100_0000_01b3)); + format!("{hash:016x}.img") +} + +/// A square cover: the image when cached, otherwise placeholder art that asks +/// for the image once it is (nearly) on screen. +pub fn view( + covers: &Covers, + url: Option, + hues: (f32, f32), + size: f32, + corner: f32, +) -> Element<'static, Message> { + if let Some(handle) = url.as_deref().and_then(|u| covers.get(u)) { + return image(handle).width(size).height(size).border_radius(corner).into(); + } + let placeholder = container(space()).width(size).height(size).style(theme::cover(hues.0, hues.1, corner)); + match url { + Some(url) => sensor(placeholder) + .on_show(move |_| Message::CoverWanted(url.clone())) + .anticipate(300) + .into(), + None => placeholder.into(), + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn file_names_are_stable_and_distinct() { + let a = file_name("https://avatars.yandex.net/get-music-content/1/100x100"); + assert_eq!(a, file_name("https://avatars.yandex.net/get-music-content/1/100x100")); + assert_ne!(a, file_name("https://avatars.yandex.net/get-music-content/1/400x400")); + assert!(a.ends_with(".img") && a.len() == 20); + } + + #[test] + fn arrivals_bump_version_only_on_flush() { + let mut covers = Covers { dir: None, ..Covers::default() }; + covers.pending.insert("u".into()); + covers.loaded("u".into(), Some(Arc::from(vec![1u8, 2, 3]))); + assert!(covers.dirty()); + assert_eq!(covers.version(), 0); + covers.flush(); + assert_eq!(covers.version(), 1); + assert!(covers.get("u").is_some()); + covers.loaded("bad".into(), None); + assert!(covers.failed.contains("bad")); + covers.flush(); + assert_eq!(covers.version(), 1, "a failure changes nothing on screen"); + } +} diff --git a/crates/musyx/src/main.rs b/crates/musyx/src/main.rs index 9b5c71e..b80321d 100644 --- a/crates/musyx/src/main.rs +++ b/crates/musyx/src/main.rs @@ -1,4 +1,5 @@ mod app; +mod covers; mod player; mod route; mod screens; diff --git a/crates/musyx/src/route.rs b/crates/musyx/src/route.rs index 9f2a389..91b9766 100644 --- a/crates/musyx/src/route.rs +++ b/crates/musyx/src/route.rs @@ -1,6 +1,8 @@ //! Every place the content area can show. Detail pages (album, artist, playlist) //! join this enum once they carry ids from the API. +use ym_api::PlaylistId; + use crate::ui::icons::Icon; #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] @@ -11,6 +13,9 @@ pub enum Route { Collection, Podcasts, Settings, + Album(i64), + Artist(i64), + Playlist(PlaylistId), } impl Route { @@ -26,6 +31,9 @@ impl Route { Route::Collection => "Collection", Route::Podcasts => "Podcasts", Route::Settings => "Settings", + Route::Album(_) => "Album", + Route::Artist(_) => "Artist", + Route::Playlist(_) => "Playlist", } } @@ -37,6 +45,9 @@ impl Route { Route::Collection => Icon::Library, Route::Podcasts => Icon::Podcast, Route::Settings => Icon::Settings, + Route::Album(_) => Icon::Disc, + Route::Artist(_) => Icon::Wave, + Route::Playlist(_) => Icon::Queue, } } } diff --git a/crates/musyx/src/screens/collection.rs b/crates/musyx/src/screens/collection.rs index 2d178ae..8b343db 100644 --- a/crates/musyx/src/screens/collection.rs +++ b/crates/musyx/src/screens/collection.rs @@ -1,20 +1,24 @@ -//! Collection: for now the liked tracks list, which is also the first thing -//! you can play. +//! Collection: liked tracks, albums, artists, and playlists (own and liked). use std::collections::HashSet; use std::sync::Arc; -use iced::widget::{Column, button, column, lazy, row}; +use iced::widget::{button, column, container, row, space}; use iced::{Alignment, Element, Fill}; -use ym_api::{Error, Track}; +use ym_api::{AlbumSummary, ArtistSummary, Error, LibraryPlaylists, PlaylistSummary, Track}; +use super::Loadable; use crate::app::Message; +use crate::covers::{self, Covers}; +use crate::route::Route; use crate::ui::icons::{Icon, icon}; use crate::ui::theme::{self, Tokens, size}; -use crate::ui::{line, para}; -use crate::widgets::track_row; +use crate::ui::{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; -/// The liked-tracks list as the app holds it. +/// The liked-tracks list as the app holds it. Also answers "is this track liked?". #[derive(Debug, Default)] pub enum Liked { #[default] @@ -23,7 +27,7 @@ pub enum Liked { Loaded { tracks: Arc<[Track]>, ids: HashSet, - /// Bumped on every reload so the cached rows rebuild. + /// Bumped on every reload so cached rows rebuild. version: u64, }, Failed(Error), @@ -31,10 +35,7 @@ pub enum Liked { impl Liked { pub fn loaded(tracks: Vec, previous: &Liked) -> Self { - let version = match previous { - Liked::Loaded { version, .. } => version + 1, - _ => 0, - }; + let version = previous.version() + 1; let ids = tracks.iter().map(|t| t.id.clone()).collect(); Liked::Loaded { tracks: tracks.into(), ids, version } } @@ -49,26 +50,259 @@ impl Liked { _ => None, } } + + pub fn version(&self) -> u64 { + match self { + Liked::Loaded { version, .. } => *version, + _ => 0, + } + } } -/// What makes the list look different; anything else reuses the built rows. -#[derive(Hash)] -struct ListKey { - version: u64, - playing: Option, - dark: bool, +#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)] +pub enum Tab { + #[default] + Tracks, + Albums, + Artists, + Playlists, } -pub fn view<'a>(t: &'static Tokens, liked: &'a Liked, playing: Option<&'a str>) -> Element<'a, Message> { - let title = line("Collection", theme::DISPLAY, size::DISPLAY_S, t.fg); +impl Tab { + const ALL: [Tab; 4] = [Tab::Tracks, Tab::Albums, Tab::Artists, Tab::Playlists]; - let body: Element<'a, Message> = match liked { + fn label(self) -> &'static str { + match self { + Tab::Tracks => "Liked tracks", + Tab::Albums => "Albums", + Tab::Artists => "Artists", + Tab::Playlists => "Playlists", + } + } +} + +/// Everything Collection shows. Parts load on first visit to their tab. +#[derive(Debug, Default)] +pub struct Library { + pub tab: Tab, + pub liked: Liked, + pub albums: Loadable>, + pub artists: Loadable>, + pub playlists: Loadable, +} + +impl Library { + fn count(&self, tab: Tab) -> Option { + match tab { + Tab::Tracks => self.liked.tracks().map(|t| t.len()), + Tab::Albums => self.albums.get().map(Vec::len), + Tab::Artists => self.artists.get().map(Vec::len), + Tab::Playlists => self.playlists.get().map(|p| p.own.len() + p.liked.len()), + } + } +} + +pub fn view<'a>(env: Env<'a>, library: &'a Library) -> Element<'a, Message> { + let t = env.t; + let tabs = row(Tab::ALL.map(|tab| tab_button(t, tab, library))).spacing(4); + + let body: Element<'a, Message> = match library.tab { + Tab::Tracks => liked_tracks(env, &library.liked), + Tab::Albums => match &library.albums { + Loadable::Loaded(albums) if albums.is_empty() => { + empty(t, "No liked albums yet. Like an album and it lands here.") + } + Loadable::Loaded(albums) => card::grid(albums.iter().map(|a| album_card(t, env.covers, a))), + other => status(t, other.state(), "albums", Message::LoadLibrary(Tab::Albums)), + }, + Tab::Artists => match &library.artists { + Loadable::Loaded(artists) if artists.is_empty() => { + empty(t, "No liked artists yet. Like an artist and they land here.") + } + Loadable::Loaded(artists) => card::grid(artists.iter().map(|a| artist_card(t, env.covers, a))), + other => status(t, other.state(), "artists", Message::LoadLibrary(Tab::Artists)), + }, + Tab::Playlists => match &library.playlists { + Loadable::Loaded(p) if p.own.is_empty() && p.liked.is_empty() => { + empty(t, "No playlists yet. Playlists you make or like show up here.") + } + Loadable::Loaded(p) => { + let mut sections = column![].spacing(28); + if !p.own.is_empty() { + sections = sections.push(section( + t, + "Your playlists", + p.own.iter().map(|pl| playlist_card(t, env.covers, pl)), + )); + } + if !p.liked.is_empty() { + sections = sections.push(section( + t, + "Liked playlists", + p.liked.iter().map(|pl| playlist_card(t, env.covers, pl)), + )); + } + sections.into() + } + other => status(t, other.state(), "playlists", Message::LoadLibrary(Tab::Playlists)), + }, + }; + + column![line("Collection", theme::DISPLAY, size::DISPLAY_S, t.fg), tabs, body] + .spacing(24) + .width(Fill) + .into() +} + +fn tab_button<'a>(t: &'static Tokens, tab: Tab, library: &Library) -> Element<'a, Message> { + let on = library.tab == tab; + 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) = library.count(tab) { + 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(Message::CollectionTab(tab)) + .into() +} + +fn liked_tracks<'a>(env: Env<'a>, liked: &'a Liked) -> Element<'a, Message> { + let t = env.t; + match liked { Liked::NotLoaded | Liked::Loading => para("Loading your liked tracks…", size::BODY, t.muted).into(), - Liked::Failed(err) => column![ + Liked::Failed(e) => status(t, LoadState::Failed(e), "liked tracks", Message::LoadLiked), + Liked::Loaded { tracks, .. } if tracks.is_empty() => { + empty(t, "No liked tracks yet. Tap the heart on any track and it lands here.") + } + Liked::Loaded { tracks, .. } => { + let total = tracks.iter().map(|t| t.duration).sum(); + column![ + play_bar(t, format!("{} · {}", tracks_word(tracks.len()), duration_words(total)), tracks), + track_list::view(env, tracks, Columns::FULL), + ] + .spacing(22) + .into() + } + } +} + +/// Play and Shuffle buttons with a summary on the left. Shared by every page with tracks. +pub fn play_bar<'a>(t: &'static Tokens, summary: String, tracks: &Arc<[Track]>) -> Element<'a, Message> { + let has_tracks = !tracks.is_empty(); + let pill = |glyph: Icon, + label: &'static str, + ink, + style: fn(&iced::Theme, button::Status) -> button::Style, + msg| { + button( + row![icon(glyph, ink), line(label, theme::SEMIBOLD, size::BODY, ink)] + .spacing(8) + .align_y(Alignment::Center), + ) + .padding([10, 18]) + .style(style) + .on_press_maybe(has_tracks.then_some(msg)) + }; + row![ + container(line(summary, theme::BODY, size::META, t.muted)).width(Fill), + pill( + Icon::Play, + "Play", + t.accent_ink, + theme::primary, + Message::PlayTracks { tracks: tracks.clone(), start: 0, shuffle: false }, + ), + pill( + Icon::Shuffle, + "Shuffle", + t.fg, + theme::ghost, + Message::PlayTracks { tracks: tracks.clone(), start: 0, shuffle: true }, + ), + ] + .spacing(10) + .align_y(Alignment::Center) + .into() +} + +pub fn album_card<'a>(t: &'static Tokens, covers: &Covers, a: &AlbumSummary) -> Element<'a, Message> { + card::view( + t, + covers, + Card { + title: a.full_title(), + subtitle: a.subtitle(), + cover: a.cover_url(covers::LARGE), + hues: a.hues(), + round: false, + on_press: Message::Navigate(Route::Album(a.id)), + }, + ) +} + +pub fn artist_card<'a>(t: &'static Tokens, covers: &Covers, a: &ArtistSummary) -> Element<'a, Message> { + card::view( + t, + covers, + Card { + title: a.name.clone(), + subtitle: a.genres.first().cloned().unwrap_or_else(|| "Artist".into()), + cover: a.cover_url(covers::LARGE), + hues: a.hues(), + round: true, + on_press: Message::Navigate(Route::Artist(a.id)), + }, + ) +} + +pub fn playlist_card<'a>(t: &'static Tokens, covers: &Covers, p: &PlaylistSummary) -> Element<'a, Message> { + card::view( + t, + covers, + Card { + title: p.title.clone(), + subtitle: p.subtitle(), + cover: p.cover_url(covers::LARGE), + hues: p.hues(), + round: false, + on_press: Message::Navigate(Route::Playlist(p.id)), + }, + ) +} + +pub fn section<'a>( + t: &'static Tokens, + heading: &'a str, + cards: impl IntoIterator>, +) -> Element<'a, Message> { + column![line(heading, theme::SEMIBOLD, size::SECTION, t.fg), card::grid(cards)] + .spacing(14) + .into() +} + +pub enum LoadState<'a> { + Loading, + Failed(&'a Error), +} + +/// Loading text, or a failure with a retry button. +pub fn status<'a>(t: &'static Tokens, state: LoadState<'_>, what: &str, retry: Message) -> Element<'a, Message> { + match state { + LoadState::Loading => para(format!("Loading your {what}…"), size::BODY, t.muted).into(), + LoadState::Failed(e) => column![ para( - match err { - Error::Network(_) => "Couldn't load your liked tracks. Check your connection and try again.", - _ => "Couldn't load your liked tracks. Try again in a moment.", + match e { + Error::Network(_) => { + format!("Couldn't load your {what}. Check your connection and try again.") + } + _ => format!("Couldn't load your {what}. Try again in a moment."), }, size::BODY, t.muted, @@ -76,63 +310,15 @@ pub fn view<'a>(t: &'static Tokens, liked: &'a Liked, playing: Option<&'a str>) button(line("Try again", theme::SEMIBOLD, size::BODY, t.accent_ink)) .padding([11, 18]) .style(theme::primary) - .on_press(Message::LoadLiked), + .on_press(retry), ] .spacing(16) .into(), - Liked::Loaded { tracks, .. } if tracks.is_empty() => para( - "No liked tracks yet. Tap the heart on any track and it lands here.", - size::BODY, - t.muted, - ) - .into(), - Liked::Loaded { tracks, version, .. } => { - let key = ListKey { version: *version, playing: playing.map(str::to_owned), dark: t == &theme::DARK }; - let tracks = tracks.clone(); - let list = lazy(key, move |key: &ListKey| { - let rows = tracks.iter().enumerate().map(|(i, track)| { - let now = key.playing.as_deref() == Some(track.id.as_str()); - track_row::view(t, i, track, now, true, Message::PlayLiked { start: i, shuffle: false }) - }); - Column::with_children(std::iter::once(track_row::header(t)).chain(rows)).spacing(2) - }); - column![header(t, liked), list].spacing(22).into() - } - }; - - column![title, body].spacing(28).width(Fill).into() + } } -fn header<'a>(t: &'static Tokens, liked: &Liked) -> Element<'a, Message> { - let count = liked.tracks().map_or(0, |t| t.len()); - let total: u64 = liked.tracks().map_or(0, |ts| ts.iter().map(|t| t.duration.as_secs()).sum()); - let summary = format!( - "{} {} · {}", - count, - if count == 1 { "track" } else { "tracks" }, - if total >= 3600 { format!("{} h {} min", total / 3600, (total % 3600) / 60) } else { format!("{} min", total / 60) }, - ); - - let pill = |glyph: Icon, label: &'static str, ink, style: fn(&iced::Theme, button::Status) -> button::Style, msg| { - button(row![icon(glyph, ink), line(label, theme::SEMIBOLD, size::BODY, ink)].spacing(8).align_y(Alignment::Center)) - .padding([10, 18]) - .style(style) - .on_press(msg) - }; - - row![ - column![ - line("Liked tracks", theme::SEMIBOLD, size::SECTION, t.fg), - line(summary, theme::BODY, size::META, t.muted), - ] - .spacing(4) - .width(Fill), - pill(Icon::Play, "Play", t.accent_ink, theme::primary, Message::PlayLiked { start: 0, shuffle: false }), - pill(Icon::Shuffle, "Shuffle", t.fg, theme::ghost, Message::PlayLiked { start: 0, shuffle: true }), - ] - .spacing(10) - .align_y(Alignment::Center) - .into() +fn empty<'a>(t: &'static Tokens, text: &'static str) -> Element<'a, Message> { + para(text, size::BODY, t.muted).into() } #[cfg(test)] @@ -147,11 +333,9 @@ mod tests { fn reload_bumps_version_and_indexes_ids() { let first = Liked::loaded(vec![track("1"), track("2")], &Liked::Loading); assert!(first.contains("2") && !first.contains("3")); + assert_eq!(first.version(), 1); let second = Liked::loaded(vec![track("3")], &first); - match second { - Liked::Loaded { version, .. } => assert_eq!(version, 1), - _ => unreachable!(), - } + assert_eq!(second.version(), 2); assert!(!Liked::Failed(Error::Denied).contains("1")); } } diff --git a/crates/musyx/src/screens/detail.rs b/crates/musyx/src/screens/detail.rs new file mode 100644 index 0000000..3fa169e --- /dev/null +++ b/crates/musyx/src/screens/detail.rs @@ -0,0 +1,229 @@ +//! Album, artist and playlist pages: a cover header, then tracks and cards. + +use std::sync::Arc; + +use iced::widget::{Row, button, column, container, row, text}; +use iced::{Alignment, Element, Fill, Task}; +use ym_api::{AlbumPage, ArtistPage, ArtistRef, Error, PlaylistPage, Track, YmClient}; + +use super::Loadable; +use super::collection::{LoadState, album_card, artist_card, play_bar, section, status}; +use crate::app::Message; +use crate::covers; +use crate::route::Route; +use crate::ui::theme::{self, size}; +use crate::ui::{compact, duration_words, line, para, tracks_word}; +use crate::widgets::track_list::{self, Env}; +use crate::widgets::track_row::Columns; + +/// A loaded page. Tracks are split out as `Arc<[Track]>` so playing them shares the list. +#[derive(Debug, Clone)] +pub enum Page { + Album { info: AlbumPage, tracks: Arc<[Track]> }, + Artist { info: ArtistPage, popular: Arc<[Track]> }, + Playlist { info: PlaylistPage, tracks: Arc<[Track]> }, +} + +/// Fetches whatever `route` shows. Non-detail routes load nothing. +pub fn load(client: &YmClient, route: Route) -> Option> { + let client = client.clone(); + let task = match route { + Route::Album(id) => Task::future(async move { + client.album(id).await.map(|mut info| { + let tracks = std::mem::take(&mut info.tracks).into(); + Page::Album { info, tracks } + }) + }), + Route::Artist(id) => Task::future(async move { + client.artist(id).await.map(|mut info| { + let popular = std::mem::take(&mut info.popular).into(); + Page::Artist { info, popular } + }) + }), + Route::Playlist(id) => Task::future(async move { + client.playlist(id).await.map(|mut info| { + let tracks = std::mem::take(&mut info.tracks).into(); + Page::Playlist { info, tracks } + }) + }), + _ => return None, + }; + Some(task.map(move |result| Message::PageLoaded(route, result))) +} + +pub fn view<'a>(env: Env<'a>, route: Route, page: &'a Loadable) -> Element<'a, Message> { + let t = env.t; + let what = match route { + Route::Album(_) => "album", + Route::Artist(_) => "artist", + _ => "playlist", + }; + match page { + Loadable::Loaded(Page::Album { info, tracks }) => album(env, info, tracks), + Loadable::Loaded(Page::Artist { info, popular }) => artist(env, info, popular), + Loadable::Loaded(Page::Playlist { info, tracks }) => playlist(env, info, tracks), + Loadable::Failed(e) => not_found_or_retry(env, e, what, route), + Loadable::NotLoaded | Loadable::Loading => { + para(format!("Loading the {what}…"), size::BODY, t.muted).into() + } + } +} + +fn not_found_or_retry<'a>(env: Env<'a>, e: &'a Error, what: &str, route: Route) -> Element<'a, Message> { + if let Error::Api(m) = e + && m.contains("not found") + { + return para(format!("This {what} isn't available on Yandex Music any more."), size::BODY, env.t.muted) + .into(); + } + status(env.t, LoadState::Failed(e), what, Message::Navigate(route)) +} + +struct Head<'a> { + cover: Option, + hues: (f32, f32), + round: bool, + kind: String, + title: String, + by: Option>, + meta: String, +} + +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 }; + row![ + covers::view(env.covers, h.cover, h.hues, size_px, corner), + column![ + line(h.kind, theme::BODY, size::META, t.muted), + text(h.title).font(theme::DISPLAY).size(size::DISPLAY_L).line_height(1.08).color(t.fg), + ] + .push(h.by) + .push(line(h.meta, theme::BODY, size::META, t.muted)) + .spacing(8) + .width(Fill), + ] + .spacing(28) + .align_y(Alignment::End) + .into() +} + +/// Artist names as links to their pages. +fn artist_links<'a>(env: Env<'a>, artists: &[ArtistRef]) -> Element<'a, Message> { + let t = env.t; + Row::with_children(artists.iter().map(|a| { + let label = line(a.name.clone(), theme::MEDIUM, size::BODY, t.fg); + match a.id { + Some(id) => button(label) + .padding(0) + .style(theme::tab(true)) + .on_press(Message::Navigate(Route::Artist(id))) + .into(), + None => label.into(), + } + })) + .spacing(12) + .into() +} + +fn album<'a>(env: Env<'a>, info: &'a AlbumPage, tracks: &'a Arc<[Track]>) -> Element<'a, Message> { + let a = &info.album; + let kind = match a.year { + Some(year) => format!("{} · {year}", a.kind.label()), + None => a.kind.label().to_owned(), + }; + // `info.tracks` was moved into `tracks`, so measure the list itself. + let length = format!("{} · {}", tracks_word(tracks.len()), duration_words(tracks.iter().map(|tr| tr.duration).sum())); + let meta = match &info.label { + Some(label) => format!("{length} · {label}"), + None => length, + }; + column![ + head(env, Head { + cover: a.cover_url(covers::LARGE), + hues: a.hues(), + round: false, + kind, + title: a.full_title(), + by: Some(artist_links(env, &a.artists)), + meta, + }), + play_bar(env.t, String::new(), tracks), + track_list::view(env, tracks, Columns::ALBUM_PAGE), + ] + .spacing(28) + .into() +} + +fn artist<'a>(env: Env<'a>, info: &'a ArtistPage, popular: &'a Arc<[Track]>) -> Element<'a, Message> { + let t = env.t; + let a = &info.artist; + let kind = if a.genres.is_empty() { "Artist".to_owned() } else { format!("Artist · {}", a.genres.join(", ")) }; + let meta = info + .monthly_listeners + .map(|n| format!("{} listeners a month", compact(n))) + .or_else(|| a.likes.map(|n| format!("{} likes", compact(n)))) + .unwrap_or_default(); + + let mut page = column![ + head(env, Head { + cover: a.cover_url(covers::LARGE), + hues: a.hues(), + round: true, + kind, + title: a.name.clone(), + by: None, + meta, + }), + ] + .spacing(34); + + if !popular.is_empty() { + page = page.push( + column![ + line("Popular tracks", theme::SEMIBOLD, size::SECTION, t.fg), + play_bar(t, String::new(), popular), + track_list::view(env, popular, Columns::FULL), + ] + .spacing(14), + ); + } + if !info.albums.is_empty() { + page = page.push(section(t, "Albums", info.albums.iter().map(|al| album_card(t, env.covers, al)))); + } + if !info.also_albums.is_empty() { + page = page.push(section(t, "Appears on", info.also_albums.iter().map(|al| album_card(t, env.covers, al)))); + } + if !info.similar.is_empty() { + page = page.push(section(t, "Similar artists", info.similar.iter().map(|ar| artist_card(t, env.covers, ar)))); + } + page.into() +} + +fn playlist<'a>(env: Env<'a>, info: &'a PlaylistPage, tracks: &'a Arc<[Track]>) -> Element<'a, Message> { + let t = env.t; + let p = &info.playlist; + let total = tracks.iter().map(|tr| tr.duration).sum(); + let mut page = column![ + head(env, Head { + cover: p.cover_url(covers::LARGE), + hues: p.hues(), + round: false, + kind: format!("Playlist · {}", if p.public { "Public" } else { "Private" }), + title: p.title.clone(), + by: Some(line(p.owner_name.clone(), theme::MEDIUM, size::BODY, t.fg).into()), + meta: format!("{} · {}", tracks_word(tracks.len()), duration_words(total)), + }), + ] + .spacing(28); + if let Some(description) = &info.description { + page = page.push(container(para(description.clone(), size::BODY, t.muted)).max_width(640)); + } + if tracks.is_empty() { + return page.push(para("This playlist is empty.", size::BODY, t.muted)).into(); + } + page.push(play_bar(t, String::new(), tracks)) + .push(track_list::view(env, tracks, Columns::FULL)) + .into() +} diff --git a/crates/musyx/src/screens/mod.rs b/crates/musyx/src/screens/mod.rs index dc209e0..0eb6195 100644 --- a/crates/musyx/src/screens/mod.rs +++ b/crates/musyx/src/screens/mod.rs @@ -1,11 +1,14 @@ //! Content for each route, plus the full-window screens shown outside a session. pub mod collection; +pub mod detail; pub mod sign_in; use iced::widget::{Column, button, column, container, row, space}; use iced::{Alignment, Element, Fill, Padding}; -use ym_api::Account; +use std::collections::HashMap; + +use ym_api::{Account, Error}; use crate::app::Message; use crate::route::Route; @@ -13,19 +16,59 @@ use crate::ui::icons::{Icon, icon, sized}; use crate::ui::theme::{self, Tokens, radius, size, space as sp}; use crate::ui::{line, para}; use crate::widgets::sidebar; +use crate::widgets::track_list::Env; + +/// Something fetched from the API: not asked for yet, on its way, here, or failed. +#[derive(Debug, Default)] +pub enum Loadable { + #[default] + NotLoaded, + Loading, + Loaded(T), + Failed(Error), +} + +impl Loadable { + pub fn get(&self) -> Option<&T> { + match self { + Loadable::Loaded(v) => Some(v), + _ => None, + } + } + + /// Not loaded yet, or failed: worth (re)requesting. + pub fn needs_load(&self) -> bool { + matches!(self, Loadable::NotLoaded | Loadable::Failed(_)) + } + + 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. pub struct Ctx<'a> { - pub t: &'static Tokens, + pub env: Env<'a>, pub route: Route, pub query: &'a str, pub me: &'a Account, - pub liked: &'a collection::Liked, - pub playing: Option<&'a str>, + pub library: &'a collection::Library, + pub pages: &'a HashMap>, } pub fn view<'a>(ctx: Ctx<'a>) -> Element<'a, Message> { - let Ctx { t, route, query, me, liked, playing } = ctx; + let Ctx { env, route, query, me, library, pages } = ctx; + let t = env.t; let content: Column<'a, Message> = match route { Route::Home => column![ wave_hero(t), @@ -43,7 +86,10 @@ pub fn view<'a>(ctx: Ctx<'a>) -> Element<'a, Message> { }), upcoming(t, Icon::Search, "Search the whole catalogue", "Tracks, albums, artists, playlists and podcasts."), ], - Route::Collection => column![collection::view(t, liked, playing)], + Route::Collection => column![collection::view(env, library)], + Route::Album(_) | Route::Artist(_) | Route::Playlist(_) => { + column![detail::view(env, route, pages.get(&route).unwrap_or(&Loadable::Loading))] + } Route::Podcasts => column![ title(t, "Podcasts and books"), upcoming(t, Icon::Podcast, "Pick up where you left off", "Podcasts and audiobooks you follow."), diff --git a/crates/musyx/src/snapshot.rs b/crates/musyx/src/snapshot.rs index a13c6a3..95815ce 100644 --- a/crates/musyx/src/snapshot.rs +++ b/crates/musyx/src/snapshot.rs @@ -42,6 +42,7 @@ impl Config { "collection" => Route::Collection, "podcasts" => Route::Podcasts, "settings" => Route::Settings, + "album" => Route::Album(1), _ => return None, }) }); @@ -97,6 +98,28 @@ impl Config { .collect() } + /// A sample album page for `MUSYX_SNAPSHOT_ROUTE=album`. + pub fn sample_album(&self) -> crate::screens::detail::Page { + let tracks: Vec = [ + ("Группа крови", 286), ("Закрой за мной дверь, я ухожу", 256), ("Война", 274), + ("Попробуй спеть вместе со мной", 283), ("Звезда по имени Солнце", 225), ("Спокойная ночь", 366), + ] + .iter() + .enumerate() + .map(|(i, (title, secs))| { + format!(r#"{{"id":{},"title":"{title}","durationMs":{},"artists":[{{"id":1,"name":"Кино"}}]}}"#, i + 1, secs * 1000) + }) + .collect(); + let json = format!( + r#"{{"id":1,"title":"Группа крови","year":1988,"artists":[{{"id":1,"name":"Кино"}}], + "labels":["Мелодия"],"volumes":[[{}]]}}"#, + tracks.join(",") + ); + let mut info = ym_api::AlbumPage::from_json(&json).expect("sample album"); + let tracks = std::mem::take(&mut info.tracks).into(); + crate::screens::detail::Page::Album { info, tracks } + } + /// Waits for fonts and the first frames, captures the window, writes the PNG, exits. pub fn capture(self) -> Task { Task::future(tokio::time::sleep(Duration::from_millis(1500))) diff --git a/crates/musyx/src/ui/mod.rs b/crates/musyx/src/ui/mod.rs index e204d4b..beba3eb 100644 --- a/crates/musyx/src/ui/mod.rs +++ b/crates/musyx/src/ui/mod.rs @@ -14,3 +14,43 @@ pub fn line<'a>(content: impl text::IntoFragment<'a>, font: Font, size: f32, col pub fn para<'a>(content: impl text::IntoFragment<'a>, size: f32, color: Color) -> Text<'a> { text(content).font(theme::BODY).size(size).color(color).line_height(1.45) } + +/// "47 min" or "1 h 12 min". +pub fn duration_words(d: std::time::Duration) -> String { + let mins = d.as_secs() / 60; + if mins >= 60 { format!("{} h {} min", mins / 60, mins % 60) } else { format!("{mins} min") } +} + +/// "1 track", "12 tracks". +pub fn tracks_word(n: usize) -> String { + if n == 1 { "1 track".into() } else { format!("{n} tracks") } +} + +/// "4.1M", "830K", "912". +pub fn compact(n: i64) -> String { + match n { + n if n >= 1_000_000 => format!("{:.1}M", n as f64 / 1e6).replace(".0M", "M"), + n if n >= 10_000 => format!("{}K", n / 1000), + n if n >= 1_000 => format!("{:.1}K", n as f64 / 1e3).replace(".0K", "K"), + n => n.to_string(), + } +} + +#[cfg(test)] +mod tests { + use super::*; + use std::time::Duration; + + #[test] + fn words() { + assert_eq!(duration_words(Duration::from_secs(47 * 60 + 5)), "47 min"); + assert_eq!(duration_words(Duration::from_secs(72 * 60)), "1 h 12 min"); + assert_eq!(tracks_word(1), "1 track"); + assert_eq!(tracks_word(12), "12 tracks"); + assert_eq!(compact(4_100_000), "4.1M"); + assert_eq!(compact(2_000_000), "2M"); + assert_eq!(compact(830_412), "830K"); + assert_eq!(compact(1_250), "1.2K"); + assert_eq!(compact(912), "912"); + } +} diff --git a/crates/musyx/src/widgets/card.rs b/crates/musyx/src/widgets/card.rs new file mode 100644 index 0000000..237874f --- /dev/null +++ b/crates/musyx/src/widgets/card.rs @@ -0,0 +1,48 @@ +//! Cover cards for albums, artists and playlists, laid out in wrapping rows. + +use iced::widget::{Row, button, column, container}; +use iced::{Element, Padding}; + +use crate::app::Message; +use crate::covers::{self, Covers}; +use crate::ui::line; +use crate::ui::theme::{self, Tokens, radius, size}; + +/// Card width; covers are square at this size. +pub const WIDTH: f32 = 168.0; + +pub struct Card { + pub title: String, + pub subtitle: String, + pub cover: Option, + pub hues: (f32, f32), + /// Artists get a round cover. + pub round: bool, + pub on_press: Message, +} + +pub fn view<'a>(t: &'static Tokens, covers: &Covers, card: Card) -> Element<'a, Message> { + let corner = if card.round { WIDTH / 2.0 } else { radius::COVER }; + button( + column![ + covers::view(covers, card.cover, card.hues, WIDTH, corner), + column![ + line(card.title, theme::MEDIUM, size::BODY, t.fg), + line(card.subtitle, theme::BODY, size::META, t.muted), + ] + .spacing(2) + .width(WIDTH) + .clip(true), + ] + .spacing(9), + ) + .padding(Padding::from(6)) + .style(theme::nav_item(false)) + .on_press(card.on_press) + .into() +} + +/// Cards in rows that wrap to the available width. +pub fn grid<'a>(cards: impl IntoIterator>) -> Element<'a, Message> { + container(Row::with_children(cards).spacing(12).wrap().vertical_spacing(14)).into() +} diff --git a/crates/musyx/src/widgets/drawer.rs b/crates/musyx/src/widgets/drawer.rs index ea59fc1..bb24bfd 100644 --- a/crates/musyx/src/widgets/drawer.rs +++ b/crates/musyx/src/widgets/drawer.rs @@ -5,6 +5,7 @@ use ym_api::Track; use iced::{Alignment, Element, Fill, Padding}; use crate::app::Message; +use crate::covers::{self, Covers}; use crate::player::{Msg, Player, Queue}; use crate::ui::icons::{Icon, icon}; use crate::ui::theme::{self, Tokens, radius, shell, size}; @@ -26,7 +27,7 @@ impl Panel { } } -pub fn view<'a>(t: &'static Tokens, panel: Panel, player: &'a Player) -> Element<'a, Message> { +pub fn view<'a>(t: &'static Tokens, panel: Panel, player: &'a Player, covers: &Covers) -> Element<'a, Message> { let tabs = row![tab(t, Panel::Queue, panel), tab(t, Panel::Lyrics, panel)].spacing(4); let head = row![ @@ -41,7 +42,7 @@ pub fn view<'a>(t: &'static Tokens, panel: Panel, player: &'a Player) -> Element .padding(Padding::default().top(14).bottom(8).left(18).right(14)); let body: Element<'a, Message> = match (panel, player.queue()) { - (Panel::Queue, Some(queue)) => queue_list(t, queue), + (Panel::Queue, Some(queue)) => queue_list(t, queue, covers), (Panel::Queue, None) => container(para( "Nothing queued yet. Tracks you play, and the ones lined up after them, show up here.", size::META, @@ -68,15 +69,14 @@ pub fn view<'a>(t: &'static Tokens, panel: Panel, player: &'a Player) -> Element /// Upcoming items shown at once; a long liked list would otherwise build thousands of rows. const SHOWN: usize = 100; -fn queue_list<'a>(t: &'static Tokens, queue: &'a Queue) -> Element<'a, Message> { +fn queue_list<'a>(t: &'static Tokens, queue: &'a Queue, covers: &Covers) -> Element<'a, Message> { let heading = |s: String| { container(line(s, theme::MEDIUM, size::SMALL, t.muted)).padding(Padding::default().top(14).bottom(8).left(8)) }; let item = |track: &Track, now: bool, msg: Option| { - let (h1, h2) = track.hues(); button( row![ - container(space()).width(40).height(40).style(theme::cover(h1, h2, radius::SMALL_COVER)), + covers::view(covers, track.cover_url(covers::SMALL), track.hues(), 40.0, radius::SMALL_COVER), column![ line(track.full_title(), theme::MEDIUM, size::BODY, if now { t.accent } else { t.fg }), line(track.artist_line(), theme::BODY, size::SMALL, t.muted), diff --git a/crates/musyx/src/widgets/mod.rs b/crates/musyx/src/widgets/mod.rs index d766687..7a288c6 100644 --- a/crates/musyx/src/widgets/mod.rs +++ b/crates/musyx/src/widgets/mod.rs @@ -1,5 +1,7 @@ +pub mod card; pub mod drawer; pub mod player_bar; pub mod sidebar; pub mod topbar; +pub mod track_list; pub mod track_row; diff --git a/crates/musyx/src/widgets/player_bar.rs b/crates/musyx/src/widgets/player_bar.rs index 07f6309..41a063c 100644 --- a/crates/musyx/src/widgets/player_bar.rs +++ b/crates/musyx/src/widgets/player_bar.rs @@ -4,6 +4,7 @@ use iced::widget::{button, column, container, row, slider, space}; use iced::{Alignment, Element, Fill, Length}; use crate::app::Message; +use crate::covers::{self, Covers}; use crate::player::{Msg, Player, Repeat, Status}; use crate::ui::icons::{Icon, icon, sized}; use crate::ui::line; @@ -14,9 +15,15 @@ fn send(msg: Msg) -> Message { Message::Player(msg) } -pub fn view<'a>(t: &'static Tokens, p: &'a Player, liked: bool, drawer: Option) -> Element<'a, Message> { +pub fn view<'a>( + t: &'static Tokens, + p: &'a Player, + liked: bool, + drawer: Option, + covers: &Covers, +) -> Element<'a, Message> { row![ - container(now_playing(t, p, liked)).width(Length::FillPortion(2)), + container(now_playing(t, p, liked, covers)).width(Length::FillPortion(2)), container(transport(t, p)).width(Length::FillPortion(3)).center_x(Fill), container(extras(t, p, drawer)).width(Length::FillPortion(2)).align_right(Fill), ] @@ -27,7 +34,7 @@ pub fn view<'a>(t: &'static Tokens, p: &'a Player, liked: bool, drawer: Option

(t: &'static Tokens, p: &'a Player, liked: bool) -> Element<'a, Message> { +fn now_playing<'a>(t: &'static Tokens, p: &'a Player, liked: bool, covers: &Covers) -> Element<'a, Message> { let Some(track) = p.track() else { let blank = container(space()).width(52).height(52).style(move |_| container::Style { background: Some(t.raised.into()), @@ -52,8 +59,7 @@ fn now_playing<'a>(t: &'static Tokens, p: &'a Player, liked: bool) -> Element<'a .into(); }; - let (h1, h2) = track.hues(); - let cover = container(space()).width(52).height(52).style(theme::cover(h1, h2, radius::CONTROL)); + let cover = covers::view(covers, track.cover_url(covers::SMALL), track.hues(), 52.0, radius::CONTROL); // A problem with the previous track shows in place of the artist line until the next one loads. let (sub, sub_colour) = match (&p.notice, p.status()) { diff --git a/crates/musyx/src/widgets/sidebar.rs b/crates/musyx/src/widgets/sidebar.rs index c4b3e83..b9beab7 100644 --- a/crates/musyx/src/widgets/sidebar.rs +++ b/crates/musyx/src/widgets/sidebar.rs @@ -1,17 +1,24 @@ //! Left column: wordmark, main navigation, playlists and the account chip. -use iced::widget::{Column, button, column, container, row, space}; +use iced::widget::{Column, button, column, container, row, scrollable, space}; use iced::{Alignment, Element, Fill, Padding}; -use ym_api::Account; +use ym_api::{Account, LibraryPlaylists}; use crate::app::Message; +use crate::covers::{self, Covers}; use crate::route::Route; use crate::ui::icons::{Icon, icon}; -use crate::ui::theme::{self, Tokens, shell, size}; +use crate::ui::theme::{self, Tokens, radius, shell, size}; use crate::ui::{line, para}; -pub fn view<'a>(t: &'static Tokens, current: Route, me: &'a Account) -> Element<'a, Message> { +pub fn view<'a>( + t: &'static Tokens, + current: Route, + me: &'a Account, + playlists: Option<&'a LibraryPlaylists>, + covers: &Covers, +) -> Element<'a, Message> { let nav = Column::with_children(Route::NAV.map(|route| nav_item(t, route, route == current))) .spacing(2); @@ -25,18 +32,42 @@ pub fn view<'a>(t: &'static Tokens, current: Route, me: &'a Account) -> Element< .align_y(Alignment::Center) .padding(Padding::default().left(10).right(2)); - let playlists = container(para( - "Your playlists will be listed here.", - size::META, - t.muted, - )) - .padding(Padding::default().left(10).right(10)); + let list: Element<'a, Message> = match playlists { + Some(p) if !p.own.is_empty() || !p.liked.is_empty() => { + let items = p.own.iter().chain(&p.liked).map(|pl| { + let route = Route::Playlist(pl.id); + let active = route == current; + button( + row![ + covers::view(covers, pl.cover_url(covers::SMALL), pl.hues(), 30.0, radius::SMALL_COVER), + line(pl.title.clone(), theme::BODY, size::BODY, if active { t.fg } else { t.muted }), + ] + .spacing(10) + .align_y(Alignment::Center), + ) + .width(Fill) + .padding([5, 10]) + .style(theme::nav_item(active)) + .on_press(Message::Navigate(route)) + .into() + }); + scrollable(Column::with_children(items).spacing(1)) + .height(Fill) + .style(theme::scroll) + .into() + } + Some(_) => container(para("Playlists you make or like show up here.", size::META, t.muted)) + .padding(Padding::default().left(10).right(10)) + .into(), + None => container(para("Loading playlists…", size::META, t.muted)) + .padding(Padding::default().left(10).right(10)) + .into(), + }; column![ wordmark(t), nav, - column![playlists_head, playlists].spacing(6), - space().height(Fill), + column![playlists_head, list].spacing(6).height(Fill), account(t, current, me), ] .spacing(22) diff --git a/crates/musyx/src/widgets/track_list.rs b/crates/musyx/src/widgets/track_list.rs new file mode 100644 index 0000000..d5b42c8 --- /dev/null +++ b/crates/musyx/src/widgets/track_list.rs @@ -0,0 +1,70 @@ +//! A whole track list, built once and reused (`lazy`) until something it +//! shows changes. Position ticks four times a second must not rebuild 1000 rows. + +use std::sync::Arc; + +use iced::widget::{Column, lazy}; +use iced::Element; +use ym_api::Track; + +use crate::app::Message; +use crate::covers::{self, Covers}; +use crate::screens::collection::Liked; +use crate::ui::theme::{self, Tokens, radius}; +use crate::widgets::track_row::{self, Columns}; + +/// What every list needs from app state. +#[derive(Clone, Copy)] +pub struct Env<'a> { + pub t: &'static Tokens, + pub covers: &'a Covers, + pub liked: &'a Liked, + pub playing: Option<&'a str>, +} + +#[derive(Hash)] +struct Key { + /// Identity of the list contents: the slice address and length. + list: (usize, usize), + columns: Columns, + playing: Option, + covers: u64, + liked: u64, + dark: bool, +} + +pub fn view<'a>(env: Env<'a>, tracks: &Arc<[Track]>, columns: Columns) -> Element<'a, Message> { + let Env { t, covers, liked, playing } = env; + let key = Key { + list: (tracks.as_ptr() as usize, tracks.len()), + columns, + // Only matters when the playing track is in this list. + playing: playing.filter(|id| tracks.iter().any(|tr| tr.id == *id)).map(str::to_owned), + covers: if columns.cover { covers.version() } else { 0 }, + liked: liked.version(), + dark: t == &theme::DARK, + }; + let tracks = tracks.clone(); + + lazy(key, move |key: &Key| { + let rows = tracks.iter().enumerate().map(|(index, track)| { + let cover = columns.cover.then(|| { + covers::view(covers, track.cover_url(covers::SMALL), track.hues(), 40.0, radius::SMALL_COVER) + }); + track_row::view( + t, + track_row::Row { + index, + track, + playing: key.playing.as_deref() == Some(track.id.as_str()), + liked: liked.contains(&track.id), + cover, + columns, + on_press: Message::PlayTracks { tracks: tracks.clone(), start: index, shuffle: false }, + }, + ) + }); + Column::with_children(std::iter::once(track_row::header(t, columns)).chain(rows)).spacing(2) + }) + .into() +} diff --git a/crates/musyx/src/widgets/track_row.rs b/crates/musyx/src/widgets/track_row.rs index 766ecf3..6c79c69 100644 --- a/crates/musyx/src/widgets/track_row.rs +++ b/crates/musyx/src/widgets/track_row.rs @@ -5,37 +5,60 @@ use iced::widget::{button, column, container, row, space}; use iced::{Alignment, Element, Fill, Length}; use ym_api::Track; +use crate::app::Message; use crate::ui::icons::{Icon, icon, sized}; use crate::ui::line; -use crate::ui::theme::{self, Tokens, radius, size}; +use crate::ui::theme::{self, Tokens, size}; use crate::widgets::player_bar::clock; pub const HEIGHT: f32 = 52.0; -/// Builds an owned (`'static`) row so lists can sit inside `lazy`. -pub fn view( - t: &'static Tokens, - index: usize, - track: &Track, - playing: bool, - liked: bool, - on_press: M, -) -> Element<'static, M> { - let (h1, h2) = track.hues(); - let accent = |c| if playing { t.accent } else { c }; +/// Which columns a list shows. Album pages drop the cover and album. +#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] +pub struct Columns { + pub cover: bool, + pub album: bool, +} - let number: Element<'static, M> = if playing { +impl Columns { + pub const FULL: Columns = Columns { cover: true, album: true }; + pub const ALBUM_PAGE: Columns = Columns { cover: false, album: false }; +} + +pub struct Row<'a> { + pub index: usize, + pub track: &'a Track, + pub playing: bool, + pub liked: bool, + pub cover: Option>, + pub columns: Columns, + pub on_press: Message, +} + +/// Builds an owned (`'static`) row so lists can sit inside `lazy`. +pub fn view(t: &'static Tokens, r: Row<'_>) -> Element<'static, Message> { + let track = r.track; + let number: Element<'static, Message> = if r.playing { sized(Icon::Wave, 16.0, t.accent).into() } else { - line((index + 1).to_string(), theme::BODY, size::META, t.muted).into() + line((r.index + 1).to_string(), theme::BODY, size::META, t.muted).into() }; let unavailable = !track.available; - let title_colour = if unavailable { t.muted } else { accent(t.fg) }; + let title_colour = match (unavailable, r.playing) { + (true, _) => t.muted, + (false, true) => t.accent, + (false, false) => t.fg, + }; - let content = row![ - container(number).width(36).center_x(36), - container(space()).width(40).height(40).style(theme::cover(h1, h2, radius::SMALL_COVER)), + let mut content = row![container(number).width(36).center_x(36)] + .spacing(12) + .align_y(Alignment::Center) + .height(HEIGHT); + if r.columns.cover { + content = content.push(r.cover.unwrap_or_else(|| space().width(40).into())); + } + content = content.push( column![ line(track.full_title(), theme::MEDIUM, size::BODY, title_colour), line(track.artist_line(), theme::BODY, size::META, t.muted), @@ -43,53 +66,61 @@ pub fn view( .spacing(1) .width(Length::FillPortion(22)) .clip(true), - container(line( - track.album.as_ref().map(|a| a.title.clone()).unwrap_or_default(), - theme::BODY, - size::META, - t.muted, - )) - .width(Length::FillPortion(14)) - .clip(true), - container(icon( - if liked { Icon::HeartFilled } else { Icon::Heart }, - if liked { t.like } else { t.muted.scale_alpha(0.0) }, - )) - .width(34) - .center_x(34), - container(line(clock(track.duration.as_secs_f32()), theme::BODY, size::META, t.muted)) - .width(52) - .align_right(52), - ] - .spacing(12) - .align_y(Alignment::Center) - .height(HEIGHT); + ); + if r.columns.album { + content = content.push( + container(line( + track.album.as_ref().map(|a| a.title.clone()).unwrap_or_default(), + theme::BODY, + size::META, + t.muted, + )) + .width(Length::FillPortion(14)) + .clip(true), + ); + } + content = content + .push( + container(icon( + if r.liked { Icon::HeartFilled } else { Icon::Heart }, + if r.liked { t.like } else { t.muted.scale_alpha(0.0) }, + )) + .width(34) + .center_x(34), + ) + .push( + container(line(clock(track.duration.as_secs_f32()), theme::BODY, size::META, t.muted)) + .width(52) + .align_right(52), + ); button(content) .width(Fill) .padding([0, 10]) .style(theme::nav_item(false)) - .on_press_maybe((!unavailable).then_some(on_press)) + .on_press_maybe((!unavailable).then_some(r.on_press)) .into() } /// Column headings above a track list, aligned with [`view`]. -pub fn header(t: &'static Tokens) -> Element<'static, M> { +pub fn header(t: &'static Tokens, columns: Columns) -> Element<'static, Message> { let label = |s: &'static str| line(s, theme::BODY, size::SMALL, t.muted); - column![ - row![ - container(label("#")).width(36).center_x(36), - space().width(40), - container(label("Title")).width(Length::FillPortion(22)), - container(label("Album")).width(Length::FillPortion(14)), - space().width(34), - container(icon(Icon::Clock, t.muted)).width(52).align_right(52), - ] + let mut heads = row![container(label("#")).width(36).center_x(36)] .spacing(12) .align_y(Alignment::Center) - .padding([0, 10]), - container(space()).width(Fill).height(1).style(theme::divider), - ] - .spacing(8) - .into() + .padding([0, 10]); + if columns.cover { + heads = heads.push(space().width(40)); + } + heads = heads.push(container(label("Title")).width(Length::FillPortion(22))); + if columns.album { + heads = heads.push(container(label("Album")).width(Length::FillPortion(14))); + } + heads = heads + .push(space().width(34)) + .push(container(icon(Icon::Clock, t.muted)).width(52).align_right(52)); + + column![heads, container(space()).width(Fill).height(1).style(theme::divider)] + .spacing(8) + .into() } diff --git a/crates/ym-api/src/client.rs b/crates/ym-api/src/client.rs index 0fbf6e6..7830931 100644 --- a/crates/ym-api/src/client.rs +++ b/crates/ym-api/src/client.rs @@ -1,6 +1,10 @@ use std::sync::Arc; use crate::auth::Credentials; +use crate::library::{ + AlbumPage, AlbumSummary, ArtistPage, ArtistSummary, LibraryPlaylists, PlaylistId, PlaylistPage, + PlaylistSummary, +}; use crate::models::{Stream, Track, best_variant}; use crate::{Error, Result}; @@ -118,6 +122,102 @@ impl YmClient { Ok(bytes.into()) } + /// Albums the user liked, newest first, with full details. + pub async fn liked_albums(&self) -> Result> { + let likes = self.inner.liked_albums(None).await?; + let ids: Vec = likes + .into_iter() + .filter_map(|like| like.album.and_then(|a| a.id).or_else(|| like.id.and_then(|i| i.as_number()))) + .collect(); + if ids.is_empty() { + return Ok(Vec::new()); + } + let albums = self.inner.albums(&ids).await?; + Ok(albums.into_iter().filter_map(AlbumSummary::from_yamuse).collect()) + } + + pub async fn liked_artists(&self) -> Result> { + let artists = self.inner.liked_artists(None).await?; + Ok(artists.into_iter().filter_map(ArtistSummary::from_yamuse).collect()) + } + + /// Playlists the user owns, and ones they liked. + pub async fn library_playlists(&self) -> Result { + let own = self.inner.user_playlists_list(None).await?; + let likes = self.inner.liked_playlists(None).await?; + let liked_ids: Vec = likes + .iter() + .filter_map(|like| { + let p = like.playlist.as_ref()?; + let owner = p.uid.or_else(|| p.owner.as_ref().and_then(|o| o.uid))?; + Some(format!("{owner}:{}", p.kind?)) + }) + .collect(); + let liked = if liked_ids.is_empty() { + Vec::new() + } else { + self.inner.playlists_list(&liked_ids).await? + }; + Ok(LibraryPlaylists { + own: own.iter().filter_map(PlaylistSummary::from_yamuse).collect(), + liked: liked.iter().filter_map(PlaylistSummary::from_yamuse).collect(), + }) + } + + pub async fn album(&self, id: i64) -> Result { + let album = self.inner.album_with_tracks(id).await?; + AlbumPage::from_yamuse(album).ok_or_else(|| Error::Api(format!("album {id} has no id"))) + } + + pub async fn artist(&self, id: i64) -> Result { + let brief = self.inner.artist_brief_info(id).await?; + ArtistPage::from_yamuse(brief).ok_or_else(|| Error::Api(format!("artist {id} not found"))) + } + + /// A playlist with all its tracks. Tracks the response didn't embed are looked up. + pub async fn playlist(&self, id: PlaylistId) -> Result { + let raw = self.inner.user_playlist(id.kind, Some(id.owner)).await?; + let playlist = PlaylistSummary::from_yamuse(&raw) + .ok_or_else(|| Error::Api(format!("playlist {}:{} incomplete", id.owner, id.kind)))?; + + let mut tracks: Vec> = Vec::with_capacity(raw.tracks.len()); + let mut missing = Vec::new(); + for (i, short) in raw.tracks.into_iter().enumerate() { + match short.track.and_then(Track::from_yamuse) { + Some(track) => tracks.push(Some(track)), + None => { + if let Some(id) = short.id { + let id = match id { + yamuse::models::Id::Number(n) => n.to_string(), + yamuse::models::Id::Text(s) => s, + }; + missing.push((i, id)); + } + tracks.push(None); + } + } + } + if !missing.is_empty() { + let fetched = self.tracks(missing.iter().map(|(_, id)| id.clone()).collect()).await?; + for ((slot, _), track) in missing.iter().zip(fetched) { + tracks[*slot] = Some(track); + } + } + + Ok(PlaylistPage { + playlist, + description: raw.description.filter(|d| !d.trim().is_empty()), + tracks: tracks.into_iter().flatten().collect(), + }) + } + + /// Downloads an image (covers are a few kilobytes). + pub async fn image(&self, url: &str) -> Result> { + Ok(yamuse::download::Downloader::new(self.inner.transport(), [url.to_owned()]) + .to_bytes() + .await?) + } + /// Re-reads the account, e.g. after a subscription may have changed. pub async fn account(&self) -> Result { let status = self.inner.refresh_account().await?; diff --git a/crates/ym-api/src/lib.rs b/crates/ym-api/src/lib.rs index 46af07e..be61246 100644 --- a/crates/ym-api/src/lib.rs +++ b/crates/ym-api/src/lib.rs @@ -6,8 +6,13 @@ pub mod auth; mod client; mod error; +mod library; mod models; pub use client::{Account, YmClient}; +pub use library::{ + AlbumKind, AlbumPage, AlbumSummary, ArtistPage, ArtistSummary, LibraryPlaylists, PlaylistId, + PlaylistPage, PlaylistSummary, +}; pub use models::{AlbumRef, ArtistRef, Stream, Track}; pub use error::{Error, Result}; diff --git a/crates/ym-api/src/library.rs b/crates/ym-api/src/library.rs new file mode 100644 index 0000000..702b662 --- /dev/null +++ b/crates/ym-api/src/library.rs @@ -0,0 +1,329 @@ +//! Albums, artists and playlists, as cards and as full pages. + +use std::time::Duration; + +use yamuse::models as y; + +use crate::models::{ArtistRef, Track, cover_url, hues_for}; + +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum AlbumKind { + Album, + Single, + Compilation, + Podcast, + Audiobook, +} + +impl AlbumKind { + fn from_api(meta_type: Option<&str>, kind: Option<&str>) -> Self { + match (meta_type, kind) { + (Some("podcast"), _) | (_, Some("podcast")) => AlbumKind::Podcast, + (_, Some("audiobook")) | (Some("audiobook"), _) => AlbumKind::Audiobook, + (_, Some("single")) => AlbumKind::Single, + (_, Some("compilation")) => AlbumKind::Compilation, + _ => AlbumKind::Album, + } + } + + pub fn label(self) -> &'static str { + match self { + AlbumKind::Album => "Album", + AlbumKind::Single => "Single", + AlbumKind::Compilation => "Compilation", + AlbumKind::Podcast => "Podcast", + AlbumKind::Audiobook => "Audiobook", + } + } +} + +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct AlbumSummary { + pub id: i64, + pub title: String, + pub version: Option, + pub artists: Vec, + pub year: Option, + pub track_count: u32, + pub kind: AlbumKind, + cover_uri: Option, +} + +impl AlbumSummary { + pub(crate) fn from_yamuse(a: y::Album) -> Option { + Some(Self { + id: a.id?, + title: a.title.unwrap_or_else(|| "Untitled".into()), + version: a.version.filter(|v| !v.trim().is_empty()), + artists: artist_refs(a.artists), + year: a.year.and_then(|y| i32::try_from(y).ok()), + track_count: a.track_count.unwrap_or(0).max(0) as u32, + kind: AlbumKind::from_api(a.meta_type.as_deref(), a.r#type.as_deref()), + cover_uri: a.cover_uri.or_else(|| a.cover.and_then(|c| c.uri)), + }) + } + + pub fn full_title(&self) -> String { + match &self.version { + Some(v) => format!("{} ({v})", self.title), + None => self.title.clone(), + } + } + + pub fn artist_line(&self) -> String { + join_names(&self.artists) + } + + /// "Кино · 1988", the line under a card. + pub fn subtitle(&self) -> String { + match self.year { + Some(year) => format!("{} · {year}", self.artist_line()), + None => self.artist_line(), + } + } + + pub fn cover_url(&self, size: u32) -> Option { + cover_url(self.cover_uri.as_deref(), size) + } + + pub fn hues(&self) -> (f32, f32) { + hues_for(self.id as u64) + } +} + +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct ArtistSummary { + pub id: i64, + pub name: String, + pub genres: Vec, + pub likes: Option, + cover_uri: Option, +} + +impl ArtistSummary { + pub(crate) fn from_yamuse(a: y::Artist) -> Option { + Some(Self { + id: a.id.and_then(|i| i.as_number())?, + name: a.name.unwrap_or_else(|| "Unknown artist".into()), + genres: a.genres, + likes: a.likes_count, + cover_uri: a.cover.and_then(|c| c.uri).or(a.og_image), + }) + } + + pub fn cover_url(&self, size: u32) -> Option { + cover_url(self.cover_uri.as_deref(), size) + } + + pub fn hues(&self) -> (f32, f32) { + hues_for(self.id as u64 ^ 0x5bd1_e995) + } +} + +/// A playlist is addressed by its owner and a per-owner number ("kind"). +#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] +pub struct PlaylistId { + pub owner: i64, + pub kind: i64, +} + +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct PlaylistSummary { + pub id: PlaylistId, + pub title: String, + pub owner_name: String, + pub track_count: u32, + pub duration: Duration, + pub public: bool, + cover_uri: Option, +} + +impl PlaylistSummary { + pub(crate) fn from_yamuse(p: &y::Playlist) -> Option { + let owner = p.owner.as_ref(); + let id = PlaylistId { owner: p.uid.or_else(|| owner.and_then(|o| o.uid))?, kind: p.kind? }; + let cover = p.cover.as_ref().and_then(|c| c.uri.clone().or_else(|| c.items_uri.first().cloned())); + Some(Self { + id, + title: p.title.clone().unwrap_or_else(|| "Untitled playlist".into()), + owner_name: owner + .and_then(|o| o.name.clone().or_else(|| o.login.clone())) + .unwrap_or_default(), + track_count: p.track_count.unwrap_or(0).max(0) as u32, + duration: Duration::from_millis(p.duration_ms.unwrap_or(0).max(0) as u64), + public: p.visibility.as_deref() == Some("public"), + cover_uri: cover.or_else(|| p.og_image.clone()), + }) + } + + pub fn cover_url(&self, size: u32) -> Option { + cover_url(self.cover_uri.as_deref(), size) + } + + pub fn hues(&self) -> (f32, f32) { + hues_for((self.id.owner as u64).wrapping_mul(1_000_003) ^ self.id.kind as u64) + } + + pub fn subtitle(&self) -> String { + let count = match self.track_count { + 1 => "1 track".to_owned(), + n => format!("{n} tracks"), + }; + if self.owner_name.is_empty() { count } else { format!("{} · {count}", self.owner_name) } + } +} + +/// The user's playlists for the sidebar and Collection. +#[derive(Debug, Clone, Default, PartialEq, Eq)] +pub struct LibraryPlaylists { + pub own: Vec, + pub liked: Vec, +} + +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct AlbumPage { + pub album: AlbumSummary, + pub tracks: Vec, + pub release_date: Option, + pub label: Option, + pub likes: Option, +} + +impl AlbumPage { + pub(crate) fn from_yamuse(a: y::Album) -> Option { + let tracks = a + .volumes + .iter() + .flatten() + .cloned() + .filter_map(Track::from_yamuse) + .collect(); + let release_date = a.release_date.clone(); + let label = a.labels.first().and_then(|l| l.name()).map(str::to_owned); + let likes = a.likes_count; + Some(Self { album: AlbumSummary::from_yamuse(a)?, tracks, release_date, label, likes }) + } + + pub fn duration(&self) -> Duration { + self.tracks.iter().map(|t| t.duration).sum() + } + + /// Decodes an album (with `volumes`) from the API's JSON, e.g. a recorded fixture. + pub fn from_json(json: &str) -> crate::Result { + let raw = serde_json::from_str(json).map_err(|e| crate::Error::Api(e.to_string()))?; + Self::from_yamuse(raw).ok_or_else(|| crate::Error::Api("album has no id".into())) + } +} + +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct ArtistPage { + pub artist: ArtistSummary, + pub popular: Vec, + pub albums: Vec, + /// Compilations and features the artist appears on. + pub also_albums: Vec, + pub similar: Vec, + pub monthly_listeners: Option, +} + +impl ArtistPage { + pub(crate) fn from_yamuse(b: y::BriefInfo) -> Option { + let monthly_listeners = b.stats.as_ref().and_then(|s| s.last_month_listeners); + Some(Self { + artist: ArtistSummary::from_yamuse(b.artist?)?, + popular: b.popular_tracks.into_iter().filter_map(Track::from_yamuse).collect(), + albums: b.albums.into_iter().filter_map(AlbumSummary::from_yamuse).collect(), + also_albums: b.also_albums.into_iter().filter_map(AlbumSummary::from_yamuse).collect(), + similar: b.similar_artists.into_iter().filter_map(ArtistSummary::from_yamuse).collect(), + monthly_listeners, + }) + } +} + +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct PlaylistPage { + pub playlist: PlaylistSummary, + pub description: Option, + pub tracks: Vec, +} + +fn artist_refs(artists: Vec) -> Vec { + artists + .into_iter() + .filter_map(|a| Some(ArtistRef { id: a.id.and_then(|i| i.as_number()), name: a.name? })) + .collect() +} + +pub(crate) fn join_names(artists: &[ArtistRef]) -> String { + if artists.is_empty() { + return "Unknown artist".into(); + } + artists.iter().map(|a| a.name.as_str()).collect::>().join(", ") +} + +#[cfg(test)] +mod tests { + use super::*; + + fn album(json: &str) -> y::Album { + serde_json::from_str(json).unwrap() + } + + #[test] + fn album_page_flattens_volumes() { + let page = AlbumPage::from_yamuse(album( + r#"{"id":5,"title":"Группа крови","year":1988,"type":"","artists":[{"id":1,"name":"Кино"}], + "coverUri":"a/%%","labels":[{"name":"Мелодия"}], + "volumes":[[{"id":1,"title":"A","durationMs":1000}],[{"id":2,"title":"B","durationMs":2000}]]}"#, + )) + .unwrap(); + assert_eq!(page.tracks.len(), 2); + assert_eq!(page.duration(), Duration::from_secs(3)); + assert_eq!(page.album.subtitle(), "Кино · 1988"); + assert_eq!(page.album.kind, AlbumKind::Album); + assert_eq!(page.label.as_deref(), Some("Мелодия")); + assert_eq!(page.album.cover_url(100).as_deref(), Some("https://a/100x100")); + } + + #[test] + fn album_kinds() { + assert_eq!(AlbumKind::from_api(None, Some("single")), AlbumKind::Single); + assert_eq!(AlbumKind::from_api(Some("podcast"), None), AlbumKind::Podcast); + assert_eq!(AlbumKind::from_api(None, Some("audiobook")), AlbumKind::Audiobook); + assert_eq!(AlbumKind::from_api(Some("music"), None), AlbumKind::Album); + } + + #[test] + fn playlist_needs_owner_and_kind_and_uses_mosaic_cover() { + let p: y::Playlist = serde_json::from_str( + r#"{"owner":{"uid":9,"name":"Юрий"},"kind":1003,"title":"Дорога","trackCount":14, + "visibility":"private","cover":{"type":"mosaic","itemsUri":["m/%%"]}}"#, + ) + .unwrap(); + let s = PlaylistSummary::from_yamuse(&p).unwrap(); + assert_eq!(s.id, PlaylistId { owner: 9, kind: 1003 }); + assert!(!s.public); + assert_eq!(s.subtitle(), "Юрий · 14 tracks"); + assert_eq!(s.cover_url(200).as_deref(), Some("https://m/200x200")); + let orphan: y::Playlist = serde_json::from_str(r#"{"title":"x"}"#).unwrap(); + assert!(PlaylistSummary::from_yamuse(&orphan).is_none()); + } + + #[test] + fn artist_page_from_brief_info() { + let b: y::BriefInfo = serde_json::from_str( + r#"{"artist":{"id":3,"name":"Земфира","genres":["rock"],"cover":{"uri":"z/%%"}}, + "popularTracks":[{"id":10,"title":"Хочешь?"}], + "albums":[{"id":20,"title":"Вендетта","year":2005}], + "similarArtists":[{"id":4,"name":"Сплин"}], + "stats":{"lastMonthListeners":4100000}}"#, + ) + .unwrap(); + let page = ArtistPage::from_yamuse(b).unwrap(); + assert_eq!(page.artist.name, "Земфира"); + assert_eq!(page.popular.len(), 1); + assert_eq!(page.albums[0].year, Some(2005)); + assert_eq!(page.similar[0].name, "Сплин"); + assert_eq!(page.monthly_listeners, Some(4_100_000)); + } +} diff --git a/crates/ym-api/src/models.rs b/crates/ym-api/src/models.rs index 99a8b12..ad6eae5 100644 --- a/crates/ym-api/src/models.rs +++ b/crates/ym-api/src/models.rs @@ -72,10 +72,7 @@ impl Track { /// "Artist A, Artist B", or "Unknown artist". pub fn artist_line(&self) -> String { - if self.artists.is_empty() { - return "Unknown artist".into(); - } - self.artists.iter().map(|a| a.name.as_str()).collect::>().join(", ") + crate::library::join_names(&self.artists) } /// Title with its version: "Song (Live)". @@ -88,20 +85,29 @@ impl Track { /// Absolute cover URL at `size`×`size` pixels. pub fn cover_url(&self, size: u32) -> Option { - let uri = self.cover_uri.as_deref()?; - Some(yamuse::models::normalize_image_url(uri, &format!("{size}x{size}"))) + cover_url(self.cover_uri.as_deref(), size) } /// Two stable hues for placeholder art, derived from the album (or track) id. pub fn hues(&self) -> (f32, f32) { - let seed = self.album.as_ref().map_or_else( + hues_for(self.album.as_ref().map_or_else( || self.id.bytes().fold(7u64, |h, b| h.wrapping_mul(31).wrapping_add(u64::from(b))), |a| a.id as u64, - ); - ((seed.wrapping_mul(47) % 360) as f32, (seed.wrapping_mul(131).wrapping_add(90) % 360) as f32) + )) } } +/// Absolute URL for a `%%`-templated image uri at `size`×`size` pixels. +pub(crate) fn cover_url(uri: Option<&str>, size: u32) -> Option { + let uri = uri.filter(|u| !u.is_empty())?; + Some(yamuse::models::normalize_image_url(uri, &format!("{size}x{size}"))) +} + +/// Two hues for placeholder art; equal seeds give equal art. +pub(crate) fn hues_for(seed: u64) -> (f32, f32) { + ((seed.wrapping_mul(47) % 360) as f32, (seed.wrapping_mul(131).wrapping_add(90) % 360) as f32) +} + /// Where a track's audio comes from. #[derive(Debug, Clone, PartialEq, Eq)] pub struct Stream {