Files
musyx/crates/ym-api/src/client.rs
T
Yuriy Panov b73af1f870 feat: playback of liked tracks with audio engine, queue and player bar
- ym-api: Track/Stream models, liked tracks, signed download URLs (full MP3
  over AAC over previews, highest bitrate) and in-memory fetch
- Audio thread on rodio, driven by commands and reporting through an iced
  subscription; generation ids drop stale events
- Opens the default output with a buffer clamped to the device's range:
  rodio's 2048-frame default fails on Bluetooth headphones that cap at 1024
- Queue with shuffle, repeat off/all/one, back/advance and jump; player
  state machine with prefetch of the next track, replay from memory, and
  skipping unplayable tracks (stops after three in a row)
- Working player bar (seek, volume, mute, quality badge), queue drawer,
  Collection screen with a lazily built liked-tracks list
- audio_probe example lists and test-opens output devices
2026-10-15 14:38:33 +06:00

168 lines
6.1 KiB
Rust

use std::sync::Arc;
use crate::auth::Credentials;
use crate::models::{Stream, Track, best_variant};
use crate::{Error, Result};
/// The signed-in user as the UI needs them.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Account {
pub uid: i64,
pub login: String,
/// Best human-readable name: display name, then full name, then login.
pub name: String,
/// Yandex Plus unlocks full-length tracks; without it the API serves 30-second previews.
pub has_plus: bool,
/// When the current subscription ends, as Yandex formats it (ISO 8601).
pub subscription_end: Option<String>,
}
impl Account {
/// One letter for the avatar.
pub fn initial(&self) -> char {
self.name.chars().find(|c| c.is_alphanumeric()).map_or('?', |c| {
c.to_uppercase().next().unwrap_or(c)
})
}
fn from_status(status: yamuse::models::Status) -> Option<Self> {
let account = status.account?;
let uid = account.uid?;
let login = account.login.unwrap_or_default();
let non_empty = |s: Option<String>| s.filter(|s| !s.trim().is_empty());
let name = non_empty(account.display_name)
.or_else(|| non_empty(account.full_name))
.unwrap_or_else(|| login.clone());
Some(Self {
uid,
login,
name,
has_plus: status.plus.and_then(|p| p.has_plus).unwrap_or(false),
subscription_end: status.subscription.and_then(|s| {
s.end.or_else(|| s.auto_renewable.into_iter().find_map(|a| a.expires))
}),
})
}
}
/// An authenticated API client. Cheap to clone.
#[derive(Debug, Clone)]
pub struct YmClient {
inner: yamuse::Client,
}
impl YmClient {
/// Builds a client for `credentials` and loads the account. Fails with
/// [`crate::Error::Unauthorized`] when the token is no longer valid.
pub async fn connect(credentials: &Credentials) -> Result<(Self, Account)> {
let inner = yamuse::Client::builder().token(&credentials.access_token).build()?;
let status = inner.refresh_account().await?;
let account = Account::from_status(status)
.ok_or_else(|| Error::Unauthorized("account status has no user".into()))?;
Ok((Self { inner }, account))
}
/// A client with no token, for previews and tests. Every account call fails.
pub fn unauthenticated() -> Result<Self> {
Ok(Self { inner: yamuse::Client::anonymous()? })
}
/// The user's liked tracks, newest like first, with full metadata.
pub async fn liked_tracks(&self) -> Result<Vec<Track>> {
let list = self.inner.liked_tracks(None).await?;
let ids: Vec<String> = list
.tracks
.into_iter()
.filter_map(|short| {
let id = match short.id? {
yamuse::models::Id::Number(n) => n.to_string(),
yamuse::models::Id::Text(s) => s,
};
Some(match short.album_id {
Some(album) if !id.contains(':') => format!("{id}:{album}"),
_ => id,
})
})
.collect();
self.tracks(ids).await
}
/// Full metadata for `ids` (`"trackId"` or `"trackId:albumId"`), in the given order.
pub async fn tracks(&self, ids: Vec<String>) -> Result<Vec<Track>> {
if ids.is_empty() {
return Ok(Vec::new());
}
let tracks = self.inner.tracks(&ids).await?;
Ok(tracks.into_iter().filter_map(Track::from_yamuse).collect())
}
/// Resolves a signed, short-lived audio URL for a track.
pub async fn stream(&self, track_id: &str) -> Result<Stream> {
let variants = self.inner.track_download_info(track_id).await?;
let variant = best_variant(&variants)
.ok_or_else(|| Error::Api(format!("no playable variant for track {track_id}")))?;
let url = variant.direct_link(self.inner.transport()).await?;
Ok(Stream {
url,
codec: variant.codec.clone().unwrap_or_default(),
bitrate_kbps: variant.bitrate_in_kbps.unwrap_or(0).max(0) as u32,
preview: variant.preview.unwrap_or(false),
})
}
/// Downloads a whole stream into memory (a 320 kbps track is about 10 MB).
pub async fn fetch(&self, stream: &Stream) -> Result<Arc<[u8]>> {
let bytes = yamuse::download::Downloader::new(self.inner.transport(), [stream.url.clone()])
.to_bytes()
.await?;
Ok(bytes.into())
}
/// Re-reads the account, e.g. after a subscription may have changed.
pub async fn account(&self) -> Result<Account> {
let status = self.inner.refresh_account().await?;
Account::from_status(status)
.ok_or_else(|| Error::Unauthorized("account status has no user".into()))
}
}
#[cfg(test)]
mod tests {
use super::*;
fn status(json: &str) -> yamuse::models::Status {
serde_json::from_str(json).unwrap()
}
#[test]
fn account_prefers_display_name_and_reads_plus() {
let a = Account::from_status(status(
r#"{"account":{"uid":42,"login":"yuriy.panov","displayName":"Юрий","fullName":"Юрий Панов"},
"plus":{"hasPlus":true},"subscription":{"end":"2027-01-01T00:00:00+03:00"}}"#,
))
.unwrap();
assert_eq!(a.uid, 42);
assert_eq!(a.name, "Юрий");
assert_eq!(a.initial(), 'Ю');
assert!(a.has_plus);
assert_eq!(a.subscription_end.as_deref(), Some("2027-01-01T00:00:00+03:00"));
}
#[test]
fn account_falls_back_to_login_and_no_plus() {
let a = Account::from_status(status(
r#"{"account":{"uid":7,"login":"listener","displayName":" "}}"#,
))
.unwrap();
assert_eq!(a.name, "listener");
assert!(!a.has_plus);
assert_eq!(a.subscription_end, None);
}
#[test]
fn anonymous_status_is_not_an_account() {
assert!(Account::from_status(status(r#"{"account":{"now":"2026-10-15"}}"#)).is_none());
assert!(Account::from_status(status("{}")).is_none());
}
}