Files
musyz-mobile/reference/ym-api/src/clips.rs
T
yuriy.pandClaude Opus 5.5 46610d95fa Musyx Mobile: Android TV player for Yandex Music
Kotlin, Compose for TV and Media3 port of the desktop Musyx, with
device-code sign-in, Home, My Wave, search, collection, detail pages,
Now Playing with queue and lyrics, and settings for streaming quality,
appearance, font size (small, medium, large) and language.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-16 22:14:54 +06:00

173 lines
6.4 KiB
Rust

//! 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));
}
}