2548 lines
93 KiB
Rust
2548 lines
93 KiB
Rust
//! Complete Playback, Queue, Rotor/Vibe, Context Matching, Pinning, Favorites Filter,
|
||
//! Playlists CRUD, Offline Audio Cache & Telemetry engine on `AppState`.
|
||
|
||
use std::collections::HashSet;
|
||
use std::sync::atomic::Ordering;
|
||
use std::time::{Duration, Instant};
|
||
|
||
use crate::api::models::*;
|
||
use crate::api::signing::{generate_request_id, iso8601_now};
|
||
use crate::api::{find_offline_track_file, open_url_in_browser, remove_offline_track_file};
|
||
use crate::config::{AppConfig, PinnedItem};
|
||
|
||
use super::state::{ApiEvent, AppState, CollectionTab, RepeatMode, Route, SearchFilter};
|
||
|
||
impl AppState {
|
||
// =========================================================================
|
||
// 1. PLAYBACK & QUEUE ENGINE (All Audited Invariants Enforced!)
|
||
// =========================================================================
|
||
|
||
pub fn start_playing_index(&mut self, idx: usize) {
|
||
if idx >= self.queue.len() {
|
||
return;
|
||
}
|
||
self.queue_index = idx;
|
||
let track = self.queue[idx].clone();
|
||
|
||
// Reset `/plays` telemetry session for the new track
|
||
self.current_play_id = generate_request_id();
|
||
self.play_start_iso = iso8601_now();
|
||
self.play_seeked = false;
|
||
self.play_paused = false;
|
||
self.play_from_cache = false;
|
||
self.last_play_heartbeat = Instant::now();
|
||
|
||
// In VibeContext: send `radioStarted` (first track) + `trackStarted` & check prefetch!
|
||
if self.is_vibe_active {
|
||
if !self.vibe_started {
|
||
self.vibe_started = true;
|
||
self.send_rotor_feedback(RotorFeedbackKind::RadioStarted, None, None);
|
||
}
|
||
self.send_rotor_feedback(RotorFeedbackKind::TrackStarted, Some(&track), None);
|
||
self.maybe_prefetch_rotor_batch();
|
||
}
|
||
|
||
self.play_history.retain(|t| t.id != track.id);
|
||
self.play_history.insert(0, track.clone());
|
||
self.play_history.truncate(50);
|
||
|
||
// 1. Check local offline audio cache FIRST (works completely offline, zero network latency!)
|
||
let cache_dir = AppConfig::offline_cache_dir();
|
||
if let Some(local_path) = find_offline_track_file(&track.id, &cache_dir) {
|
||
self.play_from_cache = true;
|
||
let ext = local_path
|
||
.extension()
|
||
.and_then(|e| e.to_str())
|
||
.unwrap_or("mp3")
|
||
.to_lowercase();
|
||
let (codec_label, bitrate_kbps) = match ext.as_str() {
|
||
"flac" => ("FLAC (Offline)".to_string(), 1000),
|
||
"m4a" => ("AAC (Offline)".to_string(), 320),
|
||
_ => ("MP3 (Offline)".to_string(), 320),
|
||
};
|
||
let stream = ResolvedStream {
|
||
url: format!("file://{}", local_path.display()),
|
||
codec_label,
|
||
bitrate_kbps,
|
||
decrypt_key_hex: None,
|
||
gain_applied: false,
|
||
};
|
||
self.send_play_telemetry("start");
|
||
self.audio.load_stream(
|
||
track.id.clone(),
|
||
stream,
|
||
track.duration_ms,
|
||
track.r128_i,
|
||
track.r128_tp,
|
||
);
|
||
self.fetch_lyrics_async(&track);
|
||
self.ensure_words_for_current_track();
|
||
return;
|
||
}
|
||
|
||
// Report track start to `POST /plays`
|
||
self.send_play_telemetry("start");
|
||
self.fetch_lyrics_async(&track);
|
||
self.ensure_words_for_current_track();
|
||
|
||
if self.api.has_token() {
|
||
let api = self.api.clone();
|
||
let tx = self.tx_api.clone();
|
||
let tid = track.id.clone();
|
||
let dur = track.duration_ms;
|
||
let r128_i = track.r128_i;
|
||
let r128_tp = track.r128_tp;
|
||
let quality = self.config.audio_quality;
|
||
self.audio.state.is_buffering.store(true, Ordering::SeqCst);
|
||
self.runtime.spawn(async move {
|
||
let result = api
|
||
.resolve_track_stream(&tid, quality)
|
||
.await
|
||
.map_err(|e| e.to_string());
|
||
let _ = tx.send(ApiEvent::StreamResolved {
|
||
track_id: tid,
|
||
duration_ms: dur,
|
||
r128_i,
|
||
r128_tp,
|
||
result,
|
||
});
|
||
});
|
||
} else {
|
||
self.audio.stop();
|
||
self.login_modal_open = true;
|
||
self.show_toast(self.i18n().toast_sign_in_required());
|
||
}
|
||
}
|
||
|
||
fn fetch_lyrics_async(&mut self, track: &Track) {
|
||
self.current_lyrics = None;
|
||
self.fetch_lyrics_for_track(track);
|
||
}
|
||
|
||
pub fn fetch_lyrics_for_track(&mut self, track: &Track) {
|
||
if !self.api.has_token() {
|
||
return;
|
||
}
|
||
let api_l = self.api.clone();
|
||
let tx_l = self.tx_api.clone();
|
||
let tr_l = track.clone();
|
||
self.runtime.spawn(async move {
|
||
match api_l.fetch_lyrics(&tr_l).await {
|
||
Ok(lyr) => {
|
||
let _ = tx_l.send(ApiEvent::LyricsLoaded(lyr));
|
||
}
|
||
Err(e) => {
|
||
eprintln!("[lyrics] track {} failed: {}", tr_l.id, e);
|
||
}
|
||
}
|
||
});
|
||
}
|
||
|
||
/// Toggle play/pause: updates `play_paused` accurately and starts track if `duration_ms == 0`.
|
||
pub fn toggle_play(&mut self) {
|
||
if self.audio.state.duration_ms.load(Ordering::Relaxed) == 0 && !self.queue.is_empty() {
|
||
self.start_playing_index(self.queue_index);
|
||
} else {
|
||
let now_playing = self.audio.toggle_play();
|
||
self.play_paused = !now_playing;
|
||
}
|
||
}
|
||
|
||
pub fn seek_ms(&mut self, ms: u64) {
|
||
let dur = self.duration_ms();
|
||
let clamped = if dur > 0 { ms.min(dur) } else { ms };
|
||
self.play_seeked = true;
|
||
self.audio.seek_ms(clamped);
|
||
}
|
||
|
||
pub fn seek_fraction(&mut self, f: f32) {
|
||
let dur = self.duration_ms();
|
||
let target = (f.clamp(0.0, 1.0) * dur as f32) as u64;
|
||
self.seek_ms(target);
|
||
}
|
||
|
||
/// Public media-key hooks (called from OS hardware media keys / SMTC in `main.rs`)
|
||
pub fn media_toggle_play(&mut self) {
|
||
self.toggle_play();
|
||
}
|
||
|
||
pub fn media_next(&mut self) {
|
||
self.play_next();
|
||
}
|
||
|
||
pub fn media_prev(&mut self) {
|
||
self.play_prev();
|
||
}
|
||
|
||
pub fn media_stop(&mut self) {
|
||
self.audio.stop();
|
||
}
|
||
|
||
pub fn play_next(&mut self) {
|
||
self.advance_track(false, false);
|
||
}
|
||
|
||
/// Exact 5.129.0 advance logic: distinguishes natural finish (`auto_finish`), manual skip, and dislike auto-skip (`from_dislike`).
|
||
pub fn advance_track(&mut self, auto_finish: bool, from_dislike: bool) {
|
||
if self.queue.is_empty() {
|
||
return;
|
||
}
|
||
let pos_sec = self.audio.state.position_ms.load(Ordering::Relaxed) as f64 / 1000.0;
|
||
let curr = self.current_track().cloned();
|
||
|
||
let reason = if from_dislike {
|
||
"dislike"
|
||
} else if auto_finish {
|
||
"finish"
|
||
} else {
|
||
"skip"
|
||
};
|
||
self.send_play_telemetry(reason);
|
||
|
||
if self.is_vibe_active {
|
||
if auto_finish {
|
||
self.send_rotor_feedback(
|
||
RotorFeedbackKind::TrackFinished,
|
||
curr.as_ref(),
|
||
Some(pos_sec),
|
||
);
|
||
} else if !from_dislike {
|
||
self.send_rotor_feedback(RotorFeedbackKind::Skip, curr.as_ref(), Some(pos_sec));
|
||
}
|
||
}
|
||
|
||
if auto_finish && self.repeat == RepeatMode::One {
|
||
self.start_playing_index(self.queue_index);
|
||
return;
|
||
}
|
||
|
||
let next_idx = if self.queue_index + 1 < self.queue.len() {
|
||
self.queue_index + 1
|
||
} else if self.repeat == RepeatMode::All && !self.is_vibe_active {
|
||
0
|
||
} else if self.is_vibe_active {
|
||
0
|
||
} else {
|
||
self.audio.stop();
|
||
return;
|
||
};
|
||
self.start_playing_index(next_idx);
|
||
}
|
||
|
||
/// Exact 5.129.0 Prev Track:
|
||
/// - If `pos > 5000ms`: seek 0
|
||
/// - If `queue_index > 0`: step to `queue_index - 1`
|
||
/// - If `queue_index == 0`: wrap ONLY if `repeat == RepeatMode::All && !is_vibe_active`,
|
||
/// otherwise seek 0 (NEVER wrap to last track in RepeatOff, RepeatOne, or MyVibe!).
|
||
pub fn play_prev(&mut self) {
|
||
if self.queue.is_empty() {
|
||
return;
|
||
}
|
||
let pos = self.audio.state.position_ms.load(Ordering::Relaxed);
|
||
if pos > 5000 {
|
||
self.play_seeked = true;
|
||
self.audio.seek_ms(0);
|
||
return;
|
||
}
|
||
if self.queue_index == 0 {
|
||
if self.repeat == RepeatMode::All && !self.is_vibe_active {
|
||
self.send_play_telemetry("back_skip");
|
||
let last = self.queue.len() - 1;
|
||
self.start_playing_index(last);
|
||
} else {
|
||
self.play_seeked = true;
|
||
self.audio.seek_ms(0);
|
||
}
|
||
return;
|
||
}
|
||
let curr = self.current_track().cloned();
|
||
let pos_sec = pos as f64 / 1000.0;
|
||
self.send_play_telemetry("back_skip");
|
||
if self.is_vibe_active {
|
||
self.send_rotor_feedback(RotorFeedbackKind::Skip, curr.as_ref(), Some(pos_sec));
|
||
}
|
||
let prev_idx = self.queue_index - 1;
|
||
self.start_playing_index(prev_idx);
|
||
}
|
||
|
||
/// Start playing a track list:
|
||
/// - ALWAYS clears `unshuffled_queue`
|
||
/// - If `is_vibe`: forces `shuffle = false` and downgrades `RepeatMode::All -> RepeatMode::Off`
|
||
/// - If `!is_vibe && shuffle`: pins `start_index` at 0 and Fisher-Yates shuffles the rest!
|
||
pub fn play_tracks(
|
||
&mut self,
|
||
tracks: Vec<Track>,
|
||
start_index: usize,
|
||
context_name: String,
|
||
context_key: String,
|
||
is_vibe: bool,
|
||
) {
|
||
if tracks.is_empty() {
|
||
return;
|
||
}
|
||
self.unshuffled_queue.clear();
|
||
self.context_name = context_name;
|
||
self.context_key = context_key;
|
||
self.is_vibe_active = is_vibe;
|
||
|
||
let clamped_start = start_index.min(tracks.len() - 1);
|
||
if is_vibe {
|
||
self.shuffle = false;
|
||
if self.repeat == RepeatMode::All {
|
||
self.repeat = RepeatMode::Off;
|
||
}
|
||
self.queue = tracks;
|
||
self.start_playing_index(clamped_start);
|
||
} else if self.shuffle && tracks.len() > 1 {
|
||
self.unshuffled_queue = tracks.clone();
|
||
let mut rest = tracks;
|
||
let current = rest.remove(clamped_start);
|
||
let seed = self.start_time.elapsed().as_nanos() as u64 ^ 0x9E37_79B9_7F4A_7C15;
|
||
fisher_yates_shuffle(&mut rest, seed);
|
||
rest.insert(0, current);
|
||
self.queue = rest;
|
||
self.start_playing_index(0);
|
||
} else {
|
||
self.queue = tracks;
|
||
self.start_playing_index(clamped_start);
|
||
}
|
||
}
|
||
|
||
/// Context matching for Playlist / Album / Artist / Favorites header Play/Pause button!
|
||
pub fn is_context_active(&self, ctx_key: &str) -> bool {
|
||
!ctx_key.is_empty() && self.context_key == ctx_key && !self.queue.is_empty()
|
||
}
|
||
|
||
pub fn is_context_playing(&self, ctx_key: &str) -> bool {
|
||
self.is_context_active(ctx_key) && self.is_audio_playing()
|
||
}
|
||
|
||
pub fn toggle_context_play(
|
||
&mut self,
|
||
tracks: Vec<Track>,
|
||
context_name: String,
|
||
context_key: String,
|
||
is_vibe: bool,
|
||
) {
|
||
if self.is_context_active(&context_key) {
|
||
self.toggle_play();
|
||
} else {
|
||
self.play_tracks(tracks, 0, context_name, context_key, is_vibe);
|
||
}
|
||
}
|
||
|
||
/// Queue removal maintaining `queue_index` invariant:
|
||
/// - If `idx < queue_index`: decrement `queue_index -= 1`
|
||
/// - If `idx == queue_index`: cleanly advance or stop!
|
||
pub fn remove_queue_at(&mut self, idx: usize) {
|
||
if idx >= self.queue.len() {
|
||
return;
|
||
}
|
||
let was_playing = self.is_audio_playing();
|
||
let old_len = self.queue.len();
|
||
let removed = self.queue.remove(idx);
|
||
self.unshuffled_queue.retain(|t| t.id != removed.id);
|
||
|
||
self.show_toast(self.i18n().toast_removed_from_queue(&removed.title));
|
||
|
||
if self.queue.is_empty() {
|
||
self.queue_index = 0;
|
||
self.unshuffled_queue.clear();
|
||
self.audio.stop();
|
||
return;
|
||
}
|
||
|
||
if idx < self.queue_index {
|
||
self.queue_index -= 1;
|
||
} else if idx == self.queue_index {
|
||
if idx < old_len - 1 {
|
||
// Next track shifted into `self.queue_index`
|
||
if was_playing {
|
||
self.start_playing_index(self.queue_index);
|
||
}
|
||
} else if self.repeat == RepeatMode::All && !self.is_vibe_active {
|
||
self.queue_index = 0;
|
||
if was_playing {
|
||
self.start_playing_index(0);
|
||
}
|
||
} else {
|
||
self.queue_index = self.queue.len() - 1;
|
||
self.audio.stop();
|
||
}
|
||
}
|
||
}
|
||
|
||
/// Queue drag-and-drop reorder: moves item from `from` to `to` while keeping `queue_index`
|
||
/// pinned to the exact same currently playing track!
|
||
pub fn move_queue(&mut self, from: usize, to: usize) {
|
||
if from >= self.queue.len() || to >= self.queue.len() || from == to {
|
||
return;
|
||
}
|
||
let item = self.queue.remove(from);
|
||
self.queue.insert(to, item);
|
||
|
||
if self.queue_index == from {
|
||
self.queue_index = to;
|
||
} else if from < self.queue_index && self.queue_index <= to {
|
||
self.queue_index -= 1;
|
||
} else if to <= self.queue_index && self.queue_index < from {
|
||
self.queue_index += 1;
|
||
}
|
||
}
|
||
|
||
pub fn clear_queue(&mut self) {
|
||
self.queue.clear();
|
||
self.unshuffled_queue.clear();
|
||
self.queue_index = 0;
|
||
self.context_key.clear();
|
||
self.audio.stop();
|
||
}
|
||
|
||
pub fn add_to_queue(&mut self, track: Track) {
|
||
self.show_toast(self.i18n().toast_play_last(&track.title));
|
||
self.queue.push(track);
|
||
}
|
||
|
||
pub fn play_next_track(&mut self, track: Track) {
|
||
self.show_toast(self.i18n().toast_play_next(&track.title));
|
||
let pos = if self.queue.is_empty() {
|
||
0
|
||
} else {
|
||
(self.queue_index + 1).min(self.queue.len())
|
||
};
|
||
self.queue.insert(pos, track);
|
||
}
|
||
|
||
pub fn add_tracks_to_queue(&mut self, tracks: Vec<Track>) {
|
||
if tracks.is_empty() {
|
||
return;
|
||
}
|
||
let count = tracks.len();
|
||
self.queue.extend(tracks);
|
||
self.show_toast(if self.i18n().is_ru() {
|
||
format!("Добавлено в конец очереди: {}", self.i18n().count_tracks(count))
|
||
} else {
|
||
format!("Added to end of queue: {}", self.i18n().count_tracks(count))
|
||
});
|
||
}
|
||
|
||
pub fn play_tracks_next(&mut self, tracks: Vec<Track>) {
|
||
if tracks.is_empty() {
|
||
return;
|
||
}
|
||
let count = tracks.len();
|
||
let insert_pos = if self.queue.is_empty() {
|
||
0
|
||
} else {
|
||
(self.queue_index + 1).min(self.queue.len())
|
||
};
|
||
for (offset, tr) in tracks.into_iter().enumerate() {
|
||
self.queue.insert(insert_pos + offset, tr);
|
||
}
|
||
self.show_toast(if self.i18n().is_ru() {
|
||
format!("Добавлено в начало очереди: {}", self.i18n().count_tracks(count))
|
||
} else {
|
||
format!("Added to play next: {}", self.i18n().count_tracks(count))
|
||
});
|
||
}
|
||
|
||
/// Exact 5.129.0 Fisher-Yates pinned Shuffle (`9091` mod 28692):
|
||
/// Forbidden in My Vibe. Enable -> pins current track at index 0, shuffles rest.
|
||
/// Disable -> restores original order and current track's original index!
|
||
pub fn toggle_shuffle(&mut self) {
|
||
let t = self.i18n();
|
||
if self.is_vibe_active {
|
||
self.shuffle = false;
|
||
self.show_toast(t.toast_shuffle_vibe_managed());
|
||
return;
|
||
}
|
||
self.shuffle = !self.shuffle;
|
||
if self.queue.len() > 1 {
|
||
if self.shuffle {
|
||
self.unshuffled_queue = self.queue.clone();
|
||
let current = self.queue.remove(self.queue_index);
|
||
let seed = self.start_time.elapsed().as_nanos() as u64 ^ 0x9E37_79B9_7F4A_7C15;
|
||
fisher_yates_shuffle(&mut self.queue, seed);
|
||
self.queue.insert(0, current);
|
||
self.queue_index = 0;
|
||
} else if !self.unshuffled_queue.is_empty() {
|
||
let current_id = self.current_track().map(|tr| tr.id.clone());
|
||
self.queue = std::mem::take(&mut self.unshuffled_queue);
|
||
if let Some(cid) = current_id {
|
||
if let Some(orig_idx) = self.queue.iter().position(|tr| tr.id == cid) {
|
||
self.queue_index = orig_idx;
|
||
}
|
||
}
|
||
}
|
||
}
|
||
self.show_toast(if self.shuffle {
|
||
t.toast_shuffle_on()
|
||
} else {
|
||
t.toast_shuffle_off()
|
||
});
|
||
}
|
||
|
||
/// Exact 5.129.0 Repeat Cycle (`Off -> All -> One -> Off`; in VibeContext toggles `Off <-> One` ONLY!)
|
||
pub fn cycle_repeat(&mut self) {
|
||
self.repeat = if self.is_vibe_active {
|
||
match self.repeat {
|
||
RepeatMode::Off => RepeatMode::One,
|
||
RepeatMode::One | RepeatMode::All => RepeatMode::Off,
|
||
}
|
||
} else {
|
||
self.repeat.next()
|
||
};
|
||
let t = self.i18n();
|
||
self.show_toast(match self.repeat {
|
||
RepeatMode::Off => t.toast_repeat_off(),
|
||
RepeatMode::All => t.toast_repeat_all(),
|
||
RepeatMode::One => t.toast_repeat_one(),
|
||
});
|
||
}
|
||
|
||
fn ensure_current_lyrics_loaded(&mut self) {
|
||
if let Some(tr) = self.current_track().cloned() {
|
||
let already_loaded = self
|
||
.current_lyrics
|
||
.as_ref()
|
||
.map_or(false, |l| l.track_id == tr.id && !l.lines.is_empty());
|
||
if !already_loaded {
|
||
self.fetch_lyrics_for_track(&tr);
|
||
}
|
||
}
|
||
}
|
||
|
||
/// Official 5.129.0 `fullscreenPlayer.showSyncLyrics()`: opens Fullscreen directly in 50/50 SyncLyrics split mode.
|
||
pub fn open_fullscreen_sync_lyrics(&mut self) {
|
||
self.fullscreen_open = true;
|
||
self.fullscreen_lyrics_open = true;
|
||
self.fullscreen_queue_open = false;
|
||
self.right_drawer = super::state::RightDrawerTab::None;
|
||
self.ensure_current_lyrics_loaded();
|
||
}
|
||
|
||
/// Official 5.129.0 `fullscreenPlayer.showPlayQueue()`: opens Fullscreen directly in 50/50 PlayQueue split mode.
|
||
pub fn open_fullscreen_queue(&mut self) {
|
||
self.fullscreen_open = true;
|
||
self.fullscreen_queue_open = true;
|
||
self.fullscreen_lyrics_open = false;
|
||
self.right_drawer = super::state::RightDrawerTab::None;
|
||
}
|
||
|
||
/// Toggles fullscreen synced lyrics split panel WITHOUT closing `fullscreen_open`!
|
||
pub fn toggle_fullscreen_lyrics(&mut self) {
|
||
self.fullscreen_lyrics_open = !self.fullscreen_lyrics_open;
|
||
if self.fullscreen_lyrics_open {
|
||
self.fullscreen_queue_open = false;
|
||
self.ensure_current_lyrics_loaded();
|
||
}
|
||
}
|
||
|
||
/// Toggles fullscreen play queue split panel WITHOUT closing `fullscreen_open`!
|
||
pub fn toggle_fullscreen_queue(&mut self) {
|
||
self.fullscreen_queue_open = !self.fullscreen_queue_open;
|
||
if self.fullscreen_queue_open {
|
||
self.fullscreen_lyrics_open = false;
|
||
}
|
||
}
|
||
|
||
/// Parses `self.context_key` (`likes`, `likes:*`, `album:{id}`, `artist:{id}`, `playlist:{uid}:{kind}`)
|
||
/// and navigates directly to the active playback source context.
|
||
pub fn navigate_to_current_context(&mut self) {
|
||
let key = self.context_key.trim().to_string();
|
||
if key.is_empty() {
|
||
return;
|
||
}
|
||
if key == "likes" || key.starts_with("likes:") {
|
||
self.navigate(Route::LikedTracks);
|
||
return;
|
||
}
|
||
if let Some(id) = key.strip_prefix("album:") {
|
||
if !id.is_empty() {
|
||
let title = if self.context_name.is_empty() {
|
||
self.i18n().album().to_string()
|
||
} else {
|
||
self.context_name.clone()
|
||
};
|
||
self.navigate(Route::Album {
|
||
id: id.to_string(),
|
||
title,
|
||
});
|
||
}
|
||
return;
|
||
}
|
||
if let Some(id) = key.strip_prefix("artist:") {
|
||
if !id.is_empty() {
|
||
let name = if self.context_name.is_empty() {
|
||
self.i18n().artist().to_string()
|
||
} else {
|
||
self.context_name.clone()
|
||
};
|
||
self.navigate(Route::Artist {
|
||
id: id.to_string(),
|
||
name,
|
||
});
|
||
}
|
||
return;
|
||
}
|
||
if let Some(rest) = key.strip_prefix("playlist:") {
|
||
let mut parts = rest.splitn(2, ':');
|
||
if let (Some(uid), Some(kind)) = (parts.next(), parts.next()) {
|
||
if !uid.is_empty() && !kind.is_empty() {
|
||
let title = if self.context_name.is_empty() {
|
||
self.i18n().playlist().to_string()
|
||
} else {
|
||
self.context_name.clone()
|
||
};
|
||
self.navigate(Route::Playlist {
|
||
owner_uid: uid.to_string(),
|
||
kind: kind.to_string(),
|
||
title,
|
||
});
|
||
}
|
||
}
|
||
}
|
||
}
|
||
|
||
/// Official 5.129.0 `RESET_VIBE_CONTEXT_BUTTON`: resets playback context back to default My Vibe.
|
||
pub fn reset_context_to_my_vibe(&mut self) {
|
||
let default_vibe = self.i18n().my_vibe().to_string();
|
||
self.target_hue = 0.12;
|
||
self.config.vibe_mood = None;
|
||
self.config.vibe_activity = None;
|
||
self.config.vibe_character = None;
|
||
self.config.vibe_language = None;
|
||
self.save_config();
|
||
self.is_vibe_active = true;
|
||
self.active_vibe_title = default_vibe.clone();
|
||
self.context_name = default_vibe.clone();
|
||
self.context_key = "vibe:user:onyourwave".into();
|
||
self.start_vibe_by_seeds(default_vibe, vec!["user:onyourwave".to_string()]);
|
||
}
|
||
|
||
// =========================================================================
|
||
// 1b. OFFICIAL 5.129.0 AI WORDS CARDS (Facts, Replies, BigCard & Feedback)
|
||
// =========================================================================
|
||
|
||
pub fn current_words_card(&self) -> Option<&WordsCard> {
|
||
let tr = self.current_track()?;
|
||
let clean_id = tr.id.split(':').next().unwrap_or(&tr.id);
|
||
self.words_cards
|
||
.get(&tr.id)
|
||
.or_else(|| self.words_cards.get(clean_id))
|
||
}
|
||
|
||
pub fn current_words_feedback_message(&self) -> Option<&str> {
|
||
let (ref msg, at) = self.words_feedback_message.as_ref()?;
|
||
if at.elapsed() < Duration::from_secs(3) {
|
||
Some(msg.as_str())
|
||
} else {
|
||
None
|
||
}
|
||
}
|
||
|
||
pub fn clear_words_cache(&mut self) {
|
||
self.words_cards.clear();
|
||
self.words_loading_tracks.clear();
|
||
self.words_empty_tracks.clear();
|
||
self.words_big_card = None;
|
||
self.words_big_card_loading = false;
|
||
self.words_big_card_open = false;
|
||
self.words_feedback_message = None;
|
||
}
|
||
|
||
pub fn ensure_words_for_current_track(&mut self) {
|
||
if !self.api.has_token() {
|
||
return;
|
||
}
|
||
let Some(curr) = self.current_track() else {
|
||
return;
|
||
};
|
||
let curr_clean = curr.id.split(':').next().unwrap_or(&curr.id).to_string();
|
||
if self.words_cards.contains_key(&curr_clean)
|
||
|| self.words_loading_tracks.contains(&curr_clean)
|
||
|| self.words_empty_tracks.contains(&curr_clean)
|
||
{
|
||
return;
|
||
}
|
||
|
||
// Batch current track + up to 2 upcoming tracks so skipping on My Vibe feels instant!
|
||
let mut req_ids: Vec<String> = Vec::new();
|
||
for offset in 0..3 {
|
||
if let Some(tr) = self.queue.get(self.queue_index + offset) {
|
||
let clean = tr.id.split(':').next().unwrap_or(&tr.id).to_string();
|
||
if !clean.is_empty()
|
||
&& !self.words_cards.contains_key(&clean)
|
||
&& !self.words_loading_tracks.contains(&clean)
|
||
&& !self.words_empty_tracks.contains(&clean)
|
||
&& !req_ids.contains(&clean)
|
||
{
|
||
self.words_loading_tracks.insert(clean.clone());
|
||
req_ids.push(clean);
|
||
}
|
||
}
|
||
}
|
||
if req_ids.is_empty() {
|
||
return;
|
||
}
|
||
|
||
let wave_seeds: Option<Vec<String>> = if self.is_vibe_active {
|
||
let parsed: Vec<String> = self
|
||
.context_key
|
||
.strip_prefix("vibe:")
|
||
.map(|s| {
|
||
s.split(',')
|
||
.map(str::trim)
|
||
.filter(|p| !p.is_empty())
|
||
.map(String::from)
|
||
.collect()
|
||
})
|
||
.unwrap_or_default();
|
||
if parsed.is_empty() {
|
||
Some(vec!["user:onyourwave".to_string()])
|
||
} else {
|
||
Some(parsed)
|
||
}
|
||
} else {
|
||
None
|
||
};
|
||
|
||
let api = self.api.clone();
|
||
let tx = self.tx_api.clone();
|
||
self.runtime.spawn(async move {
|
||
match api
|
||
.fetch_words_cards(&req_ids, wave_seeds.as_deref())
|
||
.await
|
||
{
|
||
Ok(entries) => {
|
||
let _ = tx.send(ApiEvent::WordsCardsLoaded(entries));
|
||
}
|
||
Err(e) => {
|
||
log::debug!("[words] /words/cards failed: {}", e);
|
||
let empty = req_ids.into_iter().map(|id| (id, None)).collect();
|
||
let _ = tx.send(ApiEvent::WordsCardsLoaded(empty));
|
||
}
|
||
}
|
||
});
|
||
}
|
||
|
||
pub fn open_words_big_card(&mut self, track_id: String) {
|
||
let clean_id = track_id.split(':').next().unwrap_or(&track_id).to_string();
|
||
self.words_big_card_open = true;
|
||
let maybe_req = self
|
||
.words_cards
|
||
.get(&track_id)
|
||
.or_else(|| self.words_cards.get(&clean_id))
|
||
.and_then(|c| c.big_card_ids.first().map(|bid| (bid.clone(), c.id.clone())));
|
||
|
||
let Some((big_card_id, card_id)) = maybe_req else {
|
||
self.words_big_card_loading = false;
|
||
return;
|
||
};
|
||
|
||
if self
|
||
.words_big_card
|
||
.as_ref()
|
||
.map_or(false, |bc| bc.id == big_card_id)
|
||
{
|
||
self.words_big_card_loading = false;
|
||
return;
|
||
}
|
||
|
||
self.words_big_card = None;
|
||
if !self.api.has_token() {
|
||
self.words_big_card_loading = false;
|
||
return;
|
||
}
|
||
|
||
self.words_big_card_loading = true;
|
||
let api = self.api.clone();
|
||
let tx = self.tx_api.clone();
|
||
self.runtime.spawn(async move {
|
||
let res = api
|
||
.fetch_words_big_card(&big_card_id, &clean_id, &card_id)
|
||
.await
|
||
.ok()
|
||
.flatten();
|
||
let _ = tx.send(ApiEvent::WordsBigCardLoaded(res));
|
||
});
|
||
}
|
||
|
||
pub fn send_words_feedback(&mut self, track_id: String, card_id: String, state: String) {
|
||
let clean_id = track_id.split(':').next().unwrap_or(&track_id).to_string();
|
||
let norm_state = if state.eq_ignore_ascii_case("neutral") {
|
||
None
|
||
} else {
|
||
Some(state.clone())
|
||
};
|
||
let lookup_key = if self.words_cards.contains_key(&track_id) {
|
||
&track_id
|
||
} else {
|
||
&clean_id
|
||
};
|
||
if let Some(card) = self.words_cards.get_mut(lookup_key) {
|
||
card.feedback_state = norm_state;
|
||
}
|
||
|
||
let t = self.i18n();
|
||
if state.eq_ignore_ascii_case("dislike") {
|
||
self.words_big_card_open = false;
|
||
self.words_big_card_loading = false;
|
||
self.words_feedback_message =
|
||
Some((t.words_feedback_dislike().to_string(), Instant::now()));
|
||
} else if state.eq_ignore_ascii_case("like") {
|
||
self.words_feedback_message =
|
||
Some((t.words_feedback_like().to_string(), Instant::now()));
|
||
}
|
||
|
||
if self.api.has_token() && !card_id.is_empty() {
|
||
let api = self.api.clone();
|
||
self.runtime.spawn(async move {
|
||
let _ = api.send_words_feedback(&card_id, &state).await;
|
||
});
|
||
}
|
||
}
|
||
|
||
// =========================================================================
|
||
// 2. LIKES, DISLIKES & PINS (Playlist, Album, Artist, Liked, Wave)
|
||
// =========================================================================
|
||
|
||
pub fn toggle_like(&mut self, track: Track) {
|
||
let t = self.i18n();
|
||
let now_liked = !self.liked_ids.contains(&track.id);
|
||
if now_liked {
|
||
self.liked_ids.insert(track.id.clone());
|
||
self.disliked_ids.remove(&track.id);
|
||
self.liked_tracks.retain(|tr| tr.id != track.id);
|
||
self.liked_tracks.insert(0, track.clone());
|
||
self.show_toast(t.toast_track_liked(&track.title));
|
||
} else {
|
||
self.liked_ids.remove(&track.id);
|
||
self.liked_tracks.retain(|tr| tr.id != track.id);
|
||
self.show_toast(t.toast_track_unliked(&track.title));
|
||
}
|
||
|
||
if self.is_vibe_active {
|
||
self.send_rotor_feedback(
|
||
if now_liked {
|
||
RotorFeedbackKind::Like
|
||
} else {
|
||
RotorFeedbackKind::Unlike
|
||
},
|
||
Some(&track),
|
||
None,
|
||
);
|
||
}
|
||
|
||
if let Some(ref acc) = self.account {
|
||
let api = self.api.clone();
|
||
let uid = acc.uid;
|
||
let tid = track.id.clone();
|
||
self.runtime.spawn(async move {
|
||
let _ = api.set_like(uid, &tid, now_liked).await;
|
||
});
|
||
}
|
||
}
|
||
|
||
pub fn toggle_dislike(&mut self, track: Track) {
|
||
let t = self.i18n();
|
||
let now_dis = !self.disliked_ids.contains(&track.id);
|
||
let pos_sec = self.audio.state.position_ms.load(Ordering::Relaxed) as f64 / 1000.0;
|
||
if now_dis {
|
||
self.disliked_ids.insert(track.id.clone());
|
||
self.liked_ids.remove(&track.id);
|
||
self.liked_tracks.retain(|tr| tr.id != track.id);
|
||
self.show_toast(t.toast_track_disliked());
|
||
if self.is_vibe_active {
|
||
self.send_rotor_feedback(RotorFeedbackKind::Dislike, Some(&track), Some(pos_sec));
|
||
if self.queue_index + 2 < self.queue.len() {
|
||
self.queue.truncate(self.queue_index + 2);
|
||
}
|
||
self.maybe_prefetch_rotor_batch();
|
||
}
|
||
if self.current_track().map(|tr| tr.id.as_str()) == Some(track.id.as_str()) {
|
||
self.advance_track(false, true);
|
||
}
|
||
} else {
|
||
self.disliked_ids.remove(&track.id);
|
||
self.show_toast(t.toast_track_undisliked());
|
||
if self.is_vibe_active {
|
||
self.send_rotor_feedback(RotorFeedbackKind::Undislike, Some(&track), None);
|
||
}
|
||
}
|
||
|
||
if let Some(ref acc) = self.account {
|
||
let api = self.api.clone();
|
||
let uid = acc.uid;
|
||
let tid = track.rotor_track_id();
|
||
self.runtime.spawn(async move {
|
||
let _ = api.set_dislike(uid, &tid, now_dis).await;
|
||
});
|
||
}
|
||
}
|
||
|
||
/// Check whether an entity (`kind` = `"likes"` | `"playlist"` | `"album"` | `"artist"` | `"wave"`) is currently pinned.
|
||
pub fn is_pinned(&self, kind: &str, id: &str) -> bool {
|
||
self.config.pinned_items.iter().any(|p| pin_matches(p, kind, id))
|
||
}
|
||
|
||
/// Toggle pin/unpin for Playlist, Album, Artist, Liked (`kind = "likes"`), AND Wave!
|
||
/// Returns `true` if the item is now pinned, `false` if unpinned.
|
||
pub fn toggle_pin(
|
||
&mut self,
|
||
kind: &str,
|
||
id: &str,
|
||
title: &str,
|
||
subtitle: &str,
|
||
cover_uri: Option<String>,
|
||
owner_uid: Option<String>,
|
||
) -> bool {
|
||
let t = self.i18n();
|
||
if self.is_pinned(kind, id) {
|
||
let removed_pin = self
|
||
.config
|
||
.pinned_items
|
||
.iter()
|
||
.find(|p| pin_matches(p, kind, id))
|
||
.cloned();
|
||
self.config
|
||
.pinned_items
|
||
.retain(|p| !pin_matches(p, kind, id));
|
||
self.save_config();
|
||
self.show_toast(t.toast_unpinned(kind, title));
|
||
if let Some(pin) = removed_pin {
|
||
self.sync_pin_remote(pin, false);
|
||
}
|
||
false
|
||
} else {
|
||
// Exact 5.129.0 `pinsCollection` rule: max 30 pins (evict oldest from end, unshift new at front)
|
||
if self.config.pinned_items.len() >= 30 {
|
||
self.config.pinned_items.pop();
|
||
}
|
||
let pin = PinnedItem {
|
||
id: id.to_string(),
|
||
kind: kind.to_string(),
|
||
title: title.to_string(),
|
||
subtitle: subtitle.to_string(),
|
||
cover_uri,
|
||
owner_uid,
|
||
};
|
||
self.config.pinned_items.insert(0, pin.clone());
|
||
self.save_config();
|
||
self.show_toast(t.toast_pinned(kind, title));
|
||
self.sync_pin_remote(pin, true);
|
||
true
|
||
}
|
||
}
|
||
|
||
pub fn unpin_item(&mut self, pin: PinnedItem) {
|
||
let t = self.i18n();
|
||
self.config
|
||
.pinned_items
|
||
.retain(|p| !pin_matches(p, &pin.kind, &pin.id));
|
||
self.save_config();
|
||
self.show_toast(t.toast_unpinned(&pin.kind, &pin.title));
|
||
self.sync_pin_remote(pin, false);
|
||
}
|
||
|
||
fn sync_pin_remote(&self, pin: PinnedItem, pinned: bool) {
|
||
if !self.api.has_token() {
|
||
return;
|
||
}
|
||
let api = self.api.clone();
|
||
let my_uid = self.account.as_ref().map(|a| a.uid.to_string());
|
||
self.runtime.spawn(async move {
|
||
match pin.kind.as_str() {
|
||
"likes" => {
|
||
if let Some(uid) = pin.owner_uid.or(my_uid) {
|
||
let _ = api.pin_playlist(&uid, "3", pinned).await;
|
||
}
|
||
}
|
||
"playlist" => {
|
||
let (owner, kind) = if let Some((o, k)) = pin.id.split_once(':') {
|
||
(o.to_string(), k.to_string())
|
||
} else {
|
||
(pin.owner_uid.or(my_uid).unwrap_or_default(), pin.id)
|
||
};
|
||
if !owner.is_empty() {
|
||
let _ = api.pin_playlist(&owner, &kind, pinned).await;
|
||
}
|
||
}
|
||
"album" => {
|
||
let _ = api.pin_album(&pin.id, pinned).await;
|
||
}
|
||
"artist" => {
|
||
let _ = api.pin_artist(&pin.id, pinned).await;
|
||
}
|
||
"wave" => {
|
||
let seeds: Vec<String> = pin
|
||
.id
|
||
.split(',')
|
||
.filter(|s| !s.is_empty())
|
||
.map(String::from)
|
||
.collect();
|
||
if !seeds.is_empty() {
|
||
let _ = api.pin_wave(&seeds, pinned).await;
|
||
}
|
||
}
|
||
_ => {}
|
||
}
|
||
});
|
||
}
|
||
|
||
// =========================================================================
|
||
// 3. FAVORITES FILTER TAGS (`POST /filters/tracks` + Offline Graceful Fallback)
|
||
// =========================================================================
|
||
|
||
pub fn select_favorite_filter(&mut self, filter_id: Option<String>) {
|
||
match filter_id {
|
||
None => self.selected_favorite_filter_id = None,
|
||
Some(ref id) if id == "all" || id.is_empty() => {
|
||
self.selected_favorite_filter_id = None;
|
||
}
|
||
Some(id) => {
|
||
self.selected_favorite_filter_id = Some(id.clone());
|
||
if self.api.has_token() {
|
||
let api = self.api.clone();
|
||
self.runtime.spawn(async move {
|
||
let _ = api.fetch_filter_name(&id).await;
|
||
});
|
||
}
|
||
}
|
||
}
|
||
}
|
||
|
||
/// Returns the active list of Favorites filter chips:
|
||
/// - Real server-normalized chips from `POST /filters/tracks` (>=8 tracks per chip, max 8 chips) when loaded
|
||
/// - Graceful offline/demo fallback chips derived from `liked_tracks` when offline/unauthenticated
|
||
pub fn effective_favorite_filters(&self) -> Vec<TrackFilterChip> {
|
||
if !self.favorite_filters.is_empty() {
|
||
return self.favorite_filters.clone();
|
||
}
|
||
if self.liked_tracks.len() < 2 {
|
||
return Vec::new();
|
||
}
|
||
let ru = self.config.language.is_ru();
|
||
let all_ids: HashSet<String> = self.liked_tracks.iter().map(|t| t.id.clone()).collect();
|
||
let mut chips = vec![TrackFilterChip {
|
||
id: "all".into(),
|
||
name: if ru { "Все".into() } else { "All".into() },
|
||
track_ids: all_ids,
|
||
}];
|
||
|
||
// Partition tracks into deterministic non-empty local buckets so offline/demo clicks genuinely filter!
|
||
let presets: &[(&str, &str, &str)] = &[
|
||
("fallback:lossless", "Lossless", "Lossless"),
|
||
("fallback:lyrics", "С текстом", "With lyrics"),
|
||
("fallback:energetic", "Бодрое", "Cheerful"),
|
||
("fallback:calm", "Спокойное", "Calm"),
|
||
];
|
||
for (idx, (id, name_ru, name_en)) in presets.iter().enumerate() {
|
||
let ids: HashSet<String> = self
|
||
.liked_tracks
|
||
.iter()
|
||
.enumerate()
|
||
.filter(|(i, tr)| match idx {
|
||
0 => tr.has_lossless,
|
||
1 => tr.has_lyrics,
|
||
2 => i % 2 == 0,
|
||
_ => i % 2 == 1,
|
||
})
|
||
.map(|(_, tr)| tr.id.clone())
|
||
.collect();
|
||
if !ids.is_empty() && ids.len() < self.liked_tracks.len() {
|
||
chips.push(TrackFilterChip {
|
||
id: (*id).to_string(),
|
||
name: if ru {
|
||
(*name_ru).to_string()
|
||
} else {
|
||
(*name_en).to_string()
|
||
},
|
||
track_ids: ids,
|
||
});
|
||
}
|
||
}
|
||
chips.truncate(8);
|
||
chips
|
||
}
|
||
|
||
/// Returns `liked_tracks` filtered by `selected_favorite_filter_id` (and optional text query).
|
||
pub fn filtered_liked_tracks(&self) -> Vec<Track> {
|
||
let base: Vec<Track> = match &self.selected_favorite_filter_id {
|
||
None => self.liked_tracks.clone(),
|
||
Some(sel_id) if sel_id == "all" => self.liked_tracks.clone(),
|
||
Some(sel_id) => {
|
||
let chips = self.effective_favorite_filters();
|
||
if let Some(chip) = chips.iter().find(|c| &c.id == sel_id) {
|
||
self.liked_tracks
|
||
.iter()
|
||
.filter(|tr| chip.matches_track(tr))
|
||
.cloned()
|
||
.collect()
|
||
} else {
|
||
self.liked_tracks.clone()
|
||
}
|
||
}
|
||
};
|
||
|
||
let q = self.detail_track_filter.trim().to_lowercase();
|
||
if q.is_empty() {
|
||
base
|
||
} else {
|
||
base.into_iter()
|
||
.filter(|tr| {
|
||
tr.title.to_lowercase().contains(&q)
|
||
|| tr.artists_string().to_lowercase().contains(&q)
|
||
|| tr
|
||
.album_title
|
||
.as_deref()
|
||
.map_or(false, |a| a.to_lowercase().contains(&q))
|
||
})
|
||
.collect()
|
||
}
|
||
}
|
||
|
||
// =========================================================================
|
||
// 4. DEBOUNCED LIVE SEARCH
|
||
// =========================================================================
|
||
|
||
pub fn set_search_query(&mut self, query: String) {
|
||
self.search_query = query;
|
||
if self.search_query.trim().is_empty() {
|
||
self.search_debounce_deadline = None;
|
||
self.search_results = None;
|
||
self.search_loading = false;
|
||
} else {
|
||
self.search_debounce_deadline = Some(Instant::now() + Duration::from_millis(500));
|
||
}
|
||
}
|
||
|
||
pub fn run_search(&mut self, query: String, filter: SearchFilter) {
|
||
let q = query.trim().to_string();
|
||
if q.is_empty() {
|
||
return;
|
||
}
|
||
self.search_loading = true;
|
||
self.config.search_history.retain(|s| s != &q);
|
||
self.config.search_history.insert(0, q.clone());
|
||
self.config.search_history.truncate(12);
|
||
self.save_config();
|
||
|
||
let api = self.api.clone();
|
||
let tx = self.tx_api.clone();
|
||
let fallback_tracks = self.landing.chart_tracks.clone();
|
||
let api_filter = filter.api_filter().map(String::from);
|
||
self.runtime.spawn(async move {
|
||
match api.search_instant(&q, api_filter.as_deref()).await {
|
||
Ok(res) => {
|
||
let _ = tx.send(ApiEvent::SearchLoaded(res));
|
||
}
|
||
Err(_) => {
|
||
let ql = q.to_lowercase();
|
||
let matched: Vec<Track> = fallback_tracks
|
||
.into_iter()
|
||
.filter(|tr| {
|
||
tr.title.to_lowercase().contains(&ql)
|
||
|| tr.artists_string().to_lowercase().contains(&ql)
|
||
})
|
||
.collect();
|
||
let _ = tx.send(ApiEvent::SearchLoaded(SearchResults {
|
||
query: q,
|
||
best_kind: matched.first().map(|_| "track".into()),
|
||
best_track: matched.first().cloned(),
|
||
best_artist: None,
|
||
best_album: None,
|
||
best_playlist: None,
|
||
tracks: matched,
|
||
artists: vec![],
|
||
albums: vec![],
|
||
playlists: vec![],
|
||
}));
|
||
}
|
||
}
|
||
});
|
||
}
|
||
|
||
// =========================================================================
|
||
// 5. MY VIBE & WHEEL INTERACTIONS
|
||
// =========================================================================
|
||
|
||
pub fn toggle_my_vibe(&mut self) {
|
||
if self.is_vibe_active && self.audio.state.duration_ms.load(Ordering::Relaxed) > 0 {
|
||
self.toggle_play();
|
||
return;
|
||
}
|
||
let default_title = self.i18n().my_vibe().to_string();
|
||
self.active_vibe_title = default_title.clone();
|
||
self.target_hue = 0.12;
|
||
if !self.landing.vibe_tracks.is_empty() {
|
||
let tracks = self.landing.vibe_tracks.clone();
|
||
self.play_tracks(
|
||
tracks,
|
||
0,
|
||
default_title,
|
||
"vibe:user:onyourwave".into(),
|
||
true,
|
||
);
|
||
} else {
|
||
self.is_vibe_active = true;
|
||
self.shuffle = false;
|
||
if self.repeat == RepeatMode::All {
|
||
self.repeat = RepeatMode::Off;
|
||
}
|
||
}
|
||
if self.api.has_token() {
|
||
let mut seeds = vec!["user:onyourwave".to_string()];
|
||
if let Some(ref m) = self.config.vibe_mood {
|
||
seeds.push(format!("settingMoodEnergy:{}", m));
|
||
}
|
||
if let Some(ref a) = self.config.vibe_activity {
|
||
seeds.push(format!("activity:{}", a));
|
||
}
|
||
if let Some(ref c) = self.config.vibe_character {
|
||
seeds.push(format!("settingDiversity:{}", c));
|
||
}
|
||
if let Some(ref l) = self.config.vibe_language {
|
||
seeds.push(format!("settingLanguage:{}", l));
|
||
}
|
||
let api = self.api.clone();
|
||
let tx = self.tx_api.clone();
|
||
self.runtime.spawn(async move {
|
||
if let Ok(sess) = api.rotor_session_new(&seeds, &[]).await {
|
||
let _ = tx.send(ApiEvent::RotorSessionStarted(sess, true));
|
||
}
|
||
});
|
||
}
|
||
}
|
||
|
||
pub fn start_vibe_by_seeds(&mut self, title: String, seeds: Vec<String>) {
|
||
let effective_seeds = if seeds.is_empty() {
|
||
vec!["user:onyourwave".to_string()]
|
||
} else {
|
||
seeds
|
||
};
|
||
let key = format!("vibe:{}", effective_seeds.join(","));
|
||
self.active_vibe_title = title.clone();
|
||
self.is_vibe_active = true;
|
||
self.shuffle = false;
|
||
if self.repeat == RepeatMode::All {
|
||
self.repeat = RepeatMode::Off;
|
||
}
|
||
self.context_name = title.clone();
|
||
self.context_key = key.clone();
|
||
self.show_toast(format!("{}: {}", self.i18n().my_vibe(), title));
|
||
|
||
if self.api.has_token() {
|
||
let api = self.api.clone();
|
||
let tx = self.tx_api.clone();
|
||
self.runtime.spawn(async move {
|
||
if let Ok(sess) = api.rotor_session_new(&effective_seeds, &[]).await {
|
||
let _ = tx.send(ApiEvent::RotorSessionStarted(sess, true));
|
||
}
|
||
});
|
||
} else if !self.landing.vibe_tracks.is_empty() {
|
||
let tracks = self.landing.vibe_tracks.clone();
|
||
let next = (self.queue_index + 1) % tracks.len();
|
||
self.play_tracks(tracks, next, title, key, true);
|
||
}
|
||
}
|
||
|
||
pub fn reshuffle_wheel(&mut self) {
|
||
self.start_vibe_by_seeds(
|
||
self.i18n().my_vibe().to_string(),
|
||
vec!["diversity:reshuffle".to_string()],
|
||
);
|
||
if self.api.has_token() {
|
||
let api = self.api.clone();
|
||
let tx = self.tx_api.clone();
|
||
self.runtime.spawn(async move {
|
||
if let Ok(w) = api.wheel_reshuffle(&[]).await {
|
||
if !w.is_empty() {
|
||
let _ = tx.send(ApiEvent::WheelLoaded(w));
|
||
}
|
||
}
|
||
});
|
||
}
|
||
}
|
||
|
||
/// Exact 5.129.0 click dispatcher for every WheelDesktop item type (`WAVE`, `RESHUFFLE`, `ALBUM`, `NON_MUSIC`, `ARTIST`, `PROMO_LINK`, `SETTING`).
|
||
pub fn activate_wheel_item(&mut self, item: VibeStationSummary) {
|
||
if item.is_reshuffle || item.item_type == "RESHUFFLE" {
|
||
self.reshuffle_wheel();
|
||
return;
|
||
}
|
||
match item.item_type.as_str() {
|
||
"PROMO_LINK" => {
|
||
if let Some(ref url) = item.promo_url {
|
||
self.open_promo_url(url);
|
||
} else {
|
||
self.navigate(Route::ForYou);
|
||
}
|
||
}
|
||
"SETTING" => {
|
||
self.vibe_modal_open = true;
|
||
}
|
||
"ALBUM" | "NON_MUSIC" => {
|
||
let api = self.api.clone();
|
||
let tx = self.tx_api.clone();
|
||
let aid = item.id.clone();
|
||
let title = item.title.clone();
|
||
self.runtime.spawn(async move {
|
||
if let Ok(det) = api.fetch_album_detail(&aid).await {
|
||
let _ = tx.send(ApiEvent::PlayAlbumTracks(aid, title, det.tracks));
|
||
}
|
||
});
|
||
}
|
||
"ARTIST" => {
|
||
self.navigate(Route::Artist {
|
||
id: item.id,
|
||
name: item.title,
|
||
});
|
||
}
|
||
_ => {
|
||
self.start_vibe_by_seeds(item.title, item.seeds);
|
||
}
|
||
}
|
||
}
|
||
|
||
pub fn open_promo_url(&mut self, url: &str) {
|
||
let trimmed = url.trim();
|
||
if trimmed.starts_with("http://") || trimmed.starts_with("https://") {
|
||
open_url_in_browser(trimmed);
|
||
} else if trimmed.starts_with("yandexmusic://") {
|
||
self.handle_deeplink(trimmed);
|
||
} else if trimmed.starts_with('/') {
|
||
self.handle_deeplink(trimmed);
|
||
} else if !trimmed.is_empty() {
|
||
open_url_in_browser(&format!("https://music.yandex.ru/{}", trimmed));
|
||
}
|
||
}
|
||
|
||
// =========================================================================
|
||
// 6. PLAYLISTS CRUD ACTIONS (`pages_api_spec.md` §6)
|
||
// =========================================================================
|
||
|
||
pub fn create_playlist(
|
||
&mut self,
|
||
title: String,
|
||
is_private: bool,
|
||
initial_track: Option<Track>,
|
||
) {
|
||
let clean = title.trim().to_string();
|
||
let final_title = if clean.is_empty() {
|
||
self.i18n().new_playlist_default().to_string()
|
||
} else {
|
||
clean.chars().take(100).collect()
|
||
};
|
||
let visibility = if is_private { "private" } else { "public" };
|
||
|
||
if let Some(ref acc) = self.account {
|
||
let api = self.api.clone();
|
||
let tx = self.tx_api.clone();
|
||
let uid = acc.uid;
|
||
self.runtime.spawn(async move {
|
||
let res = api
|
||
.create_playlist(uid, &final_title, visibility)
|
||
.await
|
||
.map_err(|e| e.to_string());
|
||
let _ = tx.send(ApiEvent::PlaylistCreated {
|
||
result: res,
|
||
initial_track,
|
||
});
|
||
});
|
||
} else {
|
||
// Local/offline fallback playlist creation
|
||
let local_kind = format!("local_{}", self.user_playlists.len() + 100);
|
||
let pl = PlaylistSummary {
|
||
kind: local_kind.clone(),
|
||
owner_uid: "local".into(),
|
||
owner_name: self.i18n().app_name().into(),
|
||
title: final_title.clone(),
|
||
description: None,
|
||
cover_uri: initial_track.as_ref().and_then(|t| t.cover_uri.clone()),
|
||
track_count: u32::from(initial_track.is_some()),
|
||
likes_count: 0,
|
||
generated_type: None,
|
||
revision: 1,
|
||
visibility: Some(visibility.into()),
|
||
playlist_uuid: None,
|
||
};
|
||
self.user_playlists.insert(0, pl);
|
||
self.show_toast(self.i18n().toast_playlist_created(&final_title));
|
||
self.navigate(Route::Playlist {
|
||
owner_uid: "local".into(),
|
||
kind: local_kind,
|
||
title: final_title,
|
||
});
|
||
}
|
||
}
|
||
|
||
pub fn rename_playlist(&mut self, owner_uid: String, kind: String, new_title: String) {
|
||
let clean: String = new_title.trim().chars().take(100).collect();
|
||
if clean.is_empty() {
|
||
return;
|
||
}
|
||
// Optimistic local update
|
||
if let Some(pl) = self
|
||
.user_playlists
|
||
.iter_mut()
|
||
.find(|p| p.owner_uid == owner_uid && p.kind == kind)
|
||
{
|
||
pl.title = clean.clone();
|
||
}
|
||
if let Some(ref mut det) = self.current_playlist_detail {
|
||
if det.summary.owner_uid == owner_uid && det.summary.kind == kind {
|
||
det.summary.title = clean.clone();
|
||
}
|
||
}
|
||
if let Route::Playlist {
|
||
owner_uid: ref o,
|
||
kind: ref k,
|
||
ref mut title,
|
||
} = self.route
|
||
{
|
||
if o == &owner_uid && k == &kind {
|
||
*title = clean.clone();
|
||
}
|
||
}
|
||
|
||
if let Some(ref acc) = self.account {
|
||
let api = self.api.clone();
|
||
let tx = self.tx_api.clone();
|
||
let uid = owner_uid.parse::<u64>().unwrap_or(acc.uid);
|
||
let o_c = owner_uid.clone();
|
||
let k_c = kind.clone();
|
||
self.runtime.spawn(async move {
|
||
let res = api
|
||
.rename_playlist(uid, &k_c, &clean)
|
||
.await
|
||
.map_err(|e| e.to_string());
|
||
let _ = tx.send(ApiEvent::PlaylistRenamed {
|
||
owner_uid: o_c,
|
||
kind: k_c,
|
||
result: res,
|
||
});
|
||
});
|
||
} else {
|
||
self.show_toast(self.i18n().toast_playlist_renamed(&clean));
|
||
}
|
||
}
|
||
|
||
pub fn delete_playlist(&mut self, owner_uid: String, kind: String) {
|
||
if let Some(ref acc) = self.account {
|
||
let api = self.api.clone();
|
||
let tx = self.tx_api.clone();
|
||
let uid = owner_uid.parse::<u64>().unwrap_or(acc.uid);
|
||
let o_c = owner_uid.clone();
|
||
let k_c = kind.clone();
|
||
self.runtime.spawn(async move {
|
||
let res = api.delete_playlist(uid, &k_c).await.map_err(|e| e.to_string());
|
||
let _ = tx.send(ApiEvent::PlaylistDeleted {
|
||
owner_uid: o_c,
|
||
kind: k_c,
|
||
result: res,
|
||
});
|
||
});
|
||
} else {
|
||
self.user_playlists
|
||
.retain(|p| !(p.owner_uid == owner_uid && p.kind == kind));
|
||
let pin_id = format!("{}:{}", owner_uid, kind);
|
||
self.config
|
||
.pinned_items
|
||
.retain(|p| !(p.kind == "playlist" && (p.id == pin_id || p.id == kind)));
|
||
self.save_config();
|
||
self.show_toast(self.i18n().toast_playlist_deleted());
|
||
self.collection_tab = CollectionTab::Playlists;
|
||
self.navigate(Route::Collection);
|
||
}
|
||
}
|
||
|
||
pub fn add_track_to_playlist(&mut self, owner_uid: String, kind: String, track: Track) {
|
||
let playlist_title = self
|
||
.user_playlists
|
||
.iter()
|
||
.find(|p| p.owner_uid == owner_uid && p.kind == kind)
|
||
.map(|p| p.title.clone())
|
||
.or_else(|| {
|
||
self.current_playlist_detail
|
||
.as_ref()
|
||
.filter(|d| d.summary.owner_uid == owner_uid && d.summary.kind == kind)
|
||
.map(|d| d.summary.title.clone())
|
||
})
|
||
.unwrap_or_else(|| self.i18n().playlist().to_string());
|
||
|
||
let revision = self
|
||
.current_playlist_detail
|
||
.as_ref()
|
||
.filter(|d| d.summary.owner_uid == owner_uid && d.summary.kind == kind)
|
||
.map(|d| d.revision)
|
||
.or_else(|| {
|
||
self.user_playlists
|
||
.iter()
|
||
.find(|p| p.owner_uid == owner_uid && p.kind == kind)
|
||
.map(|p| p.revision)
|
||
})
|
||
.unwrap_or(0);
|
||
|
||
if let Some(ref mut det) = self.current_playlist_detail {
|
||
if det.summary.owner_uid == owner_uid && det.summary.kind == kind {
|
||
det.tracks.insert(0, track.clone());
|
||
det.summary.track_count = det.tracks.len() as u32;
|
||
}
|
||
}
|
||
if let Some(pl) = self
|
||
.user_playlists
|
||
.iter_mut()
|
||
.find(|p| p.owner_uid == owner_uid && p.kind == kind)
|
||
{
|
||
pl.track_count = pl.track_count.saturating_add(1);
|
||
}
|
||
|
||
let toast_msg = self
|
||
.i18n()
|
||
.toast_added_to_playlist(&track.title, &playlist_title);
|
||
|
||
if let Some(ref acc) = self.account {
|
||
let api = self.api.clone();
|
||
let tx = self.tx_api.clone();
|
||
let uid = owner_uid.parse::<u64>().unwrap_or(acc.uid);
|
||
let o_c = owner_uid.clone();
|
||
let k_c = kind.clone();
|
||
self.runtime.spawn(async move {
|
||
let res = api
|
||
.playlist_add_tracks(uid, &k_c, revision, &[track])
|
||
.await
|
||
.map_err(|e| e.to_string());
|
||
let _ = tx.send(ApiEvent::PlaylistTracksChanged {
|
||
owner_uid: o_c,
|
||
kind: k_c,
|
||
revision: res,
|
||
toast_msg,
|
||
});
|
||
});
|
||
} else {
|
||
self.show_toast(toast_msg);
|
||
}
|
||
}
|
||
|
||
pub fn remove_track_from_playlist(&mut self, owner_uid: String, kind: String, index: usize) {
|
||
let mut removed_title = String::new();
|
||
let default_pl_label = self.i18n().playlist();
|
||
let mut playlist_title = default_pl_label.to_string();
|
||
let mut revision = 0u32;
|
||
|
||
if let Some(ref mut det) = self.current_playlist_detail {
|
||
if det.summary.owner_uid == owner_uid && det.summary.kind == kind {
|
||
playlist_title = det.summary.title.clone();
|
||
revision = det.revision;
|
||
if index < det.tracks.len() {
|
||
removed_title = det.tracks.remove(index).title;
|
||
det.summary.track_count = det.tracks.len() as u32;
|
||
}
|
||
}
|
||
}
|
||
if let Some(pl) = self
|
||
.user_playlists
|
||
.iter_mut()
|
||
.find(|p| p.owner_uid == owner_uid && p.kind == kind)
|
||
{
|
||
if revision == 0 {
|
||
revision = pl.revision;
|
||
}
|
||
if playlist_title == default_pl_label {
|
||
playlist_title = pl.title.clone();
|
||
}
|
||
pl.track_count = pl.track_count.saturating_sub(1);
|
||
}
|
||
|
||
let toast_msg = self
|
||
.i18n()
|
||
.toast_removed_from_playlist(&removed_title, &playlist_title);
|
||
|
||
if let Some(ref acc) = self.account {
|
||
let api = self.api.clone();
|
||
let tx = self.tx_api.clone();
|
||
let uid = owner_uid.parse::<u64>().unwrap_or(acc.uid);
|
||
let o_c = owner_uid.clone();
|
||
let k_c = kind.clone();
|
||
self.runtime.spawn(async move {
|
||
let res = api
|
||
.playlist_remove_tracks(uid, &k_c, revision, index, index + 1)
|
||
.await
|
||
.map_err(|e| e.to_string());
|
||
let _ = tx.send(ApiEvent::PlaylistTracksChanged {
|
||
owner_uid: o_c,
|
||
kind: k_c,
|
||
revision: res,
|
||
toast_msg,
|
||
});
|
||
});
|
||
} else {
|
||
self.show_toast(toast_msg);
|
||
}
|
||
}
|
||
|
||
// =========================================================================
|
||
// 7. OFFLINE AUDIO CACHE & DOWNLOADS
|
||
// =========================================================================
|
||
|
||
pub fn scan_offline_cache(&mut self) {
|
||
let dir = AppConfig::offline_cache_dir();
|
||
self.downloaded_track_ids.clear();
|
||
for tr in &self.config.downloaded_tracks {
|
||
if find_offline_track_file(&tr.id, &dir).is_some() {
|
||
self.downloaded_track_ids.insert(tr.id.clone());
|
||
}
|
||
}
|
||
// Keep config list aligned with files actually present on disk
|
||
self.config
|
||
.downloaded_tracks
|
||
.retain(|tr| self.downloaded_track_ids.contains(&tr.id));
|
||
}
|
||
|
||
pub fn is_track_downloaded(&self, track_id: &str) -> bool {
|
||
self.downloaded_track_ids.contains(track_id)
|
||
}
|
||
|
||
pub fn is_track_downloading(&self, track_id: &str) -> bool {
|
||
self.downloading_track_ids.contains(track_id)
|
||
}
|
||
|
||
pub fn is_all_downloaded(&self, tracks: &[Track]) -> bool {
|
||
!tracks.is_empty() && tracks.iter().all(|t| self.downloaded_track_ids.contains(&t.id))
|
||
}
|
||
|
||
pub fn download_progress_pct(&self) -> Option<u8> {
|
||
if self.downloading_track_ids.is_empty() || self.download_batch_total == 0 {
|
||
return None;
|
||
}
|
||
let pct = ((self.download_batch_done as f32 / self.download_batch_total as f32) * 100.0)
|
||
.round()
|
||
.clamp(0.0, 99.0) as u8;
|
||
Some(pct)
|
||
}
|
||
|
||
pub fn cancel_downloads(&mut self) {
|
||
self.download_cancel.store(true, Ordering::SeqCst);
|
||
self.downloading_track_ids.clear();
|
||
self.download_batch_total = 0;
|
||
self.download_batch_done = 0;
|
||
self.show_toast(self.i18n().toast_download_stopped());
|
||
}
|
||
|
||
pub fn download_track(&mut self, track: Track) {
|
||
if self.is_track_downloaded(&track.id) || self.is_track_downloading(&track.id) {
|
||
return;
|
||
}
|
||
if !self.api.has_token() {
|
||
self.login_modal_open = true;
|
||
self.show_toast(self.i18n().toast_sign_in_required());
|
||
return;
|
||
}
|
||
if self.downloading_track_ids.is_empty() {
|
||
self.download_cancel.store(false, Ordering::SeqCst);
|
||
}
|
||
self.downloading_track_ids.insert(track.id.clone());
|
||
self.download_batch_total += 1;
|
||
|
||
let api = self.api.clone();
|
||
let tx = self.tx_api.clone();
|
||
let quality = self.config.audio_quality;
|
||
let cache_dir = AppConfig::offline_cache_dir();
|
||
let cancel = std::sync::Arc::clone(&self.download_cancel);
|
||
self.runtime.spawn(async move {
|
||
if cancel.load(Ordering::Relaxed) {
|
||
return;
|
||
}
|
||
let res = api
|
||
.download_track_to_cache(&track, quality, &cache_dir)
|
||
.await
|
||
.map_err(|e| e.to_string());
|
||
if cancel.load(Ordering::Relaxed) {
|
||
let _ = remove_offline_track_file(&track.id, &cache_dir);
|
||
return;
|
||
}
|
||
let _ = tx.send(ApiEvent::TrackDownloaded { track, result: res });
|
||
});
|
||
}
|
||
|
||
pub fn download_tracks(&mut self, tracks: Vec<Track>) {
|
||
if !self.api.has_token() {
|
||
self.login_modal_open = true;
|
||
self.show_toast(self.i18n().toast_sign_in_required());
|
||
return;
|
||
}
|
||
self.download_cancel.store(false, Ordering::SeqCst);
|
||
let to_download: Vec<Track> = tracks
|
||
.into_iter()
|
||
.filter(|tr| !self.is_track_downloaded(&tr.id) && !self.is_track_downloading(&tr.id))
|
||
.collect();
|
||
if to_download.is_empty() {
|
||
return;
|
||
}
|
||
for tr in &to_download {
|
||
self.downloading_track_ids.insert(tr.id.clone());
|
||
self.download_batch_total += 1;
|
||
}
|
||
|
||
let api = self.api.clone();
|
||
let tx = self.tx_api.clone();
|
||
let quality = self.config.audio_quality;
|
||
let cache_dir = AppConfig::offline_cache_dir();
|
||
let cancel = std::sync::Arc::clone(&self.download_cancel);
|
||
self.runtime.spawn(async move {
|
||
for track in to_download {
|
||
if cancel.load(Ordering::Relaxed) {
|
||
break;
|
||
}
|
||
let res = api
|
||
.download_track_to_cache(&track, quality, &cache_dir)
|
||
.await
|
||
.map_err(|e| e.to_string());
|
||
if cancel.load(Ordering::Relaxed) {
|
||
let _ = remove_offline_track_file(&track.id, &cache_dir);
|
||
break;
|
||
}
|
||
let _ = tx.send(ApiEvent::TrackDownloaded { track, result: res });
|
||
}
|
||
});
|
||
}
|
||
|
||
pub fn remove_downloaded_track(&mut self, track_id: &str) {
|
||
let dir = AppConfig::offline_cache_dir();
|
||
let _ = remove_offline_track_file(track_id, &dir);
|
||
self.downloaded_track_ids.remove(track_id);
|
||
let title = self
|
||
.config
|
||
.downloaded_tracks
|
||
.iter()
|
||
.find(|t| t.id == track_id)
|
||
.map(|t| t.title.clone())
|
||
.unwrap_or_else(|| track_id.to_string());
|
||
self.config.downloaded_tracks.retain(|t| t.id != track_id);
|
||
self.save_config();
|
||
self.show_toast(self.i18n().toast_deleted_from_device(&title));
|
||
}
|
||
|
||
pub fn remove_downloaded_tracks(&mut self, ids: &[String]) {
|
||
let dir = AppConfig::offline_cache_dir();
|
||
for id in ids {
|
||
let _ = remove_offline_track_file(id, &dir);
|
||
self.downloaded_track_ids.remove(id);
|
||
}
|
||
let id_set: HashSet<&str> = ids.iter().map(|s| s.as_str()).collect();
|
||
self.config
|
||
.downloaded_tracks
|
||
.retain(|t| !id_set.contains(t.id.as_str()));
|
||
self.save_config();
|
||
self.show_toast(self.i18n().toast_cover_cache_cleared());
|
||
}
|
||
|
||
// =========================================================================
|
||
// 8. CLIPBOARD & TELEMETRY
|
||
// =========================================================================
|
||
|
||
pub fn copy_to_clipboard(&mut self, text: String, toast_msg: String) {
|
||
self.pending_clipboard_text = Some(text.clone());
|
||
if let Ok(mut cb) = arboard::Clipboard::new() {
|
||
let _ = cb.set_text(text);
|
||
}
|
||
self.show_toast(toast_msg);
|
||
}
|
||
|
||
pub(crate) fn build_play_telemetry_event(&self, change_reason: &str) -> Option<PlayTelemetryEvent> {
|
||
if !self.api.has_token() {
|
||
return None;
|
||
}
|
||
let track = self.current_track()?;
|
||
if track.id.starts_with("demo_") {
|
||
return None;
|
||
}
|
||
let pos_sec = self.audio.state.position_ms.load(Ordering::Relaxed) as f64 / 1000.0;
|
||
let len_sec = track.duration_ms as f64 / 1000.0;
|
||
let snapped_pos = if (len_sec - pos_sec).abs() < 0.5 && len_sec > 0.0 {
|
||
len_sec
|
||
} else {
|
||
pos_sec
|
||
};
|
||
let (radio_sid, batch_id, ctx_kind, ctx_item) = if self.is_vibe_active {
|
||
if let Some(ref s) = self.active_rotor_session {
|
||
(
|
||
Some(s.radio_session_id.clone()),
|
||
s.batch_id.clone(),
|
||
"radio".to_string(),
|
||
Some(s.seeds.join(",")),
|
||
)
|
||
} else {
|
||
(
|
||
None,
|
||
None,
|
||
"radio".to_string(),
|
||
Some("user:onyourwave".into()),
|
||
)
|
||
}
|
||
} else {
|
||
(
|
||
None,
|
||
None,
|
||
"playlist".to_string(),
|
||
Some(self.context_name.clone()),
|
||
)
|
||
};
|
||
Some(PlayTelemetryEvent {
|
||
play_id: self.current_play_id.clone(),
|
||
from: "desktop_win-home-my_vibe".into(),
|
||
track_id: track.id.clone(),
|
||
album_id: track.album_id.clone(),
|
||
timestamp: iso8601_now(),
|
||
start_timestamp: self.play_start_iso.clone(),
|
||
total_played_seconds: snapped_pos,
|
||
end_position_seconds: snapped_pos,
|
||
track_length_seconds: len_sec,
|
||
context: ctx_kind,
|
||
context_item: ctx_item,
|
||
from_cache: self.play_from_cache,
|
||
is_restored: false,
|
||
seek: self.play_seeked,
|
||
pause: self.play_paused,
|
||
is_repeated: self.repeat == RepeatMode::One,
|
||
change_reason: change_reason.to_string(),
|
||
radio_session_id: radio_sid,
|
||
batch_id,
|
||
})
|
||
}
|
||
|
||
pub(crate) fn send_play_telemetry(&self, change_reason: &str) {
|
||
let Some(ev) = self.build_play_telemetry_event(change_reason) else {
|
||
return;
|
||
};
|
||
let api = self.api.clone();
|
||
self.runtime.spawn(async move {
|
||
let _ = api.send_plays(&[ev]).await;
|
||
});
|
||
}
|
||
|
||
pub(crate) fn send_rotor_feedback(
|
||
&self,
|
||
kind: RotorFeedbackKind,
|
||
track: Option<&Track>,
|
||
total_played_secs: Option<f64>,
|
||
) {
|
||
if !self.is_vibe_active || !self.api.has_token() {
|
||
return;
|
||
}
|
||
let Some(ref sess) = self.active_rotor_session else {
|
||
return;
|
||
};
|
||
let api = self.api.clone();
|
||
let sid = sess.radio_session_id.clone();
|
||
let bid = sess.batch_id.clone();
|
||
let rtid = track.map(|t| t.rotor_track_id());
|
||
let len_secs = if kind == RotorFeedbackKind::TrackFinished {
|
||
track.map(|t| t.duration_ms as f64 / 1000.0)
|
||
} else {
|
||
None
|
||
};
|
||
self.runtime.spawn(async move {
|
||
let _ = api
|
||
.rotor_session_feedback(
|
||
&sid,
|
||
kind,
|
||
bid.as_deref(),
|
||
rtid.as_deref(),
|
||
total_played_secs,
|
||
len_secs,
|
||
)
|
||
.await;
|
||
});
|
||
}
|
||
|
||
pub(crate) fn maybe_prefetch_rotor_batch(&mut self) {
|
||
if !self.is_vibe_active || self.vibe_prefetching || !self.api.has_token() {
|
||
return;
|
||
}
|
||
let Some(ref sess) = self.active_rotor_session else {
|
||
return;
|
||
};
|
||
if sess.terminated || self.queue_index + 2 < self.queue.len() {
|
||
return;
|
||
}
|
||
self.vibe_prefetching = true;
|
||
let api = self.api.clone();
|
||
let tx = self.tx_api.clone();
|
||
let sid = sess.radio_session_id.clone();
|
||
let queue_ids: Vec<String> = self
|
||
.queue
|
||
.iter()
|
||
.skip(self.queue_index)
|
||
.map(|t| t.rotor_track_id())
|
||
.collect();
|
||
self.runtime.spawn(async move {
|
||
if let Ok((batch_id, tracks, terminated)) =
|
||
api.rotor_session_tracks(&sid, &queue_ids, &[]).await
|
||
{
|
||
let _ = tx.send(ApiEvent::RotorBatchAppended(batch_id, tracks, terminated));
|
||
}
|
||
});
|
||
}
|
||
}
|
||
|
||
fn pin_matches(p: &PinnedItem, kind: &str, id: &str) -> bool {
|
||
if kind == "likes" {
|
||
return p.kind == "likes" || p.id == "likes";
|
||
}
|
||
if p.kind != kind {
|
||
return false;
|
||
}
|
||
if p.id == id {
|
||
return true;
|
||
}
|
||
if kind == "playlist" {
|
||
if let Some((_, k)) = p.id.split_once(':') {
|
||
if k == id {
|
||
return true;
|
||
}
|
||
}
|
||
if let Some((_, k)) = id.split_once(':') {
|
||
if p.id == k {
|
||
return true;
|
||
}
|
||
}
|
||
}
|
||
false
|
||
}
|
||
|
||
fn fisher_yates_shuffle<T>(slice: &mut [T], mut seed: u64) {
|
||
for i in (1..slice.len()).rev() {
|
||
seed = seed
|
||
.wrapping_mul(6364136223846793005)
|
||
.wrapping_add(1442695040888963407);
|
||
let j = (seed >> 33) as usize % (i + 1);
|
||
slice.swap(i, j);
|
||
}
|
||
}
|
||
|
||
// =============================================================================
|
||
// Comprehensive Unit Tests for All Playback, Queue, Pin, Filter & Persistence Invariants
|
||
// =============================================================================
|
||
|
||
#[cfg(test)]
|
||
mod tests {
|
||
use super::*;
|
||
use crate::app::state::AppAction;
|
||
|
||
fn make_track(id: &str, title: &str) -> Track {
|
||
Track {
|
||
id: id.to_string(),
|
||
title: title.to_string(),
|
||
version: None,
|
||
artists: vec![ArtistSummary {
|
||
id: format!("art_{}", id),
|
||
name: format!("Artist {}", id),
|
||
cover_uri: None,
|
||
genres: vec![],
|
||
}],
|
||
album_id: Some(format!("alb_{}", id)),
|
||
album_title: Some(format!("Album {}", id)),
|
||
cover_uri: None,
|
||
duration_ms: 180_000,
|
||
is_explicit: false,
|
||
has_lossless: true,
|
||
has_lyrics: true,
|
||
chart_position: None,
|
||
chart_progress: None,
|
||
preview_url: None,
|
||
r128_i: None,
|
||
r128_tp: None,
|
||
derived_average_hex: None,
|
||
derived_accent_hex: None,
|
||
}
|
||
}
|
||
|
||
fn make_test_state(tracks: Vec<Track>) -> (tokio::runtime::Runtime, AppState) {
|
||
let rt = tokio::runtime::Builder::new_current_thread()
|
||
.enable_all()
|
||
.build()
|
||
.unwrap();
|
||
let cfg = AppConfig::default();
|
||
let state = AppState::new_visual_test(
|
||
rt.handle().clone(),
|
||
"TestGPU".into(),
|
||
Route::MyVibe,
|
||
cfg,
|
||
LandingData::default(),
|
||
None,
|
||
tracks.clone(),
|
||
tracks,
|
||
0,
|
||
180_000,
|
||
1.0,
|
||
);
|
||
(rt, state)
|
||
}
|
||
|
||
#[test]
|
||
fn test_queue_removal_shifts_index_before_current() {
|
||
let tracks = vec![
|
||
make_track("t0", "Zero"),
|
||
make_track("t1", "One"),
|
||
make_track("t2", "Two"),
|
||
make_track("t3", "Three"),
|
||
];
|
||
let (_rt, mut app) = make_test_state(tracks);
|
||
app.queue_index = 2; // "Two"
|
||
|
||
// Removing idx < queue_index decrements queue_index so "Two" remains current!
|
||
app.remove_queue_at(0);
|
||
assert_eq!(app.queue_index, 1);
|
||
assert_eq!(app.current_track().unwrap().id, "t2");
|
||
|
||
// Removing idx > queue_index leaves queue_index unchanged!
|
||
app.remove_queue_at(2);
|
||
assert_eq!(app.queue_index, 1);
|
||
assert_eq!(app.current_track().unwrap().id, "t2");
|
||
}
|
||
|
||
#[test]
|
||
fn test_queue_removal_at_current_index_advances_or_stops() {
|
||
let tracks = vec![
|
||
make_track("t0", "Zero"),
|
||
make_track("t1", "One"),
|
||
make_track("t2", "Two"),
|
||
];
|
||
let (_rt, mut app) = make_test_state(tracks);
|
||
app.queue_index = 1; // "One"
|
||
app.audio.state.is_playing.store(true, Ordering::SeqCst);
|
||
|
||
// Removing middle active track shifts "Two" into index 1
|
||
app.remove_queue_at(1);
|
||
assert_eq!(app.queue.len(), 2);
|
||
assert_eq!(app.queue_index, 1);
|
||
assert_eq!(app.current_track().unwrap().id, "t2");
|
||
|
||
// Removing last active track in RepeatOff stops playback and clamps queue_index
|
||
app.repeat = RepeatMode::Off;
|
||
app.audio.state.is_playing.store(true, Ordering::SeqCst);
|
||
app.remove_queue_at(1);
|
||
assert_eq!(app.queue.len(), 1);
|
||
assert_eq!(app.queue_index, 0);
|
||
assert!(!app.is_audio_playing());
|
||
|
||
// Removing final remaining track empties queue and stops
|
||
app.remove_queue_at(0);
|
||
assert!(app.queue.is_empty());
|
||
assert_eq!(app.queue_index, 0);
|
||
assert!(!app.is_audio_playing());
|
||
}
|
||
|
||
#[test]
|
||
fn test_queue_dnd_move_pins_current_track() {
|
||
let tracks = vec![
|
||
make_track("t0", "Zero"),
|
||
make_track("t1", "One"),
|
||
make_track("t2", "Two"),
|
||
make_track("t3", "Three"),
|
||
];
|
||
let (_rt, mut app) = make_test_state(tracks);
|
||
app.queue_index = 2; // "Two"
|
||
|
||
// Move item from before current (0) to after current (3)
|
||
app.move_queue(0, 3);
|
||
assert_eq!(app.current_track().unwrap().id, "t2");
|
||
assert_eq!(app.queue_index, 1);
|
||
|
||
// Move item from after current (3) to before current (0)
|
||
app.move_queue(3, 0);
|
||
assert_eq!(app.current_track().unwrap().id, "t2");
|
||
assert_eq!(app.queue_index, 2);
|
||
|
||
// Move currently playing track itself (2 -> 0)
|
||
app.move_queue(2, 0);
|
||
assert_eq!(app.current_track().unwrap().id, "t2");
|
||
assert_eq!(app.queue_index, 0);
|
||
}
|
||
|
||
#[test]
|
||
fn test_play_tracks_clears_unshuffled_and_respects_shuffle_and_vibe() {
|
||
let tracks: Vec<Track> = (0..6)
|
||
.map(|i| make_track(&format!("t{}", i), &format!("Track {}", i)))
|
||
.collect();
|
||
let (_rt, mut app) = make_test_state(vec![]);
|
||
|
||
// Seed stale unshuffled_queue and turn shuffle on
|
||
app.unshuffled_queue = vec![make_track("stale", "Stale")];
|
||
app.shuffle = true;
|
||
app.play_tracks(tracks.clone(), 3, "Album X".into(), "album:x".into(), false);
|
||
|
||
// Pinned start_index (t3) at index 0, unshuffled_queue replaced with new original order (NOT stale!)
|
||
assert_eq!(app.queue_index, 0);
|
||
assert_eq!(app.queue[0].id, "t3");
|
||
assert_eq!(app.unshuffled_queue.len(), 6);
|
||
assert_eq!(app.unshuffled_queue[0].id, "t0");
|
||
|
||
// Now start a Vibe session: MUST clear unshuffled_queue, force shuffle=false, downgrade RepeatMode::All -> Off!
|
||
app.repeat = RepeatMode::All;
|
||
app.play_tracks(tracks.clone(), 1, "My Vibe".into(), "vibe:1".into(), true);
|
||
assert!(app.is_vibe_active);
|
||
assert!(!app.shuffle);
|
||
assert_eq!(app.repeat, RepeatMode::Off);
|
||
assert!(app.unshuffled_queue.is_empty());
|
||
assert_eq!(app.queue_index, 1);
|
||
assert_eq!(app.current_track().unwrap().id, "t1");
|
||
|
||
// Cycle repeat in Vibe: MUST ONLY toggle Off <-> One (NEVER All!)
|
||
app.cycle_repeat();
|
||
assert_eq!(app.repeat, RepeatMode::One);
|
||
app.cycle_repeat();
|
||
assert_eq!(app.repeat, RepeatMode::Off);
|
||
|
||
// Toggle shuffle in Vibe: MUST stay false!
|
||
app.toggle_shuffle();
|
||
assert!(!app.shuffle);
|
||
}
|
||
|
||
#[test]
|
||
fn test_play_prev_threshold_and_zero_index_wrap_rules() {
|
||
let tracks = vec![
|
||
make_track("t0", "Zero"),
|
||
make_track("t1", "One"),
|
||
make_track("t2", "Two"),
|
||
];
|
||
let (_rt, mut app) = make_test_state(tracks);
|
||
|
||
// 1. pos > 5000ms -> seeks to 0 without changing track
|
||
app.queue_index = 1;
|
||
app.audio.state.position_ms.store(8000, Ordering::SeqCst);
|
||
app.play_prev();
|
||
assert_eq!(app.queue_index, 1);
|
||
assert_eq!(app.position_ms(), 0);
|
||
assert!(app.play_seeked);
|
||
|
||
// 2. pos <= 5000ms at index 1 -> goes to index 0
|
||
app.audio.state.position_ms.store(2000, Ordering::SeqCst);
|
||
app.play_prev();
|
||
assert_eq!(app.queue_index, 0);
|
||
|
||
// 3. index 0 with RepeatMode::Off -> NEVER wraps, seeks to 0!
|
||
app.repeat = RepeatMode::Off;
|
||
app.is_vibe_active = false;
|
||
app.audio.state.position_ms.store(1500, Ordering::SeqCst);
|
||
app.play_prev();
|
||
assert_eq!(app.queue_index, 0);
|
||
assert_eq!(app.position_ms(), 0);
|
||
|
||
// 4. index 0 with MyVibe active (even if RepeatAll somehow set) -> NEVER wraps!
|
||
app.repeat = RepeatMode::All;
|
||
app.is_vibe_active = true;
|
||
app.audio.state.position_ms.store(1000, Ordering::SeqCst);
|
||
app.play_prev();
|
||
assert_eq!(app.queue_index, 0);
|
||
assert_eq!(app.position_ms(), 0);
|
||
|
||
// 5. index 0 with RepeatMode::All && !is_vibe_active -> wraps to last track!
|
||
app.is_vibe_active = false;
|
||
app.repeat = RepeatMode::All;
|
||
app.audio.state.position_ms.store(1000, Ordering::SeqCst);
|
||
app.play_prev();
|
||
assert_eq!(app.queue_index, 2);
|
||
}
|
||
|
||
#[test]
|
||
fn test_context_matching_and_toggle_play_pause() {
|
||
let tracks = vec![make_track("t0", "Zero"), make_track("t1", "One")];
|
||
let (_rt, mut app) = make_test_state(vec![]);
|
||
|
||
assert!(!app.is_context_playing("album:42"));
|
||
app.play_tracks(tracks.clone(), 0, "Alb".into(), "album:42".into(), false);
|
||
// Simulate stream playing
|
||
app.audio.state.duration_ms.store(180_000, Ordering::SeqCst);
|
||
app.audio.state.is_playing.store(true, Ordering::SeqCst);
|
||
app.audio.state.position_ms.store(45_000, Ordering::SeqCst);
|
||
|
||
assert!(app.is_context_playing("album:42"));
|
||
assert!(!app.is_context_playing("album:99"));
|
||
|
||
// Toggling same context pauses WITHOUT resetting position!
|
||
app.toggle_context_play(tracks.clone(), "Alb".into(), "album:42".into(), false);
|
||
assert!(!app.is_context_playing("album:42"));
|
||
assert!(app.play_paused);
|
||
assert_eq!(app.position_ms(), 45_000);
|
||
|
||
// Toggling again resumes!
|
||
app.toggle_context_play(tracks, "Alb".into(), "album:42".into(), false);
|
||
assert!(app.is_context_playing("album:42"));
|
||
assert!(!app.play_paused);
|
||
}
|
||
|
||
#[test]
|
||
fn test_fullscreen_lyrics_split_preserves_fullscreen() {
|
||
let (_rt, mut app) = make_test_state(vec![]);
|
||
app.fullscreen_open = true;
|
||
assert!(!app.fullscreen_lyrics_open);
|
||
|
||
app.dispatch(AppAction::ToggleFullscreenLyrics);
|
||
assert!(app.fullscreen_open);
|
||
assert!(app.fullscreen_lyrics_open);
|
||
|
||
app.dispatch(AppAction::ToggleFullscreenLyrics);
|
||
assert!(app.fullscreen_open);
|
||
assert!(!app.fullscreen_lyrics_open);
|
||
}
|
||
|
||
#[test]
|
||
fn test_pin_unpin_all_entity_kinds() {
|
||
let (_rt, mut app) = make_test_state(vec![]);
|
||
app.config.pinned_items.clear();
|
||
|
||
let cases = [
|
||
("playlist", "100:5", "My PL", "Плейлист"),
|
||
("album", "alb_77", "My Album", "Альбом"),
|
||
("artist", "art_88", "My Artist", "Исполнитель"),
|
||
("likes", "likes", "Мне нравится", "Плейлист"),
|
||
("wave", "mood:happy", "Весёлое", "Моя волна"),
|
||
];
|
||
|
||
for (kind, id, title, sub) in cases {
|
||
assert!(!app.is_pinned(kind, id));
|
||
assert!(app.toggle_pin(kind, id, title, sub, None, None));
|
||
assert!(app.is_pinned(kind, id));
|
||
}
|
||
|
||
// Unpin every single one
|
||
for (kind, id, title, sub) in cases {
|
||
assert!(!app.toggle_pin(kind, id, title, sub, None, None));
|
||
assert!(!app.is_pinned(kind, id));
|
||
}
|
||
assert!(app.config.pinned_items.is_empty());
|
||
}
|
||
|
||
#[test]
|
||
fn test_favorites_filter_normalization_and_filtering() {
|
||
let tracks: Vec<Track> = (0..12)
|
||
.map(|i| make_track(&format!("id{}", i), &format!("Song {}", i)))
|
||
.collect();
|
||
let (_rt, mut app) = make_test_state(tracks.clone());
|
||
|
||
let all_ids: HashSet<String> = (0..12).map(|i| format!("id{}", i)).collect();
|
||
let rock_ids: HashSet<String> = (0..8).map(|i| format!("id{}", i)).collect();
|
||
let chill_ids: HashSet<String> = (4..12).map(|i| format!("id{}", i)).collect();
|
||
let tiny_ids: HashSet<String> = (0..3).map(|i| format!("id{}", i)).collect();
|
||
|
||
// Build 10 raw chips (all + tiny (<8) + 8 valid chips) -> must keep "all" + 7 valid (max 8 total), drop tiny!
|
||
let mut raw = vec![
|
||
TrackFilterChip { id: "all".into(), name: "Все".into(), track_ids: all_ids },
|
||
TrackFilterChip { id: "tiny".into(), name: "Tiny".into(), track_ids: tiny_ids },
|
||
TrackFilterChip { id: "genre:rock".into(), name: "Рок".into(), track_ids: rock_ids },
|
||
TrackFilterChip { id: "mood:chill".into(), name: "Спокойное".into(), track_ids: chill_ids.clone() },
|
||
];
|
||
for extra in 0..7 {
|
||
raw.push(TrackFilterChip {
|
||
id: format!("extra:{}", extra),
|
||
name: format!("Extra {}", extra),
|
||
track_ids: chill_ids.clone(),
|
||
});
|
||
}
|
||
let normalized = normalize_track_filters(raw);
|
||
assert_eq!(normalized.len(), 8);
|
||
assert_eq!(normalized[0].id, "all");
|
||
assert!(!normalized.iter().any(|c| c.id == "tiny"));
|
||
|
||
app.favorite_filters = normalized;
|
||
assert_eq!(app.filtered_liked_tracks().len(), 12);
|
||
|
||
// Select "genre:rock" -> actually filters to 8 tracks (id0..id7)!
|
||
app.select_favorite_filter(Some("genre:rock".into()));
|
||
let filtered = app.filtered_liked_tracks();
|
||
assert_eq!(filtered.len(), 8);
|
||
assert!(filtered.iter().all(|t| t.id != "id8" && t.id != "id11"));
|
||
|
||
// Selecting "all" restores full 12 tracks
|
||
app.select_favorite_filter(Some("all".into()));
|
||
assert_eq!(app.filtered_liked_tracks().len(), 12);
|
||
}
|
||
|
||
#[test]
|
||
fn test_persistence_roundtrip() {
|
||
let tracks = vec![
|
||
make_track("p1", "Persist One"),
|
||
make_track("p2", "Persist Two"),
|
||
make_track("p3", "Persist Three"),
|
||
];
|
||
let (_rt, mut app) = make_test_state(tracks);
|
||
app.queue_index = 1;
|
||
app.audio.state.position_ms.store(64_250, Ordering::SeqCst);
|
||
app.context_name = "My Favorites".into();
|
||
app.is_vibe_active = false;
|
||
app.shuffle = true;
|
||
app.repeat = RepeatMode::One;
|
||
|
||
app.save_playback_state();
|
||
let json = serde_json::to_string(&app.config).expect("serialize config");
|
||
let restored_cfg: AppConfig = serde_json::from_str(&json).expect("deserialize config");
|
||
|
||
let (_rt2, mut app2) = make_test_state(vec![]);
|
||
app2.config = restored_cfg;
|
||
app2.restore_from_config();
|
||
|
||
assert_eq!(app2.queue.len(), 3);
|
||
assert_eq!(app2.queue_index, 1);
|
||
assert_eq!(app2.current_track().unwrap().id, "p2");
|
||
assert_eq!(app2.position_ms(), 64_250);
|
||
assert_eq!(app2.context_name, "My Favorites");
|
||
assert!(!app2.is_vibe_active);
|
||
assert!(app2.shuffle);
|
||
assert_eq!(app2.repeat, RepeatMode::One);
|
||
}
|
||
|
||
#[test]
|
||
fn test_vibe_pause_resume_smooth_transition() {
|
||
let mut tr = make_track("v1", "Orange Track");
|
||
tr.derived_average_hex = Some("#F56E00".into());
|
||
let (_rt, mut app) = make_test_state(vec![tr]);
|
||
app.route = Route::MyVibe;
|
||
|
||
// Snap into playing state (simulates steady playback)
|
||
app.set_vibe_playback_for_test(true, 0.65, 0.80);
|
||
assert_eq!(app.smooth_playing, 1.0);
|
||
let pc_play = app.vibe_push_constants(true, None).unwrap();
|
||
assert_eq!(pc_play.playing, 1.0);
|
||
|
||
// Pause playback -> MUST NOT snap smooth_playing to 0 in a single frame!
|
||
app.audio.pause();
|
||
assert!(!app.is_audio_playing());
|
||
assert_eq!(app.smooth_playing, 1.0);
|
||
assert!(app.needs_continuous_repaint());
|
||
|
||
let mut prev = app.smooth_playing;
|
||
for _ in 0..10 {
|
||
app.tick_vibe_animation(1.0 / 60.0, None);
|
||
let cur = app.smooth_playing;
|
||
let delta = prev - cur;
|
||
assert!(delta > 0.01 && delta < 0.08, "expected smooth per-frame decay, got delta={}", delta);
|
||
prev = cur;
|
||
}
|
||
assert!(app.smooth_playing > 0.4 && app.smooth_playing < 0.7);
|
||
assert!(app.needs_continuous_repaint());
|
||
|
||
// Settle completely after ~2.5s
|
||
for _ in 0..150 {
|
||
app.tick_vibe_animation(1.0 / 60.0, None);
|
||
}
|
||
assert_eq!(app.smooth_playing, 0.0);
|
||
assert_eq!(app.vibe_push_constants(true, None).unwrap().playing, 0.0);
|
||
}
|
||
|
||
#[test]
|
||
fn test_cancel_download_and_play_favorites() {
|
||
let tracks = vec![make_track("f1", "Fav One"), make_track("f2", "Fav Two")];
|
||
let (_rt, mut app) = make_test_state(vec![]);
|
||
app.liked_tracks = tracks;
|
||
|
||
// Simulate active download batch, then cancel via AppAction::CancelDownload
|
||
app.downloading_track_ids.insert("f1".into());
|
||
app.download_batch_total = 2;
|
||
app.download_batch_done = 1;
|
||
app.dispatch(AppAction::CancelDownload);
|
||
assert!(app.download_cancel.load(Ordering::Relaxed));
|
||
assert!(app.downloading_track_ids.is_empty());
|
||
assert_eq!(app.download_batch_total, 0);
|
||
assert_eq!(app.download_batch_done, 0);
|
||
let expected_toast = app.i18n().toast_download_stopped();
|
||
assert_eq!(app.current_toast(), Some(expected_toast));
|
||
|
||
// AppAction::PlayFavorites loads liked_tracks into queue under context_key "likes"
|
||
app.dispatch(AppAction::PlayFavorites);
|
||
assert_eq!(app.context_key, "likes");
|
||
assert_eq!(app.queue.len(), 2);
|
||
assert_eq!(app.queue[0].id, "f1");
|
||
}
|
||
|
||
#[test]
|
||
fn test_fullscreen_direct_splits_and_context_navigation() {
|
||
let tracks = vec![make_track("t1", "Song 1")];
|
||
let (_rt, mut app) = make_test_state(tracks);
|
||
app.right_drawer = super::super::state::RightDrawerTab::Queue;
|
||
|
||
// OpenFullscreenSyncLyrics opens fullscreen in 50/50 lyrics mode & clears right drawer
|
||
app.dispatch(AppAction::OpenFullscreenSyncLyrics);
|
||
assert!(app.fullscreen_open);
|
||
assert!(app.fullscreen_lyrics_open);
|
||
assert!(!app.fullscreen_queue_open);
|
||
assert_eq!(app.right_drawer, super::super::state::RightDrawerTab::None);
|
||
|
||
// OpenFullscreenQueue switches to 50/50 queue mode and closes lyrics split
|
||
app.dispatch(AppAction::OpenFullscreenQueue);
|
||
assert!(app.fullscreen_open);
|
||
assert!(app.fullscreen_queue_open);
|
||
assert!(!app.fullscreen_lyrics_open);
|
||
|
||
// ToggleFullscreenQueue closes queue split WITHOUT closing fullscreen_open
|
||
app.dispatch(AppAction::ToggleFullscreenQueue);
|
||
assert!(app.fullscreen_open);
|
||
assert!(!app.fullscreen_queue_open);
|
||
|
||
// ToggleFullscreenQueue re-opens queue; ToggleFullscreenLyrics swaps cleanly
|
||
app.dispatch(AppAction::ToggleFullscreenQueue);
|
||
assert!(app.fullscreen_queue_open);
|
||
app.dispatch(AppAction::ToggleFullscreenLyrics);
|
||
assert!(app.fullscreen_open);
|
||
assert!(app.fullscreen_lyrics_open);
|
||
assert!(!app.fullscreen_queue_open);
|
||
|
||
// SetFullscreen(false) clears both split flags
|
||
app.dispatch(AppAction::SetFullscreen(false));
|
||
assert!(!app.fullscreen_open);
|
||
assert!(!app.fullscreen_lyrics_open);
|
||
assert!(!app.fullscreen_queue_open);
|
||
|
||
// DismissOverlays also clears both split flags
|
||
app.dispatch(AppAction::OpenFullscreenQueue);
|
||
app.dispatch(AppAction::DismissOverlays);
|
||
assert!(!app.fullscreen_open);
|
||
assert!(!app.fullscreen_queue_open);
|
||
assert!(!app.fullscreen_lyrics_open);
|
||
|
||
// NavigateToCurrentContext parses likes, likes:*, album, artist, playlist
|
||
app.context_key = "likes".into();
|
||
app.context_name = "Мне нравится".into();
|
||
app.dispatch(AppAction::NavigateToCurrentContext);
|
||
assert_eq!(app.route, Route::LikedTracks);
|
||
|
||
app.context_key = "album:42".into();
|
||
app.context_name = "My Album".into();
|
||
app.dispatch(AppAction::NavigateToCurrentContext);
|
||
assert_eq!(
|
||
app.route,
|
||
Route::Album {
|
||
id: "42".into(),
|
||
title: "My Album".into()
|
||
}
|
||
);
|
||
|
||
app.context_key = "likes:genre:rock".into();
|
||
app.dispatch(AppAction::NavigateToCurrentContext);
|
||
assert_eq!(app.route, Route::LikedTracks);
|
||
|
||
app.context_key = "artist:77".into();
|
||
app.context_name = "Cool Band".into();
|
||
app.dispatch(AppAction::NavigateToCurrentContext);
|
||
assert_eq!(
|
||
app.route,
|
||
Route::Artist {
|
||
id: "77".into(),
|
||
name: "Cool Band".into()
|
||
}
|
||
);
|
||
|
||
app.context_key = "playlist:100:5".into();
|
||
app.context_name = "Road Trip".into();
|
||
app.dispatch(AppAction::NavigateToCurrentContext);
|
||
assert_eq!(
|
||
app.route,
|
||
Route::Playlist {
|
||
owner_uid: "100".into(),
|
||
kind: "5".into(),
|
||
title: "Road Trip".into()
|
||
}
|
||
);
|
||
|
||
// ResetContextToMyVibe resets context back to default My Vibe
|
||
app.is_vibe_active = false;
|
||
app.shuffle = true;
|
||
app.repeat = RepeatMode::All;
|
||
app.dispatch(AppAction::ResetContextToMyVibe);
|
||
assert!(app.is_vibe_active);
|
||
assert_eq!(app.context_key, "vibe:user:onyourwave");
|
||
assert_eq!(app.active_vibe_title, app.i18n().my_vibe());
|
||
assert!(!app.shuffle);
|
||
assert_eq!(app.repeat, RepeatMode::Off);
|
||
}
|
||
|
||
#[test]
|
||
fn test_words_card_state_feedback_and_big_card() {
|
||
let tracks = vec![make_track("w1", "Track One"), make_track("w2", "Track Two")];
|
||
let (_rt, mut app) = make_test_state(tracks);
|
||
|
||
// Simulate WordsCardsLoaded delivering a FACT card for w1 and empty for w2
|
||
app.words_loading_tracks.insert("w1".into());
|
||
app.words_loading_tracks.insert("w2".into());
|
||
let card = WordsCard {
|
||
id: "c_1".into(),
|
||
track_id: "w1".into(),
|
||
text: "Факт о треке".into(),
|
||
tags: vec!["FACT".into()],
|
||
action: None,
|
||
actions: vec![WordsCardSource {
|
||
title: "Wiki".into(),
|
||
url: "https://wikipedia.org".into(),
|
||
favicon_url: None,
|
||
}],
|
||
big_card_ids: vec!["big_1".into()],
|
||
feedback_state: None,
|
||
};
|
||
let _ = app.tx_api.send(ApiEvent::WordsCardsLoaded(vec![
|
||
("w1".into(), Some(card)),
|
||
("w2".into(), None),
|
||
]));
|
||
assert!(app.poll_async_events());
|
||
assert!(app.words_loading_tracks.is_empty());
|
||
assert!(app.words_empty_tracks.contains("w2"));
|
||
|
||
let cur = app.current_words_card().expect("w1 card should be active");
|
||
assert!(cur.is_fact());
|
||
assert!(cur.has_big_card());
|
||
assert!(!cur.is_liked());
|
||
assert!(!cur.is_disliked());
|
||
|
||
// Open big card & load content
|
||
app.dispatch(AppAction::OpenWordsBigCard {
|
||
track_id: "w1".into(),
|
||
});
|
||
assert!(app.words_big_card_open);
|
||
let _ = app.tx_api.send(ApiEvent::WordsBigCardLoaded(Some(WordsBigCard {
|
||
id: "big_1".into(),
|
||
text: "Полный рассказ о треке".into(),
|
||
actions: vec![],
|
||
})));
|
||
assert!(app.poll_async_events());
|
||
assert!(!app.words_big_card_loading);
|
||
assert_eq!(
|
||
app.words_big_card.as_ref().map(|b| b.id.as_str()),
|
||
Some("big_1")
|
||
);
|
||
|
||
// Like feedback sets localized toast message
|
||
app.dispatch(AppAction::SendWordsFeedback {
|
||
track_id: "w1".into(),
|
||
card_id: "c_1".into(),
|
||
state: "like".into(),
|
||
});
|
||
assert!(app.current_words_card().unwrap().is_liked());
|
||
assert_eq!(
|
||
app.current_words_feedback_message(),
|
||
Some("Спасибо за оценку")
|
||
);
|
||
|
||
// Dislike feedback closes big card modal and sets EN message after SetLanguage(En)
|
||
app.config.language = crate::config::Language::En;
|
||
app.dispatch(AppAction::SendWordsFeedback {
|
||
track_id: "w1".into(),
|
||
card_id: "c_1".into(),
|
||
state: "dislike".into(),
|
||
});
|
||
assert!(app.current_words_card().unwrap().is_disliked());
|
||
assert!(!app.words_big_card_open);
|
||
assert_eq!(
|
||
app.current_words_feedback_message(),
|
||
Some("Thank you for making me become better!")
|
||
);
|
||
|
||
// CloseWordsBigCard & DismissOverlays clear open state
|
||
app.words_big_card_open = true;
|
||
app.dispatch(AppAction::CloseWordsBigCard);
|
||
assert!(!app.words_big_card_open);
|
||
app.words_big_card_open = true;
|
||
app.dispatch(AppAction::DismissOverlays);
|
||
assert!(!app.words_big_card_open);
|
||
}
|
||
}
|