From b099946fb3493f6e4d4f5f7df0eec2f96a5b9898 Mon Sep 17 00:00:00 2001 From: Yuriy Panov Date: Thu, 15 Oct 2026 18:54:17 +0600 Subject: [PATCH] feat: recently played tracks on Home Home lists the last ten different tracks played on any device, read from the listening history and re-read on each visit. A failed reload keeps the previous list, and a failed first load hides the section. --- crates/musyx/src/app.rs | 44 +++++++++++++++++++++++++++- crates/musyx/src/screens/browse.rs | 18 ++++++++++++ crates/ym-api/src/client.rs | 47 ++++++++++++++++++++++++++++++ 3 files changed, 108 insertions(+), 1 deletion(-) diff --git a/crates/musyx/src/app.rs b/crates/musyx/src/app.rs index f59301d..8757123 100644 --- a/crates/musyx/src/app.rs +++ b/crates/musyx/src/app.rs @@ -114,6 +114,8 @@ pub enum Message { PageLoaded(Route, Result), LoadHome, HomeLoaded(Result), + LoadRecent, + RecentLoaded(Result, Error>), LoadGenres, GenresLoaded(Result, Error>), GenreLoaded(usize, Result, Error>), @@ -660,6 +662,29 @@ impl App { } self.discover.home = Loadable::from_result(result.map(HomeData::new)); } + Message::LoadRecent => { + let Some(client) = self.client().cloned() else { return Task::none() }; + // A reload keeps showing the previous list until the new one arrives. + if !matches!(self.discover.recent, Loadable::Loaded(_)) { + self.discover.recent = Loadable::Loading; + } + return Task::future(async move { client.recently_played(browse::RECENT).await }) + .map(Message::RecentLoaded); + } + Message::RecentLoaded(result) => { + match result { + Ok(tracks) => self.discover.recent = Loadable::Loaded(tracks.into()), + Err(e) => { + if let Some(task) = self.failed("recently played", &e) { + return task; + } + // Keep an older list rather than dropping the section. + if !matches!(self.discover.recent, Loadable::Loaded(_)) { + self.discover.recent = Loadable::Failed(e); + } + } + } + } Message::LoadGenres => { let Some(client) = self.client().cloned() else { return Task::none() }; self.discover.genres = Loadable::Loading; @@ -781,7 +806,13 @@ impl App { }, Route::Home => { let home = if self.discover.home.needs_load() { self.update(Message::LoadHome) } else { Task::none() }; - Task::batch([home, self.genres_if_needed(), self.update(Message::LoadWave)]) + // History changes with every listen, so it's re-read on each visit. + let recent = if matches!(self.discover.recent, Loadable::Loading) { + Task::none() + } else { + self.update(Message::LoadRecent) + }; + Task::batch([home, recent, self.genres_if_needed(), self.update(Message::LoadWave)]) } Route::Wave => self.update(Message::LoadWave), Route::Search => self.genres_if_needed(), @@ -1222,6 +1253,17 @@ mod tests { assert!(!app.likes.clips.contains(&1)); } + #[test] + fn recently_played_shows_on_home_and_survives_a_failed_reload() { + let mut app = signed_in(); + let _ = app.update(Message::RecentLoaded(Ok(vec![track("r1"), track("r2")]))); + let _ = app.update(Message::LoadRecent); + let _ = app.update(Message::RecentLoaded(Err(Error::Network("offline".into())))); + assert_eq!(app.discover.recent.get().map(|r| r.len()), Some(2)); + let messages = click_in_window(&app, "Tr2"); + assert!(messages.first().is_some_and(|m| m.starts_with("PlayTracks")), "{messages:?}"); + } + #[test] fn menu_clicks_reach_their_items_over_the_full_window() { let mut app = signed_in(); diff --git a/crates/musyx/src/screens/browse.rs b/crates/musyx/src/screens/browse.rs index 45e83db..83fb649 100644 --- a/crates/musyx/src/screens/browse.rs +++ b/crates/musyx/src/screens/browse.rs @@ -21,6 +21,8 @@ use crate::widgets::track_row::Columns; const HOME_CHART: usize = 10; /// Cards per Home row. const HOME_CARDS: usize = 12; +/// Tracks in Home's "Recently played". +pub const RECENT: usize = 10; /// Home data with the chart split out as a playable list. #[derive(Debug)] @@ -51,6 +53,8 @@ pub struct Discover { /// Top-level genres followed by their sub-genres, so a `Route::Genre` index finds either. pub genres: Loadable>, pub podcasts: Loadable>, + /// The last tracks played on any device. Reloaded on every visit to Home. + pub recent: Loadable>, } /// Top-level genres first, then every sub-genre, each once. @@ -71,6 +75,20 @@ pub fn home<'a>(env: Env<'a>, discover: &'a Discover, hero: Element<'a, Message> let covers = env.covers; let mut page = column![hero].spacing(34); + // Only worth a section when it has something; a failure stays in the log. + if let Loadable::Loaded(recent) = &discover.recent + && !recent.is_empty() + { + page = page.push( + column![ + line("Recently played", theme::SEMIBOLD, size::SECTION, t.fg), + track_list::view(env, recent, Columns::FULL), + ] + .spacing(14) + .width(Fill), + ); + } + match &discover.home { Loadable::Loaded(data) => { let h = &data.home; diff --git a/crates/ym-api/src/client.rs b/crates/ym-api/src/client.rs index fbca7a8..46bd23f 100644 --- a/crates/ym-api/src/client.rs +++ b/crates/ym-api/src/client.rs @@ -39,6 +39,28 @@ fn tag_playlist_ids(raw: &serde_json::Value) -> Vec { .collect() } +/// `trackId:albumId` for the newest `limit` distinct tracks in the history (days, then +/// the contexts played that day, then their tracks, each newest first). +fn recent_track_ids(history: &yamuse::models::MusicHistory, limit: usize) -> Vec { + let mut seen = std::collections::HashSet::new(); + history + .history_tabs + .iter() + .flat_map(|day| &day.items) + .flat_map(|group| &group.tracks) + .filter_map(|item| { + let id = item.data.as_ref()?.item_id.as_ref()?; + let track = id.track_id.as_deref().filter(|t| !t.is_empty())?; + Some(match id.album_id.as_deref().filter(|a| !a.is_empty()) { + Some(album) => format!("{track}:{album}"), + None => track.to_owned(), + }) + }) + .filter(|id| seen.insert(id.split(':').next().unwrap_or(id).to_owned())) + .take(limit) + .collect() +} + /// A queue id, unless it's the all-zero placeholder Yandex returns for a queue it didn't keep. fn real_queue_id(id: Option) -> Option { id.filter(|id| !id.is_empty() && !id.bytes().all(|b| b == b'0')) @@ -310,6 +332,12 @@ impl YmClient { Ok(home) } + /// The last `limit` different tracks the user played, newest first, on any device. + pub async fn recently_played(&self, limit: usize) -> Result> { + let history = self.inner.music_history(0).await?; + self.tracks(recent_track_ids(&history, limit)).await + } + pub async fn chart(&self) -> Result> { let info = self.inner.chart().await?; Ok(info @@ -745,6 +773,25 @@ mod tests { assert_eq!(tag_playlist_ids(&wrapped), vec!["9:8"]); } + #[test] + fn recent_ids_walk_days_and_skip_repeats() { + let history: yamuse::models::MusicHistory = serde_json::from_value(serde_json::json!({"historyTabs": [ + {"date": "2026-10-15", "items": [{"context": {"type": "wave"}, "tracks": [ + {"type": "track", "data": {"itemId": {"trackId": "1", "albumId": "10"}}}, + {"type": "track", "data": {"itemId": {"trackId": "2"}}}, + ]}]}, + {"date": "2026-10-14", "items": [{"tracks": [ + {"type": "track", "data": {"itemId": {"trackId": "1", "albumId": "10"}}}, + {"type": "track", "data": {}}, + {"type": "track", "data": {"itemId": {"trackId": "3", "albumId": "30"}}}, + {"type": "track", "data": {"itemId": {"trackId": "4", "albumId": "40"}}}, + ]}]}, + ]})) + .unwrap(); + assert_eq!(recent_track_ids(&history, 3), ["1:10", "2", "3:30"]); + assert_eq!(recent_track_ids(&history, 10).len(), 4); + } + #[test] fn placeholder_queue_ids_are_dropped() { assert_eq!(real_queue_id(Some("000000000000000000000000".into())), None);