feat: My Wave and stations with feedback, play reporting and animated hero
- ym-api: stations, station settings (mood/character/language), track batches, rotor feedback (started, track started/finished, skip) and play-audio reports - Play reports send millisecond ISO timestamps: yamuse's default drops the milliseconds and /play-audio rejects it - Player: station mode tops up the queue when two tracks remain, waits instead of ending when a batch runs dry, ignores shuffle and batches from other stations, and reports every track left (finished or skipped with time played); feedback names the batch each track came in - Queue can grow (radio batches) and drop upcoming items (new settings) - My Wave screen with settings chips and station tiles; Home and My Wave hero draws drifting lines on a canvas, animated only while My Wave plays - Genre pages get a Play radio button
This commit is contained in:
1 parent
e7726aac3a
commit
03aa180840
12 files changed
+1115
-87
No files matched your search
@@ -7,6 +7,7 @@ use crate::library::{
|
||||
};
|
||||
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};
|
||||
|
||||
/// How many featured podcasts to resolve.
|
||||
@@ -297,6 +298,83 @@ impl YmClient {
|
||||
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(())
|
||||
}
|
||||
|
||||
/// The next tracks of a station. Pass the last track played as `after` to
|
||||
/// continue the sequence; `None` starts fresh.
|
||||
pub async fn wave_tracks(&self, station: &str, after: Option<&str>) -> Result<WaveBatch> {
|
||||
let queue = after.and_then(numeric_id);
|
||||
Ok(WaveBatch::from_yamuse(self.inner.rotor_station_tracks(station, queue).await?))
|
||||
}
|
||||
|
||||
/// Tells a station what happened, so the next batch fits better.
|
||||
pub async fn wave_feedback(&self, station: &str, event: &WaveEvent, batch_id: Option<&str>) -> Result<()> {
|
||||
use yamuse::RotorFeedback as F;
|
||||
let mut report = yamuse::RotorFeedbackReport {
|
||||
batch_id: batch_id.map(str::to_owned),
|
||||
..Default::default()
|
||||
};
|
||||
let kind = match event {
|
||||
WaveEvent::Started => {
|
||||
report.from = Some("musyx-wave".into());
|
||||
F::RadioStarted
|
||||
}
|
||||
WaveEvent::TrackStarted { track_id } => {
|
||||
report.track_id = numeric_id(track_id);
|
||||
F::TrackStarted
|
||||
}
|
||||
WaveEvent::TrackFinished { track_id, played } => {
|
||||
report.track_id = numeric_id(track_id);
|
||||
report.total_played_seconds = Some(played.as_secs_f64());
|
||||
F::TrackFinished
|
||||
}
|
||||
WaveEvent::Skipped { track_id, played } => {
|
||||
report.track_id = numeric_id(track_id);
|
||||
report.total_played_seconds = Some(played.as_secs_f64());
|
||||
F::Skip
|
||||
}
|
||||
};
|
||||
self.inner.rotor_feedback(station, kind, &report).await?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// 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(())
|
||||
}
|
||||
|
||||
/// 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()])
|
||||
|
||||
@@ -9,6 +9,7 @@ mod discover;
|
||||
mod error;
|
||||
mod library;
|
||||
mod models;
|
||||
mod wave;
|
||||
|
||||
pub use client::{Account, YmClient};
|
||||
pub use library::{
|
||||
@@ -16,5 +17,8 @@ pub use library::{
|
||||
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 error::{Error, Result};
|
||||
@@ -0,0 +1,302 @@
|
||||
//! 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; the batch id goes back with feedback.
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub struct WaveBatch {
|
||||
pub tracks: Vec<Track>,
|
||||
pub batch_id: Option<String>,
|
||||
}
|
||||
|
||||
impl WaveBatch {
|
||||
pub(crate) fn from_yamuse(r: y::StationTracksResult) -> Self {
|
||||
Self {
|
||||
tracks: r.sequence.into_iter().filter_map(|s| s.track.and_then(Track::from_yamuse)).collect(),
|
||||
batch_id: r.batch_id,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// 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 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"));
|
||||
|
||||
let b: y::StationTracksResult = serde_json::from_str(
|
||||
r#"{"batchId":"b1","sequence":[{"type":"track","track":{"id":5,"title":"A"}},{"type":"ad"}]}"#,
|
||||
)
|
||||
.unwrap();
|
||||
let batch = WaveBatch::from_yamuse(b);
|
||||
assert_eq!(batch.tracks.len(), 1);
|
||||
assert_eq!(batch.batch_id.as_deref(), Some("b1"));
|
||||
}
|
||||
|
||||
#[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);
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user