feat: search, home landing, chart, genres and podcasts

- ym-api: search by kind with paging and best match, suggestions, landing
  (personal playlists, new releases and playlists) plus the full chart
  with movement, genres, tag playlists and featured podcasts
- Tag playlist ids are parsed from raw JSON: yamuse types them as strings
  but the API sends {uid, kind} objects
- Featured podcasts capped at 48 (the API lists thousands)
- Search screen: debounced suggestions floating under the field, tabs with
  totals, top result card, Show more paging, genre browsing when empty
- Home with personal playlists, top-10 chart, new releases and playlists,
  genre tiles; Chart page; Genre pages with sub-genres; Podcasts page
- Chart lists show position movement; top-N lists are built once so
  cached rows survive playback ticks
- Snapshot mode can sign in live; api_probe example for discovery calls
This commit is contained in:
Yuriy Panov committed 2026-10-15 15:04:37 +06:00
1 parent 3b934df8cc
commit e7726aac3a
19 files changed
+1520 -59

No files matched your search

+94
View File
@@ -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<String> {
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<SearchResults> {
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<Vec<String>> {
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<Home> {
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<Vec<ChartEntry>> {
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<Vec<Genre>> {
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<Vec<PlaylistSummary>> {
// 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<Vec<AlbumSummary>> {
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<Vec<u8>> {
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());
+302
View File
@@ -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<String>,
pub best: Option<BestMatch>,
pub tracks: Vec<Track>,
pub albums: Vec<AlbumSummary>,
pub artists: Vec<ArtistSummary>,
pub playlists: Vec<PlaylistSummary>,
pub podcasts: Vec<AlbumSummary>,
/// 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<u32> {
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<T, U>(r: Option<y::SearchResult<T>>, f: impl Fn(T) -> Option<U>) -> (Vec<U>, 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<Self> {
let chart: Option<y::Chart> = 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<String>,
}
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub struct Home {
pub personal: Vec<Personal>,
pub chart: Vec<ChartEntry>,
pub new_releases: Vec<AlbumSummary>,
pub new_playlists: Vec<PlaylistSummary>,
}
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<String>,
pub sub_genres: Vec<Genre>,
}
impl Genre {
pub(crate) fn from_yamuse(g: y::Genre) -> Option<Self> {
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"));
}
}
+2
View File
@@ -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};
+11 -3
View File
@@ -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);