Files
musyx/crates/ym-api/src/models.rs
T
Yuriy Panov 60156aba94 feat: media keys, device recovery, settings and a macOS app bundle
- Media keys and Now Playing (souvlaki): title, artist, album, cover and
  position published on track and state changes; play/pause/toggle,
  next/previous and seeking from the OS controls
- Audio engine reopens the default output when the device changes or
  disappears, reloading the current track at the same position; with no
  device it keeps looking and resumes when one appears. Underruns are
  ignored rather than treated as device loss
- Settings screen: streaming quality (Best, Balanced <=192 kbps, Data
  saver <=128 kbps), appearance (system/light/dark), clear cover cache;
  quality, appearance and volume persist as JSON in the config folder
- Bitrate cap chooses the best variant within it, or the smallest above
- Lyrics failures get a retry button
- App icon drawn by tool/make_icon.py; tool/bundle-macos.sh builds an
  ad-hoc signed Musyx.app (--install copies it to /Applications)
- Release profile: thin LTO and stripped symbols
2026-10-15 16:28:07 +06:00

228 lines
8.7 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(Debug, Clone, PartialEq, Eq)]
pub struct Stream {
pub url: String,
/// "mp3" or "aac".
pub codec: String,
pub bitrate_kbps: u32,
/// True when only a 30-second preview is available (no Plus).
pub preview: bool,
}
impl Stream {
/// "MP3 320", shown in the player bar.
pub fn label(&self) -> String {
format!("{} {}", self.codec.to_ascii_uppercase(), self.bitrate_kbps)
}
}
/// 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());
}
}