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>
This commit is contained in:
commit
46610d95fa
217 files changed
+26144
No files matched your search
@@ -0,0 +1,19 @@
|
||||
[package]
|
||||
name = "ym-api"
|
||||
description = "Client for the unofficial Yandex Music API"
|
||||
version.workspace = true
|
||||
edition.workspace = true
|
||||
license.workspace = true
|
||||
publish.workspace = true
|
||||
|
||||
[dependencies]
|
||||
yamuse = "0.3.2"
|
||||
serde = { version = "1", features = ["derive"] }
|
||||
thiserror = "2"
|
||||
serde_json = "1"
|
||||
|
||||
[dev-dependencies]
|
||||
tokio = { version = "1", features = ["macros", "rt-multi-thread"] }
|
||||
|
||||
[lints]
|
||||
workspace = true
|
||||
@@ -0,0 +1,207 @@
|
||||
//! Yandex OAuth device flow: show a code, the user confirms it on Yandex's
|
||||
//! page, poll until a token arrives.
|
||||
//!
|
||||
//! Uses the official Android app's public client id (via `yamuse`), because
|
||||
//! third parties can't register an app for the music API.
|
||||
|
||||
use std::time::{Duration, SystemTime, UNIX_EPOCH};
|
||||
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
use crate::{Error, Result};
|
||||
|
||||
/// Shown on Yandex's list of signed-in devices.
|
||||
const DEVICE_NAME: &str = "Musyx";
|
||||
/// Yandex rate-limits polling; faster than this turns a pending login into a rejected one.
|
||||
const MIN_POLL: Duration = Duration::from_secs(3);
|
||||
/// Refresh once less than this much lifetime is left.
|
||||
const REFRESH_MARGIN: Duration = Duration::from_secs(7 * 24 * 3600);
|
||||
|
||||
/// A pending sign-in: what to show the user and what to poll with.
|
||||
#[derive(Clone, PartialEq, Eq)]
|
||||
pub struct DeviceCode {
|
||||
pub user_code: String,
|
||||
pub verification_url: String,
|
||||
pub expires_in: Duration,
|
||||
pub interval: Duration,
|
||||
device_code: String,
|
||||
}
|
||||
|
||||
impl std::fmt::Debug for DeviceCode {
|
||||
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||
f.debug_struct("DeviceCode")
|
||||
.field("user_code", &self.user_code)
|
||||
.field("verification_url", &self.verification_url)
|
||||
.field("expires_in", &self.expires_in)
|
||||
.field("interval", &self.interval)
|
||||
.finish_non_exhaustive()
|
||||
}
|
||||
}
|
||||
|
||||
/// What the keychain stores. `Debug` never prints the tokens.
|
||||
#[derive(Clone, PartialEq, Eq, Serialize, Deserialize)]
|
||||
pub struct Credentials {
|
||||
pub access_token: String,
|
||||
#[serde(default)]
|
||||
pub refresh_token: Option<String>,
|
||||
/// Unix seconds; `None` when Yandex didn't say (pasted tokens).
|
||||
#[serde(default)]
|
||||
pub expires_at: Option<u64>,
|
||||
}
|
||||
|
||||
impl std::fmt::Debug for Credentials {
|
||||
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||
f.debug_struct("Credentials")
|
||||
.field("access_token", &"<redacted>")
|
||||
.field("refresh_token", &self.refresh_token.as_ref().map(|_| "<redacted>"))
|
||||
.field("expires_at", &self.expires_at)
|
||||
.finish()
|
||||
}
|
||||
}
|
||||
|
||||
impl Credentials {
|
||||
/// A token the user pasted. Its lifetime is unknown, so it is never refreshed.
|
||||
pub fn from_token(token: impl Into<String>) -> Self {
|
||||
Self { access_token: token.into().trim().to_owned(), refresh_token: None, expires_at: None }
|
||||
}
|
||||
|
||||
/// True when the token expires within a week and can be refreshed.
|
||||
pub fn needs_refresh(&self, now: SystemTime) -> bool {
|
||||
let (Some(_), Some(expires_at)) = (&self.refresh_token, self.expires_at) else {
|
||||
return false;
|
||||
};
|
||||
let now = now.duration_since(UNIX_EPOCH).unwrap_or_default().as_secs();
|
||||
expires_at.saturating_sub(now) < REFRESH_MARGIN.as_secs()
|
||||
}
|
||||
|
||||
fn from_oauth(token: yamuse::models::OAuthToken, now: SystemTime) -> Result<Self> {
|
||||
let access_token = token
|
||||
.access_token
|
||||
.filter(|t| !t.is_empty())
|
||||
.ok_or_else(|| Error::Api("token response carried no access token".into()))?;
|
||||
let now = now.duration_since(UNIX_EPOCH).unwrap_or_default().as_secs();
|
||||
Ok(Self {
|
||||
access_token,
|
||||
refresh_token: token.refresh_token.filter(|t| !t.is_empty()),
|
||||
expires_at: token.expires_in.map(|s| now + s),
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub enum Poll {
|
||||
/// The user hasn't confirmed yet. Keep polling at `DeviceCode::interval`.
|
||||
Pending,
|
||||
Granted(Credentials),
|
||||
}
|
||||
|
||||
/// Talks to oauth.yandex.ru. Cheap to clone.
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct Auth {
|
||||
client: yamuse::Client,
|
||||
options: yamuse::DeviceAuthOptions,
|
||||
}
|
||||
|
||||
impl Auth {
|
||||
pub fn new() -> Result<Self> {
|
||||
Ok(Self {
|
||||
client: yamuse::Client::anonymous()?,
|
||||
options: yamuse::DeviceAuthOptions {
|
||||
device_name: DEVICE_NAME.to_owned(),
|
||||
..Default::default()
|
||||
},
|
||||
})
|
||||
}
|
||||
|
||||
pub async fn request_code(&self) -> Result<DeviceCode> {
|
||||
let code = self.client.request_device_code(&self.options).await?;
|
||||
let missing = |what: &str| Error::Api(format!("device code response carried no {what}"));
|
||||
Ok(DeviceCode {
|
||||
device_code: code.device_code.ok_or_else(|| missing("device code"))?,
|
||||
user_code: code.user_code.ok_or_else(|| missing("user code"))?,
|
||||
verification_url: code
|
||||
.verification_url
|
||||
.unwrap_or_else(|| "https://ya.ru/device".to_owned()),
|
||||
expires_in: Duration::from_secs(code.expires_in.unwrap_or(300)),
|
||||
interval: Duration::from_secs(code.interval.unwrap_or(5)).max(MIN_POLL),
|
||||
})
|
||||
}
|
||||
|
||||
/// Poll once. `Pending` is the normal answer until the user confirms.
|
||||
pub async fn poll(&self, code: &DeviceCode) -> Result<Poll> {
|
||||
match self.client.poll_device_token(&code.device_code, &self.options).await? {
|
||||
None => Ok(Poll::Pending),
|
||||
Some(token) => Ok(Poll::Granted(Credentials::from_oauth(token, SystemTime::now())?)),
|
||||
}
|
||||
}
|
||||
|
||||
/// Swap a refresh token for a new pair. Store the result: Yandex rotates the refresh token.
|
||||
pub async fn refresh(&self, credentials: &Credentials) -> Result<Credentials> {
|
||||
let refresh = credentials
|
||||
.refresh_token
|
||||
.as_deref()
|
||||
.ok_or_else(|| Error::Unauthorized("no refresh token".into()))?;
|
||||
let token = self.client.refresh_token(refresh, &self.options).await?;
|
||||
let mut fresh = Credentials::from_oauth(token, SystemTime::now())?;
|
||||
// Keep the old refresh token if Yandex didn't rotate it.
|
||||
if fresh.refresh_token.is_none() {
|
||||
fresh.refresh_token = credentials.refresh_token.clone();
|
||||
}
|
||||
Ok(fresh)
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
fn at(secs: u64) -> SystemTime {
|
||||
UNIX_EPOCH + Duration::from_secs(secs)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn debug_never_prints_tokens() {
|
||||
let c = Credentials {
|
||||
access_token: "secret-access".into(),
|
||||
refresh_token: Some("secret-refresh".into()),
|
||||
expires_at: Some(10),
|
||||
};
|
||||
let shown = format!("{c:?}");
|
||||
assert!(!shown.contains("secret"), "{shown}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn credentials_round_trip_and_tolerate_old_shape() {
|
||||
let c = Credentials { access_token: "a".into(), refresh_token: Some("r".into()), expires_at: Some(5) };
|
||||
let json = serde_json::to_string(&c).unwrap();
|
||||
assert_eq!(serde_json::from_str::<Credentials>(&json).unwrap(), c);
|
||||
let bare: Credentials = serde_json::from_str(r#"{"access_token":"a"}"#).unwrap();
|
||||
assert_eq!(bare, Credentials::from_token("a"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn refresh_only_near_expiry_and_only_with_refresh_token() {
|
||||
let week = 7 * 24 * 3600;
|
||||
let c = Credentials { access_token: "a".into(), refresh_token: Some("r".into()), expires_at: Some(10 * week) };
|
||||
assert!(!c.needs_refresh(at(8 * week)));
|
||||
assert!(c.needs_refresh(at(9 * week + 1)));
|
||||
assert!(c.needs_refresh(at(11 * week)));
|
||||
let pasted = Credentials::from_token(" a \n");
|
||||
assert_eq!(pasted.access_token, "a");
|
||||
assert!(!pasted.needs_refresh(at(u64::MAX / 2)));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn oauth_token_converts_with_absolute_expiry() {
|
||||
let token = yamuse::models::OAuthToken {
|
||||
access_token: Some("a".into()),
|
||||
refresh_token: Some(String::new()),
|
||||
expires_in: Some(100),
|
||||
token_type: Some("bearer".into()),
|
||||
};
|
||||
let c = Credentials::from_oauth(token, at(1_000)).unwrap();
|
||||
assert_eq!(c.expires_at, Some(1_100));
|
||||
assert_eq!(c.refresh_token, None);
|
||||
assert!(Credentials::from_oauth(Default::default(), at(0)).is_err());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,799 @@
|
||||
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,
|
||||
};
|
||||
use crate::edit::{LikedIds, Lyrics};
|
||||
use crate::discover::{ChartEntry, Genre, Home, SearchKind, SearchResults};
|
||||
use crate::models::{Stream, Track, best_variant, file_info_stream};
|
||||
use crate::wave::{PlayReport, Station, WaveBatch, WaveEvent, WaveSettings, iso_millis, numeric_id};
|
||||
|
||||
use crate::{Error, Result};
|
||||
|
||||
/// Playlist diffs need numeric track and album ids.
|
||||
fn diff_ids(track: &Track) -> Result<(i64, i64)> {
|
||||
let id = crate::wave::numeric_id(&track.id).ok_or_else(|| Error::Api("this track can't go in a playlist".into()))?;
|
||||
let album = track.album.as_ref().map(|a| a.id).ok_or_else(|| Error::Api("track has no album".into()))?;
|
||||
Ok((id, album))
|
||||
}
|
||||
|
||||
/// How many featured podcasts to resolve.
|
||||
pub const FEATURED_PODCASTS: usize = 48;
|
||||
|
||||
/// Playlist ids from `/tags/{id}/playlist-ids`: `{"ids":[{"uid":1,"kind":2}]}`,
|
||||
/// tolerating the `"uid:kind"` string form too.
|
||||
fn tag_playlist_ids(raw: &serde_json::Value) -> Vec<String> {
|
||||
let ids = raw.get("result").unwrap_or(raw).get("ids").and_then(|v| v.as_array());
|
||||
ids.into_iter()
|
||||
.flatten()
|
||||
.filter_map(|id| match id {
|
||||
serde_json::Value::String(s) if s.contains(':') => Some(s.clone()),
|
||||
serde_json::Value::Object(o) => {
|
||||
Some(format!("{}:{}", o.get("uid")?.as_i64()?, o.get("kind")?.as_i64()?))
|
||||
}
|
||||
_ => None,
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// `trackId:albumId` for the newest `limit` distinct tracks in the history (days, then
|
||||
/// the contexts played that day, then their tracks, each newest first).
|
||||
fn recent_track_ids(history: &yamuse::models::MusicHistory, limit: usize) -> Vec<String> {
|
||||
let mut seen = std::collections::HashSet::new();
|
||||
history
|
||||
.history_tabs
|
||||
.iter()
|
||||
.flat_map(|day| &day.items)
|
||||
.flat_map(|group| &group.tracks)
|
||||
.filter_map(|item| {
|
||||
let id = item.data.as_ref()?.item_id.as_ref()?;
|
||||
let track = id.track_id.as_deref().filter(|t| !t.is_empty())?;
|
||||
Some(match id.album_id.as_deref().filter(|a| !a.is_empty()) {
|
||||
Some(album) => format!("{track}:{album}"),
|
||||
None => track.to_owned(),
|
||||
})
|
||||
})
|
||||
.filter(|id| seen.insert(id.split(':').next().unwrap_or(id).to_owned()))
|
||||
.take(limit)
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// 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(Clone)]
|
||||
pub struct YmClient {
|
||||
inner: yamuse::Client,
|
||||
/// Kept for the few JSON endpoints yamuse doesn't expose. Never printed.
|
||||
token: Option<Arc<str>>,
|
||||
}
|
||||
|
||||
impl std::fmt::Debug for YmClient {
|
||||
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||
f.debug_struct("YmClient").finish_non_exhaustive()
|
||||
}
|
||||
}
|
||||
|
||||
/// The language Yandex writes its own titles in: genres, Home blocks, stations.
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub enum ContentLanguage {
|
||||
Russian,
|
||||
English,
|
||||
}
|
||||
|
||||
impl ContentLanguage {
|
||||
fn yamuse(self) -> yamuse::Language {
|
||||
match self {
|
||||
ContentLanguage::Russian => yamuse::Language::Ru,
|
||||
ContentLanguage::English => yamuse::Language::En,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
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, language: ContentLanguage) -> Result<(Self, Account)> {
|
||||
let inner = yamuse::Client::builder()
|
||||
.token(&credentials.access_token)
|
||||
.language(language.yamuse())
|
||||
.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, token: Some(credentials.access_token.as_str().into()) }, account))
|
||||
}
|
||||
|
||||
/// The same account, with Yandex answering in `language`. Loads the account
|
||||
/// again, since that's how the client learns whose library it reads.
|
||||
pub async fn in_language(&self, language: ContentLanguage) -> Result<Self> {
|
||||
let mut builder = yamuse::Client::builder().language(language.yamuse());
|
||||
if let Some(token) = &self.token {
|
||||
builder = builder.token(token.as_ref());
|
||||
}
|
||||
let inner = builder.build()?;
|
||||
if self.token.is_some() {
|
||||
inner.init().await?;
|
||||
}
|
||||
Ok(Self { inner, token: self.token.clone() })
|
||||
}
|
||||
|
||||
/// A client with no token, for previews and tests. Every account call fails.
|
||||
pub fn unauthenticated() -> Result<Self> {
|
||||
Ok(Self { inner: yamuse::Client::anonymous()?, token: None })
|
||||
}
|
||||
|
||||
/// 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())
|
||||
}
|
||||
|
||||
/// Tracks Yandex considers similar to `track_id` (about 20), best match first.
|
||||
pub async fn similar_tracks(&self, track_id: &str) -> Result<Vec<Track>> {
|
||||
let similar = self.inner.track_similar(track_id).await?;
|
||||
Ok(similar.similar_tracks.into_iter().filter_map(Track::from_yamuse).collect())
|
||||
}
|
||||
|
||||
/// Resolves a signed, short-lived audio URL for a track, at most `max_kbps` when set.
|
||||
pub async fn stream(&self, track_id: &str, max_kbps: Option<u32>) -> Result<Stream> {
|
||||
let variants = self.inner.track_download_info(track_id).await?;
|
||||
let variant = best_variant(&variants, max_kbps)
|
||||
.ok_or_else(|| Error::Api(format!("no playable variant for track {track_id}")))?;
|
||||
let url = variant.direct_link(self.inner.transport()).await?;
|
||||
Ok(Stream {
|
||||
urls: vec![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),
|
||||
key: None,
|
||||
})
|
||||
}
|
||||
|
||||
/// FLAC when Yandex grants it for this track and account. Otherwise Yandex
|
||||
/// answers with the best lossy file it allows (often AAC 192), which is played
|
||||
/// as is unless it's HE-AAC, which the decoder can't do justice; then the MP3
|
||||
/// path, as [`stream`](Self::stream) with no cap.
|
||||
pub async fn lossless_stream(&self, track_id: &str) -> Result<Stream> {
|
||||
match self.inner.track_lossless_info(track_id, "lossless").await.map_err(Error::from) {
|
||||
Ok(info) => {
|
||||
if let Some(stream) = file_info_stream(info) {
|
||||
return Ok(stream);
|
||||
}
|
||||
}
|
||||
Err(e @ (Error::Unauthorized(_) | Error::Network(_))) => return Err(e),
|
||||
// An API refusal (region, rights) still leaves the MP3 path.
|
||||
Err(_) => {}
|
||||
}
|
||||
self.stream(track_id, None).await
|
||||
}
|
||||
|
||||
/// Downloads a whole stream into memory, decrypting it when it is encrypted
|
||||
/// (MP3 320 is about 10 MB a track, FLAC 30–60 MB).
|
||||
pub async fn fetch(&self, stream: &Stream) -> Result<Arc<[u8]>> {
|
||||
let bytes = yamuse::download::Downloader::new(self.inner.transport(), stream.urls.iter().cloned())
|
||||
.maybe_encraw_key(stream.key.clone())
|
||||
.to_bytes()
|
||||
.await?;
|
||||
Ok(bytes.into())
|
||||
}
|
||||
|
||||
/// Albums the user liked, newest first, with full details.
|
||||
pub async fn liked_albums(&self) -> Result<Vec<AlbumSummary>> {
|
||||
let likes = self.inner.liked_albums(None).await?;
|
||||
let ids: Vec<i64> = likes
|
||||
.into_iter()
|
||||
.filter_map(|like| like.album.and_then(|a| a.id).or_else(|| like.id.and_then(|i| i.as_number())))
|
||||
.collect();
|
||||
if ids.is_empty() {
|
||||
return Ok(Vec::new());
|
||||
}
|
||||
let albums = self.inner.albums(&ids).await?;
|
||||
Ok(albums.into_iter().filter_map(AlbumSummary::from_yamuse).collect())
|
||||
}
|
||||
|
||||
pub async fn liked_artists(&self) -> Result<Vec<ArtistSummary>> {
|
||||
let artists = self.inner.liked_artists(None).await?;
|
||||
Ok(artists.into_iter().filter_map(ArtistSummary::from_yamuse).collect())
|
||||
}
|
||||
|
||||
/// Playlists the user owns, and ones they liked.
|
||||
pub async fn library_playlists(&self) -> Result<LibraryPlaylists> {
|
||||
let own = self.inner.user_playlists_list(None).await?;
|
||||
let likes = self.inner.liked_playlists(None).await?;
|
||||
let liked_ids: Vec<String> = likes
|
||||
.iter()
|
||||
.filter_map(|like| {
|
||||
let p = like.playlist.as_ref()?;
|
||||
let owner = p.uid.or_else(|| p.owner.as_ref().and_then(|o| o.uid))?;
|
||||
Some(format!("{owner}:{}", p.kind?))
|
||||
})
|
||||
.collect();
|
||||
let liked = if liked_ids.is_empty() {
|
||||
Vec::new()
|
||||
} else {
|
||||
self.inner.playlists_list(&liked_ids).await?
|
||||
};
|
||||
Ok(LibraryPlaylists {
|
||||
own: own.iter().filter_map(PlaylistSummary::from_yamuse).collect(),
|
||||
liked: liked.iter().filter_map(PlaylistSummary::from_yamuse).collect(),
|
||||
})
|
||||
}
|
||||
|
||||
pub async fn album(&self, id: i64) -> Result<AlbumPage> {
|
||||
let album = self.inner.album_with_tracks(id).await?;
|
||||
AlbumPage::from_yamuse(album).ok_or_else(|| Error::Api(format!("album {id} has no id")))
|
||||
}
|
||||
|
||||
pub async fn artist(&self, id: i64) -> Result<ArtistPage> {
|
||||
let brief = self.inner.artist_brief_info(id).await?;
|
||||
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.
|
||||
pub async fn playlist(&self, id: PlaylistId) -> Result<PlaylistPage> {
|
||||
let raw = self.inner.user_playlist(id.kind, Some(id.owner)).await?;
|
||||
let playlist = PlaylistSummary::from_yamuse(&raw)
|
||||
.ok_or_else(|| Error::Api(format!("playlist {}:{} incomplete", id.owner, id.kind)))?;
|
||||
|
||||
let mut tracks: Vec<Option<Track>> = Vec::with_capacity(raw.tracks.len());
|
||||
let mut missing = Vec::new();
|
||||
for (i, short) in raw.tracks.into_iter().enumerate() {
|
||||
match short.track.and_then(Track::from_yamuse) {
|
||||
Some(track) => tracks.push(Some(track)),
|
||||
None => {
|
||||
if let Some(id) = short.id {
|
||||
let id = match id {
|
||||
yamuse::models::Id::Number(n) => n.to_string(),
|
||||
yamuse::models::Id::Text(s) => s,
|
||||
};
|
||||
missing.push((i, id));
|
||||
}
|
||||
tracks.push(None);
|
||||
}
|
||||
}
|
||||
}
|
||||
if !missing.is_empty() {
|
||||
let fetched = self.tracks(missing.iter().map(|(_, id)| id.clone()).collect()).await?;
|
||||
for ((slot, _), track) in missing.iter().zip(fetched) {
|
||||
tracks[*slot] = Some(track);
|
||||
}
|
||||
}
|
||||
|
||||
Ok(PlaylistPage {
|
||||
playlist,
|
||||
description: raw.description.filter(|d| !d.trim().is_empty()),
|
||||
tracks: tracks.into_iter().flatten().collect(),
|
||||
})
|
||||
}
|
||||
|
||||
/// One page of search results. `page` starts at 0.
|
||||
pub async fn search(&self, text: &str, kind: SearchKind, page: u32) -> Result<SearchResults> {
|
||||
let mut query = yamuse::SearchQuery::default().of_type(kind.to_yamuse());
|
||||
query.page = page;
|
||||
Ok(SearchResults::from_yamuse(self.inner.search(text, query).await?))
|
||||
}
|
||||
|
||||
/// Completions for a partial query, best first.
|
||||
pub async fn suggest(&self, part: &str) -> Result<Vec<String>> {
|
||||
Ok(self.inner.search_suggest(part).await?.suggestions)
|
||||
}
|
||||
|
||||
/// The home page: personal playlists, new releases and playlists, the chart.
|
||||
pub async fn home(&self) -> Result<Home> {
|
||||
let landing = self
|
||||
.inner
|
||||
.landing(["personalplaylists", "new-releases", "new-playlists"])
|
||||
.await?;
|
||||
let mut home = Home::from_landing(landing);
|
||||
// The chart block on landing3 holds a handful of items; the chart endpoint has them all.
|
||||
match self.chart().await {
|
||||
Ok(chart) if !chart.is_empty() => home.chart = chart,
|
||||
Ok(_) => {}
|
||||
Err(e) => eprintln!("chart: {e}"),
|
||||
}
|
||||
Ok(home)
|
||||
}
|
||||
|
||||
/// The last `limit` different tracks the user played, newest first, on any device.
|
||||
pub async fn recently_played(&self, limit: usize) -> Result<Vec<Track>> {
|
||||
let history = self.inner.music_history(0).await?;
|
||||
self.tracks(recent_track_ids(&history, limit)).await
|
||||
}
|
||||
|
||||
pub async fn chart(&self) -> Result<Vec<ChartEntry>> {
|
||||
let info = self.inner.chart().await?;
|
||||
Ok(info
|
||||
.chart
|
||||
.map(|p| p.tracks.into_iter().filter_map(ChartEntry::from_short).collect())
|
||||
.unwrap_or_default())
|
||||
}
|
||||
|
||||
pub async fn genres(&self) -> Result<Vec<Genre>> {
|
||||
Ok(self.inner.genres().await?.into_iter().filter_map(Genre::from_yamuse).collect())
|
||||
}
|
||||
|
||||
/// Editorial playlists filed under a genre or mood tag.
|
||||
pub async fn tag_playlists(&self, tag: &str) -> Result<Vec<PlaylistSummary>> {
|
||||
// yamuse types these ids as strings; the API sends `{uid, kind}` objects.
|
||||
let raw = self
|
||||
.inner
|
||||
.get_raw(&format!("/tags/{tag}/playlist-ids"), yamuse::Params::new())
|
||||
.await?;
|
||||
let ids = tag_playlist_ids(&raw);
|
||||
if ids.is_empty() {
|
||||
return Ok(Vec::new());
|
||||
}
|
||||
let playlists = self.inner.playlists_list(&ids).await?;
|
||||
Ok(playlists.iter().filter_map(PlaylistSummary::from_yamuse).collect())
|
||||
}
|
||||
|
||||
/// Podcasts Yandex currently features (the first [`FEATURED_PODCASTS`]; the list runs to thousands).
|
||||
pub async fn featured_podcasts(&self) -> Result<Vec<AlbumSummary>> {
|
||||
let mut ids = self.inner.podcasts().await?.podcasts;
|
||||
ids.truncate(FEATURED_PODCASTS);
|
||||
if ids.is_empty() {
|
||||
return Ok(Vec::new());
|
||||
}
|
||||
let albums = self.inner.albums(&ids).await?;
|
||||
Ok(albums.into_iter().filter_map(AlbumSummary::from_yamuse).collect())
|
||||
}
|
||||
|
||||
/// Stations Yandex suggests to this user.
|
||||
pub async fn stations(&self) -> Result<Vec<Station>> {
|
||||
let dashboard = self.inner.rotor_dashboard().await?;
|
||||
Ok(dashboard.stations.into_iter().filter_map(Station::from_yamuse).collect())
|
||||
}
|
||||
|
||||
pub async fn wave_settings(&self, station: &str) -> Result<WaveSettings> {
|
||||
let info = self.inner.rotor_station_info(station).await?;
|
||||
Ok(info
|
||||
.into_iter()
|
||||
.next()
|
||||
.and_then(|r| r.settings2.or(r.settings))
|
||||
.map(|s| WaveSettings::from_api(&s))
|
||||
.unwrap_or_default())
|
||||
}
|
||||
|
||||
pub async fn set_wave_settings(&self, station: &str, settings: WaveSettings) -> Result<()> {
|
||||
let (mood, diversity, language) = settings.to_yamuse();
|
||||
self.inner
|
||||
.rotor_set_station_settings(station, mood, diversity, language, yamuse::StationType::Rotor)
|
||||
.await?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Starts a station session. My Wave's settings travel as extra seeds.
|
||||
pub async fn wave_start(&self, station: &str, settings: Option<WaveSettings>) -> Result<WaveBatch> {
|
||||
let mut seeds = vec![station.to_owned()];
|
||||
seeds.extend(settings.map(WaveSettings::seeds).unwrap_or_default());
|
||||
let body = serde_json::json!({ "seeds": seeds, "includeTracksInResponse": true });
|
||||
Ok(WaveBatch::from_session(&self.post_json("/rotor/session/new", &body).await?))
|
||||
}
|
||||
|
||||
/// The next batch of a session. `queue` is the recently queued tracks (`full_id`s).
|
||||
pub async fn wave_more(&self, session_id: &str, queue: &[String]) -> Result<WaveBatch> {
|
||||
let body = serde_json::json!({ "queue": queue });
|
||||
let path = format!("/rotor/session/{session_id}/tracks");
|
||||
let mut batch = WaveBatch::from_session(&self.post_json(&path, &body).await?);
|
||||
batch.session_id.get_or_insert_with(|| session_id.to_owned());
|
||||
Ok(batch)
|
||||
}
|
||||
|
||||
/// Tells a session what happened, so the next batch fits better.
|
||||
pub async fn wave_feedback(&self, session_id: &str, event: &WaveEvent, batch_id: Option<&str>) -> Result<()> {
|
||||
let now = iso_millis(std::time::SystemTime::now());
|
||||
let mut body = serde_json::json!({ "event": event.to_json(&now) });
|
||||
if let Some(batch) = batch_id {
|
||||
body["batchId"] = batch.into();
|
||||
}
|
||||
if matches!(event, WaveEvent::Started) {
|
||||
body["from"] = "musyx-wave".into();
|
||||
}
|
||||
self.post_json(&format!("/rotor/session/{session_id}/feedback"), &body).await?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// POSTs JSON with the same identity headers yamuse sends, returning `result`.
|
||||
async fn post_json(&self, path: &str, body: &serde_json::Value) -> Result<serde_json::Value> {
|
||||
let token = self.token.as_deref().ok_or_else(|| Error::Unauthorized("not signed in".into()))?;
|
||||
let response = self
|
||||
.inner
|
||||
.transport()
|
||||
.http()
|
||||
.post(format!("{}{path}", self.inner.base_url()))
|
||||
.header("Authorization", format!("OAuth {token}"))
|
||||
.header("X-Yandex-Music-Client", yamuse::transport::CLIENT_HEADER)
|
||||
.header("Content-Type", "application/json")
|
||||
.body(body.to_string())
|
||||
.send()
|
||||
.await
|
||||
.map_err(|e| Error::Network(e.to_string()))?;
|
||||
let status = response.status().as_u16();
|
||||
let text = response.text().await.map_err(|e| Error::Network(e.to_string()))?;
|
||||
let value: serde_json::Value = serde_json::from_str(&text).unwrap_or(serde_json::Value::Null);
|
||||
match status {
|
||||
200..=299 => Ok(value.get("result").cloned().unwrap_or(value)),
|
||||
401 | 403 => Err(Error::Unauthorized(format!("{path}: {status}"))),
|
||||
500.. => Err(Error::Network(format!("{path}: {status}"))),
|
||||
_ => {
|
||||
let message = value
|
||||
.pointer("/error/message")
|
||||
.or_else(|| value.pointer("/error/name"))
|
||||
.and_then(|m| m.as_str())
|
||||
.unwrap_or(&text);
|
||||
Err(Error::Api(format!("{path}: {status} {message}")))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Records a listen in the user's history. Tracks without numeric ids are skipped.
|
||||
pub async fn report_play(&self, report: &PlayReport) -> Result<()> {
|
||||
let Some(track_id) = numeric_id(&report.track_id) else { return Ok(()) };
|
||||
let mut r = yamuse::PlayAudioReport::new(track_id, report.album_id.unwrap_or(0), report.from.clone());
|
||||
r.track_length_seconds = report.length.as_secs();
|
||||
r.total_played_seconds = report.played.as_secs();
|
||||
r.end_position_seconds = report.end_position.as_secs();
|
||||
// yamuse's default timestamps drop the milliseconds, which the endpoint rejects.
|
||||
let now = iso_millis(std::time::SystemTime::now());
|
||||
r.timestamp = Some(now.clone());
|
||||
r.client_now = Some(now);
|
||||
self.inner.play_audio(&r).await?;
|
||||
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.
|
||||
pub async fn set_track_liked(&self, track_id: &str, liked: bool) -> Result<()> {
|
||||
self.inner.set_liked(yamuse::Likeable::Track, [track_id], liked, None).await?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// "Don't recommend": the track stops appearing in waves and mixes.
|
||||
pub async fn set_track_disliked(&self, track_id: &str, disliked: bool) -> Result<()> {
|
||||
self.inner.set_disliked(yamuse::Dislikeable::Track, [track_id], disliked, None).await?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub async fn set_album_liked(&self, id: i64, liked: bool) -> Result<()> {
|
||||
self.inner.set_liked(yamuse::Likeable::Album, [id], liked, None).await?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub async fn set_artist_liked(&self, id: i64, liked: bool) -> Result<()> {
|
||||
self.inner.set_liked(yamuse::Likeable::Artist, [id], liked, None).await?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub async fn set_playlist_liked(&self, id: PlaylistId, liked: bool) -> Result<()> {
|
||||
let key = format!("{}:{}", id.owner, id.kind);
|
||||
self.inner.set_liked(yamuse::Likeable::Playlist, [key], liked, None).await?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Ids only (no details), for drawing like state on every page.
|
||||
pub async fn liked_ids(&self) -> Result<LikedIds> {
|
||||
let albums = self.inner.liked_albums(None).await?;
|
||||
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())))
|
||||
.collect(),
|
||||
artists: artists.into_iter().filter_map(|a| a.id.and_then(|i| i.as_number())).collect(),
|
||||
playlists: playlists
|
||||
.into_iter()
|
||||
.filter_map(|l| {
|
||||
let p = l.playlist?;
|
||||
Some(PlaylistId { owner: p.uid.or_else(|| p.owner.and_then(|o| o.uid))?, kind: p.kind? })
|
||||
})
|
||||
.collect(),
|
||||
disliked_tracks: disliked
|
||||
.tracks
|
||||
.into_iter()
|
||||
.filter_map(|t| match t.id? {
|
||||
yamuse::models::Id::Number(n) => Some(n.to_string()),
|
||||
yamuse::models::Id::Text(s) => s.split(':').next().map(str::to_owned),
|
||||
})
|
||||
.collect(),
|
||||
})
|
||||
}
|
||||
|
||||
// ---- Playlists ----
|
||||
|
||||
pub async fn create_playlist(&self, title: &str, public: bool) -> Result<PlaylistSummary> {
|
||||
let visibility = if public { yamuse::Visibility::Public } else { yamuse::Visibility::Private };
|
||||
let p = self.inner.create_playlist(title, visibility).await?;
|
||||
PlaylistSummary::from_yamuse(&p).ok_or_else(|| Error::Api("created playlist has no id".into()))
|
||||
}
|
||||
|
||||
pub async fn rename_playlist(&self, id: PlaylistId, title: &str) -> Result<()> {
|
||||
self.inner.rename_playlist(id.kind, title).await?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub async fn set_playlist_public(&self, id: PlaylistId, public: bool) -> Result<()> {
|
||||
let visibility = if public { yamuse::Visibility::Public } else { yamuse::Visibility::Private };
|
||||
self.inner.set_playlist_visibility(id.kind, visibility).await?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub async fn delete_playlist(&self, id: PlaylistId) -> Result<()> {
|
||||
self.inner.delete_playlist(id.kind).await?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// The playlist's revision and length, which every edit needs fresh.
|
||||
async fn revision(&self, id: PlaylistId) -> Result<(i64, usize)> {
|
||||
let p = self.inner.user_playlist(id.kind, Some(id.owner)).await?;
|
||||
let len = p.track_count.map_or(p.tracks.len(), |n| n.max(0) as usize);
|
||||
Ok((p.revision.unwrap_or(0), len))
|
||||
}
|
||||
|
||||
/// Appends a track to the end of one of the user's playlists.
|
||||
pub async fn add_to_playlist(&self, id: PlaylistId, track: &Track) -> Result<()> {
|
||||
let (track_id, album_id) = diff_ids(track)?;
|
||||
let (revision, len) = self.revision(id).await?;
|
||||
self.inner.add_track_to_playlist(id.kind, track_id, album_id, len, revision).await?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Removes the track at `index`.
|
||||
pub async fn remove_from_playlist(&self, id: PlaylistId, index: usize) -> Result<()> {
|
||||
let (revision, _) = self.revision(id).await?;
|
||||
self.inner.remove_tracks_from_playlist(id.kind, index, index + 1, revision).await?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Moves the track at `from` so it ends up at `to`.
|
||||
pub async fn move_in_playlist(&self, id: PlaylistId, track: &Track, from: usize, to: usize) -> Result<()> {
|
||||
let (track_id, album_id) = diff_ids(track)?;
|
||||
let (revision, _) = self.revision(id).await?;
|
||||
let diff = yamuse::Difference::new()
|
||||
.delete(from, from + 1)
|
||||
.insert(to, [yamuse::DiffTrack::new(track_id, album_id)]);
|
||||
self.inner.change_playlist(id.kind, &diff, revision).await?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
// ---- Lyrics ----
|
||||
|
||||
/// Synced lyrics when Yandex has them, else plain text; `None` when there are none.
|
||||
pub async fn lyrics(&self, track_id: &str) -> Result<Option<Lyrics>> {
|
||||
for format in [yamuse::LyricsFormat::Lrc, yamuse::LyricsFormat::Text] {
|
||||
let meta = match self.inner.track_lyrics(track_id, format).await {
|
||||
Ok(meta) => meta,
|
||||
Err(yamuse::Error::NotFound(_)) => continue,
|
||||
Err(e) => return Err(e.into()),
|
||||
};
|
||||
let text = meta.text(self.inner.transport()).await?;
|
||||
if text.trim().is_empty() {
|
||||
continue;
|
||||
}
|
||||
let writers = meta.writers.clone();
|
||||
return Ok(Some(match format {
|
||||
yamuse::LyricsFormat::Lrc => Lyrics::from_lrc(&text, writers),
|
||||
yamuse::LyricsFormat::Text => Lyrics::from_text(&text, writers),
|
||||
}));
|
||||
}
|
||||
Ok(None)
|
||||
}
|
||||
|
||||
/// Downloads an image (covers are a few kilobytes).
|
||||
pub async fn image(&self, url: &str) -> Result<Vec<u8>> {
|
||||
Ok(yamuse::download::Downloader::new(self.inner.transport(), [url.to_owned()])
|
||||
.to_bytes()
|
||||
.await?)
|
||||
}
|
||||
|
||||
/// 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 tag_ids_accept_objects_and_strings() {
|
||||
let raw = serde_json::json!({"ids": [{"uid": 1, "kind": 2}, "3:4", null, {"uid": 5}]});
|
||||
assert_eq!(tag_playlist_ids(&raw), vec!["1:2", "3:4"]);
|
||||
let wrapped = serde_json::json!({"result": {"ids": [{"uid": 9, "kind": 8}]}});
|
||||
assert_eq!(tag_playlist_ids(&wrapped), vec!["9:8"]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn recent_ids_walk_days_and_skip_repeats() {
|
||||
let history: yamuse::models::MusicHistory = serde_json::from_value(serde_json::json!({"historyTabs": [
|
||||
{"date": "2026-10-15", "items": [{"context": {"type": "wave"}, "tracks": [
|
||||
{"type": "track", "data": {"itemId": {"trackId": "1", "albumId": "10"}}},
|
||||
{"type": "track", "data": {"itemId": {"trackId": "2"}}},
|
||||
]}]},
|
||||
{"date": "2026-10-14", "items": [{"tracks": [
|
||||
{"type": "track", "data": {"itemId": {"trackId": "1", "albumId": "10"}}},
|
||||
{"type": "track", "data": {}},
|
||||
{"type": "track", "data": {"itemId": {"trackId": "3", "albumId": "30"}}},
|
||||
{"type": "track", "data": {"itemId": {"trackId": "4", "albumId": "40"}}},
|
||||
]}]},
|
||||
]}))
|
||||
.unwrap();
|
||||
assert_eq!(recent_track_ids(&history, 3), ["1:10", "2", "3:30"]);
|
||||
assert_eq!(recent_track_ids(&history, 10).len(), 4);
|
||||
}
|
||||
|
||||
#[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());
|
||||
}
|
||||
}
|
||||
@@ -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));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,302 @@
|
||||
//! Search, the home landing, the chart, genres and podcasts.
|
||||
|
||||
use yamuse::models as y;
|
||||
|
||||
use crate::library::{AlbumSummary, ArtistSummary, PlaylistSummary};
|
||||
use crate::models::Track;
|
||||
|
||||
/// Which part of the catalogue a search covers.
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default)]
|
||||
pub enum SearchKind {
|
||||
#[default]
|
||||
All,
|
||||
Tracks,
|
||||
Albums,
|
||||
Artists,
|
||||
Playlists,
|
||||
Podcasts,
|
||||
}
|
||||
|
||||
impl SearchKind {
|
||||
pub const ALL: [SearchKind; 6] = [
|
||||
SearchKind::All,
|
||||
SearchKind::Tracks,
|
||||
SearchKind::Albums,
|
||||
SearchKind::Artists,
|
||||
SearchKind::Playlists,
|
||||
SearchKind::Podcasts,
|
||||
];
|
||||
|
||||
pub fn label(self) -> &'static str {
|
||||
match self {
|
||||
SearchKind::All => "All",
|
||||
SearchKind::Tracks => "Tracks",
|
||||
SearchKind::Albums => "Albums",
|
||||
SearchKind::Artists => "Artists",
|
||||
SearchKind::Playlists => "Playlists",
|
||||
SearchKind::Podcasts => "Podcasts",
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn to_yamuse(self) -> yamuse::SearchType {
|
||||
match self {
|
||||
SearchKind::All => yamuse::SearchType::All,
|
||||
SearchKind::Tracks => yamuse::SearchType::Track,
|
||||
SearchKind::Albums => yamuse::SearchType::Album,
|
||||
SearchKind::Artists => yamuse::SearchType::Artist,
|
||||
SearchKind::Playlists => yamuse::SearchType::Playlist,
|
||||
SearchKind::Podcasts => yamuse::SearchType::Podcast,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub enum BestMatch {
|
||||
Track(Track),
|
||||
Album(AlbumSummary),
|
||||
Artist(ArtistSummary),
|
||||
Playlist(PlaylistSummary),
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Default, PartialEq, Eq)]
|
||||
pub struct SearchResults {
|
||||
/// The query Yandex actually searched, when it corrected a typo.
|
||||
pub corrected: Option<String>,
|
||||
pub best: Option<BestMatch>,
|
||||
pub tracks: Vec<Track>,
|
||||
pub albums: Vec<AlbumSummary>,
|
||||
pub artists: Vec<ArtistSummary>,
|
||||
pub playlists: Vec<PlaylistSummary>,
|
||||
pub podcasts: Vec<AlbumSummary>,
|
||||
/// Total matches per kind, beyond the page returned.
|
||||
pub totals: Totals,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
|
||||
pub struct Totals {
|
||||
pub tracks: u32,
|
||||
pub albums: u32,
|
||||
pub artists: u32,
|
||||
pub playlists: u32,
|
||||
pub podcasts: u32,
|
||||
}
|
||||
|
||||
impl Totals {
|
||||
pub fn get(&self, kind: SearchKind) -> Option<u32> {
|
||||
match kind {
|
||||
SearchKind::All => None,
|
||||
SearchKind::Tracks => Some(self.tracks),
|
||||
SearchKind::Albums => Some(self.albums),
|
||||
SearchKind::Artists => Some(self.artists),
|
||||
SearchKind::Playlists => Some(self.playlists),
|
||||
SearchKind::Podcasts => Some(self.podcasts),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl SearchResults {
|
||||
pub(crate) fn from_yamuse(s: y::Search) -> Self {
|
||||
fn part<T, U>(r: Option<y::SearchResult<T>>, f: impl Fn(T) -> Option<U>) -> (Vec<U>, u32) {
|
||||
match r {
|
||||
Some(r) => (r.results.into_iter().filter_map(f).collect(), r.total.unwrap_or(0)),
|
||||
None => (Vec::new(), 0),
|
||||
}
|
||||
}
|
||||
let best = s.best.as_ref().and_then(|b| b.entity()).and_then(|e| match e {
|
||||
y::SearchEntity::Track(t) => Track::from_yamuse(*t).map(BestMatch::Track),
|
||||
y::SearchEntity::Album(a) => AlbumSummary::from_yamuse(*a).map(BestMatch::Album),
|
||||
y::SearchEntity::Artist(a) => ArtistSummary::from_yamuse(*a).map(BestMatch::Artist),
|
||||
y::SearchEntity::Playlist(p) => PlaylistSummary::from_yamuse(&p).map(BestMatch::Playlist),
|
||||
_ => None,
|
||||
});
|
||||
let (tracks, t_total) = part(s.tracks, Track::from_yamuse);
|
||||
let (albums, al_total) = part(s.albums, AlbumSummary::from_yamuse);
|
||||
let (artists, ar_total) = part(s.artists, ArtistSummary::from_yamuse);
|
||||
let (playlists, p_total) = part(s.playlists, |p| PlaylistSummary::from_yamuse(&p));
|
||||
let (podcasts, pc_total) = part(s.podcasts, AlbumSummary::from_yamuse);
|
||||
Self {
|
||||
corrected: s.misspell_corrected.unwrap_or(false).then_some(s.misspell_result).flatten(),
|
||||
best,
|
||||
tracks,
|
||||
albums,
|
||||
artists,
|
||||
playlists,
|
||||
podcasts,
|
||||
totals: Totals {
|
||||
tracks: t_total,
|
||||
albums: al_total,
|
||||
artists: ar_total,
|
||||
playlists: p_total,
|
||||
podcasts: pc_total,
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
pub fn is_empty(&self) -> bool {
|
||||
self.best.is_none()
|
||||
&& self.tracks.is_empty()
|
||||
&& self.albums.is_empty()
|
||||
&& self.artists.is_empty()
|
||||
&& self.playlists.is_empty()
|
||||
&& self.podcasts.is_empty()
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub struct ChartEntry {
|
||||
pub position: u32,
|
||||
/// Places moved since the last chart: positive is up.
|
||||
pub shift: i32,
|
||||
pub track: Track,
|
||||
}
|
||||
|
||||
impl ChartEntry {
|
||||
pub(crate) fn from_short(short: y::TrackShort) -> Option<Self> {
|
||||
let chart: Option<y::Chart> = short.chart.and_then(|c| serde_json::from_value(c).ok());
|
||||
Some(Self {
|
||||
position: chart.as_ref().and_then(|c| c.position).unwrap_or(0).max(0) as u32,
|
||||
shift: chart.as_ref().and_then(|c| c.shift).unwrap_or(0) as i32,
|
||||
track: Track::from_yamuse(short.track?)?,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
/// A personal playlist ("Playlist of the Day", "Déjà Vu"…) with its blurb.
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub struct Personal {
|
||||
pub playlist: PlaylistSummary,
|
||||
pub description: Option<String>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Default, PartialEq, Eq)]
|
||||
pub struct Home {
|
||||
pub personal: Vec<Personal>,
|
||||
pub chart: Vec<ChartEntry>,
|
||||
pub new_releases: Vec<AlbumSummary>,
|
||||
pub new_playlists: Vec<PlaylistSummary>,
|
||||
}
|
||||
|
||||
impl Home {
|
||||
pub(crate) fn from_landing(landing: y::Landing) -> Self {
|
||||
let mut home = Home::default();
|
||||
for block in landing.blocks {
|
||||
for entity in &block.entities {
|
||||
match entity.data() {
|
||||
Some(y::BlockEntityData::PersonalPlaylist(g)) => {
|
||||
if let Some(playlist) = g.data.as_ref().and_then(PlaylistSummary::from_yamuse) {
|
||||
let description = g.preview_description.clone().filter(|d| !d.trim().is_empty());
|
||||
home.personal.push(Personal { playlist, description });
|
||||
}
|
||||
}
|
||||
Some(y::BlockEntityData::Album(a)) => {
|
||||
home.new_releases.extend(AlbumSummary::from_yamuse(*a));
|
||||
}
|
||||
Some(y::BlockEntityData::Playlist(p)) => {
|
||||
home.new_playlists.extend(PlaylistSummary::from_yamuse(&p));
|
||||
}
|
||||
Some(y::BlockEntityData::ChartItem(item)) => {
|
||||
let entry = item.track.and_then(Track::from_yamuse).map(|track| ChartEntry {
|
||||
position: item.chart.as_ref().and_then(|c| c.position).unwrap_or(0).max(0) as u32,
|
||||
shift: item.chart.as_ref().and_then(|c| c.shift).unwrap_or(0) as i32,
|
||||
track,
|
||||
});
|
||||
home.chart.extend(entry);
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
}
|
||||
home
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub struct Genre {
|
||||
pub id: String,
|
||||
pub title: String,
|
||||
/// `#rrggbb` from Yandex, used to tint the genre tile.
|
||||
pub color: Option<String>,
|
||||
pub sub_genres: Vec<Genre>,
|
||||
}
|
||||
|
||||
impl Genre {
|
||||
pub(crate) fn from_yamuse(g: y::Genre) -> Option<Self> {
|
||||
let title = g
|
||||
.title
|
||||
.or_else(|| g.titles.get("en").and_then(|t| t.title.clone()))
|
||||
.or_else(|| g.titles.get("ru").and_then(|t| t.title.clone()))?;
|
||||
Some(Self {
|
||||
id: g.id?,
|
||||
title,
|
||||
color: g.color.filter(|c| c.starts_with('#')),
|
||||
sub_genres: g.sub_genres.into_iter().filter_map(Genre::from_yamuse).collect(),
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn search_results_convert_with_best_match_and_totals() {
|
||||
let s: y::Search = serde_json::from_str(
|
||||
r#"{"best":{"type":"artist","result":{"id":3,"name":"Земфира"}},
|
||||
"tracks":{"total":120,"results":[{"id":1,"title":"Хочешь?"}]},
|
||||
"albums":{"total":40,"results":[{"id":5,"title":"Вендетта"}]},
|
||||
"misspellCorrected":true,"misspellResult":"земфира"}"#,
|
||||
)
|
||||
.unwrap();
|
||||
let r = SearchResults::from_yamuse(s);
|
||||
assert!(matches!(r.best, Some(BestMatch::Artist(ref a)) if a.name == "Земфира"));
|
||||
assert_eq!(r.tracks.len(), 1);
|
||||
assert_eq!(r.totals.get(SearchKind::Tracks), Some(120));
|
||||
assert_eq!(r.totals.get(SearchKind::Albums), Some(40));
|
||||
assert_eq!(r.corrected.as_deref(), Some("земфира"));
|
||||
assert!(!r.is_empty());
|
||||
assert!(SearchResults::from_yamuse(serde_json::from_str("{}").unwrap()).is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn chart_entry_reads_position_and_shift() {
|
||||
let short: y::TrackShort = serde_json::from_str(
|
||||
r#"{"id":1,"track":{"id":1,"title":"Хит"},"chart":{"position":3,"shift":-2,"progress":"down"}}"#,
|
||||
)
|
||||
.unwrap();
|
||||
let e = ChartEntry::from_short(short).unwrap();
|
||||
assert_eq!((e.position, e.shift), (3, -2));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn landing_blocks_split_by_entity_type() {
|
||||
let landing: y::Landing = serde_json::from_str(
|
||||
r#"{"blocks":[
|
||||
{"type":"personal-playlists","entities":[{"type":"personal-playlist","data":{
|
||||
"data":{"uid":1,"kind":3,"title":"Плейлист дня","owner":{"uid":1}},
|
||||
"previewDescription":"Updated every day"}}]},
|
||||
{"type":"new-releases","entities":[{"type":"album","data":{"id":9,"title":"New"}}]},
|
||||
{"type":"chart","entities":[{"type":"chart-item","data":{
|
||||
"track":{"id":7,"title":"Top"},"chart":{"position":1,"shift":0}}}]}
|
||||
]}"#,
|
||||
)
|
||||
.unwrap();
|
||||
let home = Home::from_landing(landing);
|
||||
assert_eq!(home.personal[0].playlist.title, "Плейлист дня");
|
||||
assert_eq!(home.personal[0].description.as_deref(), Some("Updated every day"));
|
||||
assert_eq!(home.new_releases[0].id, 9);
|
||||
assert_eq!(home.chart[0].position, 1);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn genre_title_falls_back_to_localised_titles() {
|
||||
let g: y::Genre = serde_json::from_str(
|
||||
r##"{"id":"rock","titles":{"en":{"title":"Rock"}},"color":"#ff0000",
|
||||
"subGenres":[{"id":"punk","title":"Punk"}]}"##,
|
||||
)
|
||||
.unwrap();
|
||||
let g = Genre::from_yamuse(g).unwrap();
|
||||
assert_eq!(g.title, "Rock");
|
||||
assert_eq!(g.sub_genres[0].id, "punk");
|
||||
assert_eq!(g.color.as_deref(), Some("#ff0000"));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,125 @@
|
||||
//! Changing the library (likes, dislikes, playlists), lyrics, and the
|
||||
//! server-side play queue that other devices can continue from.
|
||||
|
||||
use std::collections::HashSet;
|
||||
use std::time::Duration;
|
||||
|
||||
use crate::library::PlaylistId;
|
||||
|
||||
/// What the user has liked or disliked, by id, for drawing hearts and bans.
|
||||
#[derive(Debug, Clone, Default, PartialEq, Eq)]
|
||||
pub struct LikedIds {
|
||||
pub albums: HashSet<i64>,
|
||||
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.
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub struct LyricLine {
|
||||
pub at: Option<Duration>,
|
||||
pub text: String,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub struct Lyrics {
|
||||
pub lines: Vec<LyricLine>,
|
||||
pub synced: bool,
|
||||
pub writers: Vec<String>,
|
||||
}
|
||||
|
||||
impl Lyrics {
|
||||
/// The line being sung at `position`: the last line that has started.
|
||||
pub fn current(&self, position: Duration) -> Option<usize> {
|
||||
if !self.synced {
|
||||
return None;
|
||||
}
|
||||
self.lines.iter().rposition(|l| l.at.is_some_and(|at| at <= position))
|
||||
}
|
||||
|
||||
/// Plain text: one line per line, blank lines kept as paragraph breaks.
|
||||
pub(crate) fn from_text(text: &str, writers: Vec<String>) -> Self {
|
||||
Self {
|
||||
lines: text.lines().map(|l| LyricLine { at: None, text: l.trim_end().to_owned() }).collect(),
|
||||
synced: false,
|
||||
writers,
|
||||
}
|
||||
}
|
||||
|
||||
/// LRC: `[mm:ss.xx] words`. Lines with several stamps repeat; metadata tags are dropped.
|
||||
pub(crate) fn from_lrc(lrc: &str, writers: Vec<String>) -> Self {
|
||||
let mut lines = Vec::new();
|
||||
for raw in lrc.lines() {
|
||||
let mut rest = raw.trim();
|
||||
let mut stamps = Vec::new();
|
||||
while let Some(stripped) = rest.strip_prefix('[') {
|
||||
let Some(end) = stripped.find(']') else { break };
|
||||
match parse_stamp(&stripped[..end]) {
|
||||
Some(at) => stamps.push(at),
|
||||
// `[ar:Artist]` and friends: not a lyric line.
|
||||
None => {
|
||||
stamps.clear();
|
||||
rest = "";
|
||||
break;
|
||||
}
|
||||
}
|
||||
rest = stripped[end + 1..].trim_start();
|
||||
}
|
||||
for at in stamps {
|
||||
lines.push(LyricLine { at: Some(at), text: rest.to_owned() });
|
||||
}
|
||||
}
|
||||
lines.sort_by_key(|l| l.at);
|
||||
Self { lines, synced: true, writers }
|
||||
}
|
||||
}
|
||||
|
||||
/// `mm:ss`, `mm:ss.x`, `mm:ss.xx` or `mm:ss.xxx`.
|
||||
fn parse_stamp(s: &str) -> Option<Duration> {
|
||||
let (min, sec) = s.split_once(':')?;
|
||||
let min: u64 = min.trim().parse().ok()?;
|
||||
let (whole, frac) = sec.split_once('.').unwrap_or((sec, ""));
|
||||
let whole: u64 = whole.parse().ok()?;
|
||||
if whole >= 60 || frac.len() > 3 || !frac.chars().all(|c| c.is_ascii_digit()) {
|
||||
return None;
|
||||
}
|
||||
let millis = if frac.is_empty() { 0 } else { frac.parse::<u64>().ok()? * 10u64.pow(3 - frac.len() as u32) };
|
||||
Some(Duration::from_millis((min * 60 + whole) * 1000 + millis))
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn lrc_parses_stamps_and_drops_tags() {
|
||||
let l = Lyrics::from_lrc(
|
||||
"[ar:Кино]\n[00:12.50] Первая\n[00:20.1]Вторая\n[01:02.345][00:05.00] Повтор\n\nбез метки",
|
||||
vec![],
|
||||
);
|
||||
let got: Vec<(u64, &str)> = l.lines.iter().map(|x| (x.at.unwrap().as_millis() as u64, x.text.as_str())).collect();
|
||||
assert_eq!(got, [(5_000, "Повтор"), (12_500, "Первая"), (20_100, "Вторая"), (62_345, "Повтор")]);
|
||||
assert!(l.synced);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn current_line_follows_position() {
|
||||
let l = Lyrics::from_lrc("[00:10.00]a\n[00:20.00]b", vec![]);
|
||||
assert_eq!(l.current(Duration::from_secs(5)), None);
|
||||
assert_eq!(l.current(Duration::from_secs(10)), Some(0));
|
||||
assert_eq!(l.current(Duration::from_secs(25)), Some(1));
|
||||
let plain = Lyrics::from_text("a\nb", vec![]);
|
||||
assert_eq!(plain.current(Duration::from_secs(25)), None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn bad_stamps_are_not_lyrics() {
|
||||
assert_eq!(parse_stamp("01:02"), Some(Duration::from_secs(62)));
|
||||
assert_eq!(parse_stamp("1:75"), None);
|
||||
assert_eq!(parse_stamp("ti"), None);
|
||||
assert_eq!(parse_stamp("00:01.1234"), None);
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,76 @@
|
||||
/// Errors the app can act on. Messages are for logs, not for display.
|
||||
#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
|
||||
pub enum Error {
|
||||
/// The token is missing, revoked or expired. Sign in again.
|
||||
#[error("unauthorized: {0}")]
|
||||
Unauthorized(String),
|
||||
/// The sign-in code ran out before the user confirmed it.
|
||||
#[error("sign-in code expired")]
|
||||
CodeExpired,
|
||||
/// The user declined access on Yandex's page.
|
||||
#[error("sign-in was declined")]
|
||||
Denied,
|
||||
/// No connection, DNS failure, timeout: worth retrying.
|
||||
#[error("network: {0}")]
|
||||
Network(String),
|
||||
/// Anything else the server or the decoder rejected.
|
||||
#[error("api: {0}")]
|
||||
Api(String),
|
||||
}
|
||||
|
||||
pub type Result<T> = std::result::Result<T, Error>;
|
||||
|
||||
impl Error {
|
||||
pub fn is_retryable(&self) -> bool {
|
||||
matches!(self, Error::Network(_))
|
||||
}
|
||||
}
|
||||
|
||||
impl From<yamuse::Error> for Error {
|
||||
fn from(e: yamuse::Error) -> Self {
|
||||
use yamuse::Error as Y;
|
||||
match e {
|
||||
Y::Unauthorized(m) => Error::Unauthorized(m),
|
||||
Y::Network(m) => Error::Network(m),
|
||||
Y::TimedOut => Error::Network("timed out".into()),
|
||||
Y::RateLimited { message, .. } => Error::Network(message),
|
||||
Y::DeviceAuth(m) => classify_oauth(&m),
|
||||
other => Error::Api(other.to_string()),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// OAuth rejections arrive as free text carrying the RFC 8628 error code.
|
||||
fn classify_oauth(message: &str) -> Error {
|
||||
let m = message.to_ascii_lowercase();
|
||||
if m.contains("expired") || m.contains("timed out") {
|
||||
Error::CodeExpired
|
||||
} else if m.contains("denied") {
|
||||
Error::Denied
|
||||
} else if m.contains("invalid_grant") || m.contains("bad refresh") {
|
||||
Error::Unauthorized(message.to_owned())
|
||||
} else {
|
||||
Error::Api(message.to_owned())
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn oauth_codes_map_to_actionable_errors() {
|
||||
assert_eq!(classify_oauth("expired_token: code expired"), Error::CodeExpired);
|
||||
assert_eq!(classify_oauth("device authorization timed out"), Error::CodeExpired);
|
||||
assert_eq!(classify_oauth("access_denied"), Error::Denied);
|
||||
assert!(matches!(classify_oauth("invalid_grant"), Error::Unauthorized(_)));
|
||||
assert!(matches!(classify_oauth("something new"), Error::Api(_)));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn only_network_errors_retry() {
|
||||
assert!(Error::Network("dns".into()).is_retryable());
|
||||
assert!(!Error::Unauthorized(String::new()).is_retryable());
|
||||
assert!(!Error::CodeExpired.is_retryable());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,28 @@
|
||||
//! Client for the unofficial Yandex Music API.
|
||||
//!
|
||||
//! Wraps [`yamuse`] so the app only ever sees this crate's own types: if the
|
||||
//! upstream wrapper changes or is swapped out, the UI doesn't move.
|
||||
|
||||
pub mod auth;
|
||||
mod client;
|
||||
mod clips;
|
||||
mod discover;
|
||||
mod edit;
|
||||
mod error;
|
||||
mod library;
|
||||
mod models;
|
||||
mod wave;
|
||||
|
||||
pub use client::{Account, ContentLanguage, YmClient};
|
||||
pub use clips::Clip;
|
||||
pub use library::{
|
||||
AlbumKind, AlbumPage, AlbumSummary, ArtistPage, ArtistSummary, LibraryPlaylists, PlaylistId,
|
||||
PlaylistPage, PlaylistSummary,
|
||||
};
|
||||
pub use models::{AlbumRef, ArtistRef, Stream, Track};
|
||||
pub use wave::{
|
||||
Character, Language, MY_WAVE, Mood, PlayReport, Station, WaveBatch, WaveEvent, WaveSettings,
|
||||
};
|
||||
pub use discover::{BestMatch, ChartEntry, Genre, Home, Personal, SearchKind, SearchResults, Totals};
|
||||
pub use edit::{LikedIds, LyricLine, Lyrics};
|
||||
pub use error::{Error, Result};
|
||||
@@ -0,0 +1,357 @@
|
||||
//! Albums, artists and playlists, as cards and as full pages.
|
||||
|
||||
use std::time::Duration;
|
||||
|
||||
use yamuse::models as y;
|
||||
|
||||
use crate::models::{ArtistRef, Track, cover_url, hues_for};
|
||||
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub enum AlbumKind {
|
||||
Album,
|
||||
Single,
|
||||
Compilation,
|
||||
Podcast,
|
||||
Audiobook,
|
||||
}
|
||||
|
||||
impl AlbumKind {
|
||||
pub const ALL: [AlbumKind; 5] =
|
||||
[AlbumKind::Album, AlbumKind::Single, AlbumKind::Compilation, AlbumKind::Podcast, AlbumKind::Audiobook];
|
||||
|
||||
fn from_api(meta_type: Option<&str>, kind: Option<&str>) -> Self {
|
||||
match (meta_type, kind) {
|
||||
(Some("podcast"), _) | (_, Some("podcast")) => AlbumKind::Podcast,
|
||||
(_, Some("audiobook")) | (Some("audiobook"), _) => AlbumKind::Audiobook,
|
||||
(_, Some("single")) => AlbumKind::Single,
|
||||
(_, Some("compilation")) => AlbumKind::Compilation,
|
||||
_ => AlbumKind::Album,
|
||||
}
|
||||
}
|
||||
|
||||
pub fn label(self) -> &'static str {
|
||||
match self {
|
||||
AlbumKind::Album => "Album",
|
||||
AlbumKind::Single => "Single",
|
||||
AlbumKind::Compilation => "Compilation",
|
||||
AlbumKind::Podcast => "Podcast",
|
||||
AlbumKind::Audiobook => "Audiobook",
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub struct AlbumSummary {
|
||||
pub id: i64,
|
||||
pub title: String,
|
||||
pub version: Option<String>,
|
||||
pub artists: Vec<ArtistRef>,
|
||||
pub year: Option<i32>,
|
||||
pub track_count: u32,
|
||||
pub kind: AlbumKind,
|
||||
cover_uri: Option<String>,
|
||||
}
|
||||
|
||||
impl AlbumSummary {
|
||||
pub(crate) fn from_yamuse(a: y::Album) -> Option<Self> {
|
||||
Some(Self {
|
||||
id: a.id?,
|
||||
title: a.title.unwrap_or_else(|| "Untitled".into()),
|
||||
version: a.version.filter(|v| !v.trim().is_empty()),
|
||||
artists: artist_refs(a.artists),
|
||||
year: a.year.and_then(|y| i32::try_from(y).ok()),
|
||||
track_count: a.track_count.unwrap_or(0).max(0) as u32,
|
||||
kind: AlbumKind::from_api(a.meta_type.as_deref(), a.r#type.as_deref()),
|
||||
cover_uri: a.cover_uri.or_else(|| a.cover.and_then(|c| c.uri)),
|
||||
})
|
||||
}
|
||||
|
||||
pub fn full_title(&self) -> String {
|
||||
match &self.version {
|
||||
Some(v) => format!("{} ({v})", self.title),
|
||||
None => self.title.clone(),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn artist_line(&self) -> String {
|
||||
join_names(&self.artists)
|
||||
}
|
||||
|
||||
/// "Кино · 1988", the line under a card. Podcasts often list no artist, so
|
||||
/// those fall back to their kind: "Podcast · 2022".
|
||||
pub fn subtitle(&self) -> String {
|
||||
let who = if self.artists.is_empty() { self.kind.label().to_owned() } else { self.artist_line() };
|
||||
match self.year {
|
||||
Some(year) => format!("{who} · {year}"),
|
||||
None => who,
|
||||
}
|
||||
}
|
||||
|
||||
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)
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub struct ArtistSummary {
|
||||
pub id: i64,
|
||||
pub name: String,
|
||||
pub genres: Vec<String>,
|
||||
pub likes: Option<i64>,
|
||||
cover_uri: Option<String>,
|
||||
}
|
||||
|
||||
impl ArtistSummary {
|
||||
pub(crate) fn from_yamuse(a: y::Artist) -> Option<Self> {
|
||||
Some(Self {
|
||||
id: a.id.and_then(|i| i.as_number())?,
|
||||
name: a.name.unwrap_or_else(|| "Unknown artist".into()),
|
||||
genres: a.genres,
|
||||
likes: a.likes_count,
|
||||
cover_uri: a.cover.and_then(|c| c.uri).or(a.og_image),
|
||||
})
|
||||
}
|
||||
|
||||
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 ^ 0x5bd1_e995)
|
||||
}
|
||||
}
|
||||
|
||||
/// A playlist is addressed by its owner and a per-owner number ("kind").
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
|
||||
pub struct PlaylistId {
|
||||
pub owner: i64,
|
||||
pub kind: i64,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub struct PlaylistSummary {
|
||||
pub id: PlaylistId,
|
||||
pub title: String,
|
||||
pub owner_name: String,
|
||||
pub track_count: u32,
|
||||
pub duration: Duration,
|
||||
pub public: bool,
|
||||
cover_uri: Option<String>,
|
||||
}
|
||||
|
||||
impl PlaylistSummary {
|
||||
pub(crate) fn from_yamuse(p: &y::Playlist) -> Option<Self> {
|
||||
let owner = p.owner.as_ref();
|
||||
let id = PlaylistId { owner: p.uid.or_else(|| owner.and_then(|o| o.uid))?, kind: p.kind? };
|
||||
let cover = p.cover.as_ref().and_then(|c| c.uri.clone().or_else(|| c.items_uri.first().cloned()));
|
||||
Some(Self {
|
||||
id,
|
||||
title: p.title.clone().unwrap_or_else(|| "Untitled playlist".into()),
|
||||
owner_name: owner
|
||||
.and_then(|o| o.name.clone().or_else(|| o.login.clone()))
|
||||
.unwrap_or_default(),
|
||||
track_count: p.track_count.unwrap_or(0).max(0) as u32,
|
||||
duration: Duration::from_millis(p.duration_ms.unwrap_or(0).max(0) as u64),
|
||||
public: p.visibility.as_deref() == Some("public"),
|
||||
cover_uri: cover.or_else(|| p.og_image.clone()),
|
||||
})
|
||||
}
|
||||
|
||||
pub fn cover_url(&self, size: u32) -> Option<String> {
|
||||
cover_url(self.cover_uri.as_deref(), size)
|
||||
}
|
||||
|
||||
/// A bare summary for tests and previews in other crates.
|
||||
#[doc(hidden)]
|
||||
pub fn for_tests(id: PlaylistId, title: &str) -> Self {
|
||||
Self {
|
||||
id,
|
||||
title: title.into(),
|
||||
owner_name: String::new(),
|
||||
track_count: 0,
|
||||
duration: Duration::ZERO,
|
||||
public: false,
|
||||
cover_uri: None,
|
||||
}
|
||||
}
|
||||
|
||||
pub fn hues(&self) -> (f32, f32) {
|
||||
hues_for((self.id.owner as u64).wrapping_mul(1_000_003) ^ self.id.kind as u64)
|
||||
}
|
||||
|
||||
pub fn subtitle(&self) -> String {
|
||||
let count = match self.track_count {
|
||||
1 => "1 track".to_owned(),
|
||||
n => format!("{n} tracks"),
|
||||
};
|
||||
if self.owner_name.is_empty() { count } else { format!("{} · {count}", self.owner_name) }
|
||||
}
|
||||
}
|
||||
|
||||
/// The user's playlists for the sidebar and Collection.
|
||||
#[derive(Debug, Clone, Default, PartialEq, Eq)]
|
||||
pub struct LibraryPlaylists {
|
||||
pub own: Vec<PlaylistSummary>,
|
||||
pub liked: Vec<PlaylistSummary>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub struct AlbumPage {
|
||||
pub album: AlbumSummary,
|
||||
pub tracks: Vec<Track>,
|
||||
pub release_date: Option<String>,
|
||||
pub label: Option<String>,
|
||||
pub likes: Option<i64>,
|
||||
}
|
||||
|
||||
impl AlbumPage {
|
||||
pub(crate) fn from_yamuse(a: y::Album) -> Option<Self> {
|
||||
let tracks = a
|
||||
.volumes
|
||||
.iter()
|
||||
.flatten()
|
||||
.cloned()
|
||||
.filter_map(Track::from_yamuse)
|
||||
.collect();
|
||||
let release_date = a.release_date.clone();
|
||||
let label = a.labels.first().and_then(|l| l.name()).map(str::to_owned);
|
||||
let likes = a.likes_count;
|
||||
Some(Self { album: AlbumSummary::from_yamuse(a)?, tracks, release_date, label, likes })
|
||||
}
|
||||
|
||||
pub fn duration(&self) -> Duration {
|
||||
self.tracks.iter().map(|t| t.duration).sum()
|
||||
}
|
||||
|
||||
/// Decodes an album (with `volumes`) 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("album has no id".into()))
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub struct ArtistPage {
|
||||
pub artist: ArtistSummary,
|
||||
pub popular: Vec<Track>,
|
||||
pub albums: Vec<AlbumSummary>,
|
||||
/// Compilations and features the artist appears on.
|
||||
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 {
|
||||
pub(crate) fn from_yamuse(b: y::BriefInfo) -> Option<Self> {
|
||||
let monthly_listeners = b.stats.as_ref().and_then(|s| s.last_month_listeners);
|
||||
Some(Self {
|
||||
artist: ArtistSummary::from_yamuse(b.artist?)?,
|
||||
popular: b.popular_tracks.into_iter().filter_map(Track::from_yamuse).collect(),
|
||||
albums: b.albums.into_iter().filter_map(AlbumSummary::from_yamuse).collect(),
|
||||
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(),
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub struct PlaylistPage {
|
||||
pub playlist: PlaylistSummary,
|
||||
pub description: Option<String>,
|
||||
pub tracks: Vec<Track>,
|
||||
}
|
||||
|
||||
fn artist_refs(artists: Vec<y::Artist>) -> Vec<ArtistRef> {
|
||||
artists
|
||||
.into_iter()
|
||||
.filter_map(|a| Some(ArtistRef { id: a.id.and_then(|i| i.as_number()), name: a.name? }))
|
||||
.collect()
|
||||
}
|
||||
|
||||
pub(crate) fn join_names(artists: &[ArtistRef]) -> String {
|
||||
if artists.is_empty() {
|
||||
return "Unknown artist".into();
|
||||
}
|
||||
artists.iter().map(|a| a.name.as_str()).collect::<Vec<_>>().join(", ")
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
fn album(json: &str) -> y::Album {
|
||||
serde_json::from_str(json).unwrap()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn album_page_flattens_volumes() {
|
||||
let page = AlbumPage::from_yamuse(album(
|
||||
r#"{"id":5,"title":"Группа крови","year":1988,"type":"","artists":[{"id":1,"name":"Кино"}],
|
||||
"coverUri":"a/%%","labels":[{"name":"Мелодия"}],
|
||||
"volumes":[[{"id":1,"title":"A","durationMs":1000}],[{"id":2,"title":"B","durationMs":2000}]]}"#,
|
||||
))
|
||||
.unwrap();
|
||||
assert_eq!(page.tracks.len(), 2);
|
||||
assert_eq!(page.duration(), Duration::from_secs(3));
|
||||
assert_eq!(page.album.subtitle(), "Кино · 1988");
|
||||
assert_eq!(page.album.kind, AlbumKind::Album);
|
||||
assert_eq!(page.label.as_deref(), Some("Мелодия"));
|
||||
assert_eq!(page.album.cover_url(100).as_deref(), Some("https://a/100x100"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn subtitle_without_artists_names_the_kind() {
|
||||
let a = AlbumSummary::from_yamuse(album(r#"{"id":1,"title":"TED","metaType":"podcast","year":2022}"#)).unwrap();
|
||||
assert_eq!(a.subtitle(), "Podcast · 2022");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn album_kinds() {
|
||||
assert_eq!(AlbumKind::from_api(None, Some("single")), AlbumKind::Single);
|
||||
assert_eq!(AlbumKind::from_api(Some("podcast"), None), AlbumKind::Podcast);
|
||||
assert_eq!(AlbumKind::from_api(None, Some("audiobook")), AlbumKind::Audiobook);
|
||||
assert_eq!(AlbumKind::from_api(Some("music"), None), AlbumKind::Album);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn playlist_needs_owner_and_kind_and_uses_mosaic_cover() {
|
||||
let p: y::Playlist = serde_json::from_str(
|
||||
r#"{"owner":{"uid":9,"name":"Юрий"},"kind":1003,"title":"Дорога","trackCount":14,
|
||||
"visibility":"private","cover":{"type":"mosaic","itemsUri":["m/%%"]}}"#,
|
||||
)
|
||||
.unwrap();
|
||||
let s = PlaylistSummary::from_yamuse(&p).unwrap();
|
||||
assert_eq!(s.id, PlaylistId { owner: 9, kind: 1003 });
|
||||
assert!(!s.public);
|
||||
assert_eq!(s.subtitle(), "Юрий · 14 tracks");
|
||||
assert_eq!(s.cover_url(200).as_deref(), Some("https://m/200x200"));
|
||||
let orphan: y::Playlist = serde_json::from_str(r#"{"title":"x"}"#).unwrap();
|
||||
assert!(PlaylistSummary::from_yamuse(&orphan).is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn artist_page_from_brief_info() {
|
||||
let b: y::BriefInfo = serde_json::from_str(
|
||||
r#"{"artist":{"id":3,"name":"Земфира","genres":["rock"],"cover":{"uri":"z/%%"}},
|
||||
"popularTracks":[{"id":10,"title":"Хочешь?"}],
|
||||
"albums":[{"id":20,"title":"Вендетта","year":2005}],
|
||||
"similarArtists":[{"id":4,"name":"Сплин"}],
|
||||
"stats":{"lastMonthListeners":4100000}}"#,
|
||||
)
|
||||
.unwrap();
|
||||
let page = ArtistPage::from_yamuse(b).unwrap();
|
||||
assert_eq!(page.artist.name, "Земфира");
|
||||
assert_eq!(page.popular.len(), 1);
|
||||
assert_eq!(page.albums[0].year, Some(2005));
|
||||
assert_eq!(page.similar[0].name, "Сплин");
|
||||
assert_eq!(page.monthly_listeners, Some(4_100_000));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,290 @@
|
||||
//! 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"));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,375 @@
|
||||
//! My Wave and other radio stations ("rotor"), plus listening reports.
|
||||
|
||||
use std::time::Duration;
|
||||
|
||||
use yamuse::models as y;
|
||||
|
||||
use crate::models::{Track, cover_url};
|
||||
|
||||
/// The personal station behind "My Wave".
|
||||
pub const MY_WAVE: &str = "user:onyourwave";
|
||||
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default)]
|
||||
pub enum Mood {
|
||||
#[default]
|
||||
Any,
|
||||
Energetic,
|
||||
Cheerful,
|
||||
Calm,
|
||||
Sad,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default)]
|
||||
pub enum Character {
|
||||
#[default]
|
||||
Default,
|
||||
Favourite,
|
||||
Unfamiliar,
|
||||
Popular,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default)]
|
||||
pub enum Language {
|
||||
#[default]
|
||||
Any,
|
||||
Russian,
|
||||
Foreign,
|
||||
}
|
||||
|
||||
impl Mood {
|
||||
pub const ALL: [Mood; 5] = [Mood::Any, Mood::Energetic, Mood::Cheerful, Mood::Calm, Mood::Sad];
|
||||
|
||||
pub fn label(self) -> &'static str {
|
||||
match self {
|
||||
Mood::Any => "Any",
|
||||
Mood::Energetic => "Energetic",
|
||||
Mood::Cheerful => "Cheerful",
|
||||
Mood::Calm => "Calm",
|
||||
Mood::Sad => "Sad",
|
||||
}
|
||||
}
|
||||
|
||||
fn to_yamuse(self) -> yamuse::MoodEnergy {
|
||||
match self {
|
||||
Mood::Any => yamuse::MoodEnergy::All,
|
||||
Mood::Energetic => yamuse::MoodEnergy::Active,
|
||||
Mood::Cheerful => yamuse::MoodEnergy::Fun,
|
||||
Mood::Calm => yamuse::MoodEnergy::Calm,
|
||||
Mood::Sad => yamuse::MoodEnergy::Sad,
|
||||
}
|
||||
}
|
||||
|
||||
fn from_api(s: Option<&str>) -> Self {
|
||||
match s {
|
||||
Some("active") => Mood::Energetic,
|
||||
Some("fun") => Mood::Cheerful,
|
||||
Some("calm") => Mood::Calm,
|
||||
Some("sad") => Mood::Sad,
|
||||
_ => Mood::Any,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl Character {
|
||||
pub const ALL: [Character; 4] =
|
||||
[Character::Default, Character::Favourite, Character::Unfamiliar, Character::Popular];
|
||||
|
||||
pub fn label(self) -> &'static str {
|
||||
match self {
|
||||
Character::Default => "Any",
|
||||
Character::Favourite => "Favourite",
|
||||
Character::Unfamiliar => "Unfamiliar",
|
||||
Character::Popular => "Popular",
|
||||
}
|
||||
}
|
||||
|
||||
fn to_yamuse(self) -> yamuse::Diversity {
|
||||
match self {
|
||||
Character::Default => yamuse::Diversity::Default,
|
||||
Character::Favourite => yamuse::Diversity::Favorite,
|
||||
Character::Unfamiliar => yamuse::Diversity::Discover,
|
||||
Character::Popular => yamuse::Diversity::Popular,
|
||||
}
|
||||
}
|
||||
|
||||
fn from_api(s: Option<&str>) -> Self {
|
||||
match s {
|
||||
Some("favorite") => Character::Favourite,
|
||||
Some("discover") => Character::Unfamiliar,
|
||||
Some("popular") => Character::Popular,
|
||||
_ => Character::Default,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl Language {
|
||||
pub const ALL: [Language; 3] = [Language::Any, Language::Russian, Language::Foreign];
|
||||
|
||||
pub fn label(self) -> &'static str {
|
||||
match self {
|
||||
Language::Any => "Any",
|
||||
Language::Russian => "Russian",
|
||||
Language::Foreign => "Foreign",
|
||||
}
|
||||
}
|
||||
|
||||
fn to_yamuse(self) -> yamuse::StationLanguage {
|
||||
match self {
|
||||
Language::Any => yamuse::StationLanguage::Any,
|
||||
Language::Russian => yamuse::StationLanguage::Russian,
|
||||
Language::Foreign => yamuse::StationLanguage::NotRussian,
|
||||
}
|
||||
}
|
||||
|
||||
fn from_api(s: Option<&str>) -> Self {
|
||||
match s {
|
||||
Some("russian") => Language::Russian,
|
||||
Some("not-russian") => Language::Foreign,
|
||||
_ => Language::Any,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default)]
|
||||
pub struct WaveSettings {
|
||||
pub mood: Mood,
|
||||
pub character: Character,
|
||||
pub language: Language,
|
||||
}
|
||||
|
||||
impl WaveSettings {
|
||||
pub(crate) fn from_api(s: &y::StationSettings) -> Self {
|
||||
Self {
|
||||
mood: Mood::from_api(s.mood_energy.as_deref()),
|
||||
character: Character::from_api(s.diversity.as_deref()),
|
||||
language: Language::from_api(s.language.as_deref()),
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn to_yamuse(self) -> (yamuse::MoodEnergy, yamuse::Diversity, yamuse::StationLanguage) {
|
||||
(self.mood.to_yamuse(), self.character.to_yamuse(), self.language.to_yamuse())
|
||||
}
|
||||
}
|
||||
|
||||
/// A station to start: My Wave, a genre, an activity, an era.
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub struct Station {
|
||||
/// `type:tag`, e.g. `genre:rock`.
|
||||
pub id: String,
|
||||
pub name: String,
|
||||
pub color: Option<String>,
|
||||
icon_uri: Option<String>,
|
||||
}
|
||||
|
||||
impl Station {
|
||||
pub(crate) fn from_yamuse(r: y::StationResult) -> Option<Self> {
|
||||
let s = r.station?;
|
||||
let id = s.id?.as_string()?;
|
||||
let icon = s.icon.as_ref();
|
||||
Some(Self {
|
||||
id,
|
||||
name: r.custom_name.or(s.name).unwrap_or_else(|| "Station".into()),
|
||||
color: icon.and_then(|i| i.background_color.clone()).filter(|c| c.starts_with('#')),
|
||||
icon_uri: icon.and_then(|i| i.image_url.clone()),
|
||||
})
|
||||
}
|
||||
|
||||
pub fn icon_url(&self, size: u32) -> Option<String> {
|
||||
cover_url(self.icon_uri.as_deref(), size)
|
||||
}
|
||||
}
|
||||
|
||||
/// One batch of station tracks. Feedback names the session and the batch.
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub struct WaveBatch {
|
||||
pub session_id: Option<String>,
|
||||
pub tracks: Vec<Track>,
|
||||
pub batch_id: Option<String>,
|
||||
}
|
||||
|
||||
impl WaveBatch {
|
||||
/// From a `/rotor/session/...` result: `{radioSessionId, batchId, sequence: [{track}]}`.
|
||||
pub(crate) fn from_session(v: &serde_json::Value) -> Self {
|
||||
let tracks = v
|
||||
.get("sequence")
|
||||
.and_then(|s| s.as_array())
|
||||
.into_iter()
|
||||
.flatten()
|
||||
.filter_map(|item| item.get("track"))
|
||||
.filter_map(|t| serde_json::from_value::<y::Track>(t.clone()).ok())
|
||||
.filter_map(Track::from_yamuse)
|
||||
.collect();
|
||||
let text = |k: &str| v.get(k).and_then(|x| x.as_str()).map(str::to_owned);
|
||||
Self { session_id: text("radioSessionId"), tracks, batch_id: text("batchId") }
|
||||
}
|
||||
}
|
||||
|
||||
impl WaveSettings {
|
||||
/// Settings as session seeds (`settingMoodEnergy:calm`…); defaults add nothing.
|
||||
pub(crate) fn seeds(self) -> Vec<String> {
|
||||
let mut seeds = Vec::new();
|
||||
let mood = match self.mood {
|
||||
Mood::Any => None,
|
||||
Mood::Energetic => Some("active"),
|
||||
Mood::Cheerful => Some("fun"),
|
||||
Mood::Calm => Some("calm"),
|
||||
Mood::Sad => Some("sad"),
|
||||
};
|
||||
let diversity = match self.character {
|
||||
Character::Default => None,
|
||||
Character::Favourite => Some("favorite"),
|
||||
Character::Unfamiliar => Some("discover"),
|
||||
Character::Popular => Some("popular"),
|
||||
};
|
||||
let language = match self.language {
|
||||
Language::Any => None,
|
||||
Language::Russian => Some("russian"),
|
||||
Language::Foreign => Some("not-russian"),
|
||||
};
|
||||
seeds.extend(mood.map(|m| format!("settingMoodEnergy:{m}")));
|
||||
seeds.extend(diversity.map(|d| format!("settingDiversity:{d}")));
|
||||
seeds.extend(language.map(|l| format!("settingLanguage:{l}")));
|
||||
seeds
|
||||
}
|
||||
}
|
||||
|
||||
impl WaveEvent {
|
||||
/// The session feedback body's `event` object.
|
||||
pub(crate) fn to_json(&self, now: &str) -> serde_json::Value {
|
||||
let (kind, track, played) = match self {
|
||||
WaveEvent::Started => ("radioStarted", None, None),
|
||||
WaveEvent::TrackStarted { track_id } => ("trackStarted", Some(track_id), None),
|
||||
WaveEvent::TrackFinished { track_id, played } => ("trackFinished", Some(track_id), Some(played)),
|
||||
WaveEvent::Skipped { track_id, played } => ("skip", Some(track_id), Some(played)),
|
||||
};
|
||||
let mut event = serde_json::json!({ "type": kind, "timestamp": now });
|
||||
if let Some(track) = track {
|
||||
event["trackId"] = track.clone().into();
|
||||
}
|
||||
if let Some(played) = played {
|
||||
event["totalPlayedSeconds"] = played.as_secs_f64().into();
|
||||
}
|
||||
event
|
||||
}
|
||||
}
|
||||
|
||||
/// Listening events a station learns from.
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub enum WaveEvent {
|
||||
Started,
|
||||
TrackStarted { track_id: String },
|
||||
TrackFinished { track_id: String, played: Duration },
|
||||
Skipped { track_id: String, played: Duration },
|
||||
}
|
||||
|
||||
/// A finished or abandoned listen, for the user's history and the artists' counts.
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub struct PlayReport {
|
||||
pub track_id: String,
|
||||
pub album_id: Option<i64>,
|
||||
pub length: Duration,
|
||||
pub played: Duration,
|
||||
pub end_position: Duration,
|
||||
/// Where it was played from, e.g. `musyx-wave` or `musyx-list`.
|
||||
pub from: String,
|
||||
}
|
||||
|
||||
/// `2026-10-15T15:20:01.042Z`, the only format `/play-audio` accepts.
|
||||
pub(crate) fn iso_millis(t: std::time::SystemTime) -> String {
|
||||
let ms = t.duration_since(std::time::UNIX_EPOCH).map_or(0, |d| d.as_millis()) as i64;
|
||||
let (secs, millis) = (ms.div_euclid(1000), ms.rem_euclid(1000));
|
||||
let (days, tod) = (secs.div_euclid(86_400), secs.rem_euclid(86_400));
|
||||
// Howard Hinnant's days-to-civil.
|
||||
let z = days + 719_468;
|
||||
let era = z.div_euclid(146_097);
|
||||
let doe = z.rem_euclid(146_097);
|
||||
let yoe = (doe - doe / 1460 + doe / 36_524 - doe / 146_096) / 365;
|
||||
let doy = doe - (365 * yoe + yoe / 4 - yoe / 100);
|
||||
let mp = (5 * doy + 2) / 153;
|
||||
let day = doy - (153 * mp + 2) / 5 + 1;
|
||||
let month = if mp < 10 { mp + 3 } else { mp - 9 };
|
||||
let year = yoe + era * 400 + i64::from(month <= 2);
|
||||
format!(
|
||||
"{year:04}-{month:02}-{day:02}T{:02}:{:02}:{:02}.{millis:03}Z",
|
||||
tod / 3600,
|
||||
(tod % 3600) / 60,
|
||||
tod % 60
|
||||
)
|
||||
}
|
||||
|
||||
/// `"123"` and `"123:456"` both mean track 123; uploads have no numeric id.
|
||||
pub(crate) fn numeric_id(id: &str) -> Option<i64> {
|
||||
id.split(':').next()?.parse().ok()
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn settings_round_trip_through_api_strings() {
|
||||
let s = WaveSettings::from_api(&y::StationSettings {
|
||||
mood_energy: Some("calm".into()),
|
||||
diversity: Some("discover".into()),
|
||||
language: Some("not-russian".into()),
|
||||
..Default::default()
|
||||
});
|
||||
assert_eq!(s, WaveSettings { mood: Mood::Calm, character: Character::Unfamiliar, language: Language::Foreign });
|
||||
assert_eq!(WaveSettings::from_api(&y::StationSettings::default()), WaveSettings::default());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn settings_become_seeds() {
|
||||
assert!(WaveSettings::default().seeds().is_empty());
|
||||
let s = WaveSettings { mood: Mood::Calm, character: Character::Unfamiliar, language: Language::Russian };
|
||||
assert_eq!(s.seeds(), ["settingMoodEnergy:calm", "settingDiversity:discover", "settingLanguage:russian"]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn feedback_events_serialise_like_the_official_clients() {
|
||||
let skip = WaveEvent::Skipped { track_id: "1:2".into(), played: Duration::from_millis(1500) };
|
||||
assert_eq!(
|
||||
skip.to_json("T"),
|
||||
serde_json::json!({"type": "skip", "timestamp": "T", "trackId": "1:2", "totalPlayedSeconds": 1.5})
|
||||
);
|
||||
assert_eq!(WaveEvent::Started.to_json("T"), serde_json::json!({"type": "radioStarted", "timestamp": "T"}));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn session_batch_parses() {
|
||||
let v = serde_json::json!({"radioSessionId": "s1", "batchId": "b1",
|
||||
"sequence": [{"type": "track", "track": {"id": "7", "title": "A"}}, {"type": "ad"}]});
|
||||
let b = WaveBatch::from_session(&v);
|
||||
assert_eq!((b.session_id.as_deref(), b.batch_id.as_deref(), b.tracks.len()), (Some("s1"), Some("b1"), 1));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn station_and_batch_convert() {
|
||||
let r: y::StationResult = serde_json::from_str(
|
||||
r##"{"station":{"id":{"type":"genre","tag":"rock"},"name":"Рок",
|
||||
"icon":{"backgroundColor":"#ff4444","imageUrl":"avatars.yandex.net/x/%%"}}}"##,
|
||||
)
|
||||
.unwrap();
|
||||
let s = Station::from_yamuse(r).unwrap();
|
||||
assert_eq!(s.id, "genre:rock");
|
||||
assert_eq!(s.color.as_deref(), Some("#ff4444"));
|
||||
assert_eq!(s.icon_url(200).as_deref(), Some("https://avatars.yandex.net/x/200x200"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn iso_millis_always_has_three_fraction_digits() {
|
||||
use std::time::{Duration, UNIX_EPOCH};
|
||||
assert_eq!(iso_millis(UNIX_EPOCH), "1970-01-01T00:00:00.000Z");
|
||||
let t = UNIX_EPOCH + Duration::from_millis(1_792_078_801_042);
|
||||
assert_eq!(iso_millis(t), "2026-10-15T15:40:01.042Z");
|
||||
let leap = UNIX_EPOCH + Duration::from_secs(951_782_400); // 2000-02-29
|
||||
assert_eq!(iso_millis(leap), "2000-02-29T00:00:00.000Z");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn numeric_ids() {
|
||||
assert_eq!(numeric_id("123"), Some(123));
|
||||
assert_eq!(numeric_id("123:456"), Some(123));
|
||||
assert_eq!(numeric_id("abc-upload"), None);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,15 @@
|
||||
//! Talks to the real Yandex servers. Run with `cargo test -p ym-api -- --ignored`.
|
||||
|
||||
use ym_api::auth::{Auth, Poll};
|
||||
|
||||
#[tokio::test]
|
||||
#[ignore = "network"]
|
||||
async fn device_code_is_issued_and_pending() {
|
||||
let auth = Auth::new().unwrap();
|
||||
let code = auth.request_code().await.expect("device code");
|
||||
assert!(!code.user_code.is_empty());
|
||||
assert!(code.verification_url.starts_with("https://"));
|
||||
assert!(code.interval.as_secs() >= 3);
|
||||
// Nobody confirmed it, so the first poll must say "pending", not fail.
|
||||
assert_eq!(auth.poll(&code).await.expect("poll"), Poll::Pending);
|
||||
}
|
||||
Reference in new issue
Block a user