From e2312f2d4017ac6fe2f6837bd0cddee6de95dfc1 Mon Sep 17 00:00:00 2001 From: Yuriy Panov Date: Thu, 15 Oct 2026 16:09:12 +0600 Subject: [PATCH] feat: likes, track actions, playlist editing, lyrics and queue sync - ym-api: like/unlike tracks, albums, artists and playlists; dislike tracks; liked ids for drawing state; create, rename, publish/hide and delete playlists; add, remove and move tracks (fresh revision per edit); lyrics (LRC parsed, plain text fallback); server queues - Hearts on every track row, the player bar and album, artist and playlist pages, applied at once and re-read if Yandex refuses - Track menu: Play next (moves a queued track up rather than duplicating it; the playing track's menu offers Next track instead), Add to queue, like, Add to playlist or a new one, Go to album/artist, Don't recommend, and Move up/down/Remove on the user's own playlists - New playlist from the sidebar; Rename, Make public/private and Delete (confirmed) on own playlist pages; short status messages for every edit - Lyrics panel highlights and follows the sung line and seeks on click - Lists played are published as Yandex queues and their position kept - lyricsInfo decides lyrics availability (the old flag over-reports) - MUSYX_TRACE=1 logs user actions with the resulting queue - Headless UI tests (iced_test) click through menus over the full window --- Cargo.lock | 27 ++ README.md | 5 + crates/musyx/Cargo.toml | 1 + crates/musyx/examples/api_probe.rs | 33 +++ crates/musyx/src/app.rs | 351 ++++++++++++++++++++++++- crates/musyx/src/app/edit.rs | 298 +++++++++++++++++++++ crates/musyx/src/player/mod.rs | 117 ++++++++- crates/musyx/src/player/queue.rs | 47 ++++ crates/musyx/src/screens/collection.rs | 34 +++ crates/musyx/src/screens/detail.rs | 47 +++- crates/musyx/src/widgets/drawer.rs | 76 +++++- crates/musyx/src/widgets/mod.rs | 1 + crates/musyx/src/widgets/player_bar.rs | 11 +- crates/musyx/src/widgets/sheet.rs | 308 ++++++++++++++++++++++ crates/musyx/src/widgets/sidebar.rs | 3 +- crates/musyx/src/widgets/track_list.rs | 33 ++- crates/musyx/src/widgets/track_row.rs | 20 +- crates/ym-api/src/client.rs | 177 +++++++++++++ crates/ym-api/src/edit.rs | 155 +++++++++++ crates/ym-api/src/lib.rs | 2 + crates/ym-api/src/library.rs | 14 + crates/ym-api/src/models.rs | 7 +- 22 files changed, 1733 insertions(+), 34 deletions(-) create mode 100644 crates/musyx/src/app/edit.rs create mode 100644 crates/musyx/src/widgets/sheet.rs create mode 100644 crates/ym-api/src/edit.rs diff --git a/Cargo.lock b/Cargo.lock index b679fde..e9b19d5 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -2090,6 +2090,32 @@ dependencies = [ "thiserror 2.0.21", ] +[[package]] +name = "iced_selector" +version = "0.14.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b1442ccc30959cc48b3a624233521ef7f3bc3e06528b6fe306c3a775fbddc4fe" +dependencies = [ + "iced_core", +] + +[[package]] +name = "iced_test" +version = "0.14.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b56c26cc6e63958ce6be06a68fa3136fd5f646da6302ee12abf1a0f311dd0166" +dependencies = [ + "iced_futures", + "iced_program", + "iced_renderer", + "iced_runtime", + "iced_selector", + "nom", + "png 0.18.1", + "sha2 0.10.9", + "thiserror 2.0.21", +] + [[package]] name = "iced_tiny_skia" version = "0.14.1" @@ -2883,6 +2909,7 @@ version = "0.1.0" dependencies = [ "directories", "iced", + "iced_test", "keyring", "open", "png 0.18.1", diff --git a/README.md b/README.md index 4f976b9..44f2ac3 100644 --- a/README.md +++ b/README.md @@ -53,6 +53,11 @@ 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. +### Tracing + +`MUSYX_TRACE=1 cargo run -p musyx` logs each user action (not playback ticks or cover loads) +to stderr, followed by what's playing and the next three tracks. + ### Audio `cargo run -p musyx --example audio_probe` lists the output devices and checks that each one diff --git a/crates/musyx/Cargo.toml b/crates/musyx/Cargo.toml index e75bcf0..e0d0037 100644 --- a/crates/musyx/Cargo.toml +++ b/crates/musyx/Cargo.toml @@ -19,6 +19,7 @@ directories = "6.0.0" png = { version = "0.18.1", optional = true } [dev-dependencies] +iced_test = "0.14" tokio = { version = "1", features = ["macros", "rt"] } [features] diff --git a/crates/musyx/examples/api_probe.rs b/crates/musyx/examples/api_probe.rs index c6501fe..30c93b0 100644 --- a/crates/musyx/examples/api_probe.rs +++ b/crates/musyx/examples/api_probe.rs @@ -64,6 +64,39 @@ async fn main() { ), Err(e) => println!("wave: ERROR {e}"), } + match client.liked_ids().await { + Ok(l) => println!( + "liked ids: {} albums, {} artists, {} playlists, {} disliked tracks", + l.albums.len(), l.artists.len(), l.playlists.len(), l.disliked_tracks.len() + ), + Err(e) => println!("liked ids: ERROR {e}"), + } + if let Ok(found) = client.search("eminem without me", SearchKind::Tracks, 0).await { + for track in found.tracks.iter().take(2) { + println!("track {} {} lyrics_available={}", track.id, track.title, track.lyrics_available); + match client.lyrics(&track.id).await { + Ok(Some(l)) => println!( + "lyrics {}: synced={} lines={} first_stamp={:?}", + track.id, l.synced, l.lines.len(), l.lines.first().and_then(|x| x.at) + ), + Ok(None) => println!("lyrics {}: none", track.id), + Err(e) => println!("lyrics {}: ERROR {e}", track.id), + } + } + } + if let Ok(chart) = client.chart().await { + for entry in chart.iter().take(3) { + println!("chart {} lyrics_available={}", entry.track.id, entry.track.lyrics_available); + match client.lyrics(&entry.track.id).await { + Ok(Some(l)) => println!( + "lyrics {}: synced={} lines={} first_stamp={:?}", + entry.track.id, l.synced, l.lines.len(), l.lines.first().and_then(|x| x.at) + ), + Ok(None) => println!("lyrics {}: none", entry.track.id), + Err(e) => println!("lyrics {}: ERROR {e}", entry.track.id), + } + } + } 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 01d2d97..974d808 100644 --- a/crates/musyx/src/app.rs +++ b/crates/musyx/src/app.rs @@ -1,5 +1,7 @@ //! Application state, messages and the window layout. +mod edit; + use std::collections::HashMap; use std::sync::Arc; @@ -8,8 +10,8 @@ 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, Genre, Home, LibraryPlaylists, MY_WAVE, PlaylistSummary, - Station, Track, WaveSettings, YmClient, + Account, AlbumSummary, ArtistSummary, Error, Genre, Home, LibraryPlaylists, LikedIds, Lyrics, MY_WAVE, + PlaylistId, PlaylistSummary, Station, Track, WaveSettings, YmClient, }; use crate::covers::Covers; @@ -25,6 +27,7 @@ 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::sheet::{self, Sheet}; use crate::widgets::track_list::Env; use crate::widgets::{sidebar, topbar}; @@ -57,6 +60,16 @@ pub struct App { /// Drives the My Wave hero animation. wave_phase: f32, covers: Covers, + /// Albums, artists and playlists liked, and tracks disliked, by id. + likes: LikedIds, + sheet: Option, + toast: Option<(String, std::time::Instant)>, + /// Lyrics per track id, fetched while the lyrics panel is open. + lyrics: HashMap>>>, + /// The synced line last scrolled to. + lyric_line: Option, + /// The queue published to Yandex for the list playing now. + server_queue: Option, /// A live snapshot run opens this route once signed in. #[cfg(feature = "snapshot")] snapshot_route: Option, @@ -101,6 +114,31 @@ pub enum Message { SetWaveSettings(WaveSettings), WaveSettingsSaved(WaveSettings, Result<(), Error>), WaveTick, + LoadLikedIds, + LikedIdsLoaded(Result), + LikeTrack(Track, bool), + DislikeTrack(Track, bool), + LikeAlbum(i64, bool), + LikeArtist(i64, bool), + LikePlaylist(PlaylistId, bool), + OpenSheet(Sheet), + CloseSheet, + SheetText(String), + PlayNext(Track), + /// "Next track" in the menu of the track playing now. + SkipFromMenu, + AddToQueue(Track), + AddToPlaylist(PlaylistId, Track), + CreatePlaylist, + RenamePlaylist, + SetPlaylistPublic(PlaylistId, bool), + DeletePlaylist(PlaylistId), + RemoveFromPlaylist(PlaylistId, usize), + MovePlaylistTrack { id: PlaylistId, track: Track, from: usize, to: usize }, + Edited(Box), + LyricsLoaded(String, Result>, Error>), + QueueCreated(Result, Error>), + ToastTick, CoverWanted(String), CoverLoaded(String, Option>), CoversTick, @@ -123,6 +161,12 @@ impl App { wave: WaveScreen::default(), wave_phase: 0.0, covers: Covers::default(), + likes: LikedIds::default(), + sheet: None, + toast: None, + lyrics: HashMap::new(), + lyric_line: None, + server_queue: None, #[cfg(feature = "snapshot")] snapshot_route: None, }; @@ -179,6 +223,9 @@ impl App { if hero_visible && wave_playing && matches!(self.session, Session::SignedIn { .. }) { subs.push(iced::time::every(std::time::Duration::from_millis(33)).map(|_| Message::WaveTick)); } + if self.toast.is_some() { + subs.push(iced::time::every(std::time::Duration::from_millis(500)).map(|_| Message::ToastTick)); + } // 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)); @@ -212,12 +259,28 @@ impl App { } Task::batch([ self.update(Message::LoadLiked), + self.update(Message::LoadLikedIds), self.update(Message::LoadLibrary(Tab::Playlists)), self.on_enter(first), ]) } pub fn update(&mut self, message: Message) -> Task { + let traced = trace(&message); + let task = self.update_inner(message); + if traced { + let now = self.player.track().map_or("-".to_owned(), |t| t.full_title()); + let next: Vec = self + .player + .queue() + .map(|q| q.upcoming().take(3).map(|(_, t)| t.full_title()).collect()) + .unwrap_or_default(); + eprintln!("trace: now: {now} | next: {}", next.join(" / ")); + } + task + } + + fn update_inner(&mut self, message: Message) -> Task { match message { Message::ThemeChanged(mode) => { self.theme = theme::for_mode(self.forced_mode.unwrap_or(mode)); @@ -274,8 +337,13 @@ impl App { self.genre_playlists.clear(); self.search = Search::default(); self.wave = WaveScreen::default(); + self.likes = LikedIds::default(); + self.sheet = None; + self.lyrics.clear(); + self.server_queue = None; } Message::Navigate(route) => { + self.sheet = None; self.nav.go(route); let (close, _) = self.search.update(search::Msg::CloseSuggestions, None); return Task::batch([close, self.on_enter(route)]); @@ -305,12 +373,92 @@ impl App { } Message::ToggleDrawer(panel) => { self.drawer = if self.drawer == Some(panel) { None } else { Some(panel) }; + self.lyric_line = None; + return self.want_lyrics(); } Message::CloseDrawer => self.drawer = None, Message::Player(msg) => { + let before = self.player.track().map(|t| t.id.clone()); let effects = self.player.update(msg); - return self.run(effects); + let run = self.run(effects); + if self.player.track().map(|t| t.id.as_str()) != before.as_deref() { + self.lyric_line = None; + return Task::batch([run, self.want_lyrics()]); + } + return Task::batch([run, self.follow_lyrics()]); } + Message::PlayNext(track) => { + self.sheet = None; + if self.player.track().is_some_and(|t| t.id == track.id) { + self.toast(format!("“{}” is already playing", track.full_title())); + return Task::none(); + } + self.toast(format!("“{}” plays next", track.full_title())); + return self.update(Message::Player(player::Msg::PlayNext(track))); + } + Message::SkipFromMenu => { + self.sheet = None; + return self.update(Message::Player(player::Msg::Next)); + } + Message::AddToQueue(track) => { + self.sheet = None; + self.toast(format!("Added “{}” to the queue", track.full_title())); + return self.update(Message::Player(player::Msg::Append(track))); + } + Message::OpenSheet(sheet) => { + let focus = matches!(sheet, Sheet::NewPlaylist { .. } | Sheet::Rename { .. }); + self.sheet = Some(sheet); + if focus { + return iced::widget::operation::focus(sheet::INPUT_ID); + } + } + Message::CloseSheet => self.sheet = None, + Message::SheetText(text) => { + if let Some(Sheet::NewPlaylist { name, .. } | Sheet::Rename { name, .. }) = &mut self.sheet { + *name = text; + } + } + Message::LoadLikedIds => { + let Some(client) = self.client().cloned() else { return Task::none() }; + return Task::future(async move { client.liked_ids().await }).map(Message::LikedIdsLoaded); + } + Message::LikedIdsLoaded(Ok(ids)) => self.likes = ids, + Message::LikedIdsLoaded(Err(e)) => { + if let Some(task) = self.failed("liked ids", &e) { + return task; + } + } + Message::LyricsLoaded(id, result) => { + if let Err(e) = &result + && let Some(task) = self.failed("lyrics", e) + { + return task; + } + self.lyrics.insert(id, Loadable::from_result(result)); + } + Message::QueueCreated(Ok(id)) => self.server_queue = id, + Message::QueueCreated(Err(e)) => { + eprintln!("publish queue: {e}"); + self.server_queue = None; + } + Message::ToastTick => { + if self.toast_expired() { + self.toast = None; + } + } + m @ (Message::LikeTrack(..) + | Message::DislikeTrack(..) + | Message::LikeAlbum(..) + | Message::LikeArtist(..) + | Message::LikePlaylist(..) + | Message::AddToPlaylist(..) + | Message::CreatePlaylist + | Message::RenamePlaylist + | Message::SetPlaylistPublic(..) + | Message::DeletePlaylist(..) + | Message::RemoveFromPlaylist(..) + | Message::MovePlaylistTrack { .. } + | Message::Edited(..)) => return self.update_edit(m), Message::PlayTracks { tracks, start, shuffle } => { return self.update(Message::Player(player::Msg::Play { tracks, @@ -550,6 +698,24 @@ impl App { } } + /// Scrolls the lyrics so the line being sung stays in view. + fn follow_lyrics(&mut self) -> Task { + if self.drawer != Some(Panel::Lyrics) { + return Task::none(); + } + let Some(Loadable::Loaded(Some(lyrics))) = self.player.track().and_then(|t| self.lyrics.get(&t.id)) else { + return Task::none(); + }; + let line = lyrics.current(self.player.position()); + if line == self.lyric_line { + return Task::none(); + } + self.lyric_line = line; + let Some(line) = line else { return Task::none() }; + let y = (line as f32 / lyrics.lines.len().max(1) as f32).clamp(0.0, 1.0); + iced::widget::operation::snap_to(drawer::LYRICS_ID, iced::widget::operation::RelativeOffset { x: 0.0, y }) + } + fn genres_if_needed(&mut self) -> Task { if self.discover.genres.needs_load() { self.update(Message::LoadGenres) } else { Task::none() } } @@ -601,7 +767,9 @@ impl App { t, covers: &self.covers, liked: &self.library.liked, + likes: &self.likes, playing: self.player.track().map(|tr| tr.id.as_str()), + me: account.uid, }; let page = scrollable(screens::view(screens::Ctx { @@ -643,7 +811,8 @@ impl App { .height(Fill); if let Some(panel) = self.drawer { - body = body.push(vline()).push(drawer::view(t, panel, &self.player, &self.covers)); + let lyrics = self.player.track().and_then(|tr| self.lyrics.get(&tr.id)); + body = body.push(vline()).push(drawer::view(t, panel, &self.player, &self.covers, lyrics)); } let window = column![ @@ -660,7 +829,28 @@ impl App { .style(theme::panel), ]; - container(window).width(Fill).height(Fill).style(theme::app).into() + let mut layers = stack![container(window).width(Fill).height(Fill).style(theme::app)]; + if let Some((text, _)) = &self.toast { + layers = layers.push(sheet::toast(t, text)); + } + if let Some(open) = &self.sheet { + let track_id = match open { + Sheet::Track { track, .. } => Some(track.id.as_str()), + _ => None, + }; + let own: &[PlaylistSummary] = self.library.playlists.get().map_or(&[], |p| p.own.as_slice()); + layers = layers.push(sheet::overlay( + t, + open, + sheet::Ctx { + playing: track_id.is_some() && self.player.track().map(|tr| tr.id.as_str()) == track_id, + liked: track_id.is_some_and(|id| self.library.liked.contains(id)), + disliked: track_id.is_some_and(|id| self.likes.disliked_tracks.contains(id)), + own_playlists: own, + }, + )); + } + layers.into() } /// Runs the player's requests against the API. @@ -703,6 +893,19 @@ impl App { }) .discard() } + Effect::QueueStarted { tracks, index } => Self::publish_queue(client, self.play_context(), tracks, index), + Effect::QueueMoved(index) => match self.server_queue.clone() { + Some(id) => { + let client = client.clone(); + Task::future(async move { + if let Err(e) = client.update_queue_position(&id, index).await { + eprintln!("queue position: {e}"); + } + }) + .discard() + } + None => Task::none(), + }, Effect::Report(report) => { let client = client.clone(); Task::future(async move { @@ -722,6 +925,35 @@ async fn fetch_audio(client: &YmClient, track_id: &str) -> Result Ok(Audio { stream, bytes }) } +/// `MUSYX_TRACE=1` logs every message except the frequent background ones. +/// Returns whether it logged, so the caller can add the resulting player state. +fn trace(message: &Message) -> bool { + static ON: std::sync::OnceLock = std::sync::OnceLock::new(); + if !*ON.get_or_init(|| std::env::var_os("MUSYX_TRACE").is_some()) { + return false; + } + let noisy = matches!( + message, + Message::WaveTick + | Message::CoversTick + | Message::ToastTick + | Message::CoverWanted(_) + | Message::CoverLoaded(..) + | Message::Player(player::Msg::Engine(player::engine::Event::Position { .. })) + ); + if noisy { + return false; + } + let text = match message { + Message::PlayTracks { tracks, start, shuffle } => { + format!("PlayTracks {{ {} tracks, start: {start}, shuffle: {shuffle} }}", tracks.len()) + } + other => format!("{other:?}").chars().take(160).collect(), + }; + eprintln!("trace: {text}"); + true +} + fn restore() -> Task { Task::future(session::restore()).map(Message::Restored) } @@ -744,3 +976,112 @@ fn vline<'a>() -> Element<'a, Message> { fn hline<'a>() -> Element<'a, Message> { container(space()).width(Fill).height(1).style(theme::divider).into() } + +#[cfg(test)] +mod tests { + use super::*; + + /// A signed-in app with no network behind it; tasks returned by `update` are dropped. + fn signed_in() -> App { + let (mut app, _) = App::new(); + app.session = Session::SignedIn { + client: YmClient::unauthenticated().unwrap(), + account: Account { uid: 1, login: "t".into(), name: "T".into(), has_plus: true, subscription_end: None }, + }; + app + } + + fn track(id: &str) -> Track { + Track::from_json(&format!(r#"{{"id":"{id}","title":"T{id}","durationMs":100000}}"#)).unwrap() + } + + fn upcoming(app: &App) -> Vec { + app.player.queue().map(|q| q.upcoming().map(|(_, t)| t.id.clone()).collect()).unwrap_or_default() + } + + #[test] + fn play_next_from_the_menu_lands_after_the_current_track() { + let mut app = signed_in(); + let tracks: Arc<[Track]> = vec![track("a"), track("b"), track("c")].into(); + let _ = app.update(Message::PlayTracks { tracks, start: 0, shuffle: false }); + let _ = app.update(Message::OpenSheet(Sheet::Track { track: track("n"), playlist: None, choosing: false })); + let _ = app.update(Message::PlayNext(track("n"))); + assert!(app.sheet.is_none()); + assert_eq!(upcoming(&app), ["n", "b", "c"]); + let _ = app.update(Message::Player(player::Msg::Next)); + assert_eq!(app.player.track().unwrap().id, "n"); + } + + #[test] + fn next_track_from_the_playing_tracks_menu_skips() { + let mut app = signed_in(); + let tracks: Arc<[Track]> = vec![track("a"), track("b")].into(); + let _ = app.update(Message::PlayTracks { tracks, start: 0, shuffle: false }); + let _ = app.update(Message::OpenSheet(Sheet::Track { track: track("a"), playlist: None, choosing: false })); + let messages = click_in_window(&app, "Next track"); + assert_eq!(messages, ["SkipFromMenu"]); + let _ = app.update(Message::SkipFromMenu); + assert!(app.sheet.is_none()); + assert_eq!(app.player.track().unwrap().id, "b"); + } + + #[test] + fn play_next_on_the_playing_track_says_so() { + let mut app = signed_in(); + let tracks: Arc<[Track]> = vec![track("a"), track("b")].into(); + let _ = app.update(Message::PlayTracks { tracks, start: 0, shuffle: false }); + let _ = app.update(Message::PlayNext(track("a"))); + assert_eq!(upcoming(&app), ["b"]); + assert!(app.toast.as_ref().is_some_and(|(t, _)| t.contains("already playing"))); + } + + /// Clicks `label` in the whole window with a track menu open; returns the messages. + fn click_in_window(app: &App, label: &str) -> Vec { + let mut ui = iced_test::simulator(app.view()); + ui.click(label).unwrap_or_else(|e| panic!("can't click {label}: {e:?}")); + ui.into_messages().map(|m| format!("{m:?}").chars().take(48).collect()).collect() + } + + #[test] + fn menu_clicks_do_not_fall_through_to_the_rows_beneath() { + let mut app = signed_in(); + let id = PlaylistId { owner: 1, kind: 1002 }; + let tracks: Arc<[Track]> = (0..30).map(|i| track(&i.to_string())).collect(); + let info = ym_api::PlaylistPage { + playlist: ym_api::PlaylistSummary::for_tests(id, "Дорога"), + description: None, + tracks: Vec::new(), + }; + app.pages.insert(Route::Playlist(id), Loadable::Loaded(crate::screens::detail::Page::Playlist { info, tracks: tracks.clone() })); + app.nav = Navigator::new(Route::Playlist(id)); + let _ = app.update(Message::PlayTracks { tracks: tracks.clone(), start: 0, shuffle: false }); + let _ = app.update(Message::OpenSheet(Sheet::Track { track: tracks[5].clone(), playlist: Some((id, 5, 30)), choosing: false })); + for label in ["Play next", "Add to queue", "Move up"] { + let messages = click_in_window(&app, label); + assert!( + !messages.iter().any(|m| m.starts_with("PlayTracks")), + "{label} leaked to a row: {messages:?}" + ); + } + } + + #[test] + fn menu_clicks_reach_their_items_over_the_full_window() { + let mut app = signed_in(); + let tracks: Arc<[Track]> = vec![track("a"), track("b")].into(); + let _ = app.update(Message::PlayTracks { tracks, start: 0, shuffle: false }); + for toast in [false, true] { + if toast { + app.toast("Added to Liked tracks"); + } + let _ = app.update(Message::OpenSheet(Sheet::Track { track: track("n"), playlist: None, choosing: false })); + for label in ["Play next", "Add to queue", "Add to Liked tracks"] { + let messages = click_in_window(&app, label); + assert!( + messages.first().is_some_and(|m| !m.starts_with("CloseSheet")), + "{label} (toast: {toast}) produced {messages:?}" + ); + } + } + } +} diff --git a/crates/musyx/src/app/edit.rs b/crates/musyx/src/app/edit.rs new file mode 100644 index 0000000..e8bd1e3 --- /dev/null +++ b/crates/musyx/src/app/edit.rs @@ -0,0 +1,298 @@ +//! Changing things: likes, dislikes, playlist edits, plus lyrics and the +//! server-side queue. Every change is shown at once and undone if Yandex refuses. + +use std::sync::Arc; +use std::time::{Duration, Instant}; + +use iced::Task; +use ym_api::{Error, PlaylistId, QueueContext, Track, YmClient}; + +use super::{App, Message}; +use crate::player; +use crate::route::Route; +use crate::screens::Loadable; +use crate::screens::collection::Liked; +use crate::widgets::sheet::Sheet; + +/// How long a status message stays up. +const TOAST: Duration = Duration::from_secs(4); + +/// What to reload after an edit lands. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum Refresh { + Playlist(PlaylistId), + Playlists, + Liked, + LikedIds, +} + +/// The outcome of a change sent to Yandex. +#[derive(Debug, Clone)] +pub struct Edited { + pub result: Result<(), Error>, + /// Shown when it worked. + pub done: String, + /// Shown when it didn't. + pub failed: String, + pub refresh: Vec, +} + +impl App { + pub(super) fn toast(&mut self, text: impl Into) { + self.toast = Some((text.into(), Instant::now())); + } + + /// Sends a change, then reports and refreshes through [`Message::Edited`]. + fn send_edit(&self, change: F, done: String, failed: String, refresh: Vec) -> Task + where + F: std::future::Future> + Send + 'static, + { + Task::future(change).map(move |result| { + Message::Edited(Box::new(Edited { result, done: done.clone(), failed: failed.clone(), refresh: refresh.clone() })) + }) + } + + pub(super) fn update_edit(&mut self, message: Message) -> Task { + let Some(client) = self.client().cloned() else { return Task::none() }; + match message { + Message::LikeTrack(track, on) => { + self.library.liked = self.library.liked.with(&track, on); + if on { + self.likes.disliked_tracks.remove(&track.id); + } + let id = track.full_id(); + let c = client.clone(); + self.send_edit( + async move { c.set_track_liked(&id, on).await }, + if on { "Added to Liked tracks" } else { "Removed from Liked tracks" }.into(), + "Couldn't change the like. Try again.".into(), + vec![], + ) + } + Message::DislikeTrack(track, on) => { + if on { + self.likes.disliked_tracks.insert(track.id.clone()); + self.library.liked = self.library.liked.with(&track, false); + } else { + self.likes.disliked_tracks.remove(&track.id); + } + // Not hearing it again starts now. + let skip = if on && self.player.track().is_some_and(|t| t.id == track.id) { + self.update(Message::Player(player::Msg::Next)) + } else { + Task::none() + }; + let id = track.full_id(); + let c = client.clone(); + Task::batch([ + skip, + self.send_edit( + async move { c.set_track_disliked(&id, on).await }, + if on { "You won't be recommended this track" } else { "Recommendations for this track restored" }.into(), + "Couldn't change that. Try again.".into(), + vec![], + ), + ]) + } + Message::LikeAlbum(id, on) => { + toggle(&mut self.likes.albums, id, on); + self.library.albums = Loadable::NotLoaded; + self.send_edit( + async move { client.set_album_liked(id, on).await }, + if on { "Album added to your collection" } else { "Album removed from your collection" }.into(), + "Couldn't change the like. Try again.".into(), + vec![Refresh::LikedIds], + ) + } + Message::LikeArtist(id, on) => { + toggle(&mut self.likes.artists, id, on); + self.library.artists = Loadable::NotLoaded; + self.send_edit( + async move { client.set_artist_liked(id, on).await }, + if on { "Artist added to your collection" } else { "Artist removed from your collection" }.into(), + "Couldn't change the like. Try again.".into(), + vec![Refresh::LikedIds], + ) + } + Message::LikePlaylist(id, on) => { + toggle(&mut self.likes.playlists, id, on); + self.send_edit( + async move { client.set_playlist_liked(id, on).await }, + if on { "Playlist added to your collection" } else { "Playlist removed from your collection" }.into(), + "Couldn't change the like. Try again.".into(), + vec![Refresh::Playlists, Refresh::LikedIds], + ) + } + Message::AddToPlaylist(id, track) => { + self.sheet = None; + let title = self.playlist_title(id); + self.send_edit( + async move { client.add_to_playlist(id, &track).await }, + format!("Added to “{title}”"), + format!("Couldn't add to “{title}”. Try again."), + vec![Refresh::Playlist(id), Refresh::Playlists], + ) + } + Message::CreatePlaylist => { + let Some(Sheet::NewPlaylist { name, add }) = self.sheet.take() else { return Task::none() }; + let name = name.trim().to_owned(); + if name.is_empty() { + return Task::none(); + } + let done = match &add { + Some(_) => format!("Created “{name}” with the track"), + None => format!("Created “{name}”"), + }; + self.send_edit( + async move { + let created = client.create_playlist(&name, false).await?; + if let Some(track) = add { + client.add_to_playlist(created.id, &track).await?; + } + Ok(()) + }, + done, + "Couldn't create the playlist. Try again.".into(), + vec![Refresh::Playlists], + ) + } + Message::RenamePlaylist => { + let Some(Sheet::Rename { id, name }) = self.sheet.take() else { return Task::none() }; + let name = name.trim().to_owned(); + if name.is_empty() { + return Task::none(); + } + let done = format!("Renamed to “{name}”"); + self.send_edit( + async move { client.rename_playlist(id, &name).await }, + done, + "Couldn't rename the playlist. Try again.".into(), + vec![Refresh::Playlist(id), Refresh::Playlists], + ) + } + Message::SetPlaylistPublic(id, public) => self.send_edit( + async move { client.set_playlist_public(id, public).await }, + if public { "Anyone with the link can now see this playlist" } else { "Only you can see this playlist now" }.into(), + "Couldn't change who can see it. Try again.".into(), + vec![Refresh::Playlist(id), Refresh::Playlists], + ), + Message::DeletePlaylist(id) => { + self.sheet = None; + let title = self.playlist_title(id); + if self.nav.current() == Route::Playlist(id) { + self.nav.back(); + } + self.pages.remove(&Route::Playlist(id)); + self.send_edit( + async move { client.delete_playlist(id).await }, + format!("Deleted “{title}”"), + format!("Couldn't delete “{title}”. Try again."), + vec![Refresh::Playlists], + ) + } + Message::RemoveFromPlaylist(id, index) => { + self.sheet = None; + self.send_edit( + async move { client.remove_from_playlist(id, index).await }, + "Removed from the playlist".into(), + "Couldn't remove the track. Try again.".into(), + vec![Refresh::Playlist(id), Refresh::Playlists], + ) + } + Message::MovePlaylistTrack { id, track, from, to } => { + self.sheet = None; + self.send_edit( + async move { client.move_in_playlist(id, &track, from, to).await }, + "Moved".into(), + "Couldn't move the track. Try again.".into(), + vec![Refresh::Playlist(id)], + ) + } + Message::Edited(edited) => { + let Edited { result, done, failed, refresh } = *edited; + match result { + Ok(()) => { + self.toast(done); + Task::batch(refresh.into_iter().map(|r| self.refresh(r))) + } + Err(e) => { + if let Some(task) = self.failed("edit", &e) { + return task; + } + self.toast(failed); + // The optimistic change may be wrong now; re-read the truth. + Task::batch([self.refresh(Refresh::Liked), self.refresh(Refresh::LikedIds)]) + } + } + } + _ => Task::none(), + } + } + + fn playlist_title(&self, id: PlaylistId) -> String { + self.library + .playlists + .get() + .and_then(|p| p.own.iter().chain(&p.liked).find(|pl| pl.id == id)) + .map_or_else(|| "the playlist".to_owned(), |p| p.title.clone()) + } + + pub(super) fn refresh(&mut self, what: Refresh) -> Task { + match what { + Refresh::Playlist(id) => { + let route = Route::Playlist(id); + self.pages.remove(&route); + if self.nav.current() == route { self.on_enter(route) } else { Task::none() } + } + Refresh::Playlists => self.update(Message::LoadLibrary(crate::screens::collection::Tab::Playlists)), + Refresh::Liked => { + self.library.liked = Liked::NotLoaded; + self.update(Message::LoadLiked) + } + Refresh::LikedIds => self.update(Message::LoadLikedIds), + } + } + + /// Lyrics for the playing track, fetched once per track while the panel is open. + pub(super) fn want_lyrics(&mut self) -> Task { + let (Some(client), Some(track)) = (self.client().cloned(), self.player.track()) else { return Task::none() }; + if self.drawer != Some(crate::widgets::drawer::Panel::Lyrics) || self.lyrics.contains_key(&track.id) { + return Task::none(); + } + let id = track.id.clone(); + self.lyrics.insert(id.clone(), Loadable::Loading); + Task::future(async move { + let result = client.lyrics(&id).await.map(|l| l.map(Arc::new)); + Message::LyricsLoaded(id, result) + }) + } + + /// Publishes a newly started list to Yandex so other devices can continue it. + pub(super) fn publish_queue(client: &YmClient, context: QueueContext, tracks: Vec, index: usize) -> Task { + let client = client.clone(); + Task::future(async move { client.create_queue(&context, &tracks, index).await }).map(Message::QueueCreated) + } + + /// Where a list being played comes from, judged by the page it was started on. + pub(super) fn play_context(&self) -> QueueContext { + match self.nav.current() { + Route::Album(id) => QueueContext::Album(id), + Route::Artist(id) => QueueContext::Artist(id), + Route::Playlist(id) => QueueContext::Playlist(id), + Route::Collection => QueueContext::MyMusic, + _ => QueueContext::Various, + } + } + + pub(super) fn toast_expired(&self) -> bool { + self.toast.as_ref().is_some_and(|(_, at)| at.elapsed() >= TOAST) + } +} + +fn toggle(set: &mut std::collections::HashSet, item: T, on: bool) { + if on { + set.insert(item); + } else { + set.remove(&item); + } +} diff --git a/crates/musyx/src/player/mod.rs b/crates/musyx/src/player/mod.rs index 639852e..c81dfe4 100644 --- a/crates/musyx/src/player/mod.rs +++ b/crates/musyx/src/player/mod.rs @@ -61,6 +61,11 @@ pub enum Msg { WaveBatch { station: String, result: Result }, /// The station's settings changed: replace what's queued after the current track. WaveRestart, + /// Queue a track right after the current one (or play it if nothing is queued). + PlayNext(Track), + /// Queue a track at the end. + Append(Track), + Seek(Duration), } /// Work the app has to do on the player's behalf. @@ -74,6 +79,10 @@ pub enum Effect { WaveFetch { station: String, session_id: Option, queue: Vec }, WaveFeedback { session_id: String, event: WaveEvent, batch_id: Option }, Report(PlayReport), + /// A new list started: publish it so other devices can continue (`tracks` in play order). + QueueStarted { tracks: Vec, index: usize }, + /// The list moved on to another position. + QueueMoved(usize), } /// A station being played, endlessly topped up. @@ -207,9 +216,30 @@ impl Player { self.queue = Queue::new(tracks.to_vec(), start, self.shuffle); self.skips = 0; self.notice = None; + if let Some(queue) = &self.queue { + let (order, index) = queue.in_order(); + effects.push(Effect::QueueStarted { tracks: order.into_iter().cloned().collect(), index }); + } effects.extend(self.load_current()); return effects; } + Msg::PlayNext(track) | Msg::Append(track) if self.queue.is_none() => { + return self.update(Msg::Play { tracks: Arc::from(vec![track]), start: 0, shuffle: None }); + } + Msg::PlayNext(track) => { + if let Some(queue) = &mut self.queue + && queue.insert_next(track, |a, b| a.id == b.id) + { + return self.prefetch_next(); + } + } + Msg::Append(track) => { + if let Some(queue) = &mut self.queue { + queue.extend([track]); + } + return self.prefetch_next(); + } + Msg::Seek(to) => self.seek(to), Msg::PlayWave { station } => { let mut effects = self.leave(false); self.queue = None; @@ -515,6 +545,16 @@ impl Player { } fn load_current(&mut self) -> Vec { + let mut effects = self.load_track(); + if self.wave.is_none() + && let Some(queue) = &self.queue + { + effects.push(Effect::QueueMoved(queue.in_order().1)); + } + effects + } + + fn load_track(&mut self) -> Vec { let Some(track) = self.track().cloned() else { return vec![] }; self.generation += 1; self.position = Duration::ZERO; @@ -609,11 +649,18 @@ mod tests { } } + fn fetch_generation(effects: &[Effect]) -> Option { + effects.iter().find_map(|e| match e { + Effect::Fetch { generation, .. } => Some(*generation), + _ => None, + }) + } + fn playing(n: usize, start: usize) -> Player { let mut p = Player::default(); let tracks: Arc<[Track]> = (0..n).map(|i| track(&i.to_string(), 100)).collect(); let effects = p.update(Msg::Play { tracks, start, shuffle: None }); - let Some(Effect::Fetch { generation, .. }) = effects.first().cloned() else { + let Some(generation) = fetch_generation(&effects) else { panic!("expected fetch, got {effects:?}"); }; p.update(Msg::Fetched { generation, result: Ok(audio()) }); @@ -626,7 +673,8 @@ mod tests { let mut p = Player::default(); let tracks: Arc<[Track]> = vec![track("a", 10), track("b", 20)].into(); let effects = p.update(Msg::Play { tracks, start: 0, shuffle: None }); - assert_eq!(effects, vec![Effect::Fetch { generation: 1, track_id: "a".into() }]); + assert!(effects.contains(&Effect::Fetch { generation: 1, track_id: "a".into() }), "{effects:?}"); + assert_eq!(effects.iter().filter(|e| matches!(e, Effect::Fetch { .. })).count(), 1); assert_eq!(p.status(), Status::Loading); assert!(p.update(Msg::Fetched { generation: 1, result: Ok(audio()) }).is_empty()); let effects = p.update(Msg::Engine(Event::Loaded { generation: 1, duration: None })); @@ -666,7 +714,7 @@ mod tests { ); assert_eq!(p.status(), Status::Ended); let effects = p.update(Msg::Toggle); - assert!(effects.is_empty(), "replay comes from memory: {effects:?}"); + assert!(fetch_generation(&effects).is_none(), "replay comes from memory: {effects:?}"); assert_eq!(p.status(), Status::Loading); } @@ -849,6 +897,69 @@ mod tests { assert!(p.wave_station().is_none()); } + #[test] + fn list_play_publishes_queue_and_moves() { + let mut p = Player::default(); + let tracks: Arc<[Track]> = (0..3).map(|i| track(&i.to_string(), 10)).collect(); + let effects = p.update(Msg::Play { tracks, start: 1, shuffle: None }); + assert!(matches!(&effects[0], Effect::QueueStarted { tracks, index: 1 } if tracks.len() == 3)); + assert!(effects.contains(&Effect::QueueMoved(1))); + let effects = p.update(Msg::Next); + assert!(effects.contains(&Effect::QueueMoved(2))); + } + + #[test] + fn play_next_and_append() { + let mut p = playing(3, 0); + p.update(Msg::PlayNext(track("n", 5))); + p.update(Msg::Append(track("z", 5))); + let upcoming: Vec<&str> = p.queue().unwrap().upcoming().map(|(_, t)| t.id.as_str()).collect(); + assert_eq!(upcoming, ["n", "1", "2", "z"]); + + let mut empty = Player::default(); + let effects = empty.update(Msg::Append(track("solo", 5))); + assert!(effects.iter().any(|e| matches!(e, Effect::Fetch { track_id, .. } if track_id == "solo"))); + } + + #[test] + fn play_next_wins_over_an_already_prefetched_track() { + let mut p = playing(3, 0); + p.update(Msg::Prefetched { track_id: "1".into(), result: Ok(audio()) }); + let effects = p.update(Msg::PlayNext(track("n", 5))); + assert!(effects.contains(&Effect::Prefetch { track_id: "n".into() }), "{effects:?}"); + let generation = p.generation; + let effects = p.update(Msg::Engine(Event::Ended { generation })); + assert_eq!(p.track().unwrap().id, "n", "{effects:?}"); + // A late prefetch for the old next track must not be played instead. + p.update(Msg::Prefetched { track_id: "1".into(), result: Ok(audio()) }); + assert_eq!(p.track().unwrap().id, "n"); + } + + #[test] + fn play_next_on_the_playing_track_changes_nothing() { + let mut p = playing(3, 0); + assert!(p.update(Msg::PlayNext(track("0", 100))).is_empty()); + p.update(Msg::Next); + assert_eq!(p.track().unwrap().id, "1", "skip moves on instead of replaying"); + } + + #[test] + fn play_next_then_skip_plays_it() { + let mut p = playing(3, 0); + p.update(Msg::PlayNext(track("n", 5))); + p.update(Msg::Next); + assert_eq!(p.track().unwrap().id, "n"); + } + + #[test] + fn play_next_in_a_wave() { + let mut p = wave_with(3); + loaded(&mut p); + p.update(Msg::PlayNext(track("n", 5))); + p.update(Msg::Next); + assert_eq!(p.track().unwrap().id, "n"); + } + #[test] fn mute_and_volume() { let mut p = Player::default(); diff --git a/crates/musyx/src/player/queue.rs b/crates/musyx/src/player/queue.rs index dbebab1..432e67f 100644 --- a/crates/musyx/src/player/queue.rs +++ b/crates/musyx/src/player/queue.rs @@ -140,6 +140,32 @@ impl Queue { } } + /// Puts an item right after the current one. If it's already coming up it moves + /// there instead of being duplicated; if it *is* the current item nothing changes. + /// Returns whether the queue changed. + pub fn insert_next(&mut self, item: T, same: impl Fn(&T, &T) -> bool) -> bool { + if same(self.current(), &item) { + return false; + } + let later = self.order[self.pos + 1..].iter().position(|&i| same(&self.items[i], &item)); + match later { + Some(offset) => { + let index = self.order.remove(self.pos + 1 + offset); + self.order.insert(self.pos + 1, index); + } + None => { + self.items.push(item); + self.order.insert(self.pos + 1, self.items.len() - 1); + } + } + true + } + + /// Items in play order, and the current position in it. + pub fn in_order(&self) -> (Vec<&T>, usize) { + (self.order.iter().map(|&i| &self.items[i]).collect(), self.pos) + } + /// Drops everything after the current item, e.g. when a station's settings change. pub fn clear_upcoming(&mut self) { let keep: Vec = self.order[..=self.pos].to_vec(); @@ -253,6 +279,27 @@ mod tests { assert_eq!(*q.current(), first); } + #[test] + fn insert_next_plays_after_current_even_when_shuffled() { + let mut q = q(4, 1); + q.set_shuffle(true); + assert!(q.insert_next(99, |a, b| a == b)); + assert_eq!(q.upcoming().next().map(|(_, &x)| x), Some(99)); + let (order, pos) = q.in_order(); + assert_eq!(*order[pos], 1); + assert_eq!(*order[pos + 1], 99); + } + + #[test] + fn insert_next_moves_instead_of_duplicating_and_ignores_current() { + let mut q = q(5, 1); + assert!(!q.insert_next(1, |a, b| a == b), "the current item stays put"); + assert_eq!(q.upcoming().map(|(_, &x)| x).collect::>(), [2, 3, 4]); + assert!(q.insert_next(4, |a, b| a == b)); + assert_eq!(q.upcoming().map(|(_, &x)| x).collect::>(), [4, 2, 3]); + assert_eq!(q.len(), 5, "moved, not added"); + } + #[test] fn jump_moves_to_upcoming_position() { let mut q = q(5, 0); diff --git a/crates/musyx/src/screens/collection.rs b/crates/musyx/src/screens/collection.rs index 8b343db..a6f9307 100644 --- a/crates/musyx/src/screens/collection.rs +++ b/crates/musyx/src/screens/collection.rs @@ -40,6 +40,28 @@ impl Liked { Liked::Loaded { tracks: tracks.into(), ids, version } } + /// A copy with `track` liked (at the top, like Yandex lists it) or unliked. + /// Not loaded yet: unchanged, the next load has it. + pub fn with(&self, track: &Track, liked: bool) -> Liked { + let Liked::Loaded { tracks, ids, version } = self else { + return match self { + Liked::Failed(e) => Liked::Failed(e.clone()), + Liked::Loading => Liked::Loading, + _ => Liked::NotLoaded, + }; + }; + if ids.contains(&track.id) == liked { + return Liked::Loaded { tracks: tracks.clone(), ids: ids.clone(), version: *version }; + } + let list: Vec = if liked { + std::iter::once(track.clone()).chain(tracks.iter().cloned()).collect() + } else { + tracks.iter().filter(|t| t.id != track.id).cloned().collect() + }; + let ids = list.iter().map(|t| t.id.clone()).collect(); + Liked::Loaded { tracks: list.into(), ids, version: version + 1 } + } + pub fn contains(&self, track_id: &str) -> bool { matches!(self, Liked::Loaded { ids, .. } if ids.contains(track_id)) } @@ -338,4 +360,16 @@ mod tests { assert_eq!(second.version(), 2); assert!(!Liked::Failed(Error::Denied).contains("1")); } + + #[test] + fn with_adds_on_top_and_removes() { + let base = Liked::loaded(vec![track("1"), track("2")], &Liked::Loading); + let added = base.with(&track("3"), true); + assert_eq!(added.tracks().unwrap()[0].id, "3"); + assert!(added.version() > base.version()); + let removed = added.with(&track("1"), false); + assert!(!removed.contains("1") && removed.contains("2")); + assert_eq!(removed.with(&track("2"), true).version(), removed.version(), "no-op keeps the cache"); + assert!(matches!(Liked::NotLoaded.with(&track("9"), true), Liked::NotLoaded)); + } } diff --git a/crates/musyx/src/screens/detail.rs b/crates/musyx/src/screens/detail.rs index 3fa169e..0478fe6 100644 --- a/crates/musyx/src/screens/detail.rs +++ b/crates/musyx/src/screens/detail.rs @@ -14,7 +14,9 @@ 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::sheet::Sheet; use crate::widgets::track_row::Columns; +use crate::ui::icons::{Icon, icon}; /// A loaded page. Tracks are split out as `Arc<[Track]>` so playing them shares the list. #[derive(Debug, Clone)] @@ -87,6 +89,7 @@ struct Head<'a> { title: String, by: Option>, meta: String, + actions: Vec>, } fn head<'a>(env: Env<'a>, h: Head<'a>) -> Element<'a, Message> { @@ -101,6 +104,7 @@ fn head<'a>(env: Env<'a>, h: Head<'a>) -> Element<'a, Message> { ] .push(h.by) .push(line(h.meta, theme::BODY, size::META, t.muted)) + .push((!h.actions.is_empty()).then(|| Row::with_children(h.actions).spacing(8).align_y(Alignment::Center))) .spacing(8) .width(Fill), ] @@ -109,6 +113,23 @@ fn head<'a>(env: Env<'a>, h: Head<'a>) -> Element<'a, Message> { .into() } +/// A round heart that adds or removes something from the collection. +fn like_button<'a>(t: &'static theme::Tokens, liked: bool, msg: Message) -> Element<'a, Message> { + button(icon(if liked { Icon::HeartFilled } else { Icon::Heart }, if liked { t.like } else { t.fg })) + .padding(10) + .style(theme::ghost) + .on_press(msg) + .into() +} + +fn pill<'a>(t: &'static theme::Tokens, glyph: Icon, label: &'a str, msg: Message) -> Element<'a, Message> { + button(row![icon(glyph, t.fg), line(label, theme::MEDIUM, size::META, t.fg)].spacing(6).align_y(Alignment::Center)) + .padding([8, 14]) + .style(theme::ghost) + .on_press(msg) + .into() +} + /// Artist names as links to their pages. fn artist_links<'a>(env: Env<'a>, artists: &[ArtistRef]) -> Element<'a, Message> { let t = env.t; @@ -148,6 +169,7 @@ fn album<'a>(env: Env<'a>, info: &'a AlbumPage, tracks: &'a Arc<[Track]>) -> Ele title: a.full_title(), by: Some(artist_links(env, &a.artists)), meta, + actions: vec![like_button(env.t, env.likes.albums.contains(&a.id), Message::LikeAlbum(a.id, !env.likes.albums.contains(&a.id)))], }), play_bar(env.t, String::new(), tracks), track_list::view(env, tracks, Columns::ALBUM_PAGE), @@ -175,6 +197,7 @@ fn artist<'a>(env: Env<'a>, info: &'a ArtistPage, popular: &'a Arc<[Track]>) -> title: a.name.clone(), by: None, meta, + actions: vec![like_button(t, env.likes.artists.contains(&a.id), Message::LikeArtist(a.id, !env.likes.artists.contains(&a.id)))], }), ] .spacing(34); @@ -204,6 +227,7 @@ fn artist<'a>(env: Env<'a>, info: &'a ArtistPage, popular: &'a Arc<[Track]>) -> 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 own = p.id.owner == env.me; let total = tracks.iter().map(|tr| tr.duration).sum(); let mut page = column![ head(env, Head { @@ -214,6 +238,20 @@ fn playlist<'a>(env: Env<'a>, info: &'a PlaylistPage, tracks: &'a Arc<[Track]>) 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)), + actions: if own { + vec![ + pill(t, Icon::Pencil, "Rename", Message::OpenSheet(Sheet::Rename { id: p.id, name: p.title.clone() })), + pill( + t, + if p.public { Icon::Lock } else { Icon::Globe }, + if p.public { "Make private" } else { "Make public" }, + Message::SetPlaylistPublic(p.id, !p.public), + ), + pill(t, Icon::Trash, "Delete", Message::OpenSheet(Sheet::ConfirmDelete { id: p.id, title: p.title.clone() })), + ] + } else { + vec![like_button(t, env.likes.playlists.contains(&p.id), Message::LikePlaylist(p.id, !env.likes.playlists.contains(&p.id)))] + }, }), ] .spacing(28); @@ -223,7 +261,10 @@ fn playlist<'a>(env: Env<'a>, info: &'a PlaylistPage, tracks: &'a Arc<[Track]>) 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() + let list = if own { + track_list::view_own_playlist(env, tracks, p.id) + } else { + track_list::view(env, tracks, Columns::FULL) + }; + page.push(play_bar(t, String::new(), tracks)).push(list).into() } diff --git a/crates/musyx/src/widgets/drawer.rs b/crates/musyx/src/widgets/drawer.rs index bb24bfd..fa2247b 100644 --- a/crates/musyx/src/widgets/drawer.rs +++ b/crates/musyx/src/widgets/drawer.rs @@ -1,12 +1,16 @@ //! Right-hand panel with the play queue and lyrics. -use iced::widget::{button, column, container, row, scrollable, space}; -use ym_api::Track; +use std::sync::Arc; +use std::time::Duration; + +use iced::widget::{Column, button, column, container, row, scrollable, space}; +use ym_api::{Lyrics, Track}; use iced::{Alignment, Element, Fill, Padding}; use crate::app::Message; use crate::covers::{self, Covers}; use crate::player::{Msg, Player, Queue}; +use crate::screens::Loadable; use crate::ui::icons::{Icon, icon}; use crate::ui::theme::{self, Tokens, radius, shell, size}; use crate::widgets::player_bar::clock; @@ -27,7 +31,16 @@ impl Panel { } } -pub fn view<'a>(t: &'static Tokens, panel: Panel, player: &'a Player, covers: &Covers) -> Element<'a, Message> { +/// The lyrics scrollable, so playback can keep the current line in view. +pub const LYRICS_ID: &str = "lyrics"; + +pub fn view<'a>( + t: &'static Tokens, + panel: Panel, + player: &'a Player, + covers: &Covers, + lyrics: Option<&'a Loadable>>>, +) -> Element<'a, Message> { let tabs = row![tab(t, Panel::Queue, panel), tab(t, Panel::Lyrics, panel)].spacing(4); let head = row![ @@ -50,13 +63,13 @@ pub fn view<'a>(t: &'static Tokens, panel: Panel, player: &'a Player, covers: &C )) .padding([4, 20]) .into(), - (Panel::Lyrics, _) => container(para( - "Synced lyrics arrive in a later update. They'll follow playback, and clicking a line will jump to it.", - size::META, - t.muted, - )) - .padding([4, 20]) - .into(), + (Panel::Lyrics, None) => note(t, "Play a track to see its lyrics."), + (Panel::Lyrics, Some(_)) => match lyrics { + Some(Loadable::Loaded(Some(l))) => lyrics_view(t, l, player.position()), + Some(Loadable::Loaded(None)) => note(t, "Yandex Music has no lyrics for this track."), + Some(Loadable::Failed(_)) => note(t, "Couldn't load the lyrics. Close and reopen this panel to try again."), + _ => note(t, "Loading lyrics…"), + }, }; container(column![head, body]) @@ -66,6 +79,49 @@ pub fn view<'a>(t: &'static Tokens, panel: Panel, player: &'a Player, covers: &C .into() } +fn note<'a>(t: &'static Tokens, text: &'a str) -> Element<'a, Message> { + container(para(text, size::META, t.muted)).padding([4, 20]).into() +} + +/// Synced lyrics highlight the line being sung and seek on click; plain lyrics just scroll. +fn lyrics_view<'a>(t: &'static Tokens, l: &'a Lyrics, position: Duration) -> Element<'a, Message> { + let current = l.current(position); + let lines = l.lines.iter().enumerate().map(|(i, lyric)| -> Element<'a, Message> { + let (colour, font, sz) = match current { + Some(c) if c == i => (t.fg, theme::SEMIBOLD, 17.0), + Some(c) if i < c => (t.muted.scale_alpha(0.6), theme::MEDIUM, 15.0), + _ if l.synced => (t.muted, theme::MEDIUM, 15.0), + _ => (t.fg, theme::BODY, 14.0), + }; + let text = iced::widget::text(if lyric.text.is_empty() { "♪".to_owned() } else { lyric.text.clone() }) + .font(font) + .size(sz) + .color(colour) + .line_height(1.35); + match lyric.at { + Some(at) => button(text) + .width(Fill) + .padding([5, 8]) + .style(theme::nav_item(false)) + .on_press(Message::Player(Msg::Seek(at))) + .into(), + None => container(text).padding([2, 8]).into(), + } + }); + let mut list = Column::with_children(lines).spacing(2); + if !l.writers.is_empty() { + list = list.push( + container(para(format!("Written by {}", l.writers.join(", ")), size::SMALL, t.muted)) + .padding(iced::Padding::default().top(18).left(8).right(8)), + ); + } + scrollable(list.padding(Padding::default().left(10).right(10).bottom(18))) + .id(LYRICS_ID) + .height(Fill) + .style(theme::scroll) + .into() +} + /// Upcoming items shown at once; a long liked list would otherwise build thousands of rows. const SHOWN: usize = 100; diff --git a/crates/musyx/src/widgets/mod.rs b/crates/musyx/src/widgets/mod.rs index 7a288c6..fa2d459 100644 --- a/crates/musyx/src/widgets/mod.rs +++ b/crates/musyx/src/widgets/mod.rs @@ -1,6 +1,7 @@ pub mod card; pub mod drawer; pub mod player_bar; +pub mod sheet; pub mod sidebar; pub mod topbar; pub mod track_list; diff --git a/crates/musyx/src/widgets/player_bar.rs b/crates/musyx/src/widgets/player_bar.rs index 41a063c..e204df6 100644 --- a/crates/musyx/src/widgets/player_bar.rs +++ b/crates/musyx/src/widgets/player_bar.rs @@ -75,12 +75,17 @@ fn now_playing<'a>(t: &'static Tokens, p: &'a Player, liked: bool, covers: &Cove ] .spacing(2) .width(Length::Shrink), - // Liking from here arrives with collection editing; the heart shows the current state. - container(icon( + button(icon( if liked { Icon::HeartFilled } else { Icon::Heart }, if liked { t.like } else { t.muted }, )) - .padding(8), + .padding(8) + .style(theme::icon_button(None)) + .on_press(Message::LikeTrack(track.clone(), !liked)), + button(icon(Icon::Dislike, t.muted)) + .padding(8) + .style(theme::icon_button(None)) + .on_press(Message::DislikeTrack(track.clone(), true)), ] .spacing(12) .align_y(Alignment::Center) diff --git a/crates/musyx/src/widgets/sheet.rs b/crates/musyx/src/widgets/sheet.rs new file mode 100644 index 0000000..828ebbb --- /dev/null +++ b/crates/musyx/src/widgets/sheet.rs @@ -0,0 +1,308 @@ +//! Small dialogs over the window: track actions, new/rename playlist, delete confirmation. + +use iced::widget::{Column, button, column, container, mouse_area, opaque, row, space, text_input}; +use iced::{Alignment, Element, Fill, Length}; +use ym_api::{PlaylistId, PlaylistSummary, Track}; + +use crate::app::Message; +use crate::route::Route; +use crate::ui::icons::{Icon, icon}; +use crate::ui::theme::{self, Tokens, radius, size}; +use crate::ui::{line, para}; + +#[derive(Debug, Clone)] +pub enum Sheet { + Track { + track: Track, + /// Set when opened from one of the user's own playlists: its id, the row, its length. + playlist: Option<(PlaylistId, usize, usize)>, + /// Showing the "Add to playlist" list instead of the actions. + choosing: bool, + }, + NewPlaylist { name: String, add: Option }, + Rename { id: PlaylistId, name: String }, + ConfirmDelete { id: PlaylistId, title: String }, +} + +pub const INPUT_ID: &str = "sheet-input"; + +/// What the sheet needs to know about the library. +pub struct Ctx<'a> { + /// The menu is for the track playing now: "next" means skipping ahead. + pub playing: bool, + pub liked: bool, + pub disliked: bool, + pub own_playlists: &'a [PlaylistSummary], +} + +/// The dimmed backdrop plus the dialog; clicking the backdrop closes it. +pub fn overlay<'a>(t: &'static Tokens, sheet: &'a Sheet, ctx: Ctx<'a>) -> Element<'a, Message> { + let backdrop = mouse_area( + container(space()).width(Fill).height(Fill).style(|_| container::Style { + background: Some(iced::Color::BLACK.scale_alpha(0.45).into()), + ..Default::default() + }), + ) + .on_press(Message::CloseSheet); + + let card = container(body(t, sheet, ctx)) + .width(380) + .padding(18) + .style(move |_| container::Style { + background: Some(t.panel.into()), + border: iced::Border { color: t.line, width: 1.0, radius: radius::CARD.into() }, + shadow: iced::Shadow { + color: iced::Color::BLACK.scale_alpha(0.35), + offset: iced::Vector::new(0.0, 18.0), + blur_radius: 50.0, + }, + ..Default::default() + }); + + iced::widget::stack![backdrop, container(opaque(card)).center(Fill)].into() +} + +fn body<'a>(t: &'static Tokens, sheet: &'a Sheet, ctx: Ctx<'a>) -> Element<'a, Message> { + match sheet { + Sheet::Track { track, playlist, choosing: false } => { + let mut items: Vec> = vec![ + if ctx.playing { + item(t, Icon::Next, "Next track", Some(Message::SkipFromMenu)) + } else { + item(t, Icon::Next, "Play next", Some(Message::PlayNext(track.clone()))) + }, + item(t, Icon::Queue, "Add to queue", Some(Message::AddToQueue(track.clone()))), + item( + t, + if ctx.liked { Icon::HeartFilled } else { Icon::Heart }, + if ctx.liked { "Remove from Liked tracks" } else { "Add to Liked tracks" }, + Some(Message::LikeTrack(track.clone(), !ctx.liked)), + ), + item( + t, + Icon::Plus, + "Add to playlist…", + Some(Message::OpenSheet(Sheet::Track { track: track.clone(), playlist: *playlist, choosing: true })), + ), + ]; + if let Some(album) = &track.album { + items.push(item(t, Icon::Disc, "Go to album", Some(Message::Navigate(Route::Album(album.id))))); + } + for artist in track.artists.iter().filter(|a| a.id.is_some()).take(3) { + items.push(item( + t, + Icon::Forward, + "Go to artist", + artist.id.map(|id| Message::Navigate(Route::Artist(id))), + )); + } + items.push(item( + t, + Icon::Dislike, + if ctx.disliked { "Recommend this track again" } else { "Don't recommend this track" }, + Some(Message::DislikeTrack(track.clone(), !ctx.disliked)), + )); + if let Some((id, index, len)) = *playlist { + items.push(divider()); + if index > 0 { + items.push(item(t, Icon::Back, "Move up", Some(Message::MovePlaylistTrack { + id, track: track.clone(), from: index, to: index - 1, + }))); + } + if index + 1 < len { + items.push(item(t, Icon::Forward, "Move down", Some(Message::MovePlaylistTrack { + id, track: track.clone(), from: index, to: index + 1, + }))); + } + items.push(item(t, Icon::Trash, "Remove from this playlist", Some(Message::RemoveFromPlaylist(id, index)))); + } + frame(t, track.full_title(), Some(track.artist_line()), Column::with_children(items).spacing(2).into()) + } + Sheet::Track { track, choosing: true, .. } => { + let mut items: Vec> = vec![item( + t, + Icon::Plus, + "New playlist…", + Some(Message::OpenSheet(Sheet::NewPlaylist { name: String::new(), add: Some(track.clone()) })), + )]; + items.extend(ctx.own_playlists.iter().map(|p| { + item(t, Icon::Queue, &p.title, Some(Message::AddToPlaylist(p.id, track.clone()))) + })); + frame( + t, + "Add to playlist".into(), + Some(track.full_title()), + iced::widget::scrollable(Column::with_children(items).spacing(2)).height(Length::Shrink).into(), + ) + } + Sheet::NewPlaylist { name, add } => { + let can = !name.trim().is_empty(); + let hint = if add.is_some() { "The track goes in once it's created." } else { "Only you can see it until you make it public." }; + frame( + t, + "New playlist".into(), + None, + column![ + input("Playlist name", name, can.then_some(Message::CreatePlaylist)), + para(hint, size::META, t.muted), + actions(t, "Create", can.then_some(Message::CreatePlaylist), false), + ] + .spacing(14) + .into(), + ) + } + Sheet::Rename { name, .. } => { + let can = !name.trim().is_empty(); + frame( + t, + "Rename playlist".into(), + None, + column![ + input("Playlist name", name, can.then_some(Message::RenamePlaylist)), + actions(t, "Rename", can.then_some(Message::RenamePlaylist), false), + ] + .spacing(14) + .into(), + ) + } + Sheet::ConfirmDelete { id, title } => frame( + t, + format!("Delete “{title}”?"), + None, + column![ + para("The playlist and its track order go away for good. The tracks stay in Yandex Music.", size::BODY, t.muted), + actions(t, "Delete", Some(Message::DeletePlaylist(*id)), true), + ] + .spacing(16) + .into(), + ), + } +} + +fn frame<'a>(t: &'static Tokens, title: String, subtitle: Option, content: Element<'a, Message>) -> Element<'a, Message> { + let mut head = column![line(title, theme::SEMIBOLD, size::SECTION, t.fg)].spacing(2); + if let Some(sub) = subtitle { + head = head.push(line(sub, theme::BODY, size::META, t.muted)); + } + column![ + row![ + head.width(Fill).clip(true), + button(icon(Icon::Close, t.muted)).padding(6).style(theme::icon_button(None)).on_press(Message::CloseSheet), + ] + .align_y(Alignment::Start), + content, + ] + .spacing(14) + .into() +} + +fn item<'a>(t: &'static Tokens, glyph: Icon, label: &str, msg: Option) -> Element<'a, Message> { + button(row![icon(glyph, t.muted), line(label.to_owned(), theme::MEDIUM, size::BODY, t.fg)].spacing(12).align_y(Alignment::Center)) + .width(Fill) + .padding([9, 10]) + .style(theme::nav_item(false)) + .on_press_maybe(msg) + .into() +} + +fn divider<'a>() -> Element<'a, Message> { + container(space()).width(Fill).height(1).style(theme::divider).into() +} + +fn input<'a>(placeholder: &'a str, value: &'a str, submit: Option) -> Element<'a, Message> { + text_input(placeholder, value) + .id(INPUT_ID) + .on_input(Message::SheetText) + .on_submit_maybe(submit) + .padding([10, 14]) + .style(theme::search_field) + .into() +} + +fn actions<'a>(t: &'static Tokens, confirm: &'a str, msg: Option, danger: bool) -> Element<'a, Message> { + let ink = if danger { iced::Color::WHITE } else { t.accent_ink }; + let confirm = button(line(confirm, theme::SEMIBOLD, size::BODY, if msg.is_some() { ink } else { t.muted })) + .padding([10, 18]) + .on_press_maybe(msg); + let confirm = if danger { + confirm.style(move |_, status| button::Style { + background: Some(match status { + button::Status::Hovered => theme::mix(t.like, iced::Color::WHITE, 0.1), + _ => t.like, + }.into()), + text_color: iced::Color::WHITE, + border: iced::Border { radius: radius::PILL.into(), ..Default::default() }, + ..Default::default() + }) + } else { + confirm.style(theme::primary) + }; + row![ + space().width(Fill), + button(line("Cancel", theme::MEDIUM, size::BODY, t.fg)).padding([10, 18]).style(theme::ghost).on_press(Message::CloseSheet), + confirm, + ] + .spacing(8) + .into() +} + +/// The status line that floats above the player bar after an action. +pub fn toast<'a>(t: &'static Tokens, text: &'a str) -> Element<'a, Message> { + container( + container(line(text, theme::MEDIUM, size::BODY, t.bg)) + .padding([10, 18]) + .style(move |_| container::Style { + background: Some(t.fg.into()), + border: iced::Border { radius: radius::PILL.into(), ..Default::default() }, + shadow: iced::Shadow { + color: iced::Color::BLACK.scale_alpha(0.3), + offset: iced::Vector::new(0.0, 6.0), + blur_radius: 18.0, + }, + ..Default::default() + }), + ) + .width(Fill) + .height(Fill) + .align_x(Alignment::Center) + .align_y(iced::alignment::Vertical::Bottom) + .padding(iced::Padding::default().bottom(96)) + .into() +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::ui::theme::DARK; + + fn track_sheet() -> Sheet { + let track = Track::from_json(r#"{"id":"7","title":"Хочешь?","artists":[{"id":3,"name":"Земфира"}],"albums":[{"id":5,"title":"A"}]}"#).unwrap(); + Sheet::Track { track, playlist: None, choosing: false } + } + + fn click(label: &str) -> Vec { + let sheet = track_sheet(); + let mut ui = iced_test::simulator(overlay(&DARK, &sheet, Ctx { playing: false, liked: false, disliked: false, own_playlists: &[] })); + ui.click(label).unwrap_or_else(|e| panic!("can't click {label}: {e:?}")); + ui.into_messages().map(|m| format!("{m:?}").chars().take(40).collect()).collect() + } + + #[test] + fn menu_for_the_playing_track_offers_next_track() { + let sheet = track_sheet(); + let mut ui = iced_test::simulator(overlay(&DARK, &sheet, Ctx { playing: true, liked: false, disliked: false, own_playlists: &[] })); + assert!(ui.find("Play next").is_err()); + ui.click("Next track").expect("next track item"); + let messages: Vec = ui.into_messages().map(|m| format!("{m:?}")).collect(); + assert_eq!(messages, ["SkipFromMenu"]); + } + + #[test] + fn menu_items_send_their_action_and_not_close() { + for (label, expected) in [("Play next", "PlayNext("), ("Add to queue", "AddToQueue("), ("Go to album", "Navigate(Album(5))")] { + let messages = click(label); + assert!(messages.first().is_some_and(|m| m.starts_with(expected)), "{label}: {messages:?}"); + assert!(!messages.iter().any(|m| m.starts_with("CloseSheet")), "{label} also closed the sheet: {messages:?}"); + } + } +} diff --git a/crates/musyx/src/widgets/sidebar.rs b/crates/musyx/src/widgets/sidebar.rs index b9beab7..86971d1 100644 --- a/crates/musyx/src/widgets/sidebar.rs +++ b/crates/musyx/src/widgets/sidebar.rs @@ -27,7 +27,8 @@ pub fn view<'a>( space().width(Fill), button(icon(Icon::Plus, t.muted)) .padding(4) - .style(theme::icon_button(None)), + .style(theme::icon_button(None)) + .on_press(Message::OpenSheet(crate::widgets::sheet::Sheet::NewPlaylist { name: String::new(), add: None })), ] .align_y(Alignment::Center) .padding(Padding::default().left(10).right(2)); diff --git a/crates/musyx/src/widgets/track_list.rs b/crates/musyx/src/widgets/track_list.rs index af9dd88..36da617 100644 --- a/crates/musyx/src/widgets/track_list.rs +++ b/crates/musyx/src/widgets/track_list.rs @@ -5,11 +5,12 @@ use std::sync::Arc; use iced::widget::{Column, lazy}; use iced::Element; -use ym_api::Track; +use ym_api::{LikedIds, PlaylistId, Track}; use crate::app::Message; use crate::covers::{self, Covers}; use crate::screens::collection::Liked; +use crate::widgets::sheet::Sheet; use crate::ui::theme::{self, Tokens, radius}; use crate::widgets::track_row::{self, Columns}; @@ -19,7 +20,10 @@ pub struct Env<'a> { pub t: &'static Tokens, pub covers: &'a Covers, pub liked: &'a Liked, + pub likes: &'a LikedIds, pub playing: Option<&'a str>, + /// The signed-in user's uid, to tell their own playlists apart. + pub me: i64, } #[derive(Hash)] @@ -31,10 +35,11 @@ struct Key { covers: u64, liked: u64, dark: bool, + playlist: Option, } pub fn view<'a>(env: Env<'a>, tracks: &Arc<[Track]>, columns: Columns) -> Element<'a, Message> { - view_with(env, tracks, columns, None) + build(env, tracks, columns, None, None) } /// [`view`] with chart movements, one per track. @@ -44,7 +49,22 @@ pub fn view_with<'a>( columns: Columns, shifts: Option>, ) -> Element<'a, Message> { - let Env { t, covers, liked, playing } = env; + build(env, tracks, columns, shifts, None) +} + +/// One of the user's own playlists: rows get move and remove actions. +pub fn view_own_playlist<'a>(env: Env<'a>, tracks: &Arc<[Track]>, id: PlaylistId) -> Element<'a, Message> { + build(env, tracks, Columns::FULL, None, Some(id)) +} + +fn build<'a>( + env: Env<'a>, + tracks: &Arc<[Track]>, + columns: Columns, + shifts: Option>, + playlist: Option, +) -> Element<'a, Message> { + let Env { t, covers, liked, playing, .. } = env; let key = Key { list: (tracks.as_ptr() as usize, tracks.len()), columns, @@ -53,6 +73,7 @@ pub fn view_with<'a>( covers: if columns.cover { covers.version() } else { 0 }, liked: liked.version(), dark: t == &theme::DARK, + playlist, }; let tracks = tracks.clone(); @@ -68,6 +89,12 @@ pub fn view_with<'a>( track, playing: key.playing.as_deref() == Some(track.id.as_str()), liked: liked.contains(&track.id), + on_like: Message::LikeTrack(track.clone(), !liked.contains(&track.id)), + on_more: Message::OpenSheet(Sheet::Track { + track: track.clone(), + playlist: key.playlist.map(|id| (id, index, tracks.len())), + choosing: false, + }), cover, columns, shift: shifts.as_ref().and_then(|s| s.get(index).copied()).unwrap_or(0), diff --git a/crates/musyx/src/widgets/track_row.rs b/crates/musyx/src/widgets/track_row.rs index f6ab2d9..a2f494f 100644 --- a/crates/musyx/src/widgets/track_row.rs +++ b/crates/musyx/src/widgets/track_row.rs @@ -38,6 +38,8 @@ pub struct Row<'a> { /// Places moved in the chart; shown when `columns.shift`. pub shift: i32, pub on_press: Message, + pub on_like: Message, + pub on_more: Message, } /// Builds an owned (`'static`) row so lists can sit inside `lazy`. @@ -89,17 +91,24 @@ pub fn view(t: &'static Tokens, r: Row<'_>) -> Element<'static, Message> { } content = content .push( - container(icon( + button(icon( if r.liked { Icon::HeartFilled } else { Icon::Heart }, - if r.liked { t.like } else { t.muted.scale_alpha(0.0) }, + if r.liked { t.like } else { t.muted.scale_alpha(0.35) }, )) - .width(34) - .center_x(34), + .padding(8) + .style(theme::icon_button(None)) + .on_press(r.on_like), ) .push( container(line(clock(track.duration.as_secs_f32()), theme::BODY, size::META, t.muted)) .width(52) .align_right(52), + ) + .push( + button(icon(Icon::More, t.muted)) + .padding(8) + .style(theme::icon_button(None)) + .on_press(r.on_more), ); button(content) @@ -129,7 +138,8 @@ pub fn header(t: &'static Tokens, columns: Columns) -> Element<'static, Message> } heads = heads .push(space().width(34)) - .push(container(icon(Icon::Clock, t.muted)).width(52).align_right(52)); + .push(container(icon(Icon::Clock, t.muted)).width(52).align_right(52)) + .push(space().width(34)); column![heads, container(space()).width(Fill).height(1).style(theme::divider)] .spacing(8) diff --git a/crates/ym-api/src/client.rs b/crates/ym-api/src/client.rs index 20367eb..5a8df8d 100644 --- a/crates/ym-api/src/client.rs +++ b/crates/ym-api/src/client.rs @@ -5,12 +5,20 @@ use crate::library::{ AlbumPage, AlbumSummary, ArtistPage, ArtistSummary, LibraryPlaylists, PlaylistId, PlaylistPage, PlaylistSummary, }; +use crate::edit::{LikedIds, Lyrics, QueueContext}; use crate::discover::{ChartEntry, Genre, Home, SearchKind, SearchResults}; use crate::models::{Stream, Track, best_variant}; use crate::wave::{PlayReport, Station, WaveBatch, WaveEvent, WaveSettings, iso_millis, numeric_id}; use crate::{Error, Result}; +/// Playlist diffs need numeric track and album ids. +fn diff_ids(track: &Track) -> Result<(i64, i64)> { + let id = crate::wave::numeric_id(&track.id).ok_or_else(|| Error::Api("this track can't go in a playlist".into()))?; + let album = track.album.as_ref().map(|a| a.id).ok_or_else(|| Error::Api("track has no album".into()))?; + Ok((id, album)) +} + /// How many featured podcasts to resolve. pub const FEATURED_PODCASTS: usize = 48; @@ -410,6 +418,175 @@ impl YmClient { Ok(()) } + // ---- Likes ---- + + /// Track ids are `full_id`s or plain ids; Yandex accepts both. + pub async fn set_track_liked(&self, track_id: &str, liked: bool) -> Result<()> { + self.inner.set_liked(yamuse::Likeable::Track, [track_id], liked, None).await?; + Ok(()) + } + + /// "Don't recommend": the track stops appearing in waves and mixes. + pub async fn set_track_disliked(&self, track_id: &str, disliked: bool) -> Result<()> { + self.inner.set_disliked(yamuse::Dislikeable::Track, [track_id], disliked, None).await?; + Ok(()) + } + + pub async fn set_album_liked(&self, id: i64, liked: bool) -> Result<()> { + self.inner.set_liked(yamuse::Likeable::Album, [id], liked, None).await?; + Ok(()) + } + + pub async fn set_artist_liked(&self, id: i64, liked: bool) -> Result<()> { + self.inner.set_liked(yamuse::Likeable::Artist, [id], liked, None).await?; + Ok(()) + } + + pub async fn set_playlist_liked(&self, id: PlaylistId, liked: bool) -> Result<()> { + let key = format!("{}:{}", id.owner, id.kind); + self.inner.set_liked(yamuse::Likeable::Playlist, [key], liked, None).await?; + Ok(()) + } + + /// Ids only (no details), for drawing like state on every page. + pub async fn liked_ids(&self) -> Result { + let albums = self.inner.liked_albums(None).await?; + let artists = self.inner.liked_artists(None).await?; + let playlists = self.inner.liked_playlists(None).await?; + let disliked = self.inner.disliked_tracks(None).await?; + Ok(LikedIds { + albums: albums + .into_iter() + .filter_map(|l| l.album.and_then(|a| a.id).or_else(|| l.id.and_then(|i| i.as_number()))) + .collect(), + artists: artists.into_iter().filter_map(|a| a.id.and_then(|i| i.as_number())).collect(), + playlists: playlists + .into_iter() + .filter_map(|l| { + let p = l.playlist?; + Some(PlaylistId { owner: p.uid.or_else(|| p.owner.and_then(|o| o.uid))?, kind: p.kind? }) + }) + .collect(), + disliked_tracks: disliked + .tracks + .into_iter() + .filter_map(|t| match t.id? { + yamuse::models::Id::Number(n) => Some(n.to_string()), + yamuse::models::Id::Text(s) => s.split(':').next().map(str::to_owned), + }) + .collect(), + }) + } + + // ---- Playlists ---- + + pub async fn create_playlist(&self, title: &str, public: bool) -> Result { + let visibility = if public { yamuse::Visibility::Public } else { yamuse::Visibility::Private }; + let p = self.inner.create_playlist(title, visibility).await?; + PlaylistSummary::from_yamuse(&p).ok_or_else(|| Error::Api("created playlist has no id".into())) + } + + pub async fn rename_playlist(&self, id: PlaylistId, title: &str) -> Result<()> { + self.inner.rename_playlist(id.kind, title).await?; + Ok(()) + } + + pub async fn set_playlist_public(&self, id: PlaylistId, public: bool) -> Result<()> { + let visibility = if public { yamuse::Visibility::Public } else { yamuse::Visibility::Private }; + self.inner.set_playlist_visibility(id.kind, visibility).await?; + Ok(()) + } + + pub async fn delete_playlist(&self, id: PlaylistId) -> Result<()> { + self.inner.delete_playlist(id.kind).await?; + Ok(()) + } + + /// The playlist's revision and length, which every edit needs fresh. + async fn revision(&self, id: PlaylistId) -> Result<(i64, usize)> { + let p = self.inner.user_playlist(id.kind, Some(id.owner)).await?; + let len = p.track_count.map_or(p.tracks.len(), |n| n.max(0) as usize); + Ok((p.revision.unwrap_or(0), len)) + } + + /// Appends a track to the end of one of the user's playlists. + pub async fn add_to_playlist(&self, id: PlaylistId, track: &Track) -> Result<()> { + let (track_id, album_id) = diff_ids(track)?; + let (revision, len) = self.revision(id).await?; + self.inner.add_track_to_playlist(id.kind, track_id, album_id, len, revision).await?; + Ok(()) + } + + /// Removes the track at `index`. + pub async fn remove_from_playlist(&self, id: PlaylistId, index: usize) -> Result<()> { + let (revision, _) = self.revision(id).await?; + self.inner.remove_tracks_from_playlist(id.kind, index, index + 1, revision).await?; + Ok(()) + } + + /// Moves the track at `from` so it ends up at `to`. + pub async fn move_in_playlist(&self, id: PlaylistId, track: &Track, from: usize, to: usize) -> Result<()> { + let (track_id, album_id) = diff_ids(track)?; + let (revision, _) = self.revision(id).await?; + let diff = yamuse::Difference::new() + .delete(from, from + 1) + .insert(to, [yamuse::DiffTrack::new(track_id, album_id)]); + self.inner.change_playlist(id.kind, &diff, revision).await?; + Ok(()) + } + + // ---- Lyrics ---- + + /// Synced lyrics when Yandex has them, else plain text; `None` when there are none. + pub async fn lyrics(&self, track_id: &str) -> Result> { + for format in [yamuse::LyricsFormat::Lrc, yamuse::LyricsFormat::Text] { + let meta = match self.inner.track_lyrics(track_id, format).await { + Ok(meta) => meta, + Err(yamuse::Error::NotFound(_)) => continue, + Err(e) => return Err(e.into()), + }; + let text = meta.text(self.inner.transport()).await?; + if text.trim().is_empty() { + continue; + } + let writers = meta.writers.clone(); + return Ok(Some(match format { + yamuse::LyricsFormat::Lrc => Lyrics::from_lrc(&text, writers), + yamuse::LyricsFormat::Text => Lyrics::from_text(&text, writers), + })); + } + Ok(None) + } + + // ---- Server queue ---- + + /// Publishes what's playing so other devices can continue it. Returns the queue id. + pub async fn create_queue(&self, context: &QueueContext, tracks: &[Track], current: usize) -> Result> { + let tracks: Vec = tracks + .iter() + .map(|t| { + serde_json::json!({ + "trackId": t.id.split(':').next().unwrap_or(&t.id), + "albumId": t.album.as_ref().map(|a| a.id.to_string()).unwrap_or_default(), + "from": "musyx-desktop", + }) + }) + .collect(); + let body = serde_json::json!({ + "context": context.to_json(), + "tracks": tracks, + "currentIndex": current, + "from": "musyx-desktop", + "isInteractive": true, + }); + Ok(self.inner.create_queue(&body, None).await?) + } + + pub async fn update_queue_position(&self, queue_id: &str, index: usize) -> Result<()> { + self.inner.update_queue_position(queue_id, index as i64, None).await?; + Ok(()) + } + /// 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()]) diff --git a/crates/ym-api/src/edit.rs b/crates/ym-api/src/edit.rs new file mode 100644 index 0000000..72a6320 --- /dev/null +++ b/crates/ym-api/src/edit.rs @@ -0,0 +1,155 @@ +//! Changing the library (likes, dislikes, playlists), lyrics, and the +//! server-side play queue that other devices can continue from. + +use std::collections::HashSet; +use std::time::Duration; + +use crate::library::PlaylistId; + +/// What the user has liked or disliked, by id, for drawing hearts and bans. +#[derive(Debug, Clone, Default, PartialEq, Eq)] +pub struct LikedIds { + pub albums: HashSet, + pub artists: HashSet, + pub playlists: HashSet, + pub disliked_tracks: HashSet, +} + +/// One line of lyrics; synced lyrics carry the moment it's sung. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct LyricLine { + pub at: Option, + pub text: String, +} + +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct Lyrics { + pub lines: Vec, + pub synced: bool, + pub writers: Vec, +} + +impl Lyrics { + /// The line being sung at `position`: the last line that has started. + pub fn current(&self, position: Duration) -> Option { + if !self.synced { + return None; + } + self.lines.iter().rposition(|l| l.at.is_some_and(|at| at <= position)) + } + + /// Plain text: one line per line, blank lines kept as paragraph breaks. + pub(crate) fn from_text(text: &str, writers: Vec) -> Self { + Self { + lines: text.lines().map(|l| LyricLine { at: None, text: l.trim_end().to_owned() }).collect(), + synced: false, + writers, + } + } + + /// LRC: `[mm:ss.xx] words`. Lines with several stamps repeat; metadata tags are dropped. + pub(crate) fn from_lrc(lrc: &str, writers: Vec) -> Self { + let mut lines = Vec::new(); + for raw in lrc.lines() { + let mut rest = raw.trim(); + let mut stamps = Vec::new(); + while let Some(stripped) = rest.strip_prefix('[') { + let Some(end) = stripped.find(']') else { break }; + match parse_stamp(&stripped[..end]) { + Some(at) => stamps.push(at), + // `[ar:Artist]` and friends: not a lyric line. + None => { + stamps.clear(); + rest = ""; + break; + } + } + rest = stripped[end + 1..].trim_start(); + } + for at in stamps { + lines.push(LyricLine { at: Some(at), text: rest.to_owned() }); + } + } + lines.sort_by_key(|l| l.at); + Self { lines, synced: true, writers } + } +} + +/// `mm:ss`, `mm:ss.x`, `mm:ss.xx` or `mm:ss.xxx`. +fn parse_stamp(s: &str) -> Option { + let (min, sec) = s.split_once(':')?; + let min: u64 = min.trim().parse().ok()?; + let (whole, frac) = sec.split_once('.').unwrap_or((sec, "")); + let whole: u64 = whole.parse().ok()?; + if whole >= 60 || frac.len() > 3 || !frac.chars().all(|c| c.is_ascii_digit()) { + return None; + } + let millis = if frac.is_empty() { 0 } else { frac.parse::().ok()? * 10u64.pow(3 - frac.len() as u32) }; + Some(Duration::from_millis((min * 60 + whole) * 1000 + millis)) +} + +/// Where a server queue's tracks come from; other devices show it as "Playing from…". +#[derive(Debug, Clone, PartialEq, Eq)] +pub enum QueueContext { + Album(i64), + Playlist(PlaylistId), + Artist(i64), + /// Liked tracks. + MyMusic, + /// Search results, the chart, anything else. + Various, +} + +impl QueueContext { + pub(crate) fn to_json(&self) -> serde_json::Value { + let (kind, id) = match self { + QueueContext::Album(id) => ("album", id.to_string()), + QueueContext::Playlist(p) => ("playlist", format!("{}:{}", p.owner, p.kind)), + QueueContext::Artist(id) => ("artist", id.to_string()), + QueueContext::MyMusic => ("my_music", String::new()), + QueueContext::Various => ("various", String::new()), + }; + serde_json::json!({ "type": kind, "id": id, "description": "" }) + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn lrc_parses_stamps_and_drops_tags() { + let l = Lyrics::from_lrc( + "[ar:Кино]\n[00:12.50] Первая\n[00:20.1]Вторая\n[01:02.345][00:05.00] Повтор\n\nбез метки", + vec![], + ); + let got: Vec<(u64, &str)> = l.lines.iter().map(|x| (x.at.unwrap().as_millis() as u64, x.text.as_str())).collect(); + assert_eq!(got, [(5_000, "Повтор"), (12_500, "Первая"), (20_100, "Вторая"), (62_345, "Повтор")]); + assert!(l.synced); + } + + #[test] + fn current_line_follows_position() { + let l = Lyrics::from_lrc("[00:10.00]a\n[00:20.00]b", vec![]); + assert_eq!(l.current(Duration::from_secs(5)), None); + assert_eq!(l.current(Duration::from_secs(10)), Some(0)); + assert_eq!(l.current(Duration::from_secs(25)), Some(1)); + let plain = Lyrics::from_text("a\nb", vec![]); + assert_eq!(plain.current(Duration::from_secs(25)), None); + } + + #[test] + fn bad_stamps_are_not_lyrics() { + assert_eq!(parse_stamp("01:02"), Some(Duration::from_secs(62))); + assert_eq!(parse_stamp("1:75"), None); + assert_eq!(parse_stamp("ti"), None); + assert_eq!(parse_stamp("00:01.1234"), None); + } + + #[test] + fn queue_contexts_match_the_api_shape() { + let p = QueueContext::Playlist(PlaylistId { owner: 9, kind: 3 }).to_json(); + assert_eq!(p, serde_json::json!({"type": "playlist", "id": "9:3", "description": ""})); + assert_eq!(QueueContext::MyMusic.to_json()["type"], "my_music"); + } +} diff --git a/crates/ym-api/src/lib.rs b/crates/ym-api/src/lib.rs index 85d496d..85112ae 100644 --- a/crates/ym-api/src/lib.rs +++ b/crates/ym-api/src/lib.rs @@ -6,6 +6,7 @@ pub mod auth; mod client; mod discover; +mod edit; mod error; mod library; mod models; @@ -21,4 +22,5 @@ pub use wave::{ Character, Language, MY_WAVE, Mood, PlayReport, Station, WaveBatch, WaveEvent, WaveSettings, }; pub use discover::{BestMatch, ChartEntry, Genre, Home, Personal, SearchKind, SearchResults, Totals}; +pub use edit::{LikedIds, LyricLine, Lyrics, QueueContext}; pub use error::{Error, Result}; diff --git a/crates/ym-api/src/library.rs b/crates/ym-api/src/library.rs index c276e8d..3470181 100644 --- a/crates/ym-api/src/library.rs +++ b/crates/ym-api/src/library.rs @@ -162,6 +162,20 @@ impl PlaylistSummary { cover_url(self.cover_uri.as_deref(), size) } + /// A bare summary for tests and previews in other crates. + #[doc(hidden)] + pub fn for_tests(id: PlaylistId, title: &str) -> Self { + Self { + id, + title: title.into(), + owner_name: String::new(), + track_count: 0, + duration: Duration::ZERO, + public: false, + cover_uri: None, + } + } + pub fn hues(&self) -> (f32, f32) { hues_for((self.id.owner as u64).wrapping_mul(1_000_003) ^ self.id.kind as u64) } diff --git a/crates/ym-api/src/models.rs b/crates/ym-api/src/models.rs index de963e0..a1323e1 100644 --- a/crates/ym-api/src/models.rs +++ b/crates/ym-api/src/models.rs @@ -60,7 +60,12 @@ impl Track { available: t.available.unwrap_or(true), explicit: t.explicit.unwrap_or(false) || t.content_warning.as_deref() == Some("explicit"), - lyrics_available: t.lyrics_available.unwrap_or(false), + // `lyricsInfo` is the current, per-account answer; the old flag can say yes + // when the lyrics endpoint then says no. + lyrics_available: match &t.lyrics_info { + Some(i) => i.has_available_sync_lyrics.unwrap_or(false) || i.has_available_text_lyrics.unwrap_or(false), + None => t.lyrics_available.unwrap_or(false), + }, }) }