feat: music video clips on artist pages and in Collection

Artist pages list the artist's clips and Collection gets a Clips tab with
the liked ones. A clip opens on the Yandex Music website, since there's
no video player in the app; the heart on each card likes it. Clips are
read from raw JSON because the artist block calls the id `id` where
/clips says `clipId`. Snapshot runs can open `artist:<id>`.
This commit is contained in:
Yuriy Panov committed 2026-10-15 18:50:50 +06:00
1 parent 2ef7aa9da9
commit 51e7a4f465
13 files changed
+396 -18

No files matched your search

+71 -1
View File
@@ -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<ArtistPage> {
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<Vec<Clip>> {
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<Vec<Clip>> {
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<i64> = entries.iter().filter_map(|e| if let LikedEntry::Id(id) = e { Some(*id) } else { None }).collect();
let mut found: std::collections::HashMap<i64, Clip> = std::collections::HashMap::new();
for chunk in missing.chunks(PAGE as usize) {
let ids = chunk.iter().map(i64::to_string).collect::<Vec<_>>().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())))
+172
View File
@@ -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<ArtistRef>,
pub duration: Duration,
pub explicit: bool,
cover_uri: Option<String>,
}
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<Self> {
let id = v.get("clipId").or_else(|| v.get("id")).and_then(number)?;
let names = |list: &Value| -> Vec<ArtistRef> {
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<Self> {
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<String> {
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<i64> {
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<Clip> {
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<LikedEntry> {
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));
}
}
+1
View File
@@ -13,6 +13,7 @@ pub struct LikedIds {
pub artists: HashSet<i64>,
pub playlists: HashSet<PlaylistId>,
pub disliked_tracks: HashSet<String>,
pub clips: HashSet<i64>,
}
/// One line of lyrics; synced lyrics carry the moment it's sung.
+2
View File
@@ -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,
+3
View File
@@ -240,6 +240,8 @@ pub struct ArtistPage {
pub also_albums: Vec<AlbumSummary>,
pub similar: Vec<ArtistSummary>,
pub monthly_listeners: Option<i64>,
/// Music videos; filled by a second request.
pub clips: Vec<crate::Clip>,
}
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(),
})
}
}