diff --git a/README.md b/README.md index 1c630c8..a8b8f3e 100644 --- a/README.md +++ b/README.md @@ -69,8 +69,9 @@ MUSYX_SNAPSHOT=design/shots/home.png MUSYX_SNAPSHOT_ROUTE=home MUSYX_SNAPSHOT_TH cargo run -p musyx --features snapshot ``` -`MUSYX_SNAPSHOT_ROUTE` takes home, wave, search, collection, podcasts, settings or signin. Every -route except signin renders with a sample signed-in account, so no network or keychain is needed. +`MUSYX_SNAPSHOT_ROUTE` takes home, wave, search, collection, podcasts, settings, signin or +`artist:` (live runs only). Every route except signin renders with a sample signed-in +account, so no network or keychain is needed. `MUSYX_SNAPSHOT_DRAWER` takes queue or lyrics. `MUSYX_SNAPSHOT_THEME` takes light or dark. `MUSYX_SNAPSHOT_LIVE=1` signs in with the account stored in the keychain instead of using sample data. Set `MUSYX_SNAPSHOT_DELAY` (ms) to wait longer for slow pages. diff --git a/crates/musyx/examples/api_probe.rs b/crates/musyx/examples/api_probe.rs index 30c93b0..ad8b32b 100644 --- a/crates/musyx/examples/api_probe.rs +++ b/crates/musyx/examples/api_probe.rs @@ -97,6 +97,18 @@ async fn main() { } } } + match client.artist_clips(675068).await { + Ok(c) => println!( + "artist clips: {} {:?}", + c.len(), + c.iter().take(3).map(|c| format!("{} {} — {} ({}s)", c.id, c.artist_line(), c.title, c.duration.as_secs())).collect::>() + ), + Err(e) => println!("artist clips: ERROR {e}"), + } + match client.liked_clips().await { + Ok(c) => println!("liked clips: {} {:?}", c.len(), c.iter().take(3).map(|c| &c.title).collect::>()), + Err(e) => println!("liked clips: ERROR {e}"), + } match client.suggest("зем").await { Ok(s) => println!("suggest: {:?}", s.iter().take(5).collect::>()), Err(e) => println!("suggest: ERROR {e}"), diff --git a/crates/musyx/src/app.rs b/crates/musyx/src/app.rs index 49c5137..f59301d 100644 --- a/crates/musyx/src/app.rs +++ b/crates/musyx/src/app.rs @@ -10,7 +10,7 @@ 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, LikedIds, Lyrics, MY_WAVE, + Account, AlbumSummary, ArtistSummary, Clip, Error, Genre, Home, LibraryPlaylists, LikedIds, Lyrics, MY_WAVE, PlaylistId, PlaylistSummary, Station, Track, WaveSettings, YmClient, }; @@ -107,6 +107,10 @@ pub enum Message { AlbumsLoaded(Result, Error>), ArtistsLoaded(Result, Error>), PlaylistsLoaded(Result), + ClipsLoaded(Result, Error>), + /// Clips play on the Yandex Music website. + OpenClip(Clip), + LikeClip(Clip, bool), PageLoaded(Route, Result), LoadHome, HomeLoaded(Result), @@ -553,6 +557,7 @@ impl App { | Message::LikeAlbum(..) | Message::LikeArtist(..) | Message::LikePlaylist(..) + | Message::LikeClip(..) | Message::AddToPlaylist(..) | Message::CreatePlaylist | Message::RenamePlaylist @@ -619,6 +624,21 @@ impl App { } self.library.playlists = Loadable::from_result(result); } + Message::ClipsLoaded(result) => { + if let Err(e) = &result + && let Some(task) = self.failed("liked clips", e) + { + return task; + } + self.library.clips = Loadable::from_result(result); + } + Message::OpenClip(clip) => match open::that_detached(clip.url()) { + Ok(()) => self.toast(format!("Opening “{}” in your browser", clip.title)), + Err(e) => { + eprintln!("open clip: {e}"); + self.toast("Couldn't open your browser."); + } + }, Message::PageLoaded(route, result) => { if let Err(e) = &result && let Some(task) = self.failed("page", e) @@ -828,6 +848,7 @@ impl App { Tab::Albums => self.library.albums.needs_load(), Tab::Artists => self.library.artists.needs_load(), Tab::Playlists => self.library.playlists.needs_load(), + Tab::Clips => self.library.clips.needs_load(), }; if needed { self.update(Message::LoadLibrary(tab)) } else { Task::none() } } @@ -848,6 +869,10 @@ impl App { self.library.playlists = Loadable::Loading; Task::future(async move { client.library_playlists().await }).map(Message::PlaylistsLoaded) } + Tab::Clips => { + self.library.clips = Loadable::Loading; + Task::future(async move { client.liked_clips().await }).map(Message::ClipsLoaded) + } } } @@ -1173,6 +1198,30 @@ mod tests { } } + fn clip(id: i64, title: &str) -> Clip { + Clip::from_json(&format!(r#"{{"clipId":{id},"title":"{title}","duration":263,"artists":[{{"id":3,"name":"КИНО"}}]}}"#)) + .unwrap() + } + + #[test] + fn liked_clips_open_from_collection_and_likes_update_the_list() { + let mut app = signed_in(); + app.nav = Navigator::new(Route::Collection); + app.library.tab = Tab::Clips; + app.library.clips = Loadable::Loaded(vec![clip(1, "Звезда")]); + app.likes.clips.insert(1); + let messages = click_in_window(&app, "Звезда"); + assert!(messages.first().is_some_and(|m| m.starts_with("OpenClip(")), "{messages:?}"); + + let _ = app.update(Message::LikeClip(clip(2, "Кукушка"), true)); + assert!(app.likes.clips.contains(&2)); + let ids = |app: &App| app.library.clips.get().unwrap().iter().map(|c| c.id).collect::>(); + assert_eq!(ids(&app), [2, 1]); + let _ = app.update(Message::LikeClip(clip(1, "Звезда"), false)); + assert_eq!(ids(&app), [2]); + assert!(!app.likes.clips.contains(&1)); + } + #[test] fn menu_clicks_reach_their_items_over_the_full_window() { let mut app = signed_in(); diff --git a/crates/musyx/src/app/edit.rs b/crates/musyx/src/app/edit.rs index e8bd1e3..7d71bb6 100644 --- a/crates/musyx/src/app/edit.rs +++ b/crates/musyx/src/app/edit.rs @@ -123,6 +123,21 @@ impl App { vec![Refresh::Playlists, Refresh::LikedIds], ) } + Message::LikeClip(clip, on) => { + toggle(&mut self.likes.clips, clip.id, on); + if let Loadable::Loaded(clips) = &mut self.library.clips { + clips.retain(|c| c.id != clip.id); + if on { + clips.insert(0, clip.clone()); + } + } + self.send_edit( + async move { client.set_clip_liked(clip.id, on).await }, + if on { "Clip added to your collection" } else { "Clip removed from your collection" }.into(), + "Couldn't change the like. Try again.".into(), + vec![], + ) + } Message::AddToPlaylist(id, track) => { self.sheet = None; let title = self.playlist_title(id); diff --git a/crates/musyx/src/screens/collection.rs b/crates/musyx/src/screens/collection.rs index a6f9307..a4281d3 100644 --- a/crates/musyx/src/screens/collection.rs +++ b/crates/musyx/src/screens/collection.rs @@ -1,11 +1,11 @@ -//! Collection: liked tracks, albums, artists, and playlists (own and liked). +//! Collection: liked tracks, albums, artists, playlists (own and liked) and clips. use std::collections::HashSet; use std::sync::Arc; use iced::widget::{button, column, container, row, space}; use iced::{Alignment, Element, Fill}; -use ym_api::{AlbumSummary, ArtistSummary, Error, LibraryPlaylists, PlaylistSummary, Track}; +use ym_api::{AlbumSummary, ArtistSummary, Clip, Error, LibraryPlaylists, PlaylistSummary, Track}; use super::Loadable; use crate::app::Message; @@ -88,10 +88,11 @@ pub enum Tab { Albums, Artists, Playlists, + Clips, } impl Tab { - const ALL: [Tab; 4] = [Tab::Tracks, Tab::Albums, Tab::Artists, Tab::Playlists]; + const ALL: [Tab; 5] = [Tab::Tracks, Tab::Albums, Tab::Artists, Tab::Playlists, Tab::Clips]; fn label(self) -> &'static str { match self { @@ -99,6 +100,7 @@ impl Tab { Tab::Albums => "Albums", Tab::Artists => "Artists", Tab::Playlists => "Playlists", + Tab::Clips => "Clips", } } } @@ -111,6 +113,7 @@ pub struct Library { pub albums: Loadable>, pub artists: Loadable>, pub playlists: Loadable, + pub clips: Loadable>, } impl Library { @@ -120,6 +123,7 @@ impl Library { Tab::Albums => self.albums.get().map(Vec::len), Tab::Artists => self.artists.get().map(Vec::len), Tab::Playlists => self.playlists.get().map(|p| p.own.len() + p.liked.len()), + Tab::Clips => self.clips.get().map(Vec::len), } } } @@ -168,6 +172,13 @@ pub fn view<'a>(env: Env<'a>, library: &'a Library) -> Element<'a, Message> { } other => status(t, other.state(), "playlists", Message::LoadLibrary(Tab::Playlists)), }, + Tab::Clips => match &library.clips { + Loadable::Loaded(clips) if clips.is_empty() => { + empty(t, "No liked clips yet. Like a clip on an artist's page and it lands here.") + } + Loadable::Loaded(clips) => card::grid(clips.iter().map(|c| clip_card(env, c))), + other => status(t, other.state(), "clips", Message::LoadLibrary(Tab::Clips)), + }, }; column![line("Collection", theme::DISPLAY, size::DISPLAY_S, t.fg), tabs, body] @@ -299,6 +310,26 @@ pub fn playlist_card<'a>(t: &'static Tokens, covers: &Covers, p: &PlaylistSummar ) } +/// A music video. It opens in the browser; the heart likes it. +pub fn clip_card<'a>(env: Env<'_>, c: &Clip) -> Element<'a, Message> { + let liked = env.likes.clips.contains(&c.id); + let length = crate::widgets::player_bar::clock(c.duration.as_secs_f32()); + card::with_like( + env.t, + env.covers, + Card { + title: c.title.clone(), + subtitle: format!("{} · {length}", c.artist_line()), + cover: c.cover_url(covers::LARGE), + hues: c.hues(), + round: false, + on_press: Message::OpenClip(c.clone()), + }, + liked, + Message::LikeClip(c.clone(), !liked), + ) +} + pub fn section<'a>( t: &'static Tokens, heading: &'a str, diff --git a/crates/musyx/src/screens/detail.rs b/crates/musyx/src/screens/detail.rs index 0478fe6..056776c 100644 --- a/crates/musyx/src/screens/detail.rs +++ b/crates/musyx/src/screens/detail.rs @@ -7,7 +7,7 @@ use iced::{Alignment, Element, Fill, Task}; use ym_api::{AlbumPage, ArtistPage, ArtistRef, Error, PlaylistPage, Track, YmClient}; use super::Loadable; -use super::collection::{LoadState, album_card, artist_card, play_bar, section, status}; +use super::collection::{LoadState, album_card, artist_card, clip_card, play_bar, section, status}; use crate::app::Message; use crate::covers; use crate::route::Route; @@ -218,6 +218,9 @@ fn artist<'a>(env: Env<'a>, info: &'a ArtistPage, popular: &'a Arc<[Track]>) -> if !info.also_albums.is_empty() { page = page.push(section(t, "Appears on", info.also_albums.iter().map(|al| album_card(t, env.covers, al)))); } + if !info.clips.is_empty() { + page = page.push(section(t, "Clips", info.clips.iter().map(|c| clip_card(env, c)))); + } if !info.similar.is_empty() { page = page.push(section(t, "Similar artists", info.similar.iter().map(|ar| artist_card(t, env.covers, ar)))); } diff --git a/crates/musyx/src/snapshot.rs b/crates/musyx/src/snapshot.rs index 43e324f..c192e27 100644 --- a/crates/musyx/src/snapshot.rs +++ b/crates/musyx/src/snapshot.rs @@ -48,7 +48,8 @@ impl Config { "settings" => Route::Settings, "album" => Route::Album(1), "chart" => Route::Chart, - _ => return None, + // `artist:41075`, for live runs. + other => Route::Artist(other.strip_prefix("artist:")?.parse().ok()?), }) }); let drawer = var("MUSYX_SNAPSHOT_DRAWER").and_then(|d| match d.as_str() { diff --git a/crates/musyx/src/widgets/card.rs b/crates/musyx/src/widgets/card.rs index 237874f..ee37311 100644 --- a/crates/musyx/src/widgets/card.rs +++ b/crates/musyx/src/widgets/card.rs @@ -1,10 +1,11 @@ //! Cover cards for albums, artists and playlists, laid out in wrapping rows. -use iced::widget::{Row, button, column, container}; -use iced::{Element, Padding}; +use iced::widget::{Row, button, column, container, row}; +use iced::{Alignment, Element, Fill, Padding}; use crate::app::Message; use crate::covers::{self, Covers}; +use crate::ui::icons::{Icon, icon}; use crate::ui::line; use crate::ui::theme::{self, Tokens, radius, size}; @@ -22,17 +23,34 @@ pub struct Card { } pub fn view<'a>(t: &'static Tokens, covers: &Covers, card: Card) -> Element<'a, Message> { + build(t, covers, card, None) +} + +/// A card with a heart beside its title. +pub fn with_like<'a>(t: &'static Tokens, covers: &Covers, card: Card, liked: bool, on_like: Message) -> Element<'a, Message> { + let heart = button(icon( + if liked { Icon::HeartFilled } else { Icon::Heart }, + if liked { t.like } else { t.muted }, + )) + .padding(4) + .style(theme::icon_button(None)) + .on_press(on_like); + build(t, covers, card, Some(heart.into())) +} + +fn build<'a>(t: &'static Tokens, covers: &Covers, card: Card, action: Option>) -> Element<'a, Message> { let corner = if card.round { WIDTH / 2.0 } else { radius::COVER }; + let text = column![ + line(card.title, theme::MEDIUM, size::BODY, t.fg), + line(card.subtitle, theme::BODY, size::META, t.muted), + ] + .spacing(2) + .width(Fill) + .clip(true); button( column![ covers::view(covers, card.cover, card.hues, WIDTH, corner), - column![ - line(card.title, theme::MEDIUM, size::BODY, t.fg), - line(card.subtitle, theme::BODY, size::META, t.muted), - ] - .spacing(2) - .width(WIDTH) - .clip(true), + row![text].push(action).spacing(4).align_y(Alignment::Center).width(WIDTH), ] .spacing(9), ) diff --git a/crates/ym-api/src/client.rs b/crates/ym-api/src/client.rs index ab4e64a..fbca7a8 100644 --- a/crates/ym-api/src/client.rs +++ b/crates/ym-api/src/client.rs @@ -1,6 +1,7 @@ use std::sync::Arc; use crate::auth::Credentials; +use crate::clips::{self, Clip, LikedEntry}; use crate::library::{ AlbumPage, AlbumSummary, ArtistPage, ArtistSummary, LibraryPlaylists, PlaylistId, PlaylistPage, PlaylistSummary, @@ -235,7 +236,13 @@ impl YmClient { pub async fn artist(&self, id: i64) -> Result { let brief = self.inner.artist_brief_info(id).await?; - ArtistPage::from_yamuse(brief).ok_or_else(|| Error::Api(format!("artist {id} not found"))) + let mut page = ArtistPage::from_yamuse(brief).ok_or_else(|| Error::Api(format!("artist {id} not found")))?; + // The page is still worth showing without its videos. + match self.artist_clips(id).await { + Ok(clips) => page.clips = clips, + Err(e) => eprintln!("artist clips: {e}"), + } + Ok(page) } /// A playlist with all its tracks. Tracks the response didn't embed are looked up. @@ -444,6 +451,59 @@ impl YmClient { Ok(()) } + // ---- Clips ---- + + /// An artist's music videos, newest first (the first 50). + pub async fn artist_clips(&self, artist_id: i64) -> Result> { + let raw = self + .inner + .get_raw(&format!("/artists/{artist_id}/blocks/artist-clips"), yamuse::Params::new()) + .await?; + Ok(clips::artist_block(&raw)) + } + + /// Every clip the user liked, newest first. Bare references are looked up. + pub async fn liked_clips(&self) -> Result> { + const PAGE: u64 = 100; + let uid = self.inner.account_uid().ok_or_else(|| Error::Unauthorized("not signed in".into()))?; + let mut entries = Vec::new(); + for page in 0..20 { + let params = yamuse::Params::new().add("page", page).add("pageSize", PAGE); + let raw = self.inner.get_raw(&format!("/users/{uid}/likes/clips"), params).await?; + entries.extend(clips::liked_page(&raw)); + if !clips::has_more(&raw, page) { + break; + } + } + let missing: Vec = entries.iter().filter_map(|e| if let LikedEntry::Id(id) = e { Some(*id) } else { None }).collect(); + let mut found: std::collections::HashMap = std::collections::HashMap::new(); + for chunk in missing.chunks(PAGE as usize) { + let ids = chunk.iter().map(i64::to_string).collect::>().join(","); + let raw = self.inner.get_raw("/clips", yamuse::Params::new().add("clipIds", ids)).await?; + for v in raw.as_array().into_iter().flatten() { + if let Some(clip) = Clip::from_value(v, None) { + found.insert(clip.id, clip); + } + } + } + Ok(entries + .into_iter() + .filter_map(|e| match e { + LikedEntry::Full(clip) => Some(clip), + LikedEntry::Id(id) => found.remove(&id), + }) + .collect()) + } + + pub async fn set_clip_liked(&self, id: i64, liked: bool) -> Result<()> { + if liked { + self.inner.like_clip(id).await?; + } else { + self.inner.unlike_clip(id).await?; + } + Ok(()) + } + // ---- Likes ---- /// Track ids are `full_id`s or plain ids; Yandex accepts both. @@ -480,7 +540,17 @@ impl YmClient { let artists = self.inner.liked_artists(None).await?; let playlists = self.inner.liked_playlists(None).await?; let disliked = self.inner.disliked_tracks(None).await?; + // Clips are optional: a failure here shouldn't hide every other heart. + let clips = match self.liked_clips().await { + Ok(clips) => clips.into_iter().map(|c| c.id).collect(), + Err(e @ Error::Unauthorized(_)) => return Err(e), + Err(e) => { + eprintln!("liked clips: {e}"); + Default::default() + } + }; Ok(LikedIds { + clips, albums: albums .into_iter() .filter_map(|l| l.album.and_then(|a| a.id).or_else(|| l.id.and_then(|i| i.as_number()))) diff --git a/crates/ym-api/src/clips.rs b/crates/ym-api/src/clips.rs new file mode 100644 index 0000000..36536ee --- /dev/null +++ b/crates/ym-api/src/clips.rs @@ -0,0 +1,172 @@ +//! Clips (music videos). They play on the Yandex Music website; the app lists them. +//! +//! Read from raw JSON: the artist block names the id `id` where `/clips` says +//! `clipId`, and yamuse only knows the second. + +use std::time::Duration; + +use serde_json::Value; + +use crate::models::{ArtistRef, cover_url, hues_for}; + +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct Clip { + pub id: i64, + pub title: String, + pub artists: Vec, + pub duration: Duration, + pub explicit: bool, + cover_uri: Option, +} + +impl Clip { + /// A clip object from any endpoint. `artists` stand in when the clip lists none. + pub(crate) fn from_value(v: &Value, artists: Option<&Value>) -> Option { + let id = v.get("clipId").or_else(|| v.get("id")).and_then(number)?; + let names = |list: &Value| -> Vec { + list.as_array() + .into_iter() + .flatten() + .filter_map(|a| Some(ArtistRef { id: a.get("id").and_then(number), name: a.get("name")?.as_str()?.to_owned() })) + .collect() + }; + let mut people = v.get("artists").map(names).unwrap_or_default(); + if people.is_empty() { + people = artists.map(names).unwrap_or_default(); + } + let text = |key: &str| v.get(key).and_then(Value::as_str).filter(|s| !s.is_empty()).map(str::to_owned); + Some(Self { + id, + title: text("title").unwrap_or_else(|| "Untitled clip".into()), + artists: people, + duration: Duration::from_secs(v.get("duration").and_then(Value::as_u64).unwrap_or(0)), + explicit: v.get("explicit").and_then(Value::as_bool).unwrap_or(false), + cover_uri: text("thumbnail").or_else(|| v.pointer("/cover/uri")?.as_str().map(str::to_owned)), + }) + } + + /// Decodes a clip from the API's JSON, e.g. a recorded fixture. + pub fn from_json(json: &str) -> crate::Result { + let raw: Value = serde_json::from_str(json).map_err(|e| crate::Error::Api(e.to_string()))?; + Self::from_value(&raw, None).ok_or_else(|| crate::Error::Api("clip has no id".into())) + } + + /// Where the clip plays: the Yandex Music web player. + pub fn url(&self) -> String { + format!("https://music.yandex.ru/video?ids={}", self.id) + } + + pub fn artist_line(&self) -> String { + crate::library::join_names(&self.artists) + } + + pub fn cover_url(&self, size: u32) -> Option { + cover_url(self.cover_uri.as_deref(), size) + } + + pub fn hues(&self) -> (f32, f32) { + hues_for(self.id as u64 ^ 0x2c1b_3c6d) + } +} + +/// Ids arrive as numbers or numeric strings. +fn number(v: &Value) -> Option { + v.as_i64().or_else(|| v.as_str()?.parse().ok()) +} + +/// `/artists/{id}/blocks/artist-clips`: `{"items":[{"type":"clip","data":{"clip":{…},"artists":[…]}}]}`. +pub(crate) fn artist_block(raw: &Value) -> Vec { + raw.get("items") + .and_then(Value::as_array) + .into_iter() + .flatten() + .filter_map(|item| { + let data = item.get("data")?; + Clip::from_value(data.get("clip")?, data.get("artists")) + }) + .collect() +} + +/// An entry in the liked list: a whole clip, or a bare reference still to look up. +#[derive(Debug, PartialEq)] +pub(crate) enum LikedEntry { + Full(Clip), + Id(i64), +} + +/// One page of `/users/{uid}/likes/clips`, in order. +pub(crate) fn liked_page(raw: &Value) -> Vec { + raw.get("clips") + .and_then(Value::as_array) + .into_iter() + .flatten() + .filter_map(|entry| { + let entry = entry.get("clip").unwrap_or(entry); + if entry.get("title").is_some() { + Clip::from_value(entry, None).map(LikedEntry::Full) + } else { + entry.get("clipId").or_else(|| entry.get("id")).and_then(number).map(LikedEntry::Id) + } + }) + .collect() +} + +/// Whether the pager says pages follow `page`. +pub(crate) fn has_more(raw: &Value, page: u64) -> bool { + let pager = raw.get("pager"); + let field = |k: &str| pager.and_then(|p| p.get(k)).and_then(Value::as_u64); + match (field("total"), field("perPage")) { + (Some(total), Some(per)) if per > 0 => (page + 1) * per < total, + _ => false, + } +} + +#[cfg(test)] +mod tests { + use super::*; + use serde_json::json; + + #[test] + fn artist_block_reads_id_and_takes_the_block_artists() { + let raw = json!({"items": [{"type": "clip", "data": { + "artists": [{"id": 41075, "name": "КИНО"}], + "clip": {"id": 578780, "title": "Звезда", "duration": 263, + "cover": {"uri": "https://avatars.yandex.net/get-music-content/1/e.a.2-2/%%"}} + }}, {"type": "clip", "data": {"clip": {"title": "no id"}}}]}); + let clips = artist_block(&raw); + assert_eq!(clips.len(), 1); + let c = &clips[0]; + assert_eq!((c.id, c.title.as_str(), c.artist_line()), (578780, "Звезда", "КИНО".to_owned())); + assert_eq!(c.duration, Duration::from_secs(263)); + assert_eq!(c.cover_url(200).as_deref(), Some("https://avatars.yandex.net/get-music-content/1/e.a.2-2/200x200")); + assert_eq!(c.url(), "https://music.yandex.ru/video?ids=578780"); + } + + #[test] + fn clips_endpoint_shape_uses_clip_id_and_thumbnail() { + let c = Clip::from_value( + &json!({"clipId": 7, "title": "T", "thumbnail": "a/%%", "explicit": true, + "artists": [{"id": "3", "name": "A"}]}), + Some(&json!([{"id": 9, "name": "ignored"}])), + ) + .unwrap(); + assert_eq!(c.id, 7); + assert!(c.explicit); + assert_eq!(c.artists, [ArtistRef { id: Some(3), name: "A".into() }]); + assert_eq!(c.cover_url(100).as_deref(), Some("https://a/100x100")); + } + + #[test] + fn liked_pages_keep_order_and_mark_bare_ids() { + let raw = json!({"clips": [{"clipId": 1, "title": "Full"}, {"clipId": 2}, {"id": "3", "timestamp": "x"}], + "pager": {"page": 0, "perPage": 3, "total": 5}}); + let entries = liked_page(&raw); + assert!(matches!(&entries[0], LikedEntry::Full(c) if c.id == 1)); + assert_eq!(entries[1..], [LikedEntry::Id(2), LikedEntry::Id(3)]); + assert!(has_more(&raw, 0)); + assert!(!has_more(&raw, 1)); + let empty = json!({"pager": {"page": 0, "perPage": 0, "total": 0}}); + assert!(liked_page(&empty).is_empty()); + assert!(!has_more(&empty, 0)); + } +} diff --git a/crates/ym-api/src/edit.rs b/crates/ym-api/src/edit.rs index 72a6320..d0fe930 100644 --- a/crates/ym-api/src/edit.rs +++ b/crates/ym-api/src/edit.rs @@ -13,6 +13,7 @@ pub struct LikedIds { pub artists: HashSet, pub playlists: HashSet, pub disliked_tracks: HashSet, + pub clips: HashSet, } /// One line of lyrics; synced lyrics carry the moment it's sung. diff --git a/crates/ym-api/src/lib.rs b/crates/ym-api/src/lib.rs index 85112ae..be69463 100644 --- a/crates/ym-api/src/lib.rs +++ b/crates/ym-api/src/lib.rs @@ -5,6 +5,7 @@ pub mod auth; mod client; +mod clips; mod discover; mod edit; mod error; @@ -13,6 +14,7 @@ mod models; mod wave; pub use client::{Account, YmClient}; +pub use clips::Clip; pub use library::{ AlbumKind, AlbumPage, AlbumSummary, ArtistPage, ArtistSummary, LibraryPlaylists, PlaylistId, PlaylistPage, PlaylistSummary, diff --git a/crates/ym-api/src/library.rs b/crates/ym-api/src/library.rs index 3470181..82b7054 100644 --- a/crates/ym-api/src/library.rs +++ b/crates/ym-api/src/library.rs @@ -240,6 +240,8 @@ pub struct ArtistPage { pub also_albums: Vec, pub similar: Vec, pub monthly_listeners: Option, + /// Music videos; filled by a second request. + pub clips: Vec, } impl ArtistPage { @@ -252,6 +254,7 @@ impl ArtistPage { also_albums: b.also_albums.into_iter().filter_map(AlbumSummary::from_yamuse).collect(), similar: b.similar_artists.into_iter().filter_map(ArtistSummary::from_yamuse).collect(), monthly_listeners, + clips: Vec::new(), }) } }