Files
musyx/crates/ym-api/src/client.rs
T
Yuriy Panov 51e7a4f465 feat: music video clips on artist pages and in Collection
Artist pages list the artist's clips and Collection gets a Clips tab with
the liked ones. A clip opens on the Yandex Music website, since there's
no video player in the app; the heart on each card likes it. Clips are
read from raw JSON because the artist block calls the id `id` where
/clips says `clipId`. Snapshot runs can open `artist:<id>`.
2026-10-15 18:50:50 +06:00

762 lines
32 KiB
Rust
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
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, QueueContext};
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()
}
/// A queue id, unless it's the all-zero placeholder Yandex returns for a queue it didn't keep.
fn real_queue_id(id: Option<String>) -> Option<String> {
id.filter(|id| !id.is_empty() && !id.bytes().all(|b| b == b'0'))
}
/// 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()
}
}
impl YmClient {
/// Builds a client for `credentials` and loads the account. Fails with
/// [`crate::Error::Unauthorized`] when the token is no longer valid.
pub async fn connect(credentials: &Credentials) -> Result<(Self, Account)> {
let inner = yamuse::Client::builder().token(&credentials.access_token).build()?;
let status = inner.refresh_account().await?;
let account = Account::from_status(status)
.ok_or_else(|| Error::Unauthorized("account status has no user".into()))?;
Ok((Self { inner, token: Some(credentials.access_token.as_str().into()) }, account))
}
/// A client with no token, for previews and tests. Every account call fails.
pub fn unauthenticated() -> Result<Self> {
Ok(Self { inner: yamuse::Client::anonymous()?, 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())
}
/// 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)
}
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)
}
// ---- Server queue ----
/// Publishes what's playing so other devices can continue it. Returns the queue id,
/// or `None` when Yandex didn't keep the queue.
///
/// Yandex now answers every create with the placeholder id `000000000000000000000000`
/// and lists no queues afterwards, whatever device header is sent (a stable
/// `device_id` was tried): the phone apps sync through Ynison instead. The
/// placeholder is dropped so no position updates go to a queue that doesn't exist.
pub async fn create_queue(&self, context: &QueueContext, tracks: &[Track], current: usize) -> Result<Option<String>> {
let tracks: Vec<serde_json::Value> = tracks
.iter()
.map(|t| {
serde_json::json!({
"trackId": t.id.split(':').next().unwrap_or(&t.id),
"albumId": t.album.as_ref().map(|a| a.id.to_string()).unwrap_or_default(),
"from": "musyx-desktop",
})
})
.collect();
let body = serde_json::json!({
"context": context.to_json(),
"tracks": tracks,
"currentIndex": current,
"from": "musyx-desktop",
"isInteractive": true,
});
Ok(real_queue_id(self.inner.create_queue(&body, None).await?))
}
pub async fn update_queue_position(&self, queue_id: &str, index: usize) -> Result<()> {
self.inner.update_queue_position(queue_id, index as i64, None).await?;
Ok(())
}
/// 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 placeholder_queue_ids_are_dropped() {
assert_eq!(real_queue_id(Some("000000000000000000000000".into())), None);
assert_eq!(real_queue_id(Some(String::new())), None);
assert_eq!(real_queue_id(None), None);
assert_eq!(real_queue_id(Some("6702a1f0c3".into())).as_deref(), Some("6702a1f0c3"));
}
#[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());
}
}