diff --git a/README.md b/README.md index 42a58aa..4f976b9 100644 --- a/README.md +++ b/README.md @@ -47,6 +47,11 @@ MUSYX_SNAPSHOT=design/shots/home.png MUSYX_SNAPSHOT_ROUTE=home MUSYX_SNAPSHOT_TH `MUSYX_SNAPSHOT_ROUTE` takes home, wave, search, collection, podcasts, settings or signin. Every route except signin renders with a sample signed-in account, so no network or keychain is needed. `MUSYX_SNAPSHOT_DRAWER` takes queue or lyrics. `MUSYX_SNAPSHOT_THEME` takes light or dark. +`MUSYX_SNAPSHOT_LIVE=1` signs in with the account stored in the keychain instead of using sample +data. Set `MUSYX_SNAPSHOT_DELAY` (ms) to wait longer for slow pages. + +`cargo run -p musyx --example api_probe` calls the discovery endpoints with the stored account +(read-only) and prints what came back. ### Audio diff --git a/crates/musyx/Cargo.toml b/crates/musyx/Cargo.toml index fb4eee0..a5807a8 100644 --- a/crates/musyx/Cargo.toml +++ b/crates/musyx/Cargo.toml @@ -18,6 +18,9 @@ tokio = { version = "1", features = ["time", "rt", "fs", "sync"] } directories = "6.0.0" png = { version = "0.18.1", optional = true } +[dev-dependencies] +tokio = { version = "1", features = ["macros", "rt"] } + [features] # `MUSYX_SNAPSHOT=out.png cargo run --features snapshot` renders one screen to a PNG and exits. snapshot = ["dep:png"] diff --git a/crates/musyx/assets/icons/chevron-right.svg b/crates/musyx/assets/icons/chevron-right.svg new file mode 100644 index 0000000..54f2be6 --- /dev/null +++ b/crates/musyx/assets/icons/chevron-right.svg @@ -0,0 +1,15 @@ + + + + diff --git a/crates/musyx/assets/icons/trending-up.svg b/crates/musyx/assets/icons/trending-up.svg new file mode 100644 index 0000000..6ee61e2 --- /dev/null +++ b/crates/musyx/assets/icons/trending-up.svg @@ -0,0 +1,16 @@ + + + + + diff --git a/crates/musyx/examples/api_probe.rs b/crates/musyx/examples/api_probe.rs new file mode 100644 index 0000000..213cda3 --- /dev/null +++ b/crates/musyx/examples/api_probe.rs @@ -0,0 +1,54 @@ +//! Read-only check of the discovery endpoints with the signed-in account: +//! `cargo run -p musyx --example api_probe`. Prints counts and a few titles. +use ym_api::auth::Credentials; +use ym_api::{SearchKind, YmClient}; + +#[tokio::main(flavor = "current_thread")] +async fn main() { + let raw = keyring::Entry::new("musyx", "yandex-music") + .and_then(|e| e.get_password()) + .expect("sign in with Musyx first"); + let credentials: Credentials = serde_json::from_str(&raw).expect("stored credentials"); + let (client, account) = YmClient::connect(&credentials).await.expect("connect"); + println!("account: {} (plus: {})", account.login, account.has_plus); + + match client.home().await { + Ok(h) => println!( + "home: {} personal {:?}, {} chart, {} new releases, {} new playlists", + h.personal.len(), + h.personal.iter().map(|p| p.playlist.title.as_str()).collect::>(), + h.chart.len(), + h.new_releases.len(), + h.new_playlists.len() + ), + Err(e) => println!("home: ERROR {e}"), + } + match client.genres().await { + Ok(g) => { + println!("genres: {} {:?}", g.len(), g.iter().take(8).map(|g| (&g.id, &g.title)).collect::>()); + for genre in g.iter().skip(1).take(4) { + match client.tag_playlists(&genre.id).await { + Ok(p) => println!("tag {}: {} playlists {:?}", genre.id, p.len(), p.iter().take(2).map(|p| &p.title).collect::>()), + Err(e) => println!("tag {}: ERROR {e}", genre.id), + } + } + } + Err(e) => println!("genres: ERROR {e}"), + } + match client.featured_podcasts().await { + Ok(p) => println!("podcasts: {} {:?}", p.len(), p.iter().take(3).map(|a| &a.title).collect::>()), + Err(e) => println!("podcasts: ERROR {e}"), + } + match client.search("земфира", SearchKind::All, 0).await { + Ok(r) => println!( + "search: best {:?}, {} tracks ({}), {} albums, {} artists, {} playlists, {} podcasts", + r.best.as_ref().map(|b| format!("{b:?}").chars().take(60).collect::()), + r.tracks.len(), r.totals.tracks, r.albums.len(), r.artists.len(), r.playlists.len(), r.podcasts.len() + ), + Err(e) => println!("search: ERROR {e}"), + } + match client.suggest("зем").await { + Ok(s) => println!("suggest: {:?}", s.iter().take(5).collect::>()), + Err(e) => println!("suggest: ERROR {e}"), + } +} diff --git a/crates/musyx/src/app.rs b/crates/musyx/src/app.rs index 40f095b..b3cf849 100644 --- a/crates/musyx/src/app.rs +++ b/crates/musyx/src/app.rs @@ -4,15 +4,20 @@ use std::collections::HashMap; use std::sync::Arc; use iced::theme::Mode; -use iced::widget::{column, container, row, scrollable, space}; +use iced::widget::{column, container, row, scrollable, space, stack}; use iced::{Element, Fill, Subscription, Task, Theme}; use ym_api::auth::Credentials; -use ym_api::{Account, AlbumSummary, ArtistSummary, Error, LibraryPlaylists, Track, YmClient}; +use ym_api::{ + Account, AlbumSummary, ArtistSummary, Error, Genre, Home, LibraryPlaylists, PlaylistSummary, Track, + YmClient, +}; use crate::covers::Covers; 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::detail::{self, Page}; use crate::screens::{self, Loadable, sign_in}; use crate::session::{self, Restored}; @@ -39,13 +44,18 @@ pub struct App { forced_mode: Option, session: Session, nav: Navigator, - search: String, + search: Search, drawer: Option, player: Player, library: Library, /// Album, artist and playlist pages visited this session. pages: HashMap>, + discover: Discover, + genre_playlists: HashMap>>, covers: Covers, + /// A live snapshot run opens this route once signed in. + #[cfg(feature = "snapshot")] + snapshot_route: Option, } #[derive(Debug, Clone)] @@ -60,8 +70,7 @@ pub enum Message { SignedOut, Navigate(Route), Back, - SearchChanged(String), - SearchSubmitted, + Search(search::Msg), ToggleDrawer(Panel), CloseDrawer, Player(player::Msg), @@ -74,6 +83,13 @@ pub enum Message { ArtistsLoaded(Result, Error>), PlaylistsLoaded(Result), PageLoaded(Route, Result), + LoadHome, + HomeLoaded(Result), + LoadGenres, + GenresLoaded(Result, Error>), + GenreLoaded(usize, Result, Error>), + LoadPodcasts, + PodcastsLoaded(Result, Error>), CoverWanted(String), CoverLoaded(String, Option>), CoversTick, @@ -86,29 +102,37 @@ impl App { forced_mode: None, session: Session::Restoring, nav: Navigator::new(Route::Home), - search: String::new(), + search: Search::default(), drawer: None, player: Player::default(), library: Library::default(), pages: HashMap::new(), + discover: Discover::default(), + genre_playlists: HashMap::new(), covers: Covers::default(), + #[cfg(feature = "snapshot")] + snapshot_route: None, }; let appearance = iced::system::theme().map(Message::ThemeChanged); #[cfg(feature = "snapshot")] if let Some(config) = crate::snapshot::Config::from_env() { let mut app = app; + app.drawer = config.drawer; + app.forced_mode = config.mode; + if let Some(mode) = config.mode { + app.theme = theme::for_mode(mode); + } + if config.live { + app.snapshot_route = config.route; + return (app, Task::batch([appearance, restore(), config.capture()])); + } app.session = config.session(); 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); } - app.drawer = config.drawer; - app.forced_mode = config.mode; - if let Some(mode) = config.mode { - app.theme = theme::for_mode(mode); - } return (app, Task::batch([appearance, config.capture()])); } @@ -158,8 +182,19 @@ impl App { 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))]) + // Liked tracks drive the hearts; playlists fill the sidebar; Home is the first page. + #[allow(unused_mut)] + let mut first = Route::Home; + #[cfg(feature = "snapshot")] + if let Some(route) = self.snapshot_route { + self.nav = Navigator::new(route); + first = route; + } + Task::batch([ + self.update(Message::LoadLiked), + self.update(Message::LoadLibrary(Tab::Playlists)), + self.on_enter(first), + ]) } pub fn update(&mut self, message: Message) -> Task { @@ -215,10 +250,14 @@ impl App { self.player.reset(); self.library = Library::default(); self.pages.clear(); + self.discover = Discover::default(); + self.genre_playlists.clear(); + self.search = Search::default(); } Message::Navigate(route) => { self.nav.go(route); - return self.on_enter(route); + let (close, _) = self.search.update(search::Msg::CloseSuggestions, None); + return Task::batch([close, self.on_enter(route)]); } Message::AccountRefreshed(Ok(fresh)) => { if let Session::SignedIn { account, .. } = &mut self.session { @@ -234,8 +273,15 @@ impl App { self.nav.back(); return self.on_enter(self.nav.current()); } - Message::SearchChanged(query) => self.search = query, - Message::SearchSubmitted => self.nav.go(Route::Search), + Message::Search(msg) => { + let client = self.client().cloned(); + let (task, after) = self.search.update(msg, client.as_ref()); + if let search::After::ShowResults = after { + self.nav.go(Route::Search); + return Task::batch([task, self.on_enter(Route::Search)]); + } + return task; + } Message::ToggleDrawer(panel) => { self.drawer = if self.drawer == Some(panel) { None } else { Some(panel) }; } @@ -310,6 +356,54 @@ impl App { } self.pages.insert(route, Loadable::from_result(result)); } + Message::LoadHome => { + let Some(client) = self.client().cloned() else { return Task::none() }; + self.discover.home = Loadable::Loading; + return Task::future(async move { client.home().await }).map(Message::HomeLoaded); + } + Message::HomeLoaded(result) => { + if let Err(e) = &result + && let Some(task) = self.failed("home", e) + { + return task; + } + self.discover.home = Loadable::from_result(result.map(HomeData::new)); + } + Message::LoadGenres => { + let Some(client) = self.client().cloned() else { return Task::none() }; + self.discover.genres = Loadable::Loading; + return Task::future(async move { client.genres().await }).map(Message::GenresLoaded); + } + Message::GenresLoaded(result) => { + if let Err(e) = &result + && let Some(task) = self.failed("genres", e) + { + return task; + } + self.discover.genres = Loadable::from_result(result.map(browse::flatten)); + } + Message::GenreLoaded(index, result) => { + if let Err(e) = &result + && let Some(task) = self.failed("genre playlists", e) + { + return task; + } + self.genre_playlists.insert(index, Loadable::from_result(result)); + } + Message::LoadPodcasts => { + let Some(client) = self.client().cloned() else { return Task::none() }; + self.discover.podcasts = Loadable::Loading; + return Task::future(async move { client.featured_podcasts().await }) + .map(Message::PodcastsLoaded); + } + Message::PodcastsLoaded(result) => { + if let Err(e) = &result + && let Some(task) = self.failed("podcasts", e) + { + return task; + } + self.discover.podcasts = Loadable::from_result(result); + } Message::CoverWanted(url) => { let Some(client) = self.client().cloned() else { return Task::none() }; return self.covers.want(url, &client); @@ -335,6 +429,32 @@ impl App { } None => Task::none(), }, + Route::Home => { + let home = if self.discover.home.needs_load() { self.update(Message::LoadHome) } else { Task::none() }; + Task::batch([home, self.genres_if_needed()]) + } + Route::Search => self.genres_if_needed(), + Route::Chart if self.discover.home.needs_load() => self.update(Message::LoadHome), + Route::Genre(index) => { + if self.genre_playlists.get(&index).is_some_and(|p| !p.needs_load()) { + return Task::none(); + } + let (Some(client), Some(genre)) = ( + self.client().cloned(), + self.discover.genres.get().and_then(|g| g.get(index)).cloned(), + ) else { + return Task::none(); + }; + self.genre_playlists.insert(index, Loadable::Loading); + Task::future(async move { client.tag_playlists(&genre.id).await }) + .map(move |r| Message::GenreLoaded(index, r)) + } + Route::Podcasts => { + let featured = + if self.discover.podcasts.needs_load() { self.update(Message::LoadPodcasts) } else { Task::none() }; + // "Yours" comes from liked albums. + Task::batch([featured, self.load_tab(Tab::Albums)]) + } Route::Album(_) | Route::Artist(_) | Route::Playlist(_) => { if self.pages.get(&route).is_some_and(|p| !p.needs_load()) { return Task::none(); @@ -349,6 +469,10 @@ impl App { } } + fn genres_if_needed(&mut self) -> Task { + if self.discover.genres.needs_load() { self.update(Message::LoadGenres) } else { Task::none() } + } + fn load_tab(&mut self, tab: Tab) -> Task { let needed = match tab { Tab::Tracks => matches!(self.library.liked, Liked::NotLoaded), @@ -399,21 +523,33 @@ impl App { 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 { - env, - route, - query: &self.search, - me: account, - library: &self.library, - pages: &self.pages, - })) - .height(Fill) - .style(theme::scroll), - ] - .width(Fill) - .height(Fill); + let page = scrollable(screens::view(screens::Ctx { + env, + route, + search: &self.search, + me: account, + library: &self.library, + pages: &self.pages, + discover: &self.discover, + genre_playlists: &self.genre_playlists, + })) + .height(Fill) + .style(theme::scroll); + + // Suggestions float over the page, lined up under the search field. + let page: Element<'a, Message> = match self.search.suggestions() { + Some(list) => stack![ + page, + container(search::suggestions(t, list)) + .padding(iced::Padding::default().left(theme::space::GUTTER + 44.0)), + ] + .into(), + None => page.into(), + }; + + let content = column![topbar::view(t, self.nav.can_go_back(), &self.search.text), page] + .width(Fill) + .height(Fill); let mut body = row![ sidebar::view(t, route, account, self.library.playlists.get(), &self.covers), diff --git a/crates/musyx/src/route.rs b/crates/musyx/src/route.rs index 91b9766..629185b 100644 --- a/crates/musyx/src/route.rs +++ b/crates/musyx/src/route.rs @@ -16,6 +16,9 @@ pub enum Route { Album(i64), Artist(i64), Playlist(PlaylistId), + Chart, + /// Index into the app's flattened genre list. + Genre(usize), } impl Route { @@ -34,6 +37,8 @@ impl Route { Route::Album(_) => "Album", Route::Artist(_) => "Artist", Route::Playlist(_) => "Playlist", + Route::Chart => "Chart", + Route::Genre(_) => "Genre", } } @@ -48,6 +53,8 @@ impl Route { Route::Album(_) => Icon::Disc, Route::Artist(_) => Icon::Wave, Route::Playlist(_) => Icon::Queue, + Route::Chart => Icon::Chart, + Route::Genre(_) => Icon::Library, } } } diff --git a/crates/musyx/src/screens/browse.rs b/crates/musyx/src/screens/browse.rs new file mode 100644 index 0000000..bb23f87 --- /dev/null +++ b/crates/musyx/src/screens/browse.rs @@ -0,0 +1,321 @@ +//! Discovery: Home, the chart, genres and podcasts. + +use std::sync::Arc; + +use iced::widget::{Row, button, column, container, row}; +use iced::{Alignment, Color, Element, Fill}; +use ym_api::{AlbumKind, AlbumSummary, ChartEntry, Genre, Home, PlaylistSummary, Track}; + +use super::Loadable; +use super::collection::{LoadState, album_card, play_bar, playlist_card, section, status}; +use crate::app::Message; +use crate::covers; +use crate::route::Route; +use crate::ui::theme::{self, Tokens, radius, size}; +use crate::ui::{line, para}; +use crate::widgets::card::{self, Card}; +use crate::widgets::track_list::{self, Env}; +use crate::widgets::track_row::Columns; + +/// Chart rows shown on Home before "Show all". +const HOME_CHART: usize = 10; +/// Cards per Home row. +const HOME_CARDS: usize = 12; + +/// Home data with the chart split out as a playable list. +#[derive(Debug)] +pub struct HomeData { + pub home: Home, + pub chart: Arc<[Track]>, + pub shifts: Arc<[i32]>, + /// The first rows of the chart for Home, built once so the cached list stays valid. + top: Arc<[Track]>, + top_shifts: Arc<[i32]>, +} + +impl HomeData { + pub fn new(mut home: Home) -> Self { + let entries = std::mem::take(&mut home.chart); + let (chart, shifts): (Vec, Vec) = + entries.into_iter().map(|ChartEntry { track, shift, .. }| (track, shift)).unzip(); + let top = chart.iter().take(HOME_CHART).cloned().collect(); + let top_shifts = shifts.iter().take(HOME_CHART).copied().collect(); + Self { home, chart: chart.into(), shifts: shifts.into(), top, top_shifts } + } +} + +/// Everything the discovery screens show. Each part loads on first visit. +#[derive(Debug, Default)] +pub struct Discover { + pub home: Loadable, + /// Top-level genres followed by their sub-genres, so a `Route::Genre` index finds either. + pub genres: Loadable>, + pub podcasts: Loadable>, +} + +/// Top-level genres first, then every sub-genre, each once. +pub fn flatten(genres: Vec) -> Vec { + let mut flat: Vec = genres.clone(); + for g in genres { + for sub in g.sub_genres { + if !flat.iter().any(|f| f.id == sub.id) { + flat.push(sub); + } + } + } + flat +} + +pub fn home<'a>(env: Env<'a>, discover: &'a Discover, hero: Element<'a, Message>) -> Element<'a, Message> { + let t = env.t; + let covers = env.covers; + let mut page = column![hero].spacing(34); + + match &discover.home { + Loadable::Loaded(data) => { + let h = &data.home; + if !h.personal.is_empty() { + page = page.push(section( + t, + "Made for you", + h.personal.iter().map(|p| { + card::view(t, covers, Card { + title: p.playlist.title.clone(), + subtitle: p.description.clone().unwrap_or_else(|| p.playlist.subtitle()), + cover: p.playlist.cover_url(covers::LARGE), + hues: p.playlist.hues(), + round: false, + on_press: Message::Navigate(Route::Playlist(p.playlist.id)), + }) + }), + )); + } + if !data.chart.is_empty() { + page = page.push( + column![ + row![ + line("Chart", theme::SEMIBOLD, size::SECTION, t.fg).width(Fill), + button(line(format!("Show all {}", data.chart.len()), theme::MEDIUM, size::META, t.muted)) + .padding(0) + .style(theme::tab(false)) + .on_press(Message::Navigate(Route::Chart)), + ] + .align_y(Alignment::Center), + track_list::view_with(env, &data.top, Columns::CHART, Some(data.top_shifts.clone())), + ] + .spacing(14), + ); + } + if !h.new_releases.is_empty() { + page = page.push(section( + t, + "New releases", + h.new_releases.iter().take(HOME_CARDS).map(|a| album_card(t, covers, a)), + )); + } + if !h.new_playlists.is_empty() { + page = page.push(section( + t, + "New playlists", + h.new_playlists.iter().take(HOME_CARDS).map(|p| playlist_card(t, covers, p)), + )); + } + } + Loadable::Failed(e) => page = page.push(status(t, LoadState::Failed(e), "home page", Message::LoadHome)), + _ => page = page.push(para("Loading your picks…", size::BODY, t.muted)), + } + + page.push(genres_section(env, &discover.genres)).into() +} + +pub fn chart<'a>(env: Env<'a>, discover: &'a Discover) -> Element<'a, Message> { + let t = env.t; + let body: Element<'a, Message> = match &discover.home { + Loadable::Loaded(data) if !data.chart.is_empty() => column![ + play_bar(t, "The most played tracks on Yandex Music today".into(), &data.chart), + track_list::view_with(env, &data.chart, Columns::CHART, Some(data.shifts.clone())), + ] + .spacing(22) + .into(), + Loadable::Loaded(_) => para("The chart is empty right now.", size::BODY, t.muted).into(), + Loadable::Failed(e) => status(t, LoadState::Failed(e), "chart", Message::LoadHome), + _ => para("Loading the chart…", size::BODY, t.muted).into(), + }; + column![line("Chart", theme::DISPLAY, size::DISPLAY_S, t.fg), body].spacing(24).into() +} + +pub fn genres_section<'a>(env: Env<'a>, genres: &'a Loadable>) -> Element<'a, Message> { + let t = env.t; + let body: Element<'a, Message> = match genres { + // Sub-genres are reached from their parent's page. + Loadable::Loaded(list) => { + let top = list.iter().enumerate().filter(|(_, g)| !is_sub_genre(list, g)); + Row::with_children(top.map(|(i, g)| genre_tile(t, i, g))).spacing(12).wrap().vertical_spacing(12).into() + } + Loadable::Failed(e) => status(t, LoadState::Failed(e), "genres", Message::LoadGenres), + _ => para("Loading genres…", size::BODY, t.muted).into(), + }; + column![line("Genres", theme::SEMIBOLD, size::SECTION, t.fg), body].spacing(14).into() +} + +fn is_sub_genre(all: &[Genre], g: &Genre) -> bool { + all.iter().any(|parent| parent.sub_genres.iter().any(|s| s.id == g.id)) +} + +fn genre_tile<'a>(t: &'static Tokens, index: usize, g: &Genre) -> Element<'a, Message> { + let tint = g.color.as_deref().and_then(parse_hex).unwrap_or(t.raised); + button( + container(line(g.title.clone(), theme::SEMIBOLD, size::BODY, Color::WHITE)) + .padding([0, 16]) + .align_y(iced::alignment::Vertical::Center) + .height(72) + .width(card::WIDTH), + ) + .padding(0) + .style(move |_, status| { + let lift = matches!(status, button::Status::Hovered | button::Status::Pressed); + button::Style { + background: Some(iced::Background::Gradient( + iced::gradient::Linear::new(std::f32::consts::FRAC_PI_4 * 3.0) + .add_stop(0.0, if lift { theme::mix(tint, Color::WHITE, 0.12) } else { tint }) + .add_stop(1.0, theme::mix(tint, Color::BLACK, 0.45)) + .into(), + )), + text_color: Color::WHITE, + border: iced::Border { radius: radius::COVER.into(), ..Default::default() }, + ..Default::default() + } + }) + .on_press(Message::Navigate(Route::Genre(index))) + .into() +} + +/// `#rrggbb` → colour. +pub fn parse_hex(s: &str) -> Option { + let h = s.strip_prefix('#')?; + if h.len() != 6 { + return None; + } + let n = u32::from_str_radix(h, 16).ok()?; + Some(Color::from_rgb8((n >> 16) as u8, (n >> 8) as u8, n as u8)) +} + +pub fn genre<'a>( + env: Env<'a>, + genres: &'a [Genre], + index: usize, + playlists: &'a Loadable>, +) -> Element<'a, Message> { + let t = env.t; + let Some(g) = genres.get(index) else { + return para("This genre isn't available any more.", size::BODY, t.muted).into(); + }; + let mut page = column![line(g.title.clone(), theme::DISPLAY, size::DISPLAY_S, t.fg)].spacing(24); + + let subs: Vec> = g + .sub_genres + .iter() + .filter_map(|s| genres.iter().position(|f| f.id == s.id).map(|i| (i, s))) + .map(|(i, s)| { + button(line(s.title.clone(), theme::MEDIUM, size::META, t.fg)) + .padding([7, 13]) + .style(theme::ghost) + .on_press(Message::Navigate(Route::Genre(i))) + .into() + }) + .collect(); + if !subs.is_empty() { + page = page.push(Row::with_children(subs).spacing(6).wrap().vertical_spacing(6)); + } + + let body: Element<'a, Message> = match playlists { + Loadable::Loaded(list) if list.is_empty() => { + para("No playlists in this genre yet.", size::BODY, t.muted).into() + } + Loadable::Loaded(list) => section(t, "Playlists", list.iter().map(|p| playlist_card(t, env.covers, p))), + Loadable::Failed(e) => status(t, LoadState::Failed(e), "playlists", Message::Navigate(Route::Genre(index))), + _ => para("Loading playlists…", size::BODY, t.muted).into(), + }; + page.push(body).into() +} + +pub fn podcasts<'a>( + env: Env<'a>, + discover: &'a Discover, + liked: &'a Loadable>, +) -> Element<'a, Message> { + let t = env.t; + let covers = env.covers; + let mut page = column![line("Podcasts and books", theme::DISPLAY, size::DISPLAY_S, t.fg)].spacing(34); + + if let Loadable::Loaded(albums) = liked { + let mine: Vec<&AlbumSummary> = + albums.iter().filter(|a| matches!(a.kind, AlbumKind::Podcast | AlbumKind::Audiobook)).collect(); + if !mine.is_empty() { + page = page.push(section(t, "Yours", mine.into_iter().map(|a| album_card(t, covers, a)))); + } + } + + page.push(match &discover.podcasts { + Loadable::Loaded(list) => section(t, "Featured", list.iter().map(|a| album_card(t, covers, a))), + Loadable::Failed(e) => status(t, LoadState::Failed(e), "podcasts", Message::LoadPodcasts), + _ => para("Loading podcasts…", size::BODY, t.muted).into(), + }) + .into() +} + +/// The arrow beside a chart position. +pub fn shift_marker(t: &'static Tokens, shift: i32) -> Element<'static, Message> { + let (glyph, colour) = match shift { + s if s > 0 => ("▲", t.ok), + s if s < 0 => ("▼", t.like), + _ => ("–", t.muted), + }; + container(line(glyph, theme::DISPLAY, 9.0, colour)).width(14).center_x(14).into() +} + +#[cfg(test)] +mod tests { + use super::*; + + fn genre(id: &str, subs: &[&str]) -> Genre { + Genre { + id: id.into(), + title: id.into(), + color: None, + sub_genres: subs.iter().map(|s| genre(s, &[])).collect(), + } + } + + #[test] + fn flatten_appends_each_sub_genre_once() { + let flat = flatten(vec![genre("rock", &["punk", "metal"]), genre("metal", &["doom"]), genre("pop", &["punk"])]); + let ids: Vec<&str> = flat.iter().map(|g| g.id.as_str()).collect(); + assert_eq!(ids, ["rock", "metal", "pop", "punk", "doom"]); + assert!(is_sub_genre(&flat, &flat[3])); + assert!(!is_sub_genre(&flat, &flat[0])); + } + + #[test] + fn hex_colours() { + assert_eq!(parse_hex("#ff8000"), Some(Color::from_rgb8(255, 128, 0))); + assert_eq!(parse_hex("ff8000"), None); + assert_eq!(parse_hex("#fff"), None); + } + + #[test] + fn home_data_splits_chart() { + let track = |id: &str| Track::from_json(&format!(r#"{{"id":"{id}"}}"#)).unwrap(); + let home = Home { + chart: vec![ + ChartEntry { position: 1, shift: 2, track: track("a") }, + ChartEntry { position: 2, shift: -1, track: track("b") }, + ], + ..Default::default() + }; + let data = HomeData::new(home); + assert_eq!(data.chart.len(), 2); + assert_eq!(&*data.shifts, &[2, -1]); + assert!(data.home.chart.is_empty()); + } +} diff --git a/crates/musyx/src/screens/mod.rs b/crates/musyx/src/screens/mod.rs index 0eb6195..043d299 100644 --- a/crates/musyx/src/screens/mod.rs +++ b/crates/musyx/src/screens/mod.rs @@ -1,14 +1,16 @@ //! Content for each route, plus the full-window screens shown outside a session. +pub mod browse; pub mod collection; pub mod detail; +pub mod search; pub mod sign_in; use iced::widget::{Column, button, column, container, row, space}; use iced::{Alignment, Element, Fill, Padding}; use std::collections::HashMap; -use ym_api::{Account, Error}; +use ym_api::{Account, Error, PlaylistSummary}; use crate::app::Message; use crate::route::Route; @@ -60,40 +62,36 @@ impl Loadable { pub struct Ctx<'a> { pub env: Env<'a>, pub route: Route, - pub query: &'a str, + pub search: &'a search::Search, pub me: &'a Account, pub library: &'a collection::Library, pub pages: &'a HashMap>, + pub discover: &'a browse::Discover, + pub genre_playlists: &'a HashMap>>, } pub fn view<'a>(ctx: Ctx<'a>) -> Element<'a, Message> { - let Ctx { env, route, query, me, library, pages } = ctx; + let Ctx { env, route, search, me, library, pages, discover, genre_playlists } = ctx; let t = env.t; let content: Column<'a, Message> = match route { - Route::Home => column![ - wave_hero(t), - upcoming(t, Icon::Library, "Made for you", "Daily playlists, the chart and albums picked from what you play."), - ], + Route::Home => column![browse::home(env, discover, wave_hero(t))], Route::Wave => column![ title(t, "My Wave"), upcoming(t, Icon::Wave, "An endless stream that learns from you", "Every like, skip and full listen steers what comes next."), ], - Route::Search => column![ - title(t, if query.trim().is_empty() { - "Search".to_owned() - } else { - format!("Results for “{}”", query.trim()) - }), - upcoming(t, Icon::Search, "Search the whole catalogue", "Tracks, albums, artists, playlists and podcasts."), - ], + Route::Search => column![search::view(env, search, browse::genres_section(env, &discover.genres))], + Route::Chart => column![browse::chart(env, discover)], + Route::Genre(i) => column![browse::genre( + env, + discover.genres.get().map_or(&[][..], Vec::as_slice), + i, + genre_playlists.get(&i).unwrap_or(&Loadable::Loading), + )], 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."), - ], + Route::Podcasts => column![browse::podcasts(env, discover, &library.albums)], Route::Settings => column![title(t, "Settings"), account_card(t, me)], }; diff --git a/crates/musyx/src/screens/search.rs b/crates/musyx/src/screens/search.rs new file mode 100644 index 0000000..7d2f6d0 --- /dev/null +++ b/crates/musyx/src/screens/search.rs @@ -0,0 +1,466 @@ +//! Search: suggestions while typing, results by kind, more pages on request. +//! With no query it shows genres to browse. + +use std::sync::Arc; +use std::time::Duration; + +use iced::widget::{button, column, container, row}; +use iced::{Alignment, Element, Fill, Task}; +use ym_api::{BestMatch, Error, SearchKind, SearchResults, Track, YmClient}; + +use super::collection::{ + LoadState, album_card, artist_card, play_bar, playlist_card, section, status, +}; +use super::Loadable; +use crate::app::Message; +use crate::covers; +use crate::route::Route; +use crate::ui::icons::{Icon, icon}; +use crate::ui::theme::{self, radius, size}; +use crate::ui::{compact, line, para}; +use crate::widgets::card; +use crate::widgets::track_list::{self, Env}; +use crate::widgets::track_row::Columns; + +/// Wait this long after the last keystroke before asking for suggestions. +const DEBOUNCE: Duration = Duration::from_millis(250); +/// Tracks shown in the "All" tab before "Show all". +const ALL_TAB_TRACKS: usize = 5; + +#[derive(Debug, Clone)] +pub enum Msg { + Changed(String), + /// The debounce timer for this text ran out. + Settled(String), + Suggestions(String, Result, Error>), + Pick(String), + Submit, + CloseSuggestions, + Tab(SearchKind), + Loaded { query: String, kind: SearchKind, page: u32, result: Box> }, + More, +} + +/// Results for one query and kind, with the tracks as a playable list. +#[derive(Debug)] +pub struct Results { + pub data: SearchResults, + pub tracks: Arc<[Track]>, + /// The first few tracks for the "All" tab, built once so the cached list stays valid. + top: Arc<[Track]>, + pub page: u32, + loading_more: bool, +} + +#[derive(Debug, Default)] +pub struct Search { + pub text: String, + /// The query the results are for; `text` may have moved on since. + query: String, + kind: SearchKind, + results: Loadable, + suggestions: Vec, + show_suggestions: bool, +} + +/// What the app should do after a search message besides running the task. +pub enum After { + Nothing, + ShowResults, +} + +impl Search { + pub fn suggestions(&self) -> Option<&[String]> { + (self.show_suggestions && !self.suggestions.is_empty()).then_some(&self.suggestions) + } + + pub fn update(&mut self, msg: Msg, client: Option<&YmClient>) -> (Task, After) { + match msg { + Msg::Changed(text) => { + self.text = text.clone(); + self.show_suggestions = !text.trim().is_empty(); + if text.trim().is_empty() { + self.suggestions.clear(); + return (Task::none(), After::Nothing); + } + let task = Task::future(async move { + tokio::time::sleep(DEBOUNCE).await; + text + }) + .map(|t| Message::Search(Msg::Settled(t))); + return (task, After::Nothing); + } + Msg::Settled(text) => { + // Only the last keystroke's timer asks. + if text != self.text { + return (Task::none(), After::Nothing); + } + let Some(client) = client.cloned() else { return (Task::none(), After::Nothing) }; + let part = text.clone(); + let task = Task::future(async move { client.suggest(&part).await }) + .map(move |r| Message::Search(Msg::Suggestions(text.clone(), r))); + return (task, After::Nothing); + } + Msg::Suggestions(text, Ok(list)) if text == self.text => self.suggestions = list, + Msg::Suggestions(_, Err(e)) => eprintln!("suggest: {e}"), + Msg::Suggestions(..) => {} + Msg::Pick(text) => { + self.text = text; + return self.update(Msg::Submit, client); + } + Msg::Submit => { + self.show_suggestions = false; + let query = self.text.trim().to_owned(); + if query.is_empty() { + return (Task::none(), After::ShowResults); + } + if query != self.query || self.results.needs_load() { + self.query = query; + return (self.fetch(client, 0), After::ShowResults); + } + return (Task::none(), After::ShowResults); + } + Msg::CloseSuggestions => self.show_suggestions = false, + Msg::Tab(kind) => { + if kind != self.kind { + self.kind = kind; + if !self.query.is_empty() { + return (self.fetch(client, 0), After::Nothing); + } + } + } + Msg::Loaded { query, kind, page, result } => { + if query != self.query || kind != self.kind { + return (Task::none(), After::Nothing); + } + match (*result, &mut self.results) { + (Ok(more), Loadable::Loaded(current)) if page > 0 => { + current.data.tracks.extend(more.tracks); + current.data.albums.extend(more.albums); + current.data.artists.extend(more.artists); + current.data.playlists.extend(more.playlists); + current.data.podcasts.extend(more.podcasts); + current.tracks = current.data.tracks.clone().into(); + current.top = top_of(¤t.tracks); + current.page = page; + current.loading_more = false; + } + (Ok(data), _) => { + let tracks: Arc<[Track]> = data.tracks.clone().into(); + let top = top_of(&tracks); + self.results = Loadable::Loaded(Results { data, tracks, top, page, loading_more: false }); + } + (Err(e), Loadable::Loaded(current)) if page > 0 => { + eprintln!("search more: {e}"); + current.loading_more = false; + } + (Err(e), _) => { + eprintln!("search: {e}"); + self.results = Loadable::Failed(e); + } + } + } + Msg::More => { + if let Loadable::Loaded(current) = &mut self.results + && !current.loading_more + { + current.loading_more = true; + let next = current.page + 1; + return (self.fetch(client, next), After::Nothing); + } + } + } + (Task::none(), After::Nothing) + } + + fn fetch(&mut self, client: Option<&YmClient>, page: u32) -> Task { + let Some(client) = client.cloned() else { return Task::none() }; + if page == 0 { + self.results = Loadable::Loading; + } + let (query, kind) = (self.query.clone(), self.kind); + Task::future(async move { + let result = client.search(&query, kind, page).await; + Msg::Loaded { query, kind, page, result: Box::new(result) } + }) + .map(Message::Search) + } + + fn has_more(&self, r: &Results) -> bool { + let Some(total) = r.data.totals.get(self.kind) else { return false }; + let shown = match self.kind { + SearchKind::All => return false, + SearchKind::Tracks => r.data.tracks.len(), + SearchKind::Albums => r.data.albums.len(), + SearchKind::Artists => r.data.artists.len(), + SearchKind::Playlists => r.data.playlists.len(), + SearchKind::Podcasts => r.data.podcasts.len(), + }; + (shown as u32) < total + } +} + +pub fn view<'a>(env: Env<'a>, search: &'a Search, browse: Element<'a, Message>) -> Element<'a, Message> { + let t = env.t; + if search.query.is_empty() { + return column![line("Browse", theme::DISPLAY, size::DISPLAY_S, t.fg), browse].spacing(24).into(); + } + + let tabs = row(SearchKind::ALL.map(|kind| { + let on = kind == search.kind; + let total = search.results.get().and_then(|r| r.data.totals.get(kind)).filter(|n| *n > 0); + let mut label = row![line(kind.label(), theme::MEDIUM, size::BODY, if on { t.fg } else { t.muted })] + .spacing(6) + .align_y(Alignment::Center); + if let Some(n) = total { + label = label.push(line(compact(i64::from(n)), theme::BODY, size::SMALL, t.muted)); + } + button( + column![ + label, + container(iced::widget::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::Search(Msg::Tab(kind))) + .into() + })) + .spacing(4); + + let title = line(format!("Results for “{}”", search.query), theme::DISPLAY, size::DISPLAY_S, t.fg); + let body: Element<'a, Message> = match &search.results { + Loadable::Loaded(r) if r.data.is_empty() => para( + format!("Nothing found for “{}”. Check the spelling or try fewer words.", search.query), + size::BODY, + t.muted, + ) + .into(), + Loadable::Loaded(r) => results(env, search, r), + Loadable::Failed(e) => status(t, LoadState::Failed(e), "results", Message::Search(Msg::Submit)), + _ => para("Searching…", size::BODY, t.muted).into(), + }; + + let mut page = column![title].spacing(24); + if let Some(corrected) = search.results.get().and_then(|r| r.data.corrected.as_ref()) { + page = page.push(line(format!("Showing results for “{corrected}”"), theme::BODY, size::META, t.muted)); + } + page.push(tabs).push(body).into() +} + +fn results<'a>(env: Env<'a>, search: &'a Search, r: &'a Results) -> Element<'a, Message> { + let t = env.t; + let covers = env.covers; + let d = &r.data; + let more = search.has_more(r).then(|| { + button(line(if r.loading_more { "Loading…" } else { "Show more" }, theme::MEDIUM, size::BODY, t.fg)) + .padding([10, 18]) + .style(theme::ghost) + .on_press_maybe((!r.loading_more).then_some(Message::Search(Msg::More))) + }); + + let body: Element<'a, Message> = match search.kind { + SearchKind::All => { + let mut all = column![].spacing(34); + if let Some(best) = &d.best { + all = all.push(best_card(env, best)); + } + if !r.tracks.is_empty() { + all = all.push( + column![ + row![ + line("Tracks", theme::SEMIBOLD, size::SECTION, t.fg).width(Fill), + button(line("Show all", theme::MEDIUM, size::META, t.muted)) + .padding(0) + .style(theme::tab(false)) + .on_press(Message::Search(Msg::Tab(SearchKind::Tracks))), + ], + track_list::view(env, &r.top, Columns::FULL), + ] + .spacing(14), + ); + } + if !d.artists.is_empty() { + all = all.push(section(t, "Artists", d.artists.iter().take(6).map(|a| artist_card(t, covers, a)))); + } + if !d.albums.is_empty() { + all = all.push(section(t, "Albums", d.albums.iter().take(6).map(|a| album_card(t, covers, a)))); + } + if !d.playlists.is_empty() { + all = all.push(section(t, "Playlists", d.playlists.iter().take(6).map(|p| playlist_card(t, covers, p)))); + } + if !d.podcasts.is_empty() { + all = all.push(section(t, "Podcasts", d.podcasts.iter().take(6).map(|a| album_card(t, covers, a)))); + } + all.into() + } + SearchKind::Tracks => column![ + play_bar(t, String::new(), &r.tracks), + track_list::view(env, &r.tracks, Columns::FULL), + ] + .spacing(18) + .into(), + SearchKind::Albums => card::grid(d.albums.iter().map(|a| album_card(t, covers, a))), + SearchKind::Artists => card::grid(d.artists.iter().map(|a| artist_card(t, covers, a))), + SearchKind::Playlists => card::grid(d.playlists.iter().map(|p| playlist_card(t, covers, p))), + SearchKind::Podcasts => card::grid(d.podcasts.iter().map(|a| album_card(t, covers, a))), + }; + column![body].push(more).spacing(22).into() +} + +/// The top result as a wide card: cover, name, kind, and the action it implies. +fn best_card<'a>(env: Env<'a>, best: &'a BestMatch) -> Element<'a, Message> { + let t = env.t; + let (cover, hues, round, title, kind, action) = match best { + BestMatch::Artist(a) => ( + a.cover_url(covers::LARGE), a.hues(), true, a.name.clone(), "Artist".to_owned(), + Message::Navigate(Route::Artist(a.id)), + ), + BestMatch::Album(a) => ( + a.cover_url(covers::LARGE), a.hues(), false, a.full_title(), format!("{} · {}", a.kind.label(), a.artist_line()), + Message::Navigate(Route::Album(a.id)), + ), + BestMatch::Playlist(p) => ( + p.cover_url(covers::LARGE), p.hues(), false, p.title.clone(), format!("Playlist · {}", p.owner_name), + Message::Navigate(Route::Playlist(p.id)), + ), + BestMatch::Track(tr) => ( + tr.cover_url(covers::LARGE), tr.hues(), false, tr.full_title(), format!("Track · {}", tr.artist_line()), + Message::PlayTracks { tracks: Arc::from(vec![tr.clone()]), start: 0, shuffle: false }, + ), + }; + let size_px = 108.0; + let corner = if round { size_px / 2.0 } else { radius::COVER }; + let glyph = if matches!(best, BestMatch::Track(_)) { Icon::Play } else { Icon::Forward }; + button( + row![ + covers::view(env.covers, cover, hues, size_px, corner), + column![ + line("Top result", theme::MEDIUM, size::SMALL, t.muted), + line(title, theme::DISPLAY, 24.0, t.fg), + line(kind, theme::BODY, size::META, t.muted), + ] + .spacing(6) + .width(Fill), + container(icon(glyph, t.accent_ink)) + .center(44) + .style(move |_| container::Style { + background: Some(t.accent.into()), + border: iced::Border { radius: radius::PILL.into(), ..Default::default() }, + ..Default::default() + }) + .padding(0), + ] + .spacing(20) + .align_y(Alignment::Center), + ) + .padding(18) + .width(Fill) + .style(move |th, status| { + let mut s = theme::nav_item(false)(th, status); + if s.background.is_none() { + s.background = Some(t.panel.into()); + } + s.border = iced::Border { color: t.line, width: 1.0, radius: radius::CARD.into() }; + s + }) + .on_press(action) + .into() +} + +fn top_of(tracks: &[Track]) -> Arc<[Track]> { + tracks.iter().take(ALL_TAB_TRACKS).cloned().collect() +} + +/// The suggestion list floating under the search field. +pub fn suggestions<'a>(t: &'static theme::Tokens, list: &'a [String]) -> Element<'a, Message> { + let items = list.iter().take(8).map(|s| { + button( + row![icon(Icon::Search, t.muted), line(s.clone(), theme::BODY, size::BODY, t.fg)] + .spacing(10) + .align_y(Alignment::Center), + ) + .width(Fill) + .padding([8, 12]) + .style(theme::nav_item(false)) + .on_press(Message::Search(Msg::Pick(s.clone()))) + .into() + }); + container(column(items).spacing(2)) + .padding(6) + .width(420) + .style(move |_| container::Style { + background: Some(t.panel.into()), + border: iced::Border { color: t.line, width: 1.0, radius: 12.0.into() }, + shadow: iced::Shadow { + color: iced::Color::BLACK.scale_alpha(0.3), + offset: iced::Vector::new(0.0, 12.0), + blur_radius: 30.0, + }, + ..Default::default() + }) + .into() +} + +#[cfg(test)] +mod tests { + use super::*; + + fn loaded(page: u32, titles: &[&str], total: u32) -> Msg { + let tracks = titles + .iter() + .enumerate() + .map(|(i, t)| Track::from_json(&format!(r#"{{"id":"{}{i}","title":"{t}"}}"#, page)).unwrap()) + .collect(); + let mut data = SearchResults { tracks, ..Default::default() }; + data.totals.tracks = total; + Msg::Loaded { query: "q".into(), kind: SearchKind::Tracks, page, result: Box::new(Ok(data)) } + } + + fn searched() -> Search { + let mut s = Search::default(); + let _ = s.update(Msg::Changed("q".into()), None); + let _ = s.update(Msg::Submit, None); + let _ = s.update(Msg::Tab(SearchKind::Tracks), None); + s + } + + #[test] + fn stale_suggestions_and_results_are_dropped() { + let mut s = Search::default(); + let _ = s.update(Msg::Changed("зем".into()), None); + let _ = s.update(Msg::Changed("земф".into()), None); + let _ = s.update(Msg::Suggestions("зем".into(), Ok(vec!["old".into()])), None); + assert!(s.suggestions().is_none()); + let _ = s.update(Msg::Suggestions("земф".into(), Ok(vec!["земфира".into()])), None); + assert_eq!(s.suggestions().unwrap(), ["земфира".to_owned()]); + let _ = s.update(Msg::Submit, None); + assert!(s.suggestions().is_none(), "submitting hides suggestions"); + } + + #[test] + fn more_pages_append() { + let mut s = searched(); + let _ = s.update(loaded(0, &["a", "b"], 4), None); + let Loadable::Loaded(r) = &s.results else { panic!() }; + assert!(s.has_more(r)); + let _ = s.update(Msg::More, None); + let _ = s.update(loaded(1, &["c", "d"], 4), None); + let Loadable::Loaded(r) = &s.results else { panic!() }; + assert_eq!(r.tracks.len(), 4); + assert!(!s.has_more(r)); + } + + #[test] + fn results_for_another_tab_are_ignored() { + let mut s = searched(); + let mut msg = loaded(0, &["a"], 1); + if let Msg::Loaded { kind, .. } = &mut msg { + *kind = SearchKind::Albums; + } + let _ = s.update(msg, None); + assert!(s.results.get().is_none()); + } +} diff --git a/crates/musyx/src/snapshot.rs b/crates/musyx/src/snapshot.rs index 95815ce..43e324f 100644 --- a/crates/musyx/src/snapshot.rs +++ b/crates/musyx/src/snapshot.rs @@ -27,6 +27,10 @@ pub struct Config { pub route: Option, pub drawer: Option, pub mode: Option, + /// `MUSYX_SNAPSHOT_LIVE=1`: sign in with the stored account instead of sample data. + pub live: bool, + /// `MUSYX_SNAPSHOT_DELAY` in ms before capturing (default 1500; live runs need longer). + pub delay: Duration, } impl Config { @@ -43,6 +47,7 @@ impl Config { "podcasts" => Route::Podcasts, "settings" => Route::Settings, "album" => Route::Album(1), + "chart" => Route::Chart, _ => return None, }) }); @@ -56,7 +61,11 @@ impl Config { "dark" => Some(Mode::Dark), _ => None, }); - Some(Self { out, signed_out, route, drawer, mode }) + let live = var("MUSYX_SNAPSHOT_LIVE").is_some_and(|v| v == "1"); + let delay = var("MUSYX_SNAPSHOT_DELAY") + .and_then(|d| d.parse().ok()) + .map_or(Duration::from_millis(if live { 8000 } else { 1500 }), Duration::from_millis); + Some(Self { out, signed_out, route, drawer, mode, live, delay }) } /// A made-up account so the shell renders without a network or keychain. @@ -122,7 +131,7 @@ impl Config { /// 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))) + Task::future(tokio::time::sleep(self.delay)) .then(|()| window::latest()) .then(|id| match id { Some(id) => window::screenshot(id), diff --git a/crates/musyx/src/ui/icons.rs b/crates/musyx/src/ui/icons.rs index 80927c8..bff9d03 100644 --- a/crates/musyx/src/ui/icons.rs +++ b/crates/musyx/src/ui/icons.rs @@ -37,6 +37,8 @@ icons! { Plus => "plus", LogOut => "log-out", Back => "chevron-left", + Forward => "chevron-right", + Chart => "trending-up", Play => "play-fill", Pause => "pause-fill", Previous => "skip-back", diff --git a/crates/musyx/src/widgets/topbar.rs b/crates/musyx/src/widgets/topbar.rs index 4f1a715..095cfd3 100644 --- a/crates/musyx/src/widgets/topbar.rs +++ b/crates/musyx/src/widgets/topbar.rs @@ -4,6 +4,7 @@ use iced::widget::{button, row, text_input}; use iced::{Alignment, Element}; use crate::app::Message; +use crate::screens::search::Msg; use crate::ui::icons::{Icon, icon}; use crate::ui::theme::{self, Tokens, size, space}; @@ -17,8 +18,8 @@ pub fn view<'a>(t: &'static Tokens, can_go_back: bool, query: &str) -> Element<' let search = text_input("Search artists, tracks, podcasts", query) .id(SEARCH_ID) - .on_input(Message::SearchChanged) - .on_submit(Message::SearchSubmitted) + .on_input(|text| Message::Search(Msg::Changed(text))) + .on_submit(Message::Search(Msg::Submit)) .font(theme::BODY) .size(size::BODY) .padding([10, 16]) diff --git a/crates/musyx/src/widgets/track_list.rs b/crates/musyx/src/widgets/track_list.rs index d5b42c8..af9dd88 100644 --- a/crates/musyx/src/widgets/track_list.rs +++ b/crates/musyx/src/widgets/track_list.rs @@ -34,6 +34,16 @@ struct Key { } pub fn view<'a>(env: Env<'a>, tracks: &Arc<[Track]>, columns: Columns) -> Element<'a, Message> { + view_with(env, tracks, columns, None) +} + +/// [`view`] with chart movements, one per track. +pub fn view_with<'a>( + env: Env<'a>, + tracks: &Arc<[Track]>, + columns: Columns, + shifts: Option>, +) -> Element<'a, Message> { let Env { t, covers, liked, playing } = env; let key = Key { list: (tracks.as_ptr() as usize, tracks.len()), @@ -60,6 +70,7 @@ pub fn view<'a>(env: Env<'a>, tracks: &Arc<[Track]>, columns: Columns) -> Elemen liked: liked.contains(&track.id), cover, columns, + shift: shifts.as_ref().and_then(|s| s.get(index).copied()).unwrap_or(0), on_press: Message::PlayTracks { tracks: tracks.clone(), start: index, shuffle: false }, }, ) diff --git a/crates/musyx/src/widgets/track_row.rs b/crates/musyx/src/widgets/track_row.rs index 6c79c69..f6ab2d9 100644 --- a/crates/musyx/src/widgets/track_row.rs +++ b/crates/musyx/src/widgets/track_row.rs @@ -18,11 +18,14 @@ pub const HEIGHT: f32 = 52.0; pub struct Columns { pub cover: bool, pub album: bool, + /// Chart lists show how far each track moved. + pub shift: bool, } impl Columns { - pub const FULL: Columns = Columns { cover: true, album: true }; - pub const ALBUM_PAGE: Columns = Columns { cover: false, album: false }; + pub const FULL: Columns = Columns { cover: true, album: true, shift: false }; + pub const ALBUM_PAGE: Columns = Columns { cover: false, album: false, shift: false }; + pub const CHART: Columns = Columns { cover: true, album: true, shift: true }; } pub struct Row<'a> { @@ -32,6 +35,8 @@ pub struct Row<'a> { pub liked: bool, pub cover: Option>, pub columns: Columns, + /// Places moved in the chart; shown when `columns.shift`. + pub shift: i32, pub on_press: Message, } @@ -55,6 +60,9 @@ pub fn view(t: &'static Tokens, r: Row<'_>) -> Element<'static, Message> { .spacing(12) .align_y(Alignment::Center) .height(HEIGHT); + if r.columns.shift { + content = content.push(crate::screens::browse::shift_marker(t, r.shift)); + } if r.columns.cover { content = content.push(r.cover.unwrap_or_else(|| space().width(40).into())); } @@ -109,6 +117,9 @@ pub fn header(t: &'static Tokens, columns: Columns) -> Element<'static, Message> .spacing(12) .align_y(Alignment::Center) .padding([0, 10]); + if columns.shift { + heads = heads.push(space().width(14)); + } if columns.cover { heads = heads.push(space().width(40)); } diff --git a/crates/ym-api/src/client.rs b/crates/ym-api/src/client.rs index 7830931..4fd54bc 100644 --- a/crates/ym-api/src/client.rs +++ b/crates/ym-api/src/client.rs @@ -5,9 +5,29 @@ use crate::library::{ AlbumPage, AlbumSummary, ArtistPage, ArtistSummary, LibraryPlaylists, PlaylistId, PlaylistPage, PlaylistSummary, }; +use crate::discover::{ChartEntry, Genre, Home, SearchKind, SearchResults}; use crate::models::{Stream, Track, best_variant}; use crate::{Error, Result}; +/// How many featured podcasts to resolve. +pub const FEATURED_PODCASTS: usize = 48; + +/// Playlist ids from `/tags/{id}/playlist-ids`: `{"ids":[{"uid":1,"kind":2}]}`, +/// tolerating the `"uid:kind"` string form too. +fn tag_playlist_ids(raw: &serde_json::Value) -> Vec { + let ids = raw.get("result").unwrap_or(raw).get("ids").and_then(|v| v.as_array()); + ids.into_iter() + .flatten() + .filter_map(|id| match id { + serde_json::Value::String(s) if s.contains(':') => Some(s.clone()), + serde_json::Value::Object(o) => { + Some(format!("{}:{}", o.get("uid")?.as_i64()?, o.get("kind")?.as_i64()?)) + } + _ => None, + }) + .collect() +} + /// The signed-in user as the UI needs them. #[derive(Debug, Clone, PartialEq, Eq)] pub struct Account { @@ -211,6 +231,72 @@ impl YmClient { }) } + /// One page of search results. `page` starts at 0. + pub async fn search(&self, text: &str, kind: SearchKind, page: u32) -> Result { + let mut query = yamuse::SearchQuery::default().of_type(kind.to_yamuse()); + query.page = page; + Ok(SearchResults::from_yamuse(self.inner.search(text, query).await?)) + } + + /// Completions for a partial query, best first. + pub async fn suggest(&self, part: &str) -> Result> { + Ok(self.inner.search_suggest(part).await?.suggestions) + } + + /// The home page: personal playlists, new releases and playlists, the chart. + pub async fn home(&self) -> Result { + let landing = self + .inner + .landing(["personalplaylists", "new-releases", "new-playlists"]) + .await?; + let mut home = Home::from_landing(landing); + // The chart block on landing3 holds a handful of items; the chart endpoint has them all. + match self.chart().await { + Ok(chart) if !chart.is_empty() => home.chart = chart, + Ok(_) => {} + Err(e) => eprintln!("chart: {e}"), + } + Ok(home) + } + + pub async fn chart(&self) -> Result> { + let info = self.inner.chart().await?; + Ok(info + .chart + .map(|p| p.tracks.into_iter().filter_map(ChartEntry::from_short).collect()) + .unwrap_or_default()) + } + + pub async fn genres(&self) -> Result> { + Ok(self.inner.genres().await?.into_iter().filter_map(Genre::from_yamuse).collect()) + } + + /// Editorial playlists filed under a genre or mood tag. + pub async fn tag_playlists(&self, tag: &str) -> Result> { + // yamuse types these ids as strings; the API sends `{uid, kind}` objects. + let raw = self + .inner + .get_raw(&format!("/tags/{tag}/playlist-ids"), yamuse::Params::new()) + .await?; + let ids = tag_playlist_ids(&raw); + if ids.is_empty() { + return Ok(Vec::new()); + } + let playlists = self.inner.playlists_list(&ids).await?; + Ok(playlists.iter().filter_map(PlaylistSummary::from_yamuse).collect()) + } + + /// Podcasts Yandex currently features (the first [`FEATURED_PODCASTS`]; the list runs to thousands). + pub async fn featured_podcasts(&self) -> Result> { + let mut ids = self.inner.podcasts().await?.podcasts; + ids.truncate(FEATURED_PODCASTS); + 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()) + } + /// 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()]) @@ -259,6 +345,14 @@ mod tests { assert_eq!(a.subscription_end, None); } + #[test] + fn tag_ids_accept_objects_and_strings() { + let raw = serde_json::json!({"ids": [{"uid": 1, "kind": 2}, "3:4", null, {"uid": 5}]}); + assert_eq!(tag_playlist_ids(&raw), vec!["1:2", "3:4"]); + let wrapped = serde_json::json!({"result": {"ids": [{"uid": 9, "kind": 8}]}}); + assert_eq!(tag_playlist_ids(&wrapped), vec!["9:8"]); + } + #[test] fn anonymous_status_is_not_an_account() { assert!(Account::from_status(status(r#"{"account":{"now":"2026-10-15"}}"#)).is_none()); diff --git a/crates/ym-api/src/discover.rs b/crates/ym-api/src/discover.rs new file mode 100644 index 0000000..536b43b --- /dev/null +++ b/crates/ym-api/src/discover.rs @@ -0,0 +1,302 @@ +//! Search, the home landing, the chart, genres and podcasts. + +use yamuse::models as y; + +use crate::library::{AlbumSummary, ArtistSummary, PlaylistSummary}; +use crate::models::Track; + +/// Which part of the catalogue a search covers. +#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default)] +pub enum SearchKind { + #[default] + All, + Tracks, + Albums, + Artists, + Playlists, + Podcasts, +} + +impl SearchKind { + pub const ALL: [SearchKind; 6] = [ + SearchKind::All, + SearchKind::Tracks, + SearchKind::Albums, + SearchKind::Artists, + SearchKind::Playlists, + SearchKind::Podcasts, + ]; + + pub fn label(self) -> &'static str { + match self { + SearchKind::All => "All", + SearchKind::Tracks => "Tracks", + SearchKind::Albums => "Albums", + SearchKind::Artists => "Artists", + SearchKind::Playlists => "Playlists", + SearchKind::Podcasts => "Podcasts", + } + } + + pub(crate) fn to_yamuse(self) -> yamuse::SearchType { + match self { + SearchKind::All => yamuse::SearchType::All, + SearchKind::Tracks => yamuse::SearchType::Track, + SearchKind::Albums => yamuse::SearchType::Album, + SearchKind::Artists => yamuse::SearchType::Artist, + SearchKind::Playlists => yamuse::SearchType::Playlist, + SearchKind::Podcasts => yamuse::SearchType::Podcast, + } + } +} + +#[derive(Debug, Clone, PartialEq, Eq)] +pub enum BestMatch { + Track(Track), + Album(AlbumSummary), + Artist(ArtistSummary), + Playlist(PlaylistSummary), +} + +#[derive(Debug, Clone, Default, PartialEq, Eq)] +pub struct SearchResults { + /// The query Yandex actually searched, when it corrected a typo. + pub corrected: Option, + pub best: Option, + pub tracks: Vec, + pub albums: Vec, + pub artists: Vec, + pub playlists: Vec, + pub podcasts: Vec, + /// Total matches per kind, beyond the page returned. + pub totals: Totals, +} + +#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)] +pub struct Totals { + pub tracks: u32, + pub albums: u32, + pub artists: u32, + pub playlists: u32, + pub podcasts: u32, +} + +impl Totals { + pub fn get(&self, kind: SearchKind) -> Option { + match kind { + SearchKind::All => None, + SearchKind::Tracks => Some(self.tracks), + SearchKind::Albums => Some(self.albums), + SearchKind::Artists => Some(self.artists), + SearchKind::Playlists => Some(self.playlists), + SearchKind::Podcasts => Some(self.podcasts), + } + } +} + +impl SearchResults { + pub(crate) fn from_yamuse(s: y::Search) -> Self { + fn part(r: Option>, f: impl Fn(T) -> Option) -> (Vec, u32) { + match r { + Some(r) => (r.results.into_iter().filter_map(f).collect(), r.total.unwrap_or(0)), + None => (Vec::new(), 0), + } + } + let best = s.best.as_ref().and_then(|b| b.entity()).and_then(|e| match e { + y::SearchEntity::Track(t) => Track::from_yamuse(*t).map(BestMatch::Track), + y::SearchEntity::Album(a) => AlbumSummary::from_yamuse(*a).map(BestMatch::Album), + y::SearchEntity::Artist(a) => ArtistSummary::from_yamuse(*a).map(BestMatch::Artist), + y::SearchEntity::Playlist(p) => PlaylistSummary::from_yamuse(&p).map(BestMatch::Playlist), + _ => None, + }); + let (tracks, t_total) = part(s.tracks, Track::from_yamuse); + let (albums, al_total) = part(s.albums, AlbumSummary::from_yamuse); + let (artists, ar_total) = part(s.artists, ArtistSummary::from_yamuse); + let (playlists, p_total) = part(s.playlists, |p| PlaylistSummary::from_yamuse(&p)); + let (podcasts, pc_total) = part(s.podcasts, AlbumSummary::from_yamuse); + Self { + corrected: s.misspell_corrected.unwrap_or(false).then_some(s.misspell_result).flatten(), + best, + tracks, + albums, + artists, + playlists, + podcasts, + totals: Totals { + tracks: t_total, + albums: al_total, + artists: ar_total, + playlists: p_total, + podcasts: pc_total, + }, + } + } + + pub fn is_empty(&self) -> bool { + self.best.is_none() + && self.tracks.is_empty() + && self.albums.is_empty() + && self.artists.is_empty() + && self.playlists.is_empty() + && self.podcasts.is_empty() + } +} + +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct ChartEntry { + pub position: u32, + /// Places moved since the last chart: positive is up. + pub shift: i32, + pub track: Track, +} + +impl ChartEntry { + pub(crate) fn from_short(short: y::TrackShort) -> Option { + let chart: Option = short.chart.and_then(|c| serde_json::from_value(c).ok()); + Some(Self { + position: chart.as_ref().and_then(|c| c.position).unwrap_or(0).max(0) as u32, + shift: chart.as_ref().and_then(|c| c.shift).unwrap_or(0) as i32, + track: Track::from_yamuse(short.track?)?, + }) + } +} + +/// A personal playlist ("Playlist of the Day", "Déjà Vu"…) with its blurb. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct Personal { + pub playlist: PlaylistSummary, + pub description: Option, +} + +#[derive(Debug, Clone, Default, PartialEq, Eq)] +pub struct Home { + pub personal: Vec, + pub chart: Vec, + pub new_releases: Vec, + pub new_playlists: Vec, +} + +impl Home { + pub(crate) fn from_landing(landing: y::Landing) -> Self { + let mut home = Home::default(); + for block in landing.blocks { + for entity in &block.entities { + match entity.data() { + Some(y::BlockEntityData::PersonalPlaylist(g)) => { + if let Some(playlist) = g.data.as_ref().and_then(PlaylistSummary::from_yamuse) { + let description = g.preview_description.clone().filter(|d| !d.trim().is_empty()); + home.personal.push(Personal { playlist, description }); + } + } + Some(y::BlockEntityData::Album(a)) => { + home.new_releases.extend(AlbumSummary::from_yamuse(*a)); + } + Some(y::BlockEntityData::Playlist(p)) => { + home.new_playlists.extend(PlaylistSummary::from_yamuse(&p)); + } + Some(y::BlockEntityData::ChartItem(item)) => { + let entry = item.track.and_then(Track::from_yamuse).map(|track| ChartEntry { + position: item.chart.as_ref().and_then(|c| c.position).unwrap_or(0).max(0) as u32, + shift: item.chart.as_ref().and_then(|c| c.shift).unwrap_or(0) as i32, + track, + }); + home.chart.extend(entry); + } + _ => {} + } + } + } + home + } +} + +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct Genre { + pub id: String, + pub title: String, + /// `#rrggbb` from Yandex, used to tint the genre tile. + pub color: Option, + pub sub_genres: Vec, +} + +impl Genre { + pub(crate) fn from_yamuse(g: y::Genre) -> Option { + let title = g + .title + .or_else(|| g.titles.get("en").and_then(|t| t.title.clone())) + .or_else(|| g.titles.get("ru").and_then(|t| t.title.clone()))?; + Some(Self { + id: g.id?, + title, + color: g.color.filter(|c| c.starts_with('#')), + sub_genres: g.sub_genres.into_iter().filter_map(Genre::from_yamuse).collect(), + }) + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn search_results_convert_with_best_match_and_totals() { + let s: y::Search = serde_json::from_str( + r#"{"best":{"type":"artist","result":{"id":3,"name":"Земфира"}}, + "tracks":{"total":120,"results":[{"id":1,"title":"Хочешь?"}]}, + "albums":{"total":40,"results":[{"id":5,"title":"Вендетта"}]}, + "misspellCorrected":true,"misspellResult":"земфира"}"#, + ) + .unwrap(); + let r = SearchResults::from_yamuse(s); + assert!(matches!(r.best, Some(BestMatch::Artist(ref a)) if a.name == "Земфира")); + assert_eq!(r.tracks.len(), 1); + assert_eq!(r.totals.get(SearchKind::Tracks), Some(120)); + assert_eq!(r.totals.get(SearchKind::Albums), Some(40)); + assert_eq!(r.corrected.as_deref(), Some("земфира")); + assert!(!r.is_empty()); + assert!(SearchResults::from_yamuse(serde_json::from_str("{}").unwrap()).is_empty()); + } + + #[test] + fn chart_entry_reads_position_and_shift() { + let short: y::TrackShort = serde_json::from_str( + r#"{"id":1,"track":{"id":1,"title":"Хит"},"chart":{"position":3,"shift":-2,"progress":"down"}}"#, + ) + .unwrap(); + let e = ChartEntry::from_short(short).unwrap(); + assert_eq!((e.position, e.shift), (3, -2)); + } + + #[test] + fn landing_blocks_split_by_entity_type() { + let landing: y::Landing = serde_json::from_str( + r#"{"blocks":[ + {"type":"personal-playlists","entities":[{"type":"personal-playlist","data":{ + "data":{"uid":1,"kind":3,"title":"Плейлист дня","owner":{"uid":1}}, + "previewDescription":"Updated every day"}}]}, + {"type":"new-releases","entities":[{"type":"album","data":{"id":9,"title":"New"}}]}, + {"type":"chart","entities":[{"type":"chart-item","data":{ + "track":{"id":7,"title":"Top"},"chart":{"position":1,"shift":0}}}]} + ]}"#, + ) + .unwrap(); + let home = Home::from_landing(landing); + assert_eq!(home.personal[0].playlist.title, "Плейлист дня"); + assert_eq!(home.personal[0].description.as_deref(), Some("Updated every day")); + assert_eq!(home.new_releases[0].id, 9); + assert_eq!(home.chart[0].position, 1); + } + + #[test] + fn genre_title_falls_back_to_localised_titles() { + let g: y::Genre = serde_json::from_str( + r##"{"id":"rock","titles":{"en":{"title":"Rock"}},"color":"#ff0000", + "subGenres":[{"id":"punk","title":"Punk"}]}"##, + ) + .unwrap(); + let g = Genre::from_yamuse(g).unwrap(); + assert_eq!(g.title, "Rock"); + assert_eq!(g.sub_genres[0].id, "punk"); + assert_eq!(g.color.as_deref(), Some("#ff0000")); + } +} diff --git a/crates/ym-api/src/lib.rs b/crates/ym-api/src/lib.rs index be61246..9c0a413 100644 --- a/crates/ym-api/src/lib.rs +++ b/crates/ym-api/src/lib.rs @@ -5,6 +5,7 @@ pub mod auth; mod client; +mod discover; mod error; mod library; mod models; @@ -15,4 +16,5 @@ pub use library::{ PlaylistPage, PlaylistSummary, }; pub use models::{AlbumRef, ArtistRef, Stream, Track}; +pub use discover::{BestMatch, ChartEntry, Genre, Home, Personal, SearchKind, SearchResults, Totals}; pub use error::{Error, Result}; diff --git a/crates/ym-api/src/library.rs b/crates/ym-api/src/library.rs index 702b662..c276e8d 100644 --- a/crates/ym-api/src/library.rs +++ b/crates/ym-api/src/library.rs @@ -74,11 +74,13 @@ impl AlbumSummary { join_names(&self.artists) } - /// "Кино · 1988", the line under a card. + /// "Кино · 1988", the line under a card. Podcasts often list no artist, so + /// those fall back to their kind: "Podcast · 2022". pub fn subtitle(&self) -> String { + let who = if self.artists.is_empty() { self.kind.label().to_owned() } else { self.artist_line() }; match self.year { - Some(year) => format!("{} · {year}", self.artist_line()), - None => self.artist_line(), + Some(year) => format!("{who} · {year}"), + None => who, } } @@ -285,6 +287,12 @@ mod tests { assert_eq!(page.album.cover_url(100).as_deref(), Some("https://a/100x100")); } + #[test] + fn subtitle_without_artists_names_the_kind() { + let a = AlbumSummary::from_yamuse(album(r#"{"id":1,"title":"TED","metaType":"podcast","year":2022}"#)).unwrap(); + assert_eq!(a.subtitle(), "Podcast · 2022"); + } + #[test] fn album_kinds() { assert_eq!(AlbumKind::from_api(None, Some("single")), AlbumKind::Single);