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
@@ -8,7 +8,7 @@ publish.workspace = true
|
||||
|
||||
[dependencies]
|
||||
ym-api = { path = "../ym-api" }
|
||||
iced = { version = "0.14.0", features = ["svg", "image", "tokio", "advanced", "qr_code", "lazy"] }
|
||||
iced = { version = "0.14.0", features = ["svg", "image", "tokio", "advanced", "qr_code", "lazy", "canvas"] }
|
||||
keyring = "4.2.0"
|
||||
rodio = { version = "0.23.0", default-features = false, features = ["playback", "mp3", "mp4", "flac"] }
|
||||
rand = "0.9"
|
||||
|
||||
@@ -47,6 +47,22 @@ async fn main() {
|
||||
),
|
||||
Err(e) => println!("search: ERROR {e}"),
|
||||
}
|
||||
match client.stations().await {
|
||||
Ok(st) => println!("stations: {} {:?}", st.len(), st.iter().take(6).map(|s| (&s.id, &s.name)).collect::<Vec<_>>()),
|
||||
Err(e) => println!("stations: ERROR {e}"),
|
||||
}
|
||||
match client.wave_settings(ym_api::MY_WAVE).await {
|
||||
Ok(s) => println!("wave settings: {s:?}"),
|
||||
Err(e) => println!("wave settings: ERROR {e}"),
|
||||
}
|
||||
match client.wave_tracks(ym_api::MY_WAVE, None).await {
|
||||
Ok(b) => println!(
|
||||
"wave batch {:?}: {:?}",
|
||||
b.batch_id,
|
||||
b.tracks.iter().map(|t| format!("{} — {}", t.artist_line(), t.title)).collect::<Vec<_>>()
|
||||
),
|
||||
Err(e) => println!("wave: ERROR {e}"),
|
||||
}
|
||||
match client.suggest("зем").await {
|
||||
Ok(s) => println!("suggest: {:?}", s.iter().take(5).collect::<Vec<_>>()),
|
||||
Err(e) => println!("suggest: ERROR {e}"),
|
||||
|
||||
+113
-3
@@ -8,8 +8,8 @@ use iced::widget::{column, container, row, scrollable, space, stack};
|
||||
use iced::{Element, Fill, Subscription, Task, Theme};
|
||||
use ym_api::auth::Credentials;
|
||||
use ym_api::{
|
||||
Account, AlbumSummary, ArtistSummary, Error, Genre, Home, LibraryPlaylists, PlaylistSummary, Track,
|
||||
YmClient,
|
||||
Account, AlbumSummary, ArtistSummary, Error, Genre, Home, LibraryPlaylists, MY_WAVE, PlaylistSummary,
|
||||
Station, Track, WaveSettings, YmClient,
|
||||
};
|
||||
|
||||
use crate::covers::Covers;
|
||||
@@ -18,6 +18,7 @@ use crate::route::{Navigator, Route};
|
||||
use crate::screens::browse::{self, Discover, HomeData};
|
||||
use crate::screens::collection::{Library, Liked, Tab};
|
||||
use crate::screens::search::{self, Search};
|
||||
use crate::screens::wave::WaveScreen;
|
||||
use crate::screens::detail::{self, Page};
|
||||
use crate::screens::{self, Loadable, sign_in};
|
||||
use crate::session::{self, Restored};
|
||||
@@ -52,6 +53,9 @@ pub struct App {
|
||||
pages: HashMap<Route, Loadable<Page>>,
|
||||
discover: Discover,
|
||||
genre_playlists: HashMap<usize, Loadable<Vec<PlaylistSummary>>>,
|
||||
wave: WaveScreen,
|
||||
/// Drives the My Wave hero animation.
|
||||
wave_phase: f32,
|
||||
covers: Covers,
|
||||
/// A live snapshot run opens this route once signed in.
|
||||
#[cfg(feature = "snapshot")]
|
||||
@@ -90,6 +94,13 @@ pub enum Message {
|
||||
GenreLoaded(usize, Result<Vec<PlaylistSummary>, Error>),
|
||||
LoadPodcasts,
|
||||
PodcastsLoaded(Result<Vec<AlbumSummary>, Error>),
|
||||
PlayWave(String),
|
||||
LoadWave,
|
||||
WaveSettingsLoaded(Result<WaveSettings, Error>),
|
||||
StationsLoaded(Result<Vec<Station>, Error>),
|
||||
SetWaveSettings(WaveSettings),
|
||||
WaveSettingsSaved(WaveSettings, Result<(), Error>),
|
||||
WaveTick,
|
||||
CoverWanted(String),
|
||||
CoverLoaded(String, Option<Arc<[u8]>>),
|
||||
CoversTick,
|
||||
@@ -109,6 +120,8 @@ impl App {
|
||||
pages: HashMap::new(),
|
||||
discover: Discover::default(),
|
||||
genre_playlists: HashMap::new(),
|
||||
wave: WaveScreen::default(),
|
||||
wave_phase: 0.0,
|
||||
covers: Covers::default(),
|
||||
#[cfg(feature = "snapshot")]
|
||||
snapshot_route: None,
|
||||
@@ -159,6 +172,13 @@ impl App {
|
||||
if let Session::SignedOut(sign_in) = &self.session {
|
||||
subs.push(sign_in.subscription().map(Message::SignIn));
|
||||
}
|
||||
// The hero's lines drift only while My Wave plays and the hero is on screen.
|
||||
let hero_visible = matches!(self.nav.current(), Route::Home | Route::Wave);
|
||||
let wave_playing = self.player.wave_station() == Some(MY_WAVE)
|
||||
&& self.player.status() == player::Status::Playing;
|
||||
if hero_visible && wave_playing && matches!(self.session, Session::SignedIn { .. }) {
|
||||
subs.push(iced::time::every(std::time::Duration::from_millis(33)).map(|_| Message::WaveTick));
|
||||
}
|
||||
// Show arriving covers in batches instead of rebuilding lists for each one.
|
||||
if self.covers.dirty() {
|
||||
subs.push(iced::time::every(std::time::Duration::from_millis(150)).map(|_| Message::CoversTick));
|
||||
@@ -253,6 +273,7 @@ impl App {
|
||||
self.discover = Discover::default();
|
||||
self.genre_playlists.clear();
|
||||
self.search = Search::default();
|
||||
self.wave = WaveScreen::default();
|
||||
}
|
||||
Message::Navigate(route) => {
|
||||
self.nav.go(route);
|
||||
@@ -404,6 +425,65 @@ impl App {
|
||||
}
|
||||
self.discover.podcasts = Loadable::from_result(result);
|
||||
}
|
||||
Message::PlayWave(station) => {
|
||||
return self.update(Message::Player(player::Msg::PlayWave { station }));
|
||||
}
|
||||
Message::LoadWave => {
|
||||
let Some(client) = self.client().cloned() else { return Task::none() };
|
||||
let mut tasks = Vec::new();
|
||||
if self.wave.settings.needs_load() {
|
||||
self.wave.settings = Loadable::Loading;
|
||||
let c = client.clone();
|
||||
tasks.push(
|
||||
Task::future(async move { c.wave_settings(MY_WAVE).await }).map(Message::WaveSettingsLoaded),
|
||||
);
|
||||
}
|
||||
if self.wave.stations.needs_load() {
|
||||
self.wave.stations = Loadable::Loading;
|
||||
tasks.push(Task::future(async move { client.stations().await }).map(Message::StationsLoaded));
|
||||
}
|
||||
return Task::batch(tasks);
|
||||
}
|
||||
Message::WaveSettingsLoaded(result) => {
|
||||
if let Err(e) = &result
|
||||
&& let Some(task) = self.failed("wave settings", e)
|
||||
{
|
||||
return task;
|
||||
}
|
||||
self.wave.settings = Loadable::from_result(result);
|
||||
}
|
||||
Message::StationsLoaded(result) => {
|
||||
if let Err(e) = &result
|
||||
&& let Some(task) = self.failed("stations", e)
|
||||
{
|
||||
return task;
|
||||
}
|
||||
self.wave.stations = Loadable::from_result(result);
|
||||
}
|
||||
Message::SetWaveSettings(settings) => {
|
||||
let Some(client) = self.client().cloned() else { return Task::none() };
|
||||
self.wave.saving = Some(settings);
|
||||
return Task::future(async move { client.set_wave_settings(MY_WAVE, settings).await })
|
||||
.map(move |r| Message::WaveSettingsSaved(settings, r));
|
||||
}
|
||||
Message::WaveSettingsSaved(settings, result) => {
|
||||
self.wave.saving = None;
|
||||
match result {
|
||||
Ok(()) => {
|
||||
self.wave.settings = Loadable::Loaded(settings);
|
||||
// A playing My Wave picks the new settings up from the next track.
|
||||
if self.player.wave_station() == Some(MY_WAVE) {
|
||||
return self.update(Message::Player(player::Msg::WaveRestart));
|
||||
}
|
||||
}
|
||||
Err(e) => {
|
||||
if let Some(task) = self.failed("save wave settings", &e) {
|
||||
return task;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
Message::WaveTick => self.wave_phase = (self.wave_phase + 0.04) % 10_000.0,
|
||||
Message::CoverWanted(url) => {
|
||||
let Some(client) = self.client().cloned() else { return Task::none() };
|
||||
return self.covers.want(url, &client);
|
||||
@@ -431,8 +511,9 @@ impl App {
|
||||
},
|
||||
Route::Home => {
|
||||
let home = if self.discover.home.needs_load() { self.update(Message::LoadHome) } else { Task::none() };
|
||||
Task::batch([home, self.genres_if_needed()])
|
||||
Task::batch([home, self.genres_if_needed(), self.update(Message::LoadWave)])
|
||||
}
|
||||
Route::Wave => self.update(Message::LoadWave),
|
||||
Route::Search => self.genres_if_needed(),
|
||||
Route::Chart if self.discover.home.needs_load() => self.update(Message::LoadHome),
|
||||
Route::Genre(index) => {
|
||||
@@ -532,6 +613,9 @@ impl App {
|
||||
pages: &self.pages,
|
||||
discover: &self.discover,
|
||||
genre_playlists: &self.genre_playlists,
|
||||
player: &self.player,
|
||||
wave: &self.wave,
|
||||
wave_phase: self.wave_phase,
|
||||
}))
|
||||
.height(Fill)
|
||||
.style(theme::scroll);
|
||||
@@ -597,6 +681,32 @@ impl App {
|
||||
.map(|(track_id, result)| Message::Player(player::Msg::Prefetched { track_id, result }))
|
||||
}
|
||||
Effect::SignedOut => Task::done(Message::SignOut),
|
||||
Effect::WaveFetch { station, after } => {
|
||||
let client = client.clone();
|
||||
Task::future(async move {
|
||||
let result = client.wave_tracks(&station, after.as_deref()).await;
|
||||
Message::Player(player::Msg::WaveBatch { station, result })
|
||||
})
|
||||
}
|
||||
// Feedback and reports are fire-and-forget: a lost one only blunts recommendations.
|
||||
Effect::WaveFeedback { station, event, batch_id } => {
|
||||
let client = client.clone();
|
||||
Task::future(async move {
|
||||
if let Err(e) = client.wave_feedback(&station, &event, batch_id.as_deref()).await {
|
||||
eprintln!("wave feedback {event:?} (batch {batch_id:?}): {e}");
|
||||
}
|
||||
})
|
||||
.discard()
|
||||
}
|
||||
Effect::Report(report) => {
|
||||
let client = client.clone();
|
||||
Task::future(async move {
|
||||
if let Err(e) = client.report_play(&report).await {
|
||||
eprintln!("play report: {e}");
|
||||
}
|
||||
})
|
||||
.discard()
|
||||
}
|
||||
}))
|
||||
}
|
||||
}
|
||||
|
||||
+276
-12
@@ -8,7 +8,7 @@ pub mod queue;
|
||||
use std::sync::Arc;
|
||||
use std::time::Duration;
|
||||
|
||||
use ym_api::{Error, Stream, Track};
|
||||
use ym_api::{Error, PlayReport, Stream, Track, WaveBatch, WaveEvent};
|
||||
|
||||
use engine::{Command, Event};
|
||||
pub use queue::{Queue, Repeat};
|
||||
@@ -17,6 +17,8 @@ pub use queue::{Queue, Repeat};
|
||||
const MAX_SKIPS: u8 = 3;
|
||||
/// "Previous" restarts the current track once it has played this long.
|
||||
const RESTART_AFTER: Duration = Duration::from_secs(3);
|
||||
/// Ask a station for more once this few tracks are left.
|
||||
const WAVE_LOW_WATER: usize = 2;
|
||||
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub enum Status {
|
||||
@@ -52,6 +54,11 @@ pub enum Msg {
|
||||
JumpTo(usize),
|
||||
Fetched { generation: u64, result: Result<Audio, Error> },
|
||||
Prefetched { track_id: String, result: Result<Audio, Error> },
|
||||
/// Start a station (`type:tag`).
|
||||
PlayWave { station: String },
|
||||
WaveBatch { station: String, result: Result<WaveBatch, Error> },
|
||||
/// The station's settings changed: replace what's queued after the current track.
|
||||
WaveRestart,
|
||||
}
|
||||
|
||||
/// Work the app has to do on the player's behalf.
|
||||
@@ -61,6 +68,20 @@ pub enum Effect {
|
||||
Prefetch { track_id: String },
|
||||
/// The token stopped working mid-session.
|
||||
SignedOut,
|
||||
WaveFetch { station: String, after: Option<String> },
|
||||
WaveFeedback { station: String, event: WaveEvent, batch_id: Option<String> },
|
||||
Report(PlayReport),
|
||||
}
|
||||
|
||||
/// A station being played, endlessly topped up.
|
||||
#[derive(Debug, Clone)]
|
||||
struct Wave {
|
||||
station: String,
|
||||
/// The batch each queued track came in; feedback must name the track's own batch.
|
||||
batches: std::collections::HashMap<String, String>,
|
||||
fetching: bool,
|
||||
/// The queue ran out before the next batch came; advance when it does.
|
||||
waiting: bool,
|
||||
}
|
||||
|
||||
pub struct Player {
|
||||
@@ -82,6 +103,9 @@ pub struct Player {
|
||||
seeking: Option<f32>,
|
||||
/// One line for the player bar when something went wrong.
|
||||
pub notice: Option<String>,
|
||||
wave: Option<Wave>,
|
||||
/// The track that started playing and hasn't been reported yet.
|
||||
started: Option<String>,
|
||||
}
|
||||
|
||||
impl Default for Player {
|
||||
@@ -103,6 +127,8 @@ impl Default for Player {
|
||||
skips: 0,
|
||||
seeking: None,
|
||||
notice: None,
|
||||
wave: None,
|
||||
started: None,
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -110,6 +136,7 @@ impl Default for Player {
|
||||
impl Player {
|
||||
/// Stops playback and forgets the queue (sign-out). The device and volume stay.
|
||||
pub fn reset(&mut self) {
|
||||
// No reports: the session they'd go to is ending.
|
||||
self.send(Command::Stop);
|
||||
*self = Self { engine: self.engine.take(), volume: self.volume, muted: self.muted, ..Self::default() };
|
||||
}
|
||||
@@ -130,6 +157,11 @@ impl Player {
|
||||
self.shuffle
|
||||
}
|
||||
|
||||
/// The station playing, if the queue is a wave.
|
||||
pub fn wave_station(&self) -> Option<&str> {
|
||||
self.wave.as_ref().map(|w| w.station.as_str())
|
||||
}
|
||||
|
||||
/// Where the seek bar should sit: the drag position while dragging.
|
||||
pub fn position(&self) -> Duration {
|
||||
self.seeking.map_or(self.position, Duration::from_secs_f32)
|
||||
@@ -165,10 +197,45 @@ impl Player {
|
||||
} else {
|
||||
start
|
||||
};
|
||||
let mut effects = self.leave(false);
|
||||
self.wave = None;
|
||||
self.queue = Queue::new(tracks.to_vec(), start, self.shuffle);
|
||||
self.skips = 0;
|
||||
self.notice = None;
|
||||
return self.load_current();
|
||||
effects.extend(self.load_current());
|
||||
return effects;
|
||||
}
|
||||
Msg::PlayWave { station } => {
|
||||
let mut effects = self.leave(false);
|
||||
self.queue = None;
|
||||
self.current = None;
|
||||
self.skips = 0;
|
||||
self.notice = None;
|
||||
self.status = Status::Loading;
|
||||
self.send(Command::Stop);
|
||||
self.wave = Some(Wave {
|
||||
station: station.clone(),
|
||||
batches: Default::default(),
|
||||
fetching: true,
|
||||
waiting: true,
|
||||
});
|
||||
effects.push(Effect::WaveFeedback { station: station.clone(), event: WaveEvent::Started, batch_id: None });
|
||||
effects.push(Effect::WaveFetch { station, after: None });
|
||||
return effects;
|
||||
}
|
||||
Msg::WaveBatch { station, result } => return self.on_batch(station, result),
|
||||
Msg::WaveRestart => {
|
||||
let after = self.track().map(|t| t.id.clone());
|
||||
let Some(wave) = &mut self.wave else { return vec![] };
|
||||
if let Some(queue) = &mut self.queue {
|
||||
queue.clear_upcoming();
|
||||
}
|
||||
self.prefetched = None;
|
||||
if wave.fetching {
|
||||
return vec![];
|
||||
}
|
||||
wave.fetching = true;
|
||||
return vec![Effect::WaveFetch { station: wave.station.clone(), after }];
|
||||
}
|
||||
Msg::Toggle => match self.status {
|
||||
Status::Playing => {
|
||||
@@ -187,11 +254,17 @@ impl Player {
|
||||
Msg::Previous => {
|
||||
if self.position >= RESTART_AFTER || !self.can_go_back() {
|
||||
self.seek(Duration::ZERO);
|
||||
} else if let Some(queue) = &mut self.queue {
|
||||
queue.back(self.repeat);
|
||||
return self.load_current();
|
||||
} else {
|
||||
let mut effects = self.leave(false);
|
||||
if let Some(queue) = &mut self.queue {
|
||||
queue.back(self.repeat);
|
||||
effects.extend(self.load_current());
|
||||
}
|
||||
return effects;
|
||||
}
|
||||
}
|
||||
// A station decides its own order.
|
||||
Msg::ToggleShuffle if self.wave.is_some() => {}
|
||||
Msg::ToggleShuffle => {
|
||||
self.shuffle = !self.shuffle;
|
||||
if let Some(queue) = &mut self.queue {
|
||||
@@ -222,10 +295,12 @@ impl Player {
|
||||
self.send(Command::Volume(self.effective_volume()));
|
||||
}
|
||||
Msg::JumpTo(pos) => {
|
||||
let mut effects = self.leave(false);
|
||||
if let Some(queue) = &mut self.queue {
|
||||
queue.jump(pos);
|
||||
return self.load_current();
|
||||
effects.extend(self.load_current());
|
||||
}
|
||||
return effects;
|
||||
}
|
||||
Msg::Fetched { generation, result } => {
|
||||
if generation != self.generation {
|
||||
@@ -267,7 +342,20 @@ impl Player {
|
||||
}
|
||||
self.status = Status::Playing;
|
||||
self.skips = 0;
|
||||
return self.prefetch_next();
|
||||
let mut effects = Vec::new();
|
||||
if let Some(id) = self.track().map(|t| t.id.clone()) {
|
||||
if let Some(wave) = &self.wave {
|
||||
effects.push(Effect::WaveFeedback {
|
||||
station: wave.station.clone(),
|
||||
event: WaveEvent::TrackStarted { track_id: id.clone() },
|
||||
batch_id: wave.batches.get(&id).cloned(),
|
||||
});
|
||||
}
|
||||
self.started = Some(id);
|
||||
}
|
||||
effects.extend(self.prefetch_next());
|
||||
effects.extend(self.top_up());
|
||||
return effects;
|
||||
}
|
||||
Event::Position { generation, position } if generation == self.generation => {
|
||||
self.position = position;
|
||||
@@ -305,13 +393,97 @@ impl Player {
|
||||
/// Next track. `finished` distinguishes a natural end (repeat-one replays)
|
||||
/// from a skip; `user` skips always move on.
|
||||
fn step(&mut self, user: bool, finished: bool) -> Vec<Effect> {
|
||||
let Some(queue) = &mut self.queue else { return vec![] };
|
||||
let mut effects = self.leave(finished && !user);
|
||||
let Some(queue) = &mut self.queue else { return effects };
|
||||
if queue.advance(self.repeat, finished && !user) {
|
||||
self.load_current()
|
||||
effects.extend(self.load_current());
|
||||
} else if let Some(wave) = &mut self.wave {
|
||||
// The batch ran dry; carry on as soon as the next one lands.
|
||||
wave.waiting = true;
|
||||
self.status = Status::Loading;
|
||||
effects.extend(self.top_up());
|
||||
} else {
|
||||
self.status = Status::Ended;
|
||||
self.position = self.duration;
|
||||
vec![]
|
||||
}
|
||||
effects
|
||||
}
|
||||
|
||||
/// Reports the track being left: to the listening history always, and to the
|
||||
/// station when it's a wave. `finished` means it played to the end.
|
||||
fn leave(&mut self, finished: bool) -> Vec<Effect> {
|
||||
let Some(id) = self.started.take() else { return vec![] };
|
||||
let Some(track) = self.track().filter(|t| t.id == id) else { return vec![] };
|
||||
let played = if finished { self.duration } else { self.position.min(self.duration) };
|
||||
let mut effects = vec![Effect::Report(PlayReport {
|
||||
track_id: id.clone(),
|
||||
album_id: track.album.as_ref().map(|a| a.id),
|
||||
length: self.duration,
|
||||
played,
|
||||
end_position: played,
|
||||
from: if self.wave.is_some() { "musyx-wave".into() } else { "musyx-desktop".into() },
|
||||
})];
|
||||
if let Some(wave) = &self.wave {
|
||||
let batch_id = wave.batches.get(&id).cloned();
|
||||
let event = if finished {
|
||||
WaveEvent::TrackFinished { track_id: id, played }
|
||||
} else {
|
||||
WaveEvent::Skipped { track_id: id, played }
|
||||
};
|
||||
effects.push(Effect::WaveFeedback { station: wave.station.clone(), event, batch_id });
|
||||
}
|
||||
effects
|
||||
}
|
||||
|
||||
/// Asks the station for more when the queue runs low.
|
||||
fn top_up(&mut self) -> Vec<Effect> {
|
||||
let (Some(wave), Some(queue)) = (&mut self.wave, &self.queue) else { return vec![] };
|
||||
if wave.fetching || queue.upcoming().count() >= WAVE_LOW_WATER {
|
||||
return vec![];
|
||||
}
|
||||
wave.fetching = true;
|
||||
vec![Effect::WaveFetch { station: wave.station.clone(), after: Some(queue.last().id.clone()) }]
|
||||
}
|
||||
|
||||
fn on_batch(&mut self, station: String, result: Result<WaveBatch, Error>) -> Vec<Effect> {
|
||||
let Some(wave) = self.wave.as_mut().filter(|w| w.station == station) else { return vec![] };
|
||||
wave.fetching = false;
|
||||
let batch = match result {
|
||||
Ok(batch) if !batch.tracks.is_empty() => batch,
|
||||
Ok(_) | Err(_) => {
|
||||
if let Err(Error::Unauthorized(_)) = result {
|
||||
return vec![Effect::SignedOut];
|
||||
}
|
||||
if let Err(e) = &result {
|
||||
eprintln!("wave batch: {e}");
|
||||
}
|
||||
if wave.waiting {
|
||||
wave.waiting = false;
|
||||
self.status = if self.queue.is_some() { Status::Ended } else { Status::Paused };
|
||||
self.notice = Some("Couldn't load more of this station. Check your connection and try again.".into());
|
||||
}
|
||||
return vec![];
|
||||
}
|
||||
};
|
||||
if let Some(batch_id) = &batch.batch_id {
|
||||
for track in &batch.tracks {
|
||||
wave.batches.insert(track.id.clone(), batch_id.clone());
|
||||
}
|
||||
}
|
||||
let waiting = std::mem::replace(&mut wave.waiting, false);
|
||||
match &mut self.queue {
|
||||
None => {
|
||||
self.queue = Queue::new(batch.tracks, 0, false);
|
||||
self.load_current()
|
||||
}
|
||||
Some(queue) => {
|
||||
queue.extend(batch.tracks);
|
||||
if waiting && queue.advance(Repeat::Off, false) {
|
||||
self.load_current()
|
||||
} else {
|
||||
self.prefetch_next()
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -460,7 +632,11 @@ mod tests {
|
||||
fn end_of_queue_stops_and_play_restarts_last_track() {
|
||||
let mut p = playing(1, 0);
|
||||
let generation = p.generation;
|
||||
assert!(p.update(Msg::Engine(Event::Ended { generation })).is_empty());
|
||||
let effects = p.update(Msg::Engine(Event::Ended { generation }));
|
||||
assert!(
|
||||
matches!(effects.as_slice(), [Effect::Report(r)] if r.played == Duration::from_secs(100) && r.from == "musyx-desktop"),
|
||||
"a finished track is reported once: {effects:?}"
|
||||
);
|
||||
assert_eq!(p.status(), Status::Ended);
|
||||
let effects = p.update(Msg::Toggle);
|
||||
assert!(effects.is_empty(), "replay comes from memory: {effects:?}");
|
||||
@@ -475,7 +651,7 @@ mod tests {
|
||||
assert_eq!(p.repeat, Repeat::One);
|
||||
let generation = p.generation;
|
||||
let effects = p.update(Msg::Engine(Event::Ended { generation }));
|
||||
assert!(effects.is_empty(), "{effects:?}");
|
||||
assert!(!effects.iter().any(|e| matches!(e, Effect::Fetch { .. })), "{effects:?}");
|
||||
assert_eq!(p.track().unwrap().id, "1");
|
||||
}
|
||||
|
||||
@@ -545,6 +721,94 @@ mod tests {
|
||||
assert_eq!(p.volume, 0.3);
|
||||
}
|
||||
|
||||
fn wave_with(n: usize) -> Player {
|
||||
let mut p = Player::default();
|
||||
let effects = p.update(Msg::PlayWave { station: "user:onyourwave".into() });
|
||||
assert!(matches!(
|
||||
effects.as_slice(),
|
||||
[Effect::WaveFeedback { event: WaveEvent::Started, .. }, Effect::WaveFetch { after: None, .. }]
|
||||
));
|
||||
let batch = WaveBatch { tracks: (0..n).map(|i| track(&format!("w{i}"), 100)).collect(), batch_id: Some("b1".into()) };
|
||||
let effects = p.update(Msg::WaveBatch { station: "user:onyourwave".into(), result: Ok(batch) });
|
||||
let Some(Effect::Fetch { generation, .. }) = effects.first().cloned() else { panic!("{effects:?}") };
|
||||
p.update(Msg::Fetched { generation, result: Ok(audio()) });
|
||||
p
|
||||
}
|
||||
|
||||
fn loaded(p: &mut Player) -> Vec<Effect> {
|
||||
let generation = p.generation;
|
||||
p.update(Msg::Engine(Event::Loaded { generation, duration: None }))
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn wave_reports_start_and_tops_up_when_low() {
|
||||
let mut p = wave_with(3);
|
||||
let effects = loaded(&mut p);
|
||||
assert!(effects.iter().any(|e| matches!(e,
|
||||
Effect::WaveFeedback { event: WaveEvent::TrackStarted { track_id }, batch_id: Some(b), .. }
|
||||
if track_id == "w0" && b == "b1")));
|
||||
assert!(!effects.iter().any(|e| matches!(e, Effect::WaveFetch { .. })), "two still queued");
|
||||
|
||||
let generation = p.generation;
|
||||
p.update(Msg::Engine(Event::Position { generation, position: Duration::from_secs(20) }));
|
||||
let effects = p.update(Msg::Next);
|
||||
assert!(effects.iter().any(|e| matches!(e,
|
||||
Effect::WaveFeedback { event: WaveEvent::Skipped { track_id, played }, .. }
|
||||
if track_id == "w0" && *played == Duration::from_secs(20))));
|
||||
assert!(effects.iter().any(|e| matches!(e, Effect::Report(r) if r.from == "musyx-wave")));
|
||||
|
||||
let generation = p.generation;
|
||||
p.update(Msg::Fetched { generation, result: Ok(audio()) });
|
||||
let effects = loaded(&mut p);
|
||||
assert!(
|
||||
effects.iter().any(|e| matches!(e, Effect::WaveFetch { after: Some(last), .. } if last == "w2")),
|
||||
"one left, so ask for more after the last queued: {effects:?}"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn feedback_names_each_tracks_own_batch() {
|
||||
let mut p = wave_with(2);
|
||||
loaded(&mut p);
|
||||
let more = WaveBatch { tracks: vec![track("n0", 10)], batch_id: Some("b2".into()) };
|
||||
p.update(Msg::WaveBatch { station: "user:onyourwave".into(), result: Ok(more) });
|
||||
let effects = p.update(Msg::Next);
|
||||
assert!(effects.iter().any(|e| matches!(e,
|
||||
Effect::WaveFeedback { event: WaveEvent::Skipped { .. }, batch_id: Some(b), .. } if b == "b1")),
|
||||
"w0 came in b1 even though b2 arrived since: {effects:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn wave_waits_for_the_next_batch_when_dry() {
|
||||
let mut p = wave_with(1);
|
||||
loaded(&mut p);
|
||||
let generation = p.generation;
|
||||
let effects = p.update(Msg::Engine(Event::Ended { generation }));
|
||||
assert!(effects.iter().any(|e| matches!(e, Effect::WaveFeedback { event: WaveEvent::TrackFinished { .. }, .. })));
|
||||
assert_eq!(p.status(), Status::Loading, "a wave doesn't end");
|
||||
let batch = WaveBatch { tracks: vec![track("w9", 50)], batch_id: Some("b2".into()) };
|
||||
let effects = p.update(Msg::WaveBatch { station: "user:onyourwave".into(), result: Ok(batch) });
|
||||
assert!(matches!(effects.first(), Some(Effect::Fetch { track_id, .. }) if track_id == "w9"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn batches_for_another_station_are_ignored() {
|
||||
let mut p = wave_with(2);
|
||||
let batch = WaveBatch { tracks: vec![track("x", 10)], batch_id: None };
|
||||
assert!(p.update(Msg::WaveBatch { station: "genre:rock".into(), result: Ok(batch) }).is_empty());
|
||||
assert_eq!(p.queue().unwrap().len(), 2);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn playing_a_list_leaves_wave_mode_and_shuffle_is_ignored_in_waves() {
|
||||
let mut p = wave_with(2);
|
||||
p.update(Msg::ToggleShuffle);
|
||||
assert!(!p.shuffle());
|
||||
let tracks: Arc<[Track]> = vec![track("a", 10)].into();
|
||||
p.update(Msg::Play { tracks, start: 0, shuffle: None });
|
||||
assert!(p.wave_station().is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn mute_and_volume() {
|
||||
let mut p = Player::default();
|
||||
|
||||
@@ -125,6 +125,28 @@ impl<T> Queue<T> {
|
||||
pub fn len(&self) -> usize {
|
||||
self.items.len()
|
||||
}
|
||||
|
||||
/// The item that plays last.
|
||||
pub fn last(&self) -> &T {
|
||||
&self.items[*self.order.last().expect("queues are never empty")]
|
||||
}
|
||||
|
||||
/// Adds items to the end of the play order (radio batches arriving).
|
||||
pub fn extend(&mut self, more: impl IntoIterator<Item = T>) {
|
||||
for item in more {
|
||||
self.order.push(self.items.len());
|
||||
self.items.push(item);
|
||||
}
|
||||
}
|
||||
|
||||
/// Drops everything after the current item, e.g. when a station's settings change.
|
||||
pub fn clear_upcoming(&mut self) {
|
||||
let keep: Vec<usize> = self.order[..=self.pos].to_vec();
|
||||
let items = std::mem::take(&mut self.items);
|
||||
let mut kept: Vec<Option<T>> = items.into_iter().map(Some).collect();
|
||||
self.items = keep.iter().map(|&i| kept[i].take().expect("each index once")).collect();
|
||||
self.order = (0..self.items.len()).collect();
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
@@ -206,6 +228,30 @@ mod tests {
|
||||
assert_eq!(q.upcoming().count(), 49 - now);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn extend_appends_after_everything() {
|
||||
let mut q = q(2, 1);
|
||||
assert!(!q.advance(Repeat::Off, true));
|
||||
q.extend([10, 11]);
|
||||
assert!(q.advance(Repeat::Off, true));
|
||||
assert_eq!(*q.current(), 10);
|
||||
assert_eq!(q.upcoming().map(|(_, &x)| x).collect::<Vec<_>>(), [11]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn clear_upcoming_keeps_history_and_current() {
|
||||
let mut q = q(5, 0);
|
||||
q.set_shuffle(true);
|
||||
q.advance(Repeat::Off, false);
|
||||
let (first, now) = (q.order[0], *q.current());
|
||||
q.clear_upcoming();
|
||||
assert_eq!(q.len(), 2);
|
||||
assert_eq!(*q.current(), now);
|
||||
assert_eq!(q.upcoming().count(), 0);
|
||||
assert!(q.back(Repeat::Off));
|
||||
assert_eq!(*q.current(), first);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn jump_moves_to_upcoming_position() {
|
||||
let mut q = q(5, 0);
|
||||
|
||||
@@ -210,7 +210,22 @@ pub fn genre<'a>(
|
||||
let Some(g) = genres.get(index) else {
|
||||
return para("This genre isn't available any more.", size::BODY, t.muted).into();
|
||||
};
|
||||
let mut page = column![line(g.title.clone(), theme::DISPLAY, size::DISPLAY_S, t.fg)].spacing(24);
|
||||
let radio = button(
|
||||
row![
|
||||
crate::ui::icons::icon(crate::ui::icons::Icon::Wave, t.accent_ink),
|
||||
line("Play radio", theme::SEMIBOLD, size::BODY, t.accent_ink),
|
||||
]
|
||||
.spacing(8)
|
||||
.align_y(Alignment::Center),
|
||||
)
|
||||
.padding([10, 18])
|
||||
.style(theme::primary)
|
||||
.on_press(Message::PlayWave(format!("genre:{}", g.id)));
|
||||
let mut page = column![
|
||||
row![line(g.title.clone(), theme::DISPLAY, size::DISPLAY_S, t.fg).width(Fill), radio]
|
||||
.align_y(Alignment::Center)
|
||||
]
|
||||
.spacing(24);
|
||||
|
||||
let subs: Vec<Element<'a, Message>> = g
|
||||
.sub_genres
|
||||
|
||||
@@ -5,6 +5,7 @@ pub mod collection;
|
||||
pub mod detail;
|
||||
pub mod search;
|
||||
pub mod sign_in;
|
||||
pub mod wave;
|
||||
|
||||
use iced::widget::{Column, button, column, container, row, space};
|
||||
use iced::{Alignment, Element, Fill, Padding};
|
||||
@@ -14,8 +15,8 @@ use ym_api::{Account, Error, PlaylistSummary};
|
||||
|
||||
use crate::app::Message;
|
||||
use crate::route::Route;
|
||||
use crate::ui::icons::{Icon, icon, sized};
|
||||
use crate::ui::theme::{self, Tokens, radius, size, space as sp};
|
||||
use crate::ui::icons::{Icon, icon};
|
||||
use crate::ui::theme::{self, Tokens, size, space as sp};
|
||||
use crate::ui::{line, para};
|
||||
use crate::widgets::sidebar;
|
||||
use crate::widgets::track_list::Env;
|
||||
@@ -68,17 +69,24 @@ pub struct Ctx<'a> {
|
||||
pub pages: &'a HashMap<Route, Loadable<detail::Page>>,
|
||||
pub discover: &'a browse::Discover,
|
||||
pub genre_playlists: &'a HashMap<usize, Loadable<Vec<PlaylistSummary>>>,
|
||||
pub player: &'a crate::player::Player,
|
||||
pub wave: &'a wave::WaveScreen,
|
||||
pub wave_phase: f32,
|
||||
}
|
||||
|
||||
pub fn view<'a>(ctx: Ctx<'a>) -> Element<'a, Message> {
|
||||
let Ctx { env, route, search, me, library, pages, discover, genre_playlists } = ctx;
|
||||
let Ctx { env, route, search, me, library, pages, discover, genre_playlists, player, wave, wave_phase } = ctx;
|
||||
let t = env.t;
|
||||
let content: Column<'a, Message> = match route {
|
||||
Route::Home => column![browse::home(env, discover, wave_hero(t))],
|
||||
Route::Wave => column![
|
||||
title(t, "My Wave"),
|
||||
upcoming(t, Icon::Wave, "An endless stream that learns from you", "Every like, skip and full listen steers what comes next."),
|
||||
],
|
||||
Route::Home => {
|
||||
column![browse::home(env, discover, wave::hero(t, player, wave_phase, wave.shown(), false))]
|
||||
}
|
||||
Route::Wave => column![wave::view(
|
||||
t,
|
||||
env.covers,
|
||||
wave,
|
||||
wave::hero(t, player, wave_phase, wave.shown(), true),
|
||||
)],
|
||||
Route::Search => column![search::view(env, search, browse::genres_section(env, &discover.genres))],
|
||||
Route::Chart => column![browse::chart(env, discover)],
|
||||
Route::Genre(i) => column![browse::genre(
|
||||
@@ -106,26 +114,6 @@ fn title<'a>(t: &'static Tokens, text: impl Into<String>) -> Element<'a, Message
|
||||
line(text.into(), theme::DISPLAY, size::DISPLAY_S, t.fg).into()
|
||||
}
|
||||
|
||||
/// A section whose content arrives in a later build.
|
||||
fn upcoming<'a>(t: &'static Tokens, glyph: Icon, heading: &'a str, body: &'a str) -> Element<'a, Message> {
|
||||
container(
|
||||
column![
|
||||
sized(glyph, 28.0, t.accent),
|
||||
column![
|
||||
line(heading, theme::SEMIBOLD, size::SECTION, t.fg),
|
||||
container(para(body, size::BODY, t.muted)).max_width(460),
|
||||
line("Arrives in the next Musyx update.", theme::MEDIUM, size::META, t.muted),
|
||||
]
|
||||
.spacing(6),
|
||||
]
|
||||
.spacing(18),
|
||||
)
|
||||
.padding(28)
|
||||
.width(Fill)
|
||||
.style(theme::card)
|
||||
.into()
|
||||
}
|
||||
|
||||
fn account_card<'a>(t: &'static Tokens, me: &'a Account) -> Element<'a, Message> {
|
||||
let avatar = container(line(me.initial().to_string(), theme::SEMIBOLD, 22.0, iced::Color::from_rgb8(0x1C, 0x1A, 0x22)))
|
||||
.center(56)
|
||||
@@ -180,48 +168,6 @@ pub fn human_date(iso: &str) -> Option<String> {
|
||||
Some(format!("{day} {month} {y}"))
|
||||
}
|
||||
|
||||
/// Static version of the My Wave hero; the animated wave arrives with playback.
|
||||
fn wave_hero<'a>(t: &'static Tokens) -> Element<'a, Message> {
|
||||
container(
|
||||
row![
|
||||
column![
|
||||
line("My Wave", theme::DISPLAY, size::DISPLAY_M, t.fg),
|
||||
container(para(
|
||||
"An endless stream picked from what you play, like and skip.",
|
||||
size::BODY,
|
||||
t.muted,
|
||||
))
|
||||
.max_width(380),
|
||||
]
|
||||
.spacing(6)
|
||||
.width(Fill),
|
||||
button(
|
||||
row![icon(Icon::Play, t.muted), line("Play My Wave", theme::SEMIBOLD, size::BODY, t.muted)]
|
||||
.spacing(8)
|
||||
.align_y(Alignment::Center),
|
||||
)
|
||||
.padding([11, 18])
|
||||
.style(theme::primary),
|
||||
]
|
||||
.spacing(28)
|
||||
.align_y(Alignment::End),
|
||||
)
|
||||
.padding(Padding::default().top(120).bottom(26).left(28).right(28))
|
||||
.width(Fill)
|
||||
.style(move |th| {
|
||||
let mut s = theme::card(th);
|
||||
s.border.radius = radius::HERO.into();
|
||||
s.background = Some(iced::Background::Gradient(
|
||||
iced::gradient::Linear::new(0.0)
|
||||
.add_stop(0.0, t.panel)
|
||||
.add_stop(1.0, theme::mix(t.panel, t.accent, 0.16))
|
||||
.into(),
|
||||
));
|
||||
s
|
||||
})
|
||||
.into()
|
||||
}
|
||||
|
||||
/// Full-window holding screen while the stored session is checked or a new one connects.
|
||||
pub fn connecting<'a>(t: &'static Tokens, label: &'a str) -> Element<'a, Message> {
|
||||
container(
|
||||
|
||||
@@ -0,0 +1,225 @@
|
||||
//! My Wave: the animated hero, station settings and other stations.
|
||||
|
||||
use iced::widget::canvas::{self, Frame, Geometry, Path, Stroke};
|
||||
use iced::widget::{Row, button, canvas as canvas_widget, column, container, row, stack};
|
||||
use iced::{Alignment, Color, Element, Fill, Length, Padding, Point, Rectangle, Renderer, Theme, mouse};
|
||||
use ym_api::{Character, Language, MY_WAVE, Mood, Station, WaveSettings};
|
||||
|
||||
use super::Loadable;
|
||||
use super::collection::{LoadState, status};
|
||||
use crate::app::Message;
|
||||
use crate::covers::{self, Covers};
|
||||
use crate::player::{self, Player, Status};
|
||||
use crate::ui::icons::{Icon, icon};
|
||||
use crate::ui::theme::{self, Tokens, radius, size};
|
||||
use crate::ui::{line, para};
|
||||
use crate::widgets::card;
|
||||
|
||||
/// Everything the My Wave screen shows.
|
||||
#[derive(Debug, Default)]
|
||||
pub struct WaveScreen {
|
||||
pub settings: Loadable<WaveSettings>,
|
||||
pub stations: Loadable<Vec<Station>>,
|
||||
/// Settings picked but not yet confirmed by Yandex.
|
||||
pub saving: Option<WaveSettings>,
|
||||
}
|
||||
|
||||
impl WaveScreen {
|
||||
/// The settings to show: the pending choice while saving.
|
||||
pub fn shown(&self) -> Option<WaveSettings> {
|
||||
self.saving.or_else(|| self.settings.get().copied())
|
||||
}
|
||||
}
|
||||
|
||||
/// Lines drifting across the hero. Moves only while a station plays.
|
||||
struct WaveArt {
|
||||
phase: f32,
|
||||
energy: f32,
|
||||
color: Color,
|
||||
}
|
||||
|
||||
impl canvas::Program<Message> for WaveArt {
|
||||
type State = ();
|
||||
|
||||
fn draw(&self, _: &(), renderer: &Renderer, _: &Theme, bounds: Rectangle, _: mouse::Cursor) -> Vec<Geometry> {
|
||||
let mut frame = Frame::new(renderer, bounds.size());
|
||||
let (w, h) = (bounds.width, bounds.height);
|
||||
const LINES: usize = 14;
|
||||
for k in 0..LINES {
|
||||
let kf = k as f32;
|
||||
let base = h * (0.22 + kf * 0.028);
|
||||
let amp = h * (0.05 + kf * 0.006) * self.energy;
|
||||
let freq = 1.6 + kf * 0.09;
|
||||
let ph = self.phase * (0.35 + kf * 0.02) + kf * 0.5;
|
||||
let path = Path::new(|b| {
|
||||
let steps = (w / 6.0).ceil() as usize;
|
||||
for i in 0..=steps {
|
||||
let x = i as f32 * 6.0;
|
||||
let u = x / w;
|
||||
let y = base
|
||||
+ (u * std::f32::consts::PI * freq + ph).sin() * amp
|
||||
+ (u * std::f32::consts::PI * 4.2 - ph * 0.7).sin() * amp * 0.35;
|
||||
if i == 0 { b.move_to(Point::new(x, y)) } else { b.line_to(Point::new(x, y)) }
|
||||
}
|
||||
});
|
||||
let alpha = 0.08 + (kf / LINES as f32) * 0.55;
|
||||
frame.stroke(&path, Stroke::default().with_color(self.color.scale_alpha(alpha)).with_width(1.0 + kf * 0.08));
|
||||
}
|
||||
vec![frame.into_geometry()]
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether My Wave itself is what's playing.
|
||||
fn my_wave_state(p: &Player) -> Option<Status> {
|
||||
(p.wave_station() == Some(MY_WAVE)).then(|| p.status())
|
||||
}
|
||||
|
||||
/// The My Wave hero, on Home (`big = false`) and the My Wave screen.
|
||||
pub fn hero<'a>(
|
||||
t: &'static Tokens,
|
||||
player: &Player,
|
||||
phase: f32,
|
||||
settings: Option<WaveSettings>,
|
||||
big: bool,
|
||||
) -> Element<'a, Message> {
|
||||
let state = my_wave_state(player);
|
||||
let playing = state == Some(Status::Playing);
|
||||
let art = canvas_widget(WaveArt { phase, energy: if playing { 1.0 } else { 0.45 }, color: t.accent })
|
||||
.width(Fill)
|
||||
.height(Fill);
|
||||
|
||||
let blurb = match settings {
|
||||
Some(s) if s != WaveSettings::default() => format!(
|
||||
"Tuned to: {} mood, {} tracks, {} language.",
|
||||
s.mood.label().to_lowercase(),
|
||||
s.character.label().to_lowercase(),
|
||||
s.language.label().to_lowercase()
|
||||
),
|
||||
_ => "An endless stream picked from what you play, like and skip.".to_owned(),
|
||||
};
|
||||
|
||||
let (label, glyph, msg) = match state {
|
||||
Some(Status::Playing | Status::Loading) => ("Pause", Icon::Pause, Message::Player(player::Msg::Toggle)),
|
||||
Some(_) => ("Resume", Icon::Play, Message::Player(player::Msg::Toggle)),
|
||||
None => ("Play My Wave", Icon::Play, Message::PlayWave(MY_WAVE.to_owned())),
|
||||
};
|
||||
|
||||
let content = row![
|
||||
column![
|
||||
line("My Wave", theme::DISPLAY, if big { size::DISPLAY_XL } else { size::DISPLAY_M }, t.fg),
|
||||
container(para(blurb, size::BODY, t.muted)).max_width(420),
|
||||
]
|
||||
.spacing(6)
|
||||
.width(Fill),
|
||||
button(row![icon(glyph, t.accent_ink), line(label, theme::SEMIBOLD, size::BODY, t.accent_ink)].spacing(8).align_y(Alignment::Center))
|
||||
.padding([11, 18])
|
||||
.style(theme::primary)
|
||||
.on_press(msg),
|
||||
]
|
||||
.spacing(28)
|
||||
.align_y(Alignment::End);
|
||||
|
||||
let height = if big { 340.0 } else { 260.0 };
|
||||
container(stack![
|
||||
art,
|
||||
container(content).padding(Padding::from([26, 28])).height(Fill).align_y(iced::alignment::Vertical::Bottom),
|
||||
])
|
||||
.height(height)
|
||||
.width(Fill)
|
||||
.clip(true)
|
||||
.style(move |th| {
|
||||
let mut s = theme::card(th);
|
||||
s.border.radius = radius::HERO.into();
|
||||
s.background = Some(iced::Background::Gradient(
|
||||
iced::gradient::Linear::new(0.0)
|
||||
.add_stop(0.0, t.panel)
|
||||
.add_stop(1.0, theme::mix(t.panel, t.accent, 0.10))
|
||||
.into(),
|
||||
));
|
||||
s
|
||||
})
|
||||
.into()
|
||||
}
|
||||
|
||||
pub fn view<'a>(
|
||||
t: &'static Tokens,
|
||||
covers: &Covers,
|
||||
screen: &'a WaveScreen,
|
||||
hero: Element<'a, Message>,
|
||||
) -> Element<'a, Message> {
|
||||
let settings: Element<'a, Message> = match (&screen.settings, screen.shown()) {
|
||||
(_, Some(s)) => {
|
||||
let saving = screen.saving.is_some();
|
||||
row![
|
||||
setting(t, "Mood", Mood::ALL.map(|m| (m.label(), m == s.mood, WaveSettings { mood: m, ..s })), saving),
|
||||
setting(t, "Character", Character::ALL.map(|c| (c.label(), c == s.character, WaveSettings { character: c, ..s })), saving),
|
||||
setting(t, "Language", Language::ALL.map(|l| (l.label(), l == s.language, WaveSettings { language: l, ..s })), saving),
|
||||
]
|
||||
.spacing(28)
|
||||
.wrap()
|
||||
.vertical_spacing(18)
|
||||
.into()
|
||||
}
|
||||
(Loadable::Failed(e), None) => status(t, LoadState::Failed(e), "station settings", Message::LoadWave),
|
||||
_ => para("Loading your settings…", size::BODY, t.muted).into(),
|
||||
};
|
||||
|
||||
let stations: Element<'a, Message> = match &screen.stations {
|
||||
Loadable::Loaded(list) => {
|
||||
let others: Vec<&Station> = list.iter().filter(|s| s.id != MY_WAVE).collect();
|
||||
if others.is_empty() {
|
||||
para("No other stations suggested right now.", size::BODY, t.muted).into()
|
||||
} else {
|
||||
Row::with_children(others.into_iter().map(|s| station_tile(t, covers, s)))
|
||||
.spacing(12)
|
||||
.wrap()
|
||||
.vertical_spacing(14)
|
||||
.into()
|
||||
}
|
||||
}
|
||||
Loadable::Failed(e) => status(t, LoadState::Failed(e), "stations", Message::LoadWave),
|
||||
_ => para("Loading stations…", size::BODY, t.muted).into(),
|
||||
};
|
||||
|
||||
column![
|
||||
hero,
|
||||
settings,
|
||||
column![line("Stations", theme::SEMIBOLD, size::SECTION, t.fg), stations].spacing(14),
|
||||
]
|
||||
.spacing(34)
|
||||
.into()
|
||||
}
|
||||
|
||||
fn setting<'a, const N: usize>(
|
||||
t: &'static Tokens,
|
||||
title: &'a str,
|
||||
options: [(&'static str, bool, WaveSettings); N],
|
||||
saving: bool,
|
||||
) -> Element<'a, Message> {
|
||||
let chips = options.map(|(label, on, next)| {
|
||||
button(line(label, theme::MEDIUM, 13.5, if on { t.accent_ink } else { t.fg }))
|
||||
.padding([7, 13])
|
||||
.style(theme::chip(on))
|
||||
.on_press_maybe((!on && !saving).then_some(Message::SetWaveSettings(next)))
|
||||
.into()
|
||||
});
|
||||
column![line(title, theme::MEDIUM, size::BODY, t.muted), Row::with_children(chips).spacing(6)]
|
||||
.spacing(10)
|
||||
.into()
|
||||
}
|
||||
|
||||
fn station_tile<'a>(t: &'static Tokens, covers: &Covers, s: &Station) -> Element<'a, Message> {
|
||||
let tint = s.color.as_deref().and_then(super::browse::parse_hex).unwrap_or(t.raised);
|
||||
let art = container(covers::view(covers, s.icon_url(200), (0.0, 0.0), 96.0, 0.0))
|
||||
.center(card::WIDTH)
|
||||
.style(move |_| container::Style {
|
||||
background: Some(tint.into()),
|
||||
border: iced::Border { radius: radius::COVER.into(), ..Default::default() },
|
||||
..Default::default()
|
||||
});
|
||||
button(column![art, line(s.name.clone(), theme::MEDIUM, size::BODY, t.fg)].spacing(9).width(Length::Fixed(card::WIDTH)))
|
||||
.padding(6)
|
||||
.style(theme::nav_item(false))
|
||||
.on_press(Message::PlayWave(s.id.clone()))
|
||||
.into()
|
||||
}
|
||||
@@ -326,6 +326,28 @@ pub fn ghost(theme: &Theme, status: button::Status) -> button::Style {
|
||||
}
|
||||
}
|
||||
|
||||
/// A pill in a segmented choice (My Wave settings). The selected one is filled.
|
||||
pub fn chip(selected: bool) -> impl Fn(&Theme, button::Status) -> button::Style {
|
||||
move |theme, status| {
|
||||
let t = tokens(theme);
|
||||
let hovered = matches!(status, button::Status::Hovered | button::Status::Pressed);
|
||||
button::Style {
|
||||
background: if selected {
|
||||
Some(t.accent.into())
|
||||
} else {
|
||||
hovered.then(|| t.raised.into())
|
||||
},
|
||||
text_color: if selected { t.accent_ink } else { t.fg },
|
||||
border: Border {
|
||||
radius: radius::PILL.into(),
|
||||
..hairline(if selected { t.accent } else { t.line })
|
||||
},
|
||||
shadow: Shadow::default(),
|
||||
snap: true,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Tab in a tab strip (drawer Queue | Lyrics, collection tabs).
|
||||
pub fn tab(selected: bool) -> impl Fn(&Theme, button::Status) -> button::Style {
|
||||
move |theme, status| {
|
||||
|
||||
@@ -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