Files
musyz-mobile/reference/ym-api/src/models.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

291 lines
12 KiB
Rust
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
//! The app-facing shapes of API objects. Converted from `yamuse` models,
//! keeping only what the UI uses and resolving every `Option` once, here.
use std::time::Duration;
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ArtistRef {
pub id: Option<i64>,
pub name: String,
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct AlbumRef {
pub id: i64,
pub title: String,
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Track {
/// Numeric track id as a string; user-uploaded tracks use non-numeric ids.
pub id: String,
pub title: String,
/// "Remastered 2011", "Live" and the like.
pub version: Option<String>,
pub artists: Vec<ArtistRef>,
pub album: Option<AlbumRef>,
pub duration: Duration,
/// `%%`-templated image uri; see [`Track::cover_url`].
cover_uri: Option<String>,
/// False for tracks removed from the catalogue or blocked in the region.
pub available: bool,
pub explicit: bool,
pub lyrics_available: bool,
}
impl Track {
pub(crate) fn from_yamuse(t: yamuse::models::Track) -> Option<Self> {
let id = match t.id? {
yamuse::models::Id::Number(n) => n.to_string(),
yamuse::models::Id::Text(s) if !s.is_empty() => s,
yamuse::models::Id::Text(_) => return None,
};
let album = t.albums.into_iter().find_map(|a| {
Some(AlbumRef { id: a.id?, title: a.title.unwrap_or_default() })
});
Some(Self {
id,
title: t.title.unwrap_or_else(|| "Untitled".into()),
version: t.version.filter(|v| !v.trim().is_empty()),
artists: t
.artists
.into_iter()
.filter_map(|a| {
Some(ArtistRef { id: a.id.and_then(|i| i.as_number()), name: a.name? })
})
.collect(),
album,
duration: Duration::from_millis(t.duration_ms.unwrap_or(0).max(0) as u64),
cover_uri: t.cover_uri.or(t.og_image),
available: t.available.unwrap_or(true),
explicit: t.explicit.unwrap_or(false)
|| t.content_warning.as_deref() == Some("explicit"),
// `lyricsInfo` is the current, per-account answer; the old flag can say yes
// when the lyrics endpoint then says no.
lyrics_available: match &t.lyrics_info {
Some(i) => i.has_available_sync_lyrics.unwrap_or(false) || i.has_available_text_lyrics.unwrap_or(false),
None => t.lyrics_available.unwrap_or(false),
},
})
}
/// Decodes a track from the API's JSON, e.g. a recorded fixture.
pub fn from_json(json: &str) -> crate::Result<Self> {
let raw = serde_json::from_str(json).map_err(|e| crate::Error::Api(e.to_string()))?;
Self::from_yamuse(raw).ok_or_else(|| crate::Error::Api("track has no id".into()))
}
/// `trackId:albumId`, the form station feedback and queues use.
pub fn full_id(&self) -> String {
match &self.album {
Some(album) if !self.id.contains(':') => format!("{}:{}", self.id, album.id),
_ => self.id.clone(),
}
}
/// "Artist A, Artist B", or "Unknown artist".
pub fn artist_line(&self) -> String {
crate::library::join_names(&self.artists)
}
/// Title with its version: "Song (Live)".
pub fn full_title(&self) -> String {
match &self.version {
Some(v) => format!("{} ({v})", self.title),
None => self.title.clone(),
}
}
/// Absolute cover URL at `size`×`size` pixels.
pub fn cover_url(&self, size: u32) -> Option<String> {
cover_url(self.cover_uri.as_deref(), size)
}
/// Two stable hues for placeholder art, derived from the album (or track) id.
pub fn hues(&self) -> (f32, f32) {
hues_for(self.album.as_ref().map_or_else(
|| self.id.bytes().fold(7u64, |h, b| h.wrapping_mul(31).wrapping_add(u64::from(b))),
|a| a.id as u64,
))
}
}
/// Absolute URL for a `%%`-templated image uri at `size`×`size` pixels.
pub(crate) fn cover_url(uri: Option<&str>, size: u32) -> Option<String> {
let uri = uri.filter(|u| !u.is_empty())?;
Some(yamuse::models::normalize_image_url(uri, &format!("{size}x{size}")))
}
/// Two hues for placeholder art; equal seeds give equal art.
pub(crate) fn hues_for(seed: u64) -> (f32, f32) {
((seed.wrapping_mul(47) % 360) as f32, (seed.wrapping_mul(131).wrapping_add(90) % 360) as f32)
}
/// Where a track's audio comes from.
#[derive(Clone, PartialEq, Eq)]
pub struct Stream {
/// Mirrors of the same file; any one works.
pub urls: Vec<String>,
/// "mp3", "aac", "flac" or "flac-mp4".
pub codec: String,
/// 0 when Yandex doesn't say (lossless).
pub bitrate_kbps: u32,
/// True when only a 30-second preview is available (no Plus).
pub preview: bool,
/// Hex AES-CTR key for an encrypted (`encraw`) lossless file.
pub key: Option<String>,
}
impl Stream {
/// "MP3 320" or "FLAC", shown in the player bar.
pub fn label(&self) -> String {
let name = self.codec.trim_end_matches("-mp4").to_ascii_uppercase();
if self.lossless() || self.bitrate_kbps == 0 { name } else { format!("{name} {}", self.bitrate_kbps) }
}
pub fn lossless(&self) -> bool {
matches!(self.codec.as_str(), "flac" | "flac-mp4")
}
/// The file format, for the decoder: "flac-mp4" is FLAC inside an MP4 container.
pub fn container(&self) -> &str {
if self.codec.ends_with("-mp4") { "mp4" } else { &self.codec }
}
}
/// Signed URLs and the key stay out of logs.
impl std::fmt::Debug for Stream {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("Stream")
.field("codec", &self.codec)
.field("bitrate_kbps", &self.bitrate_kbps)
.field("preview", &self.preview)
.field("mirrors", &self.urls.len())
.field("encrypted", &self.key.is_some())
.finish()
}
}
/// Builds a stream from a `/get-file-info` reply, when it's a codec we decode well.
pub(crate) fn file_info_stream(info: yamuse::models::LosslessDownloadInfo) -> Option<Stream> {
let urls = info.links();
let playable = matches!(info.codec.as_deref(), Some("flac" | "flac-mp4" | "mp3" | "aac" | "aac-mp4"));
if !playable || urls.is_empty() {
return None;
}
Some(Stream {
urls,
codec: info.codec.unwrap_or_default(),
bitrate_kbps: info.bitrate.unwrap_or(0).max(0) as u32,
preview: false,
key: info.key.filter(|k| !k.is_empty()),
})
}
/// Picks the variant to play: full tracks over previews, then the highest bitrate
/// within `max_kbps` (or the lowest there is, when everything is above it), then
/// MP3 over AAC (MP3 seeks reliably).
pub(crate) fn best_variant(
variants: &[yamuse::models::DownloadInfo],
max_kbps: Option<u32>,
) -> Option<&yamuse::models::DownloadInfo> {
let cap = max_kbps.map_or(i64::MAX, i64::from);
variants
.iter()
.filter(|v| v.download_info_url.is_some())
.filter(|v| matches!(v.codec.as_deref(), Some("mp3" | "aac")))
.max_by_key(|v| {
let kbps = v.bitrate_in_kbps.unwrap_or(0);
// Within the cap, higher is better; above it, closer to the cap is better.
let fit = if kbps <= cap { (1, kbps) } else { (0, -kbps) };
(!v.preview.unwrap_or(false), fit, v.codec.as_deref() == Some("mp3"))
})
}
#[cfg(test)]
mod tests {
use super::*;
fn track(json: &str) -> Track {
Track::from_yamuse(serde_json::from_str(json).unwrap()).unwrap()
}
#[test]
fn track_converts_with_artists_album_and_cover() {
let t = track(
r#"{"id":"12345","title":"Звезда по имени Солнце","durationMs":225000,
"artists":[{"id":1,"name":"Кино"}],
"albums":[{"id":77,"title":"Звезда по имени Солнце"}],
"coverUri":"avatars.yandex.net/get-music-content/x/%%","lyricsAvailable":true}"#,
);
assert_eq!(t.id, "12345");
assert_eq!(t.artist_line(), "Кино");
assert_eq!(t.album.as_ref().unwrap().id, 77);
assert_eq!(t.duration, Duration::from_secs(225));
assert_eq!(
t.cover_url(200).as_deref(),
Some("https://avatars.yandex.net/get-music-content/x/200x200")
);
assert!(t.available && t.lyrics_available && !t.explicit);
}
#[test]
fn numeric_ids_and_versions() {
let t = track(r#"{"id":42,"title":"Song","version":"Live","artists":[]}"#);
assert_eq!(t.id, "42");
assert_eq!(t.full_title(), "Song (Live)");
assert_eq!(t.artist_line(), "Unknown artist");
assert!(Track::from_yamuse(serde_json::from_str(r#"{"title":"no id"}"#).unwrap()).is_none());
}
#[test]
fn hues_are_stable_and_in_range() {
let a = track(r#"{"id":1,"albums":[{"id":5}]}"#);
let b = track(r#"{"id":2,"albums":[{"id":5}]}"#);
assert_eq!(a.hues(), b.hues(), "same album, same art");
let (h1, h2) = a.hues();
assert!((0.0..360.0).contains(&h1) && (0.0..360.0).contains(&h2));
}
#[test]
fn best_variant_prefers_full_mp3_at_top_bitrate() {
let v: Vec<yamuse::models::DownloadInfo> = serde_json::from_str(
r#"[{"codec":"aac","bitrateInKbps":256,"downloadInfoUrl":"a"},
{"codec":"mp3","bitrateInKbps":192,"downloadInfoUrl":"b"},
{"codec":"mp3","bitrateInKbps":320,"downloadInfoUrl":"c"},
{"codec":"mp3","bitrateInKbps":320,"downloadInfoUrl":"p","preview":true},
{"codec":"flac","bitrateInKbps":900,"downloadInfoUrl":"f"}]"#,
)
.unwrap();
assert_eq!(best_variant(&v, None).unwrap().download_info_url.as_deref(), Some("c"));
assert_eq!(best_variant(&v, Some(192)).unwrap().download_info_url.as_deref(), Some("b"));
assert_eq!(best_variant(&v, Some(64)).unwrap().download_info_url.as_deref(), Some("b"), "nothing fits: take the smallest");
let previews: Vec<yamuse::models::DownloadInfo> = serde_json::from_str(
r#"[{"codec":"mp3","bitrateInKbps":128,"downloadInfoUrl":"p","preview":true}]"#,
)
.unwrap();
assert!(best_variant(&previews, None).unwrap().preview.unwrap());
assert!(best_variant(&[], None).is_none());
}
#[test]
fn file_info_replies_become_streams_except_he_aac() {
let info = |json: &str| serde_json::from_str::<yamuse::models::LosslessDownloadInfo>(json).unwrap();
let flac = file_info_stream(info(
r#"{"codec":"flac-mp4","bitrate":0,"transport":"encraw","key":"00ff","urls":["https://a","https://b"]}"#,
))
.unwrap();
assert_eq!(flac.urls, ["https://a", "https://b"]);
assert_eq!((flac.label().as_str(), flac.container()), ("FLAC", "mp4"));
assert_eq!(flac.key.as_deref(), Some("00ff"));
assert!(!format!("{flac:?}").contains("00ff"), "key leaked into Debug");
assert!(flac.lossless());
let aac = file_info_stream(info(r#"{"codec":"aac-mp4","quality":"nq","bitrate":192,"key":"00ff","urls":["https://a"]}"#)).unwrap();
assert_eq!((aac.label().as_str(), aac.container(), aac.lossless()), ("AAC 192", "mp4", false));
assert!(file_info_stream(info(r#"{"codec":"he-aac-mp4","bitrate":64,"urls":["https://a"]}"#)).is_none());
assert!(file_info_stream(info(r#"{"codec":"flac","urls":[]}"#)).is_none());
let mp3 = Stream { urls: vec![], codec: "mp3".into(), bitrate_kbps: 320, preview: false, key: None };
assert_eq!((mp3.label().as_str(), mp3.container()), ("MP3 320", "mp3"));
}
}