feat: likes, track actions, playlist editing, lyrics and queue sync
- ym-api: like/unlike tracks, albums, artists and playlists; dislike tracks; liked ids for drawing state; create, rename, publish/hide and delete playlists; add, remove and move tracks (fresh revision per edit); lyrics (LRC parsed, plain text fallback); server queues - Hearts on every track row, the player bar and album, artist and playlist pages, applied at once and re-read if Yandex refuses - Track menu: Play next (moves a queued track up rather than duplicating it; the playing track's menu offers Next track instead), Add to queue, like, Add to playlist or a new one, Go to album/artist, Don't recommend, and Move up/down/Remove on the user's own playlists - New playlist from the sidebar; Rename, Make public/private and Delete (confirmed) on own playlist pages; short status messages for every edit - Lyrics panel highlights and follows the sung line and seeks on click - Lists played are published as Yandex queues and their position kept - lyricsInfo decides lyrics availability (the old flag over-reports) - MUSYX_TRACE=1 logs user actions with the resulting queue - Headless UI tests (iced_test) click through menus over the full window
This commit is contained in:
1 parent
99f795b500
commit
e2312f2d40
22 files changed
+1733
-34
No files matched your search
@@ -5,12 +5,20 @@ 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};
|
||||
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;
|
||||
|
||||
@@ -410,6 +418,175 @@ impl YmClient {
|
||||
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?;
|
||||
Ok(LikedIds {
|
||||
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.
|
||||
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(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()])
|
||||
|
||||
@@ -0,0 +1,155 @@
|
||||
//! 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>,
|
||||
}
|
||||
|
||||
/// 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))
|
||||
}
|
||||
|
||||
/// Where a server queue's tracks come from; other devices show it as "Playing from…".
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub enum QueueContext {
|
||||
Album(i64),
|
||||
Playlist(PlaylistId),
|
||||
Artist(i64),
|
||||
/// Liked tracks.
|
||||
MyMusic,
|
||||
/// Search results, the chart, anything else.
|
||||
Various,
|
||||
}
|
||||
|
||||
impl QueueContext {
|
||||
pub(crate) fn to_json(&self) -> serde_json::Value {
|
||||
let (kind, id) = match self {
|
||||
QueueContext::Album(id) => ("album", id.to_string()),
|
||||
QueueContext::Playlist(p) => ("playlist", format!("{}:{}", p.owner, p.kind)),
|
||||
QueueContext::Artist(id) => ("artist", id.to_string()),
|
||||
QueueContext::MyMusic => ("my_music", String::new()),
|
||||
QueueContext::Various => ("various", String::new()),
|
||||
};
|
||||
serde_json::json!({ "type": kind, "id": id, "description": "" })
|
||||
}
|
||||
}
|
||||
|
||||
#[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);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn queue_contexts_match_the_api_shape() {
|
||||
let p = QueueContext::Playlist(PlaylistId { owner: 9, kind: 3 }).to_json();
|
||||
assert_eq!(p, serde_json::json!({"type": "playlist", "id": "9:3", "description": ""}));
|
||||
assert_eq!(QueueContext::MyMusic.to_json()["type"], "my_music");
|
||||
}
|
||||
}
|
||||
@@ -6,6 +6,7 @@
|
||||
pub mod auth;
|
||||
mod client;
|
||||
mod discover;
|
||||
mod edit;
|
||||
mod error;
|
||||
mod library;
|
||||
mod models;
|
||||
@@ -21,4 +22,5 @@ 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, QueueContext};
|
||||
pub use error::{Error, Result};
|
||||
@@ -162,6 +162,20 @@ impl PlaylistSummary {
|
||||
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)
|
||||
}
|
||||
|
||||
@@ -60,7 +60,12 @@ impl Track {
|
||||
available: t.available.unwrap_or(true),
|
||||
explicit: t.explicit.unwrap_or(false)
|
||||
|| t.content_warning.as_deref() == Some("explicit"),
|
||||
lyrics_available: t.lyrics_available.unwrap_or(false),
|
||||
// `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),
|
||||
},
|
||||
})
|
||||
}
|
||||
|
||||
|
||||
Reference in new issue
Block a user