3121 lines
116 KiB
Rust
3121 lines
116 KiB
Rust
use crossbeam_channel::{unbounded, Receiver, Sender};
|
||
use std::collections::{HashMap, HashSet};
|
||
use std::path::PathBuf;
|
||
use std::sync::atomic::{AtomicBool, Ordering};
|
||
use std::sync::Arc;
|
||
use std::time::{Duration, Instant};
|
||
|
||
use crate::api::models::*;
|
||
use crate::api::signing::{extract_oauth_token, generate_request_id, iso8601_now};
|
||
use crate::api::{open_url_in_browser, YandexApiClient, YANDEX_OAUTH_URL};
|
||
use crate::audio::AudioEngine;
|
||
use crate::config::{AppConfig, AudioQuality, Language, PinnedItem, ThemeMode};
|
||
use crate::telemetry::PerfTelemetry;
|
||
use crate::vulkan::vibe_renderer::VibePushConstants;
|
||
|
||
use super::i18n::{tr, I18n, APP_VERSION};
|
||
|
||
// =============================================================================
|
||
// Public Navigation, Tab, Mode & Modal Enums
|
||
// =============================================================================
|
||
|
||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||
pub enum WindowCommand {
|
||
None,
|
||
DragWindow,
|
||
Minimize,
|
||
ToggleMaximize,
|
||
Close,
|
||
}
|
||
|
||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||
pub enum Route {
|
||
MyVibe,
|
||
ForYou,
|
||
Search,
|
||
Concerts,
|
||
Podcasts,
|
||
Collection,
|
||
Kids,
|
||
Chart,
|
||
Settings,
|
||
LikedTracks,
|
||
Metatags,
|
||
Metatag {
|
||
id: String,
|
||
title: String,
|
||
},
|
||
Playlist {
|
||
owner_uid: String,
|
||
kind: String,
|
||
title: String,
|
||
},
|
||
Album {
|
||
id: String,
|
||
title: String,
|
||
},
|
||
Artist {
|
||
id: String,
|
||
name: String,
|
||
},
|
||
}
|
||
|
||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||
pub enum ForYouTab {
|
||
ForYou,
|
||
Trends,
|
||
}
|
||
|
||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||
pub enum CollectionTab {
|
||
Tracks,
|
||
Playlists,
|
||
Albums,
|
||
Artists,
|
||
PodcastsAndBooks,
|
||
Downloaded,
|
||
History,
|
||
}
|
||
|
||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||
pub enum SearchFilter {
|
||
All,
|
||
Tracks,
|
||
Artists,
|
||
Albums,
|
||
Playlists,
|
||
}
|
||
|
||
impl SearchFilter {
|
||
pub fn api_filter(self) -> Option<&'static str> {
|
||
match self {
|
||
SearchFilter::All => None,
|
||
SearchFilter::Tracks => Some("track"),
|
||
SearchFilter::Artists => Some("artist"),
|
||
SearchFilter::Albums => Some("album"),
|
||
SearchFilter::Playlists => Some("playlist"),
|
||
}
|
||
}
|
||
}
|
||
|
||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||
pub enum SearchBrowseTab {
|
||
Popular,
|
||
History,
|
||
}
|
||
|
||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||
pub enum RepeatMode {
|
||
Off,
|
||
All,
|
||
One,
|
||
}
|
||
|
||
impl RepeatMode {
|
||
pub fn next(self) -> Self {
|
||
match self {
|
||
RepeatMode::Off => RepeatMode::All,
|
||
RepeatMode::All => RepeatMode::One,
|
||
RepeatMode::One => RepeatMode::Off,
|
||
}
|
||
}
|
||
|
||
pub fn as_str(self) -> &'static str {
|
||
match self {
|
||
RepeatMode::Off => "off",
|
||
RepeatMode::All => "all",
|
||
RepeatMode::One => "one",
|
||
}
|
||
}
|
||
|
||
pub fn from_config_str(s: &str) -> Self {
|
||
match s {
|
||
"all" => RepeatMode::All,
|
||
"one" => RepeatMode::One,
|
||
_ => RepeatMode::Off,
|
||
}
|
||
}
|
||
}
|
||
|
||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||
pub enum RightDrawerTab {
|
||
None,
|
||
Queue,
|
||
Lyrics,
|
||
}
|
||
|
||
#[derive(Debug, Clone)]
|
||
pub enum PlaylistModalState {
|
||
None,
|
||
Create {
|
||
title_draft: String,
|
||
is_private: bool,
|
||
initial_track: Option<Track>,
|
||
},
|
||
Rename {
|
||
owner_uid: String,
|
||
kind: String,
|
||
title_draft: String,
|
||
},
|
||
}
|
||
|
||
// =============================================================================
|
||
// Unified Action Enum (emitted by all Chrome, Overlays & Content Views)
|
||
// =============================================================================
|
||
|
||
#[derive(Debug, Clone)]
|
||
pub enum AppAction {
|
||
None,
|
||
|
||
// Navigation & Shell
|
||
Navigate(Route),
|
||
NavigateToCurrentContext,
|
||
NavigateCollectionTab(CollectionTab),
|
||
SetForYouTab(ForYouTab),
|
||
GoBack,
|
||
GoForward,
|
||
ToggleSidebarCollapse,
|
||
OpenPin(PinnedItem),
|
||
PlayWavePin(PinnedItem),
|
||
OpenUrl(String),
|
||
OpenPromoUrl(String),
|
||
|
||
// Playback & Queue
|
||
TogglePlay,
|
||
Play,
|
||
Pause,
|
||
Stop,
|
||
Prev,
|
||
Next,
|
||
SeekMs(u64),
|
||
SeekFraction(f32),
|
||
SetVolume(f32),
|
||
ToggleMute,
|
||
ToggleShuffle,
|
||
CycleRepeat,
|
||
PlayTracks {
|
||
tracks: Vec<Track>,
|
||
start_index: usize,
|
||
context_name: String,
|
||
context_key: String,
|
||
is_vibe: bool,
|
||
},
|
||
ToggleContextPlay {
|
||
tracks: Vec<Track>,
|
||
context_name: String,
|
||
context_key: String,
|
||
is_vibe: bool,
|
||
},
|
||
PlayAlbum {
|
||
id: String,
|
||
title: String,
|
||
},
|
||
PlayPlaylist {
|
||
owner_uid: String,
|
||
kind: String,
|
||
title: String,
|
||
},
|
||
PlayArtist {
|
||
id: String,
|
||
name: String,
|
||
},
|
||
PlayFavorites,
|
||
JumpQueue(usize),
|
||
RemoveQueueAt(usize),
|
||
MoveQueue {
|
||
from: usize,
|
||
to: usize,
|
||
},
|
||
ClearQueue,
|
||
AddToQueue(Track),
|
||
PlayNext(Track),
|
||
AddTracksToQueue(Vec<Track>),
|
||
PlayTracksNext(Vec<Track>),
|
||
|
||
// My Vibe & Wheel
|
||
ToggleMyVibe,
|
||
ResetContextToMyVibe,
|
||
SelectVibeStation {
|
||
label: String,
|
||
hue: f32,
|
||
mood: Option<String>,
|
||
activity: Option<String>,
|
||
seeds: Vec<String>,
|
||
},
|
||
ActivateWheelItem(VibeStationSummary),
|
||
ReshuffleWheel,
|
||
StartVibeBySeeds {
|
||
title: String,
|
||
seeds: Vec<String>,
|
||
},
|
||
StartVibeStation {
|
||
title: String,
|
||
seeds: Vec<String>,
|
||
},
|
||
RefreshConcerts,
|
||
RefreshNonMusic,
|
||
ApplyVibeSettings {
|
||
mood: Option<String>,
|
||
activity: Option<String>,
|
||
character: Option<String>,
|
||
language: Option<String>,
|
||
},
|
||
|
||
// Likes, Dislikes & Pins
|
||
ToggleLike(Track),
|
||
ToggleDislike(Track),
|
||
TogglePin {
|
||
kind: String,
|
||
id: String,
|
||
title: String,
|
||
subtitle: String,
|
||
cover_uri: Option<String>,
|
||
owner_uid: Option<String>,
|
||
},
|
||
UnpinItem(PinnedItem),
|
||
|
||
// Favorites Filter & Search
|
||
SelectFavoriteFilter(Option<String>),
|
||
SetSearchQuery(String),
|
||
RunSearchNow(String),
|
||
SetSearchFilter(SearchFilter),
|
||
SetSearchBrowseTab(SearchBrowseTab),
|
||
ClearSearchHistory,
|
||
|
||
// Playlists CRUD & Modals
|
||
OpenCreatePlaylistModal {
|
||
initial_track: Option<Track>,
|
||
},
|
||
OpenRenamePlaylistModal {
|
||
owner_uid: String,
|
||
kind: String,
|
||
current_title: String,
|
||
},
|
||
ClosePlaylistModal,
|
||
CreatePlaylist {
|
||
title: String,
|
||
is_private: bool,
|
||
initial_track: Option<Track>,
|
||
},
|
||
RenamePlaylist {
|
||
owner_uid: String,
|
||
kind: String,
|
||
new_title: String,
|
||
},
|
||
DeletePlaylist {
|
||
owner_uid: String,
|
||
kind: String,
|
||
},
|
||
AddTrackToPlaylist {
|
||
owner_uid: String,
|
||
kind: String,
|
||
track: Track,
|
||
},
|
||
RemoveTrackFromPlaylist {
|
||
owner_uid: String,
|
||
kind: String,
|
||
index: usize,
|
||
},
|
||
|
||
// Offline Downloads
|
||
DownloadTrack(Track),
|
||
DownloadTracks(Vec<Track>),
|
||
CancelDownload,
|
||
RemoveDownloadedTrack(String),
|
||
RemoveDownloadedTracks(Vec<String>),
|
||
|
||
// Share & Clipboard
|
||
CopyToClipboard {
|
||
text: String,
|
||
toast_msg: String,
|
||
},
|
||
CopyTrackLink(Track),
|
||
CopyTrackEmbed(Track),
|
||
CopyEntityLink {
|
||
kind: String,
|
||
url: String,
|
||
},
|
||
|
||
// Overlays & Modals
|
||
ToggleRightDrawer(RightDrawerTab),
|
||
CloseRightDrawer,
|
||
ToggleFullscreen,
|
||
SetFullscreen(bool),
|
||
OpenFullscreenSyncLyrics,
|
||
OpenFullscreenQueue,
|
||
ToggleFullscreenLyrics,
|
||
ToggleFullscreenQueue,
|
||
SetVibeModalOpen(bool),
|
||
SetLoginModalOpen(bool),
|
||
SetEqPopoverOpen(bool),
|
||
OpenTrackDetailModal(Track),
|
||
CloseTrackDetailModal,
|
||
OpenWordsBigCard {
|
||
track_id: String,
|
||
},
|
||
CloseWordsBigCard,
|
||
SendWordsFeedback {
|
||
track_id: String,
|
||
card_id: String,
|
||
state: String,
|
||
},
|
||
DismissOverlays,
|
||
|
||
// Account, Settings & Lifecycle
|
||
SetTheme(ThemeMode),
|
||
SetLanguage(Language),
|
||
ToggleLanguage,
|
||
SetAudioQuality(AudioQuality),
|
||
SetNormalizeLoudness(bool),
|
||
SetCrossfadeSecs(f32),
|
||
SetAiContentReduction(bool),
|
||
SetChildMode(bool),
|
||
SetCloseToTray(bool),
|
||
UpdateEq {
|
||
enabled: bool,
|
||
bands: [f32; 10],
|
||
},
|
||
SetMaxCoverCache(usize),
|
||
ClearCoverCache,
|
||
TogglePerfHud(bool),
|
||
OpenOAuthBrowser,
|
||
SubmitOAuthToken(String),
|
||
Logout,
|
||
CheckForUpdates,
|
||
ShowToast(String),
|
||
}
|
||
|
||
// =============================================================================
|
||
// Internal Async API Event Channel
|
||
// =============================================================================
|
||
|
||
pub(crate) enum ApiEvent {
|
||
AccountLoaded(Result<UserAccount, String>),
|
||
LandingLoaded(LandingData),
|
||
ConcertsLoaded(Vec<ConcertItem>),
|
||
NonMusicLoaded(Vec<NonMusicSection>, Vec<AlbumSummary>),
|
||
SearchHistoryLoaded(Vec<String>),
|
||
LikedTracksLoaded(Vec<Track>),
|
||
FavoriteFiltersLoaded(Vec<TrackFilterChip>),
|
||
LibraryIdsLoaded(LibraryAllIds),
|
||
LikedAlbumsLoaded(Vec<AlbumSummary>),
|
||
LikedArtistsLoaded(Vec<ArtistSummary>),
|
||
BookshelfLoaded(Vec<AlbumSummary>),
|
||
PinsLoaded(Vec<PinnedItem>),
|
||
WheelLoaded(Vec<VibeStationSummary>),
|
||
MusicHistoryLoaded(Vec<Track>),
|
||
UserPlaylistsLoaded(Vec<PlaylistSummary>),
|
||
MetatagsLoaded(Vec<MetatagTree>),
|
||
MetatagDetailLoaded(MetatagDetail),
|
||
SearchLoaded(SearchResults),
|
||
PlaylistDetailLoaded(PlaylistDetail),
|
||
AlbumDetailLoaded(AlbumDetail),
|
||
ArtistDetailLoaded(ArtistDetail),
|
||
PlayAlbumTracks(String, String, Vec<Track>),
|
||
PlayPlaylistTracks(String, String, Vec<Track>),
|
||
PlayArtistTracks(String, String, Vec<Track>),
|
||
VibeTracksLoaded(Vec<Track>, bool),
|
||
RotorSessionStarted(RotorSession, bool),
|
||
RotorBatchAppended(Option<String>, Vec<Track>, bool),
|
||
StreamResolved {
|
||
track_id: String,
|
||
duration_ms: u64,
|
||
r128_i: Option<f32>,
|
||
r128_tp: Option<f32>,
|
||
result: Result<ResolvedStream, String>,
|
||
},
|
||
LyricsLoaded(TrackLyrics),
|
||
WordsCardsLoaded(Vec<(String, Option<WordsCard>)>),
|
||
WordsBigCardLoaded(Option<WordsBigCard>),
|
||
QueueTracksHydrated(Vec<Track>),
|
||
OAuthTokenReceived(Result<String, String>),
|
||
PlaylistCreated {
|
||
result: Result<PlaylistSummary, String>,
|
||
initial_track: Option<Track>,
|
||
},
|
||
PlaylistRenamed {
|
||
owner_uid: String,
|
||
kind: String,
|
||
result: Result<PlaylistSummary, String>,
|
||
},
|
||
PlaylistDeleted {
|
||
owner_uid: String,
|
||
kind: String,
|
||
result: Result<(), String>,
|
||
},
|
||
PlaylistTracksChanged {
|
||
owner_uid: String,
|
||
kind: String,
|
||
revision: Result<u32, String>,
|
||
toast_msg: String,
|
||
},
|
||
TrackDownloaded {
|
||
track: Track,
|
||
result: Result<PathBuf, String>,
|
||
},
|
||
UpdateCheckFinished(Result<Option<(String, String)>, String>),
|
||
}
|
||
|
||
// =============================================================================
|
||
// Complete egui-free Application State
|
||
// =============================================================================
|
||
|
||
pub struct AppState {
|
||
pub config: AppConfig,
|
||
pub audio: AudioEngine,
|
||
pub perf: PerfTelemetry,
|
||
pub gpu_name: String,
|
||
|
||
pub(crate) runtime: tokio::runtime::Handle,
|
||
pub(crate) api: YandexApiClient,
|
||
pub(crate) tx_api: Sender<ApiEvent>,
|
||
pub(crate) rx_api: Receiver<ApiEvent>,
|
||
|
||
// Navigation & History
|
||
pub route: Route,
|
||
pub history_back: Vec<Route>,
|
||
pub history_forward: Vec<Route>,
|
||
pub for_you_tab: ForYouTab,
|
||
|
||
// Data state
|
||
pub account: Option<UserAccount>,
|
||
pub landing: LandingData,
|
||
pub concerts: Vec<ConcertItem>,
|
||
pub concerts_loading: bool,
|
||
pub non_music_sections: Vec<NonMusicSection>,
|
||
pub non_music_loading: bool,
|
||
pub liked_tracks: Vec<Track>,
|
||
pub liked_ids: HashSet<String>,
|
||
pub disliked_ids: HashSet<String>,
|
||
pub liked_albums: Vec<AlbumSummary>,
|
||
pub liked_artists: Vec<ArtistSummary>,
|
||
pub bookshelf_items: Vec<AlbumSummary>,
|
||
pub user_playlists: Vec<PlaylistSummary>,
|
||
pub play_history: Vec<Track>,
|
||
pub wheel_stations: Vec<VibeStationSummary>,
|
||
pub metatags: Vec<MetatagTree>,
|
||
pub current_metatag_detail: Option<MetatagDetail>,
|
||
|
||
// Favorites filter chips (`POST /filters/tracks`)
|
||
pub favorite_filters: Vec<TrackFilterChip>,
|
||
pub selected_favorite_filter_id: Option<String>,
|
||
|
||
// Offline cache & download tracking
|
||
pub downloaded_track_ids: HashSet<String>,
|
||
pub downloading_track_ids: HashSet<String>,
|
||
pub download_batch_total: usize,
|
||
pub download_batch_done: usize,
|
||
pub download_cancel: Arc<AtomicBool>,
|
||
|
||
// Page-specific states
|
||
pub search_query: String,
|
||
pub search_debounce_deadline: Option<Instant>,
|
||
pub search_filter: SearchFilter,
|
||
pub search_browse_tab: SearchBrowseTab,
|
||
pub search_loading: bool,
|
||
pub search_results: Option<SearchResults>,
|
||
pub collection_tab: CollectionTab,
|
||
pub detail_loading: bool,
|
||
pub detail_track_filter: String,
|
||
pub current_playlist_detail: Option<PlaylistDetail>,
|
||
pub current_album_detail: Option<AlbumDetail>,
|
||
pub current_artist_detail: Option<ArtistDetail>,
|
||
|
||
// Playback queue & My Vibe Rotor Session state
|
||
pub queue: Vec<Track>,
|
||
pub unshuffled_queue: Vec<Track>,
|
||
pub queue_index: usize,
|
||
pub context_name: String,
|
||
pub context_key: String,
|
||
pub active_vibe_title: String,
|
||
pub is_vibe_active: bool,
|
||
pub active_rotor_session: Option<RotorSession>,
|
||
pub vibe_started: bool,
|
||
pub vibe_prefetching: bool,
|
||
pub shuffle: bool,
|
||
pub repeat: RepeatMode,
|
||
pub current_lyrics: Option<TrackLyrics>,
|
||
pub modal_lyrics: Option<TrackLyrics>,
|
||
|
||
// Official 5.129.0 AI WordsCard state (`POST /words/cards`, `/words/big-cards`, `PUT /words/cards/feedback`)
|
||
pub words_cards: HashMap<String, WordsCard>,
|
||
pub words_loading_tracks: HashSet<String>,
|
||
pub words_empty_tracks: HashSet<String>,
|
||
pub words_big_card: Option<WordsBigCard>,
|
||
pub words_big_card_loading: bool,
|
||
pub words_big_card_open: bool,
|
||
pub words_feedback_message: Option<(String, Instant)>,
|
||
pub current_hue: f32,
|
||
pub target_hue: f32,
|
||
pub smooth_sat: f32,
|
||
pub smooth_light: f32,
|
||
pub vibe_phase: f32,
|
||
pub smooth_playing: f32,
|
||
pub smooth_energy: f32,
|
||
pub smooth_bass: f32,
|
||
pub last_vibe_tick: Instant,
|
||
|
||
// Exact 5.129.0 `/plays` telemetry tracking
|
||
pub current_play_id: String,
|
||
pub play_start_iso: String,
|
||
pub play_seeked: bool,
|
||
pub play_paused: bool,
|
||
pub play_from_cache: bool,
|
||
pub last_play_heartbeat: Instant,
|
||
pub last_unfocused_at: Option<Instant>,
|
||
|
||
// Overlays, Drawers & Modals
|
||
pub right_drawer: RightDrawerTab,
|
||
pub fullscreen_open: bool,
|
||
pub fullscreen_lyrics_open: bool,
|
||
pub fullscreen_queue_open: bool,
|
||
pub vibe_modal_open: bool,
|
||
pub login_modal_open: bool,
|
||
pub eq_popover_open: bool,
|
||
pub playlist_modal: PlaylistModalState,
|
||
pub track_detail_modal: Option<Track>,
|
||
pub token_input: String,
|
||
pub toast: Option<(String, Instant)>,
|
||
|
||
// Lifecycle, Clipboard & Shell Sync Flags
|
||
pub start_time: Instant,
|
||
pub fixed_vibe_time: Option<f32>,
|
||
pub theme_dirty: bool,
|
||
pub clear_cover_cache_requested: bool,
|
||
pub cover_cache_capacity_dirty: bool,
|
||
pub pending_clipboard_text: Option<String>,
|
||
pub available_update: Option<(String, String)>,
|
||
pub persist_enabled: bool,
|
||
}
|
||
|
||
impl AppState {
|
||
pub fn new(runtime: tokio::runtime::Handle, gpu_name: String) -> Self {
|
||
let config = AppConfig::load();
|
||
let audio = AudioEngine::new(
|
||
config.volume,
|
||
config.muted,
|
||
config.eq_enabled,
|
||
config.eq_bands_db,
|
||
config.normalize_loudness,
|
||
config.crossfade_secs,
|
||
);
|
||
let mut api = YandexApiClient::new(config.oauth_token.clone());
|
||
api.set_language(config.language.api_code());
|
||
api.set_ai_content_reduction(config.ai_content_reduction);
|
||
let (tx_api, rx_api) = unbounded();
|
||
|
||
let initial_route = std::env::args()
|
||
.find_map(|a| a.strip_prefix("--page=").map(String::from))
|
||
.map(|p| match p.as_str() {
|
||
"search" => Route::Search,
|
||
"foryou" => Route::ForYou,
|
||
"favorites" => Route::LikedTracks,
|
||
"settings" => Route::Settings,
|
||
"collection" => Route::Collection,
|
||
_ => Route::MyVibe,
|
||
})
|
||
.unwrap_or(Route::MyVibe);
|
||
|
||
let fixed_time = std::env::args()
|
||
.find_map(|a| a.strip_prefix("--fixed-time=").and_then(|v| v.parse::<f32>().ok()));
|
||
let offline_mode = std::env::args().any(|a| a == "--offline");
|
||
|
||
let default_vibe = tr(config.language).my_vibe().to_string();
|
||
let mut app = Self {
|
||
config,
|
||
audio,
|
||
perf: PerfTelemetry::new(),
|
||
gpu_name,
|
||
runtime,
|
||
api,
|
||
tx_api,
|
||
rx_api,
|
||
route: initial_route,
|
||
history_back: Vec::new(),
|
||
history_forward: Vec::new(),
|
||
for_you_tab: ForYouTab::ForYou,
|
||
account: None,
|
||
landing: LandingData::default(),
|
||
concerts: Vec::new(),
|
||
concerts_loading: false,
|
||
non_music_sections: Vec::new(),
|
||
non_music_loading: false,
|
||
liked_tracks: Vec::new(),
|
||
liked_ids: HashSet::new(),
|
||
disliked_ids: HashSet::new(),
|
||
liked_albums: Vec::new(),
|
||
liked_artists: Vec::new(),
|
||
bookshelf_items: Vec::new(),
|
||
user_playlists: Vec::new(),
|
||
play_history: Vec::new(),
|
||
wheel_stations: Vec::new(),
|
||
metatags: Vec::new(),
|
||
current_metatag_detail: None,
|
||
favorite_filters: Vec::new(),
|
||
selected_favorite_filter_id: None,
|
||
downloaded_track_ids: HashSet::new(),
|
||
downloading_track_ids: HashSet::new(),
|
||
download_batch_total: 0,
|
||
download_batch_done: 0,
|
||
download_cancel: Arc::new(AtomicBool::new(false)),
|
||
search_query: String::new(),
|
||
search_debounce_deadline: None,
|
||
search_filter: SearchFilter::All,
|
||
search_browse_tab: SearchBrowseTab::Popular,
|
||
search_loading: false,
|
||
search_results: None,
|
||
collection_tab: CollectionTab::Tracks,
|
||
detail_loading: false,
|
||
detail_track_filter: String::new(),
|
||
current_playlist_detail: None,
|
||
current_album_detail: None,
|
||
current_artist_detail: None,
|
||
queue: Vec::new(),
|
||
unshuffled_queue: Vec::new(),
|
||
queue_index: 0,
|
||
context_name: default_vibe.clone(),
|
||
context_key: String::new(),
|
||
active_vibe_title: default_vibe,
|
||
is_vibe_active: false,
|
||
active_rotor_session: None,
|
||
vibe_started: false,
|
||
vibe_prefetching: false,
|
||
shuffle: false,
|
||
repeat: RepeatMode::Off,
|
||
current_lyrics: None,
|
||
modal_lyrics: None,
|
||
words_cards: HashMap::new(),
|
||
words_loading_tracks: HashSet::new(),
|
||
words_empty_tracks: HashSet::new(),
|
||
words_big_card: None,
|
||
words_big_card_loading: false,
|
||
words_big_card_open: false,
|
||
words_feedback_message: None,
|
||
current_hue: 0.12,
|
||
target_hue: 0.12,
|
||
smooth_sat: 1.0,
|
||
smooth_light: 0.50,
|
||
vibe_phase: 0.0,
|
||
smooth_playing: 0.0,
|
||
smooth_energy: 0.0,
|
||
smooth_bass: 0.0,
|
||
last_vibe_tick: Instant::now(),
|
||
current_play_id: generate_request_id(),
|
||
play_start_iso: iso8601_now(),
|
||
play_seeked: false,
|
||
play_paused: false,
|
||
play_from_cache: false,
|
||
last_play_heartbeat: Instant::now(),
|
||
last_unfocused_at: None,
|
||
right_drawer: RightDrawerTab::None,
|
||
fullscreen_open: false,
|
||
fullscreen_lyrics_open: false,
|
||
fullscreen_queue_open: false,
|
||
vibe_modal_open: false,
|
||
login_modal_open: false,
|
||
eq_popover_open: false,
|
||
playlist_modal: PlaylistModalState::None,
|
||
track_detail_modal: None,
|
||
token_input: String::new(),
|
||
toast: None,
|
||
start_time: Instant::now(),
|
||
fixed_vibe_time: fixed_time,
|
||
theme_dirty: true,
|
||
clear_cover_cache_requested: false,
|
||
cover_cache_capacity_dirty: false,
|
||
pending_clipboard_text: None,
|
||
available_update: None,
|
||
persist_enabled: true,
|
||
};
|
||
|
||
app.restore_from_config();
|
||
app.scan_offline_cache();
|
||
|
||
if !offline_mode {
|
||
app.bootstrap_api();
|
||
}
|
||
app
|
||
}
|
||
|
||
/// Deterministic offline constructor for headless visual parity tests and unit tests.
|
||
/// Does NOT touch user config on disk, does NOT spawn audio or network calls.
|
||
#[allow(clippy::too_many_arguments)]
|
||
pub fn new_visual_test(
|
||
runtime: tokio::runtime::Handle,
|
||
gpu_name: String,
|
||
route: Route,
|
||
config: AppConfig,
|
||
landing: LandingData,
|
||
account: Option<UserAccount>,
|
||
liked_tracks: Vec<Track>,
|
||
queue: Vec<Track>,
|
||
position_ms: u64,
|
||
duration_ms: u64,
|
||
fixed_vibe_time: f32,
|
||
) -> Self {
|
||
let audio = AudioEngine::new_headless(
|
||
config.volume,
|
||
config.muted,
|
||
config.eq_enabled,
|
||
config.eq_bands_db,
|
||
);
|
||
audio.state.position_ms.store(position_ms, Ordering::SeqCst);
|
||
audio.state.duration_ms.store(duration_ms, Ordering::SeqCst);
|
||
let api = YandexApiClient::new(None);
|
||
let (tx_api, rx_api) = unbounded();
|
||
let liked_ids: HashSet<String> = liked_tracks.iter().map(|t| t.id.clone()).collect();
|
||
let downloaded_ids: HashSet<String> = config
|
||
.downloaded_tracks
|
||
.iter()
|
||
.map(|t| t.id.clone())
|
||
.collect();
|
||
let default_vibe = tr(config.language).my_vibe().to_string();
|
||
|
||
Self {
|
||
config,
|
||
audio,
|
||
perf: PerfTelemetry::new(),
|
||
gpu_name,
|
||
runtime,
|
||
api,
|
||
tx_api,
|
||
rx_api,
|
||
route,
|
||
history_back: vec![Route::ForYou],
|
||
history_forward: Vec::new(),
|
||
for_you_tab: ForYouTab::ForYou,
|
||
account,
|
||
landing,
|
||
concerts: Vec::new(),
|
||
concerts_loading: false,
|
||
non_music_sections: Vec::new(),
|
||
non_music_loading: false,
|
||
liked_tracks,
|
||
liked_ids,
|
||
disliked_ids: HashSet::new(),
|
||
liked_albums: Vec::new(),
|
||
liked_artists: Vec::new(),
|
||
bookshelf_items: Vec::new(),
|
||
user_playlists: Vec::new(),
|
||
play_history: Vec::new(),
|
||
wheel_stations: Vec::new(),
|
||
metatags: Vec::new(),
|
||
current_metatag_detail: None,
|
||
favorite_filters: Vec::new(),
|
||
selected_favorite_filter_id: None,
|
||
downloaded_track_ids: downloaded_ids,
|
||
downloading_track_ids: HashSet::new(),
|
||
download_batch_total: 0,
|
||
download_batch_done: 0,
|
||
download_cancel: Arc::new(AtomicBool::new(false)),
|
||
search_query: String::new(),
|
||
search_debounce_deadline: None,
|
||
search_filter: SearchFilter::All,
|
||
search_browse_tab: SearchBrowseTab::Popular,
|
||
search_loading: false,
|
||
search_results: None,
|
||
collection_tab: CollectionTab::Tracks,
|
||
detail_loading: false,
|
||
detail_track_filter: String::new(),
|
||
current_playlist_detail: None,
|
||
current_album_detail: None,
|
||
current_artist_detail: None,
|
||
queue,
|
||
unshuffled_queue: Vec::new(),
|
||
queue_index: 0,
|
||
context_name: default_vibe.clone(),
|
||
context_key: String::new(),
|
||
active_vibe_title: default_vibe,
|
||
is_vibe_active: false,
|
||
active_rotor_session: None,
|
||
vibe_started: false,
|
||
vibe_prefetching: false,
|
||
shuffle: false,
|
||
repeat: RepeatMode::Off,
|
||
current_lyrics: None,
|
||
modal_lyrics: None,
|
||
words_cards: HashMap::new(),
|
||
words_loading_tracks: HashSet::new(),
|
||
words_empty_tracks: HashSet::new(),
|
||
words_big_card: None,
|
||
words_big_card_loading: false,
|
||
words_big_card_open: false,
|
||
words_feedback_message: None,
|
||
current_hue: 0.12,
|
||
target_hue: 0.12,
|
||
smooth_sat: 1.0,
|
||
smooth_light: 0.50,
|
||
vibe_phase: 0.0,
|
||
smooth_playing: 0.0,
|
||
smooth_energy: 0.0,
|
||
smooth_bass: 0.0,
|
||
last_vibe_tick: Instant::now(),
|
||
current_play_id: String::new(),
|
||
play_start_iso: String::new(),
|
||
play_seeked: false,
|
||
play_paused: false,
|
||
play_from_cache: false,
|
||
last_play_heartbeat: Instant::now(),
|
||
last_unfocused_at: None,
|
||
right_drawer: RightDrawerTab::None,
|
||
fullscreen_open: false,
|
||
fullscreen_lyrics_open: false,
|
||
fullscreen_queue_open: false,
|
||
vibe_modal_open: false,
|
||
login_modal_open: false,
|
||
eq_popover_open: false,
|
||
playlist_modal: PlaylistModalState::None,
|
||
track_detail_modal: None,
|
||
token_input: String::new(),
|
||
toast: None,
|
||
start_time: Instant::now(),
|
||
fixed_vibe_time: Some(fixed_vibe_time),
|
||
theme_dirty: true,
|
||
clear_cover_cache_requested: false,
|
||
cover_cache_capacity_dirty: false,
|
||
pending_clipboard_text: None,
|
||
available_update: None,
|
||
persist_enabled: false,
|
||
}
|
||
}
|
||
|
||
/// Restore persisted queue, position, context, shuffle, and repeat from `self.config`.
|
||
pub fn restore_from_config(&mut self) {
|
||
if !self.config.last_queue.is_empty() {
|
||
self.queue = self.config.last_queue.clone();
|
||
self.queue_index = self
|
||
.config
|
||
.last_queue_index
|
||
.min(self.queue.len().saturating_sub(1));
|
||
self.audio
|
||
.state
|
||
.position_ms
|
||
.store(self.config.last_position_ms, Ordering::SeqCst);
|
||
if let Some(tr) = self.queue.get(self.queue_index) {
|
||
// Keep duration_ms = 0 until playback starts so `toggle_play` resolves & loads audio!
|
||
let _ = tr;
|
||
}
|
||
}
|
||
if !self.config.last_context_name.is_empty() {
|
||
self.context_name = self.config.last_context_name.clone();
|
||
}
|
||
self.is_vibe_active = self.config.last_is_vibe;
|
||
self.repeat = RepeatMode::from_config_str(&self.config.repeat_mode);
|
||
self.shuffle = self.config.shuffle;
|
||
if self.is_vibe_active {
|
||
self.shuffle = false;
|
||
if self.repeat == RepeatMode::All {
|
||
self.repeat = RepeatMode::Off;
|
||
}
|
||
}
|
||
}
|
||
|
||
/// Persist playback session state into `self.config` (and write to disk if `persist_enabled`).
|
||
pub fn save_playback_state(&mut self) {
|
||
self.config.last_queue = self.queue.iter().take(200).cloned().collect();
|
||
self.config.last_queue_index = self.queue_index;
|
||
self.config.last_position_ms = self.audio.state.position_ms.load(Ordering::Relaxed);
|
||
self.config.last_context_name = self.context_name.clone();
|
||
self.config.last_is_vibe = self.is_vibe_active;
|
||
self.config.shuffle = self.shuffle;
|
||
self.config.repeat_mode = self.repeat.as_str().to_string();
|
||
if self.persist_enabled {
|
||
self.config.save();
|
||
}
|
||
}
|
||
|
||
pub(crate) fn save_config(&self) {
|
||
if self.persist_enabled {
|
||
self.config.save();
|
||
}
|
||
}
|
||
|
||
/// Clean shutdown: flushes final `POST /plays` synchronously (1.5s timeout), saves config, stops audio!
|
||
pub fn graceful_shutdown(&mut self) {
|
||
self.save_playback_state();
|
||
|
||
if let Some(ev) = self.build_play_telemetry_event("close") {
|
||
let api = self.api.clone();
|
||
// Flush synchronously with a 1.5s timeout without panicking if called inside a runtime
|
||
if tokio::runtime::Handle::try_current().is_err() {
|
||
let _ = self.runtime.block_on(async move {
|
||
let _ = tokio::time::timeout(
|
||
Duration::from_millis(1500),
|
||
api.send_plays(&[ev]),
|
||
)
|
||
.await;
|
||
});
|
||
} else {
|
||
let rt = self.runtime.clone();
|
||
let handle = std::thread::spawn(move || {
|
||
let _ = rt.block_on(async move {
|
||
let _ = tokio::time::timeout(
|
||
Duration::from_millis(1500),
|
||
api.send_plays(&[ev]),
|
||
)
|
||
.await;
|
||
});
|
||
});
|
||
let _ = handle.join();
|
||
}
|
||
}
|
||
|
||
self.audio.stop();
|
||
}
|
||
|
||
pub fn i18n(&self) -> I18n {
|
||
tr(self.config.language)
|
||
}
|
||
|
||
pub fn has_token(&self) -> bool {
|
||
self.api.has_token()
|
||
}
|
||
|
||
pub fn is_audio_playing(&self) -> bool {
|
||
self.audio.state.is_playing.load(Ordering::Relaxed)
|
||
}
|
||
|
||
pub fn is_buffering(&self) -> bool {
|
||
self.audio.state.is_buffering.load(Ordering::Relaxed)
|
||
}
|
||
|
||
pub fn position_ms(&self) -> u64 {
|
||
self.audio.state.position_ms.load(Ordering::Acquire)
|
||
}
|
||
|
||
pub fn duration_ms(&self) -> u64 {
|
||
self.audio
|
||
.state
|
||
.duration_ms
|
||
.load(Ordering::Relaxed)
|
||
.max(self.current_track().map_or(0, |t| t.duration_ms))
|
||
}
|
||
|
||
pub fn current_track(&self) -> Option<&Track> {
|
||
self.queue.get(self.queue_index)
|
||
}
|
||
|
||
#[inline]
|
||
pub fn has_active_vibe_surface(&self) -> bool {
|
||
matches!(self.route, Route::MyVibe) && !self.fullscreen_open
|
||
}
|
||
|
||
pub fn needs_continuous_repaint(&self) -> bool {
|
||
let playing = self.audio.state.is_playing.load(Ordering::Relaxed);
|
||
let target_playing = if playing { 1.0_f32 } else { 0.0_f32 };
|
||
let vibe_transitioning = (self.smooth_playing - target_playing).abs() > 0.003
|
||
|| self.smooth_energy > 0.003
|
||
|| self.smooth_bass > 0.003;
|
||
let on_vibe = self.has_active_vibe_surface();
|
||
playing || on_vibe || vibe_transitioning || self.search_debounce_deadline.is_some()
|
||
}
|
||
|
||
/// Adaptive background repaint interval (`None` = purely event-driven, 0 FPS GPU usage).
|
||
/// Eliminates unnecessary 60 FPS full-screen Vulkan submits on static pages and unfocused windows!
|
||
pub fn continuous_repaint_interval(&self, window_focused: bool) -> Option<Duration> {
|
||
if self.search_debounce_deadline.is_some() {
|
||
return Some(Duration::from_millis(50));
|
||
}
|
||
|
||
let playing = self.audio.state.is_playing.load(Ordering::Relaxed);
|
||
if self.has_active_vibe_surface() {
|
||
if !window_focused {
|
||
// Background/unfocused My Vibe: low-power 15 FPS drift instead of 60 FPS
|
||
return Some(Duration::from_millis(66));
|
||
}
|
||
// Focused My Vibe: full 60 FPS smoothness (identical to original!)
|
||
return Some(Duration::from_millis(16));
|
||
}
|
||
|
||
if playing {
|
||
// Static pages (Favorites, ForYou, Search, Collection, Fullscreen, Detail):
|
||
// Progress bar moves ~1px every 150-250ms; no reason to spin GPU at 60 FPS!
|
||
let lyrics_visible = (self.fullscreen_open && self.fullscreen_lyrics_open)
|
||
|| self.right_drawer == RightDrawerTab::Lyrics;
|
||
if lyrics_visible {
|
||
return Some(Duration::from_millis(if window_focused { 100 } else { 500 }));
|
||
}
|
||
return Some(Duration::from_millis(if window_focused { 250 } else { 1000 }));
|
||
}
|
||
|
||
if self.toast.is_some() {
|
||
return Some(Duration::from_millis(250));
|
||
}
|
||
|
||
// Completely idle on a static page -> 0 FPS!
|
||
None
|
||
}
|
||
|
||
pub fn show_toast(&mut self, msg: impl Into<String>) {
|
||
self.toast = Some((msg.into(), Instant::now()));
|
||
}
|
||
|
||
/// Returns active toast message if within 3s display window.
|
||
pub fn current_toast(&mut self) -> Option<&str> {
|
||
if let Some((_, ts)) = self.toast {
|
||
if ts.elapsed() >= Duration::from_secs(3) {
|
||
self.toast = None;
|
||
return None;
|
||
}
|
||
}
|
||
self.toast.as_ref().map(|(m, _)| m.as_str())
|
||
}
|
||
|
||
pub fn take_clear_cover_cache_requested(&mut self) -> bool {
|
||
std::mem::take(&mut self.clear_cover_cache_requested)
|
||
}
|
||
|
||
pub fn take_cover_cache_capacity_dirty(&mut self) -> bool {
|
||
std::mem::take(&mut self.cover_cache_capacity_dirty)
|
||
}
|
||
|
||
pub fn take_pending_clipboard_text(&mut self) -> Option<String> {
|
||
self.pending_clipboard_text.take()
|
||
}
|
||
|
||
pub fn set_route_for_test(&mut self, route: Route) {
|
||
self.route = route;
|
||
self.detail_track_filter.clear();
|
||
self.selected_favorite_filter_id = None;
|
||
}
|
||
|
||
pub fn set_vibe_playback_for_test(&mut self, playing: bool, energy: f32, bass: f32) {
|
||
self.fixed_vibe_time = None;
|
||
self.audio.state.is_playing.store(playing, Ordering::SeqCst);
|
||
self.audio
|
||
.state
|
||
.energy_bits
|
||
.store(energy.to_bits(), Ordering::SeqCst);
|
||
self.audio
|
||
.state
|
||
.bass_bits
|
||
.store(bass.to_bits(), Ordering::SeqCst);
|
||
// Snap smoothly-damped playback state immediately for deterministic test setups
|
||
self.smooth_playing = if playing { 1.0 } else { 0.0 };
|
||
self.smooth_energy = if playing { energy.clamp(0.0, 1.0) } else { 0.0 };
|
||
self.smooth_bass = if playing { bass.clamp(0.0, 1.0) } else { 0.0 };
|
||
if let Some(tr) = self.queue.get(self.queue_index) {
|
||
let raw_rgb = tr
|
||
.derived_average_hex
|
||
.as_deref()
|
||
.and_then(parse_hex_rgb)
|
||
.or_else(|| tr.derived_accent_hex.as_deref().and_then(parse_hex_rgb));
|
||
if let Some(rgb) = raw_rgb {
|
||
let bucket = vibe_bucket_primary_rgb(Some(rgb));
|
||
let h = rgb_to_hue_f32(bucket[0], bucket[1], bucket[2]);
|
||
let (s, l) = rgb_to_hsl_sl_f32(bucket);
|
||
self.current_hue = h;
|
||
self.target_hue = h;
|
||
self.smooth_sat = s;
|
||
self.smooth_light = l;
|
||
} else {
|
||
self.current_hue = 0.12;
|
||
self.target_hue = 0.12;
|
||
self.smooth_sat = 1.0;
|
||
self.smooth_light = 0.50;
|
||
}
|
||
}
|
||
}
|
||
|
||
pub fn set_fixed_vibe_time_for_test(&mut self, t: Option<f32>) {
|
||
self.fixed_vibe_time = t;
|
||
}
|
||
|
||
pub fn set_wheel_stations_for_test(&mut self, stations: Vec<VibeStationSummary>) {
|
||
self.wheel_stations = stations;
|
||
}
|
||
|
||
/// Advance Vibe orb phase, audio smoothing, play/pause damping, and color interpolation (pure RGB, zero UI deps).
|
||
pub fn tick_vibe_animation(&mut self, dt_secs: f32, fallback_cover_rgb: Option<[u8; 3]>) {
|
||
let dt = dt_secs.clamp(0.0, 0.05);
|
||
let playing = self.audio.state.is_playing.load(Ordering::Relaxed);
|
||
let target_playing = if playing { 1.0_f32 } else { 0.0_f32 };
|
||
let alpha_p = 1.0 - (-dt * 3.5).exp();
|
||
self.smooth_playing += (target_playing - self.smooth_playing) * alpha_p;
|
||
if (self.smooth_playing - target_playing).abs() < 0.0005 {
|
||
self.smooth_playing = target_playing;
|
||
}
|
||
|
||
let raw_e = if playing {
|
||
self.audio.state.energy().clamp(0.0, 1.0)
|
||
} else {
|
||
0.0
|
||
};
|
||
let raw_b = if playing {
|
||
self.audio.state.bass().clamp(0.0, 1.0)
|
||
} else {
|
||
0.0
|
||
};
|
||
let alpha_e = 1.0 - (-dt * 6.0).exp();
|
||
let alpha_b = 1.0 - (-dt * 10.0).exp();
|
||
self.smooth_energy += (raw_e - self.smooth_energy) * alpha_e;
|
||
self.smooth_bass += (raw_b - self.smooth_bass) * alpha_b;
|
||
if self.smooth_energy < 0.0005 && !playing {
|
||
self.smooth_energy = 0.0;
|
||
}
|
||
if self.smooth_bass < 0.0005 && !playing {
|
||
self.smooth_bass = 0.0;
|
||
}
|
||
|
||
// Official `vibe_worker_0.js` phase speed: 0.20 idle -> 0.64 playing (+ energy modulation), smoothly blended!
|
||
let speed = 0.20 + (0.44 + self.smooth_energy * 0.35) * self.smooth_playing;
|
||
self.vibe_phase += dt * speed;
|
||
|
||
let (target_sat, target_light) = if let Some(tr) = self.queue.get(self.queue_index) {
|
||
let raw_rgb = tr
|
||
.derived_average_hex
|
||
.as_deref()
|
||
.and_then(parse_hex_rgb)
|
||
.or_else(|| tr.derived_accent_hex.as_deref().and_then(parse_hex_rgb))
|
||
.or(fallback_cover_rgb);
|
||
if let Some(rgb) = raw_rgb {
|
||
let bucket = vibe_bucket_primary_rgb(Some(rgb));
|
||
self.target_hue = rgb_to_hue_f32(bucket[0], bucket[1], bucket[2]);
|
||
rgb_to_hsl_sl_f32(bucket)
|
||
} else {
|
||
self.target_hue = 0.12;
|
||
(1.0, 0.50)
|
||
}
|
||
} else {
|
||
(1.0, 0.50)
|
||
};
|
||
let alpha_c = 1.0 - (-dt * 1.8).exp();
|
||
let mut dh = self.target_hue - self.current_hue;
|
||
if dh > 0.5 {
|
||
dh -= 1.0;
|
||
}
|
||
if dh < -0.5 {
|
||
dh += 1.0;
|
||
}
|
||
self.current_hue = (self.current_hue + dh * alpha_c).rem_euclid(1.0);
|
||
self.smooth_sat += (target_sat - self.smooth_sat) * alpha_c;
|
||
self.smooth_light += (target_light - self.smooth_light) * alpha_c;
|
||
}
|
||
|
||
pub fn vibe_push_constants(
|
||
&self,
|
||
is_dark: bool,
|
||
fallback_cover_rgb: Option<[u8; 3]>,
|
||
) -> Option<VibePushConstants> {
|
||
// FullscreenPlayer never renders VIBE_TEXTURE_ID — only run Vibe shader when MyVibe is visible!
|
||
if !self.has_active_vibe_surface() {
|
||
return None;
|
||
}
|
||
// In static fixed-time mode (before any tick), compute direct bucket S/L; in live mode use smoothly interpolated S/L!
|
||
let (track_sat, track_light) = if self.fixed_vibe_time.is_some() {
|
||
let raw_rgb = self
|
||
.queue
|
||
.get(self.queue_index)
|
||
.and_then(|tr| {
|
||
tr.derived_average_hex
|
||
.as_deref()
|
||
.and_then(parse_hex_rgb)
|
||
.or_else(|| tr.derived_accent_hex.as_deref().and_then(parse_hex_rgb))
|
||
})
|
||
.or(fallback_cover_rgb);
|
||
if let Some(rgb) = raw_rgb {
|
||
let bucket = vibe_bucket_primary_rgb(Some(rgb));
|
||
rgb_to_hsl_sl_f32(bucket)
|
||
} else {
|
||
(1.0, 0.50)
|
||
}
|
||
} else {
|
||
(self.smooth_sat, self.smooth_light)
|
||
};
|
||
Some(VibePushConstants {
|
||
resolution: [650.0, 650.0],
|
||
time: self
|
||
.fixed_vibe_time
|
||
.map(|t| t * 0.44)
|
||
.unwrap_or(self.vibe_phase),
|
||
energy: self.smooth_energy,
|
||
bass: self.smooth_bass,
|
||
hue_shift: self.current_hue,
|
||
playing: self.smooth_playing.clamp(0.0, 1.0),
|
||
light_mode: if is_dark { 0.0 } else { 1.0 },
|
||
track_sat,
|
||
track_light,
|
||
})
|
||
}
|
||
|
||
/// Shows version status toast (`APP_VERSION` = `0.1.0`) & checks `git.tatar/marwy/yandex-music-rs` latest release asynchronously.
|
||
/// If an update was already detected, clicking again opens its release page immediately.
|
||
pub fn check_for_updates(&mut self) {
|
||
if let Some((_, ref url)) = self.available_update {
|
||
open_url_in_browser(url);
|
||
}
|
||
self.show_toast(self.i18n().toast_checking_updates());
|
||
let tx = self.tx_api.clone();
|
||
self.runtime.spawn(async move {
|
||
const LATEST_RELEASE_API: &str =
|
||
"https://git.tatar/api/v1/repos/marwy/yandex-music-rs/releases/latest";
|
||
const LATEST_RELEASE_WEB: &str =
|
||
"https://git.tatar/marwy/yandex-music-rs/releases/latest";
|
||
|
||
let client = reqwest::Client::builder()
|
||
.timeout(Duration::from_secs(6))
|
||
.user_agent(format!("yandex-music-rs/{}", APP_VERSION))
|
||
.build();
|
||
let res = match client {
|
||
Ok(http) => match http.get(LATEST_RELEASE_API).send().await {
|
||
Ok(resp) if resp.status().is_success() => {
|
||
match resp.json::<serde_json::Value>().await {
|
||
Ok(val) => {
|
||
let tag = val["tag_name"]
|
||
.as_str()
|
||
.map(|s| s.trim().trim_start_matches(['v', 'V']).to_string())
|
||
.unwrap_or_default();
|
||
let html_url = val["html_url"]
|
||
.as_str()
|
||
.map(str::trim)
|
||
.filter(|s| !s.is_empty())
|
||
.unwrap_or(LATEST_RELEASE_WEB)
|
||
.to_string();
|
||
if !tag.is_empty() && is_newer_version(&tag, APP_VERSION) {
|
||
Ok(Some((tag, html_url)))
|
||
} else {
|
||
Ok(None)
|
||
}
|
||
}
|
||
Err(e) => Err(e.to_string()),
|
||
}
|
||
}
|
||
Ok(resp) if resp.status().as_u16() == 404 => Ok(None),
|
||
Ok(resp) => Err(format!("HTTP {}", resp.status().as_u16())),
|
||
Err(e) => Err(e.to_string()),
|
||
},
|
||
Err(e) => Err(e.to_string()),
|
||
};
|
||
let _ = tx.send(ApiEvent::UpdateCheckFinished(res));
|
||
});
|
||
}
|
||
|
||
pub fn bootstrap_api(&self) {
|
||
// 1. Landing data + Concerts + Metatags
|
||
{
|
||
let api = self.api.clone();
|
||
let tx = self.tx_api.clone();
|
||
self.runtime.spawn(async move {
|
||
if let Ok(landing) = api.fetch_landing().await {
|
||
let _ = tx.send(ApiEvent::LandingLoaded(landing));
|
||
}
|
||
});
|
||
}
|
||
{
|
||
let api = self.api.clone();
|
||
let tx = self.tx_api.clone();
|
||
self.runtime.spawn(async move {
|
||
let concerts = api.fetch_concerts_feed().await.unwrap_or_default();
|
||
let _ = tx.send(ApiEvent::ConcertsLoaded(concerts));
|
||
});
|
||
}
|
||
{
|
||
let api = self.api.clone();
|
||
let tx = self.tx_api.clone();
|
||
self.runtime.spawn(async move {
|
||
let (sections, albums) = api.fetch_non_music_landing().await.unwrap_or_default();
|
||
let _ = tx.send(ApiEvent::NonMusicLoaded(sections, albums));
|
||
});
|
||
}
|
||
{
|
||
let api = self.api.clone();
|
||
let tx = self.tx_api.clone();
|
||
self.runtime.spawn(async move {
|
||
if let Ok(trees) = api.fetch_metatags().await {
|
||
if !trees.is_empty() {
|
||
let _ = tx.send(ApiEvent::MetatagsLoaded(trees));
|
||
}
|
||
}
|
||
});
|
||
}
|
||
|
||
// 2. Left Vibe Wheel stations (`POST /wheel/new` -> `rotor/stations/dashboard` -> Pumpkin CDN)
|
||
{
|
||
let api = self.api.clone();
|
||
let tx = self.tx_api.clone();
|
||
let is_ru = self.config.language.is_ru();
|
||
self.runtime.spawn(async move {
|
||
let mut stations = Vec::new();
|
||
if api.has_token() {
|
||
if let Ok(w) = api.wheel_new(&[]).await {
|
||
if !w.is_empty() {
|
||
stations = w;
|
||
}
|
||
}
|
||
if stations.is_empty() {
|
||
if let Ok(d) = api.rotor_stations_dashboard(12).await {
|
||
if !d.is_empty() {
|
||
stations = d;
|
||
}
|
||
}
|
||
}
|
||
}
|
||
if stations.is_empty() {
|
||
stations = YandexApiClient::official_pumpkin_wheel_for(is_ru);
|
||
}
|
||
let _ = tx.send(ApiEvent::WheelLoaded(stations));
|
||
});
|
||
}
|
||
|
||
// 3. Authenticated user profile, pins, library, likes, playlists, albums, artists, bookshelf, history & Rotor
|
||
if self.api.has_token() {
|
||
// Hydrate any stale cached session queue tracks missing `album_id` (e.g. from pre-v2 config.json)
|
||
let stale_queue_ids: Vec<String> = self
|
||
.queue
|
||
.iter()
|
||
.filter(|tr| tr.album_id.is_none() && !tr.id.starts_with("demo_"))
|
||
.map(|tr| tr.id.clone())
|
||
.take(100)
|
||
.collect();
|
||
if !stale_queue_ids.is_empty() {
|
||
let api_q = self.api.clone();
|
||
let tx_q = self.tx_api.clone();
|
||
self.runtime.spawn(async move {
|
||
if let Ok(hydrated) = api_q.fetch_tracks_by_ids(&stale_queue_ids).await {
|
||
if !hydrated.is_empty() {
|
||
let _ = tx_q.send(ApiEvent::QueueTracksHydrated(hydrated));
|
||
}
|
||
}
|
||
});
|
||
}
|
||
|
||
let api = self.api.clone();
|
||
let tx = self.tx_api.clone();
|
||
let rt = self.runtime.clone();
|
||
self.runtime.spawn(async move {
|
||
{
|
||
let api_c = api.clone();
|
||
let tx_c = tx.clone();
|
||
rt.spawn(async move {
|
||
if let Ok(pins) = api_c.fetch_pins().await {
|
||
if !pins.is_empty() {
|
||
let _ = tx_c.send(ApiEvent::PinsLoaded(pins));
|
||
}
|
||
}
|
||
});
|
||
}
|
||
{
|
||
let api_c = api.clone();
|
||
let tx_c = tx.clone();
|
||
rt.spawn(async move {
|
||
if let Ok(all_ids) = api_c.fetch_library_all_ids().await {
|
||
let _ = tx_c.send(ApiEvent::LibraryIdsLoaded(all_ids));
|
||
}
|
||
});
|
||
}
|
||
{
|
||
let api_c = api.clone();
|
||
let tx_c = tx.clone();
|
||
rt.spawn(async move {
|
||
if let Ok(hist) = api_c.fetch_music_history(20).await {
|
||
if !hist.is_empty() {
|
||
let _ = tx_c.send(ApiEvent::MusicHistoryLoaded(hist));
|
||
}
|
||
}
|
||
});
|
||
}
|
||
{
|
||
let api_c = api.clone();
|
||
let tx_c = tx.clone();
|
||
rt.spawn(async move {
|
||
if let Ok(shelf) = api_c.fetch_bookshelf_liked().await {
|
||
let _ = tx_c.send(ApiEvent::BookshelfLoaded(shelf));
|
||
}
|
||
});
|
||
}
|
||
{
|
||
let api_c = api.clone();
|
||
let tx_c = tx.clone();
|
||
rt.spawn(async move {
|
||
if let Ok(sess) = api_c
|
||
.rotor_session_new(&["user:onyourwave".to_string()], &[])
|
||
.await
|
||
{
|
||
let _ = tx_c.send(ApiEvent::RotorSessionStarted(sess, false));
|
||
}
|
||
});
|
||
}
|
||
|
||
match api.account_status().await {
|
||
Ok(acc) => {
|
||
let uid = acc.uid;
|
||
let _ = tx.send(ApiEvent::AccountLoaded(Ok(acc)));
|
||
{
|
||
let api_c = api.clone();
|
||
let tx_c = tx.clone();
|
||
rt.spawn(async move {
|
||
if let Ok(likes) = api_c.fetch_liked_tracks(uid).await {
|
||
let ids: Vec<String> =
|
||
likes.iter().map(|t| t.rotor_track_id()).collect();
|
||
let _ = tx_c.send(ApiEvent::LikedTracksLoaded(likes));
|
||
if !ids.is_empty() {
|
||
if let Ok(chips) = api_c.fetch_track_filters(&ids).await {
|
||
let _ =
|
||
tx_c.send(ApiEvent::FavoriteFiltersLoaded(chips));
|
||
}
|
||
}
|
||
}
|
||
});
|
||
}
|
||
{
|
||
let api_c = api.clone();
|
||
let tx_c = tx.clone();
|
||
rt.spawn(async move {
|
||
let mut merged = Vec::new();
|
||
let mut seen = HashSet::new();
|
||
if let Ok(pls) = api_c.fetch_user_playlists(uid).await {
|
||
for pl in pls {
|
||
if seen.insert((pl.owner_uid.clone(), pl.kind.clone())) {
|
||
merged.push(pl);
|
||
}
|
||
}
|
||
}
|
||
if let Ok(liked_pls) = api_c.fetch_liked_playlists(uid).await {
|
||
for pl in liked_pls {
|
||
if seen.insert((pl.owner_uid.clone(), pl.kind.clone())) {
|
||
merged.push(pl);
|
||
}
|
||
}
|
||
}
|
||
if !merged.is_empty() {
|
||
let _ = tx_c.send(ApiEvent::UserPlaylistsLoaded(merged));
|
||
}
|
||
});
|
||
}
|
||
{
|
||
let api_c = api.clone();
|
||
let tx_c = tx.clone();
|
||
rt.spawn(async move {
|
||
if let Ok(albs) = api_c.fetch_liked_albums(uid).await {
|
||
let _ = tx_c.send(ApiEvent::LikedAlbumsLoaded(albs));
|
||
}
|
||
});
|
||
}
|
||
{
|
||
let api_c = api.clone();
|
||
let tx_c = tx.clone();
|
||
rt.spawn(async move {
|
||
if let Ok(arts) = api_c.fetch_liked_artists(uid).await {
|
||
let _ = tx_c.send(ApiEvent::LikedArtistsLoaded(arts));
|
||
}
|
||
});
|
||
}
|
||
{
|
||
let api_c = api.clone();
|
||
let tx_c = tx.clone();
|
||
rt.spawn(async move {
|
||
if let Ok(sh) = api_c.fetch_search_history(uid).await {
|
||
if !sh.is_empty() {
|
||
let _ = tx_c.send(ApiEvent::SearchHistoryLoaded(sh));
|
||
}
|
||
}
|
||
});
|
||
}
|
||
}
|
||
Err(e) => {
|
||
let _ = tx.send(ApiEvent::AccountLoaded(Err(e.to_string())));
|
||
}
|
||
}
|
||
});
|
||
}
|
||
}
|
||
|
||
/// Exact Desktop 5.129.0 10-minute idle refresh (`REFRESH_EVENT_TRIGGER_TIME_MS = 600_000`)
|
||
pub fn on_window_focus_changed(&mut self, focused: bool) {
|
||
if !focused {
|
||
self.last_unfocused_at = Some(Instant::now());
|
||
} else if let Some(since) = self.last_unfocused_at.take() {
|
||
if since.elapsed() >= Duration::from_secs(600) && self.api.has_token() {
|
||
self.bootstrap_api();
|
||
}
|
||
}
|
||
}
|
||
|
||
/// Exact Desktop 5.129.0 `yandexmusic://` deeplink navigation (`index.js:1325-1406`)
|
||
pub fn handle_deeplink(&mut self, raw_uri: &str) {
|
||
let stripped = raw_uri
|
||
.trim()
|
||
.strip_prefix("yandexmusic://")
|
||
.unwrap_or(raw_uri)
|
||
.trim_start_matches('/');
|
||
if stripped.contains("..") {
|
||
return;
|
||
}
|
||
let parts: Vec<&str> = stripped.split('/').filter(|s| !s.is_empty()).collect();
|
||
match parts.as_slice() {
|
||
["myvibe"] | ["vibe"] => self.navigate(Route::MyVibe),
|
||
["search"] => self.navigate(Route::Search),
|
||
["chart"] => self.navigate(Route::Chart),
|
||
["mixes"] => self.navigate(Route::Metatags),
|
||
["genre", id, ..] | ["metatags", id, ..] | ["tag", id, ..] => {
|
||
self.navigate(Route::Metatag {
|
||
id: (*id).to_string(),
|
||
title: (*id).to_string(),
|
||
});
|
||
}
|
||
["music-history"] => {
|
||
self.collection_tab = CollectionTab::History;
|
||
self.navigate(Route::Collection);
|
||
}
|
||
["collection", ..] => self.navigate(Route::Collection),
|
||
["settings"] => self.navigate(Route::Settings),
|
||
["concerts", ..] => self.navigate(Route::Concerts),
|
||
["album", album_id, ..] => self.navigate(Route::Album {
|
||
id: (*album_id).to_string(),
|
||
title: self.i18n().album().into(),
|
||
}),
|
||
["artist", artist_id, ..] => self.navigate(Route::Artist {
|
||
id: (*artist_id).to_string(),
|
||
name: self.i18n().artist().into(),
|
||
}),
|
||
["users", owner, "playlists", kind, ..] => self.navigate(Route::Playlist {
|
||
owner_uid: (*owner).to_string(),
|
||
kind: (*kind).to_string(),
|
||
title: self.i18n().playlist().into(),
|
||
}),
|
||
_ => {}
|
||
}
|
||
}
|
||
|
||
pub fn navigate(&mut self, next: Route) {
|
||
if self.route == next {
|
||
return;
|
||
}
|
||
self.history_back.push(self.route.clone());
|
||
self.history_forward.clear();
|
||
self.detail_track_filter.clear();
|
||
self.selected_favorite_filter_id = None;
|
||
self.route = next.clone();
|
||
self.load_route_data(&next);
|
||
}
|
||
|
||
pub fn go_back(&mut self) {
|
||
if let Some(prev) = self.history_back.pop() {
|
||
self.history_forward.push(self.route.clone());
|
||
self.detail_track_filter.clear();
|
||
self.selected_favorite_filter_id = None;
|
||
self.route = prev.clone();
|
||
self.load_route_data(&prev);
|
||
}
|
||
}
|
||
|
||
pub fn go_forward(&mut self) {
|
||
if let Some(next) = self.history_forward.pop() {
|
||
self.history_back.push(self.route.clone());
|
||
self.detail_track_filter.clear();
|
||
self.selected_favorite_filter_id = None;
|
||
self.route = next.clone();
|
||
self.load_route_data(&next);
|
||
}
|
||
}
|
||
|
||
pub(crate) fn load_route_data(&mut self, route: &Route) {
|
||
match route {
|
||
Route::Playlist {
|
||
owner_uid, kind, ..
|
||
} => {
|
||
self.current_playlist_detail = None;
|
||
self.detail_loading = true;
|
||
let api = self.api.clone();
|
||
let tx = self.tx_api.clone();
|
||
let o = owner_uid.clone();
|
||
let k = kind.clone();
|
||
self.runtime.spawn(async move {
|
||
if let Ok(det) = api.fetch_playlist_detail(&o, &k).await {
|
||
let _ = tx.send(ApiEvent::PlaylistDetailLoaded(det));
|
||
}
|
||
});
|
||
}
|
||
Route::Album { id, .. } => {
|
||
self.current_album_detail = None;
|
||
self.detail_loading = true;
|
||
let api = self.api.clone();
|
||
let tx = self.tx_api.clone();
|
||
let aid = id.clone();
|
||
self.runtime.spawn(async move {
|
||
if let Ok(det) = api.fetch_album_detail(&aid).await {
|
||
let _ = tx.send(ApiEvent::AlbumDetailLoaded(det));
|
||
}
|
||
});
|
||
}
|
||
Route::Artist { id, .. } => {
|
||
self.current_artist_detail = None;
|
||
self.detail_loading = true;
|
||
let api = self.api.clone();
|
||
let tx = self.tx_api.clone();
|
||
let aid = id.clone();
|
||
self.runtime.spawn(async move {
|
||
if let Ok(det) = api.fetch_artist_detail(&aid).await {
|
||
let _ = tx.send(ApiEvent::ArtistDetailLoaded(det));
|
||
}
|
||
});
|
||
}
|
||
Route::Metatags => {
|
||
if self.metatags.is_empty() {
|
||
self.detail_loading = true;
|
||
let api = self.api.clone();
|
||
let tx = self.tx_api.clone();
|
||
self.runtime.spawn(async move {
|
||
if let Ok(trees) = api.fetch_metatags().await {
|
||
let _ = tx.send(ApiEvent::MetatagsLoaded(trees));
|
||
}
|
||
});
|
||
} else {
|
||
self.detail_loading = false;
|
||
}
|
||
}
|
||
Route::Metatag { id, .. } => {
|
||
self.current_metatag_detail = None;
|
||
self.detail_loading = true;
|
||
let api = self.api.clone();
|
||
let tx = self.tx_api.clone();
|
||
let mid = id.clone();
|
||
self.runtime.spawn(async move {
|
||
if let Ok(det) = api.fetch_metatag_detail(&mid).await {
|
||
let _ = tx.send(ApiEvent::MetatagDetailLoaded(det));
|
||
}
|
||
});
|
||
}
|
||
Route::Concerts => {
|
||
self.detail_loading = false;
|
||
if self.concerts.is_empty() && !self.concerts_loading {
|
||
self.refresh_concerts();
|
||
}
|
||
}
|
||
Route::Podcasts => {
|
||
self.detail_loading = false;
|
||
if self.non_music_sections.is_empty() && !self.non_music_loading {
|
||
self.refresh_non_music();
|
||
}
|
||
}
|
||
_ => {
|
||
self.detail_loading = false;
|
||
}
|
||
}
|
||
}
|
||
|
||
pub fn refresh_concerts(&mut self) {
|
||
self.concerts_loading = true;
|
||
let api = self.api.clone();
|
||
let tx = self.tx_api.clone();
|
||
self.runtime.spawn(async move {
|
||
let concerts = api.fetch_concerts_feed().await.unwrap_or_default();
|
||
let _ = tx.send(ApiEvent::ConcertsLoaded(concerts));
|
||
});
|
||
}
|
||
|
||
pub fn refresh_non_music(&mut self) {
|
||
self.non_music_loading = true;
|
||
let api = self.api.clone();
|
||
let tx = self.tx_api.clone();
|
||
self.runtime.spawn(async move {
|
||
let (sections, albums) = api.fetch_non_music_landing().await.unwrap_or_default();
|
||
let _ = tx.send(ApiEvent::NonMusicLoaded(sections, albums));
|
||
});
|
||
if self.api.has_token() {
|
||
let api = self.api.clone();
|
||
let tx = self.tx_api.clone();
|
||
self.runtime.spawn(async move {
|
||
if let Ok(shelf) = api.fetch_bookshelf_liked().await {
|
||
let _ = tx.send(ApiEvent::BookshelfLoaded(shelf));
|
||
}
|
||
});
|
||
}
|
||
}
|
||
|
||
pub fn launch_oauth_login(&mut self) {
|
||
self.show_toast(self.i18n().toast_opening_oauth());
|
||
let tx = self.tx_api.clone();
|
||
std::thread::Builder::new()
|
||
.name("ym-oauth-wait".into())
|
||
.spawn(move || {
|
||
let res = crate::native::spawn_auth_webview_subprocess().map_err(|e| e.to_string());
|
||
let _ = tx.send(ApiEvent::OAuthTokenReceived(res));
|
||
})
|
||
.ok();
|
||
}
|
||
|
||
pub fn submit_oauth_token(&mut self, raw: String) {
|
||
if let Some(tok) = extract_oauth_token(&raw) {
|
||
self.config.oauth_token = Some(tok.clone());
|
||
self.save_config();
|
||
self.api.set_token(Some(tok));
|
||
self.token_input.clear();
|
||
self.login_modal_open = false;
|
||
self.show_toast(self.i18n().toast_signing_in());
|
||
self.bootstrap_api();
|
||
} else {
|
||
self.show_toast(self.i18n().toast_invalid_token());
|
||
}
|
||
}
|
||
|
||
/// Poll async API responses, audio track completion, debounced live search, and 30s `/plays` heartbeat.
|
||
/// Returns `true` if any visible application state changed (requiring a UI redraw).
|
||
pub fn poll_async_events(&mut self) -> bool {
|
||
let mut changed = false;
|
||
if self.audio.take_track_finished() {
|
||
self.advance_track(true, false);
|
||
changed = true;
|
||
}
|
||
|
||
// Debounced 500ms live search trigger
|
||
if let Some(deadline) = self.search_debounce_deadline {
|
||
if Instant::now() >= deadline {
|
||
self.search_debounce_deadline = None;
|
||
let q = self.search_query.trim().to_string();
|
||
if !q.is_empty() {
|
||
self.run_search(q, self.search_filter);
|
||
}
|
||
changed = true;
|
||
}
|
||
}
|
||
|
||
// Exact 5.129.0 periodic `POST /plays` heartbeat every 30s while playing
|
||
if self.audio.state.is_playing.load(Ordering::Relaxed)
|
||
&& self.last_play_heartbeat.elapsed() >= Duration::from_secs(30)
|
||
{
|
||
self.last_play_heartbeat = Instant::now();
|
||
self.send_play_telemetry("in_progress");
|
||
}
|
||
|
||
if let Some(err) = self.audio.state.take_error() {
|
||
self.show_toast(err);
|
||
changed = true;
|
||
}
|
||
|
||
while let Ok(ev) = self.rx_api.try_recv() {
|
||
self.handle_api_event(ev);
|
||
changed = true;
|
||
}
|
||
changed
|
||
}
|
||
|
||
fn handle_api_event(&mut self, ev: ApiEvent) {
|
||
let t = self.i18n();
|
||
match ev {
|
||
ApiEvent::AccountLoaded(Ok(acc)) => {
|
||
self.show_toast(t.toast_welcome(&acc.display_name));
|
||
let uid = acc.uid;
|
||
self.account = Some(acc);
|
||
normalize_pins(&mut self.config.pinned_items, Some(uid), t.is_ru());
|
||
self.save_config();
|
||
self.ensure_words_for_current_track();
|
||
if self.concerts.is_empty() && !self.concerts_loading {
|
||
self.refresh_concerts();
|
||
}
|
||
if self.non_music_sections.is_empty() && !self.non_music_loading {
|
||
self.refresh_non_music();
|
||
}
|
||
}
|
||
ApiEvent::AccountLoaded(Err(e)) => {
|
||
self.show_toast(if t.is_ru() {
|
||
format!("Ошибка входа: {}", e)
|
||
} else {
|
||
format!("Sign-in error: {}", e)
|
||
});
|
||
}
|
||
ApiEvent::ConcertsLoaded(concerts) => {
|
||
self.concerts_loading = false;
|
||
if !concerts.is_empty() || self.concerts.is_empty() {
|
||
self.concerts = concerts;
|
||
}
|
||
}
|
||
ApiEvent::NonMusicLoaded(sections, albums) => {
|
||
self.non_music_loading = false;
|
||
if !sections.is_empty() {
|
||
self.non_music_sections = sections;
|
||
}
|
||
if !albums.is_empty() {
|
||
self.landing.podcasts = albums;
|
||
}
|
||
}
|
||
ApiEvent::SearchHistoryLoaded(hist) => {
|
||
self.config.search_history = hist;
|
||
self.save_config();
|
||
}
|
||
ApiEvent::PlayAlbumTracks(id, title, tracks) => {
|
||
if !tracks.is_empty() {
|
||
self.play_tracks(tracks, 0, title, format!("album:{}", id), false);
|
||
}
|
||
}
|
||
ApiEvent::PlayPlaylistTracks(key, title, tracks) => {
|
||
if !tracks.is_empty() {
|
||
self.play_tracks(tracks, 0, title, key, false);
|
||
}
|
||
}
|
||
ApiEvent::PlayArtistTracks(id, name, tracks) => {
|
||
if !tracks.is_empty() {
|
||
self.play_tracks(tracks, 0, name, format!("artist:{}", id), false);
|
||
}
|
||
}
|
||
ApiEvent::LandingLoaded(data) => {
|
||
let queue_is_empty_or_demo = self
|
||
.queue
|
||
.first()
|
||
.map_or(true, |tr| tr.id.starts_with("demo_"));
|
||
let playing = self.audio.state.is_playing.load(Ordering::Relaxed);
|
||
if !self.api.has_token() && !data.chart_tracks.is_empty() {
|
||
if !playing && queue_is_empty_or_demo {
|
||
self.queue = data.chart_tracks.clone();
|
||
self.queue_index = 0;
|
||
}
|
||
if self.liked_tracks.is_empty() {
|
||
self.liked_tracks = data.chart_tracks.clone();
|
||
self.liked_ids = self.liked_tracks.iter().map(|tr| tr.id.clone()).collect();
|
||
}
|
||
} else if queue_is_empty_or_demo && !playing {
|
||
let real_vibe = data
|
||
.vibe_tracks
|
||
.iter()
|
||
.any(|tr| !tr.id.starts_with("demo_"));
|
||
if real_vibe {
|
||
self.queue = data.vibe_tracks.clone();
|
||
self.queue_index = 0;
|
||
} else if !data.chart_tracks.is_empty()
|
||
&& data.chart_tracks.iter().any(|tr| !tr.id.starts_with("demo_"))
|
||
{
|
||
self.queue = data.chart_tracks.clone();
|
||
self.queue_index = 0;
|
||
}
|
||
}
|
||
let mut data = data;
|
||
if data.podcasts.is_empty() && !self.landing.podcasts.is_empty() {
|
||
data.podcasts = self.landing.podcasts.clone();
|
||
}
|
||
self.landing = data;
|
||
}
|
||
ApiEvent::LikedTracksLoaded(tracks) => {
|
||
self.liked_ids = tracks.iter().map(|tr| tr.id.clone()).collect();
|
||
let queue_is_empty_or_demo = self
|
||
.queue
|
||
.first()
|
||
.map_or(true, |tr| tr.id.starts_with("demo_"));
|
||
if queue_is_empty_or_demo
|
||
&& !tracks.is_empty()
|
||
&& !self.audio.state.is_playing.load(Ordering::Relaxed)
|
||
{
|
||
self.queue = tracks.clone();
|
||
self.queue_index = 0;
|
||
}
|
||
self.liked_tracks = tracks;
|
||
}
|
||
ApiEvent::FavoriteFiltersLoaded(chips) => {
|
||
self.favorite_filters = chips;
|
||
}
|
||
ApiEvent::LibraryIdsLoaded(ids) => {
|
||
for id in ids.liked_track_ids {
|
||
self.liked_ids.insert(id);
|
||
}
|
||
for id in ids.disliked_track_ids {
|
||
self.disliked_ids.insert(id);
|
||
}
|
||
}
|
||
ApiEvent::LikedAlbumsLoaded(albs) => {
|
||
self.liked_albums = albs;
|
||
}
|
||
ApiEvent::LikedArtistsLoaded(arts) => {
|
||
self.liked_artists = arts;
|
||
}
|
||
ApiEvent::BookshelfLoaded(items) => {
|
||
self.bookshelf_items = items;
|
||
}
|
||
ApiEvent::PinsLoaded(mut pins) => {
|
||
let my_uid = self.account.as_ref().map(|a| a.uid);
|
||
normalize_pins(&mut pins, my_uid, t.is_ru());
|
||
self.config.pinned_items = pins;
|
||
self.save_config();
|
||
}
|
||
ApiEvent::WheelLoaded(stations) => {
|
||
self.wheel_stations = stations;
|
||
}
|
||
ApiEvent::MusicHistoryLoaded(hist) => {
|
||
self.play_history = hist;
|
||
}
|
||
ApiEvent::UserPlaylistsLoaded(pls) => {
|
||
self.user_playlists = pls;
|
||
}
|
||
ApiEvent::MetatagsLoaded(trees) => {
|
||
self.detail_loading = false;
|
||
self.metatags = trees;
|
||
}
|
||
ApiEvent::MetatagDetailLoaded(det) => {
|
||
self.detail_loading = false;
|
||
self.current_metatag_detail = Some(det);
|
||
}
|
||
ApiEvent::SearchLoaded(res) => {
|
||
self.search_loading = false;
|
||
self.search_results = Some(res);
|
||
}
|
||
ApiEvent::PlaylistDetailLoaded(det) => {
|
||
self.detail_loading = false;
|
||
self.current_playlist_detail = Some(det);
|
||
}
|
||
ApiEvent::AlbumDetailLoaded(det) => {
|
||
self.detail_loading = false;
|
||
self.current_album_detail = Some(det);
|
||
}
|
||
ApiEvent::ArtistDetailLoaded(det) => {
|
||
self.detail_loading = false;
|
||
self.current_artist_detail = Some(det);
|
||
}
|
||
ApiEvent::VibeTracksLoaded(tracks, auto_play) => {
|
||
if !tracks.is_empty() {
|
||
self.landing.vibe_tracks = tracks.clone();
|
||
if auto_play {
|
||
let name = self.i18n().my_vibe().to_string();
|
||
self.play_tracks(tracks, 0, name, "vibe:user:onyourwave".into(), true);
|
||
}
|
||
}
|
||
}
|
||
ApiEvent::RotorSessionStarted(session, auto_play) => {
|
||
self.vibe_prefetching = false;
|
||
if !session.tracks.is_empty() {
|
||
self.landing.vibe_tracks = session.tracks.clone();
|
||
let tracks = session.tracks.clone();
|
||
let seeds_key = format!("vibe:{}", session.seeds.join(","));
|
||
let wave_name = session.wave_name.clone();
|
||
self.active_rotor_session = Some(session);
|
||
self.vibe_started = false;
|
||
let queue_is_empty_or_demo = self
|
||
.queue
|
||
.first()
|
||
.map_or(true, |tr| tr.id.starts_with("demo_"));
|
||
if auto_play {
|
||
self.play_tracks(tracks, 0, wave_name, seeds_key, true);
|
||
} else if queue_is_empty_or_demo
|
||
&& !self.audio.state.is_playing.load(Ordering::Relaxed)
|
||
{
|
||
self.queue = tracks;
|
||
self.queue_index = 0;
|
||
self.context_key = seeds_key;
|
||
self.is_vibe_active = true;
|
||
self.shuffle = false;
|
||
if self.repeat == RepeatMode::All {
|
||
self.repeat = RepeatMode::Off;
|
||
}
|
||
}
|
||
}
|
||
}
|
||
ApiEvent::RotorBatchAppended(batch_id, tracks, terminated) => {
|
||
self.vibe_prefetching = false;
|
||
if let Some(ref mut sess) = self.active_rotor_session {
|
||
if let Some(bid) = batch_id {
|
||
sess.batch_id = Some(bid);
|
||
}
|
||
sess.terminated = terminated;
|
||
}
|
||
if self.is_vibe_active && !tracks.is_empty() {
|
||
self.queue.extend(tracks);
|
||
}
|
||
}
|
||
ApiEvent::StreamResolved {
|
||
track_id,
|
||
duration_ms,
|
||
r128_i,
|
||
r128_tp,
|
||
result,
|
||
} => {
|
||
if self.current_track().map(|tr| tr.id.as_str()) == Some(track_id.as_str()) {
|
||
match result {
|
||
Ok(stream) => {
|
||
self.audio
|
||
.load_stream(track_id, stream, duration_ms, r128_i, r128_tp);
|
||
}
|
||
Err(e) => {
|
||
log::warn!("Stream resolve failed: {}", e);
|
||
self.audio.state.is_buffering.store(false, Ordering::SeqCst);
|
||
self.audio.state.is_playing.store(false, Ordering::SeqCst);
|
||
self.show_toast(if t.is_ru() {
|
||
format!("Не удалось загрузить трек: {}", e)
|
||
} else {
|
||
format!("Failed to load track: {}", e)
|
||
});
|
||
}
|
||
}
|
||
}
|
||
}
|
||
ApiEvent::LyricsLoaded(lyr) => {
|
||
let has_lines = !lyr.lines.is_empty();
|
||
if self.current_track().map(|tr| tr.id.as_str()) == Some(lyr.track_id.as_str()) {
|
||
self.current_lyrics = Some(lyr.clone());
|
||
if has_lines {
|
||
if let Some(tr) = self.queue.get_mut(self.queue_index) {
|
||
tr.has_lyrics = true;
|
||
}
|
||
}
|
||
}
|
||
if self
|
||
.track_detail_modal
|
||
.as_ref()
|
||
.map(|tr| tr.id.as_str())
|
||
== Some(lyr.track_id.as_str())
|
||
{
|
||
self.modal_lyrics = Some(lyr);
|
||
if has_lines {
|
||
if let Some(ref mut tr) = self.track_detail_modal {
|
||
tr.has_lyrics = true;
|
||
}
|
||
}
|
||
}
|
||
}
|
||
ApiEvent::WordsCardsLoaded(entries) => {
|
||
for (track_id, maybe_card) in entries {
|
||
self.words_loading_tracks.remove(&track_id);
|
||
if let Some(card) = maybe_card {
|
||
self.words_empty_tracks.remove(&track_id);
|
||
self.words_cards.insert(track_id, card);
|
||
} else {
|
||
self.words_empty_tracks.insert(track_id);
|
||
}
|
||
}
|
||
}
|
||
ApiEvent::WordsBigCardLoaded(big) => {
|
||
self.words_big_card_loading = false;
|
||
if let Some(bc) = big {
|
||
self.words_big_card = Some(bc);
|
||
}
|
||
}
|
||
ApiEvent::QueueTracksHydrated(hydrated) => {
|
||
let mut updated_any = false;
|
||
for fresh in &hydrated {
|
||
for slot in self
|
||
.queue
|
||
.iter_mut()
|
||
.chain(self.unshuffled_queue.iter_mut())
|
||
{
|
||
if slot.id == fresh.id {
|
||
if slot.album_id.is_none() && fresh.album_id.is_some() {
|
||
slot.album_id = fresh.album_id.clone();
|
||
updated_any = true;
|
||
}
|
||
if slot.album_title.is_none() && fresh.album_title.is_some() {
|
||
slot.album_title = fresh.album_title.clone();
|
||
updated_any = true;
|
||
}
|
||
if fresh.has_lyrics && !slot.has_lyrics {
|
||
slot.has_lyrics = true;
|
||
updated_any = true;
|
||
}
|
||
if slot.version.is_none() && fresh.version.is_some() {
|
||
slot.version = fresh.version.clone();
|
||
updated_any = true;
|
||
}
|
||
if slot.derived_average_hex.is_none()
|
||
&& fresh.derived_average_hex.is_some()
|
||
{
|
||
slot.derived_average_hex = fresh.derived_average_hex.clone();
|
||
updated_any = true;
|
||
}
|
||
if slot.derived_accent_hex.is_none()
|
||
&& fresh.derived_accent_hex.is_some()
|
||
{
|
||
slot.derived_accent_hex = fresh.derived_accent_hex.clone();
|
||
updated_any = true;
|
||
}
|
||
if slot.cover_uri.is_none() && fresh.cover_uri.is_some() {
|
||
slot.cover_uri = fresh.cover_uri.clone();
|
||
updated_any = true;
|
||
}
|
||
}
|
||
}
|
||
}
|
||
if updated_any {
|
||
self.save_playback_state();
|
||
}
|
||
self.ensure_words_for_current_track();
|
||
}
|
||
ApiEvent::OAuthTokenReceived(res) => match res {
|
||
Ok(tok) => {
|
||
self.submit_oauth_token(tok);
|
||
}
|
||
Err(e) => {
|
||
if e.contains("unavailable") {
|
||
open_url_in_browser(YANDEX_OAUTH_URL);
|
||
self.show_toast(if t.is_ru() {
|
||
"WebView недоступен — открыт вход в браузере"
|
||
} else {
|
||
"WebView unavailable — opened sign-in in browser"
|
||
});
|
||
} else {
|
||
self.show_toast(e);
|
||
}
|
||
}
|
||
},
|
||
ApiEvent::PlaylistCreated {
|
||
result,
|
||
initial_track,
|
||
} => match result {
|
||
Ok(pl) => {
|
||
self.show_toast(t.toast_playlist_created(&pl.title));
|
||
let owner = pl.owner_uid.clone();
|
||
let kind = pl.kind.clone();
|
||
let title = pl.title.clone();
|
||
self.user_playlists.insert(0, pl);
|
||
if let Some(tr) = initial_track {
|
||
self.add_track_to_playlist(owner.clone(), kind.clone(), tr);
|
||
}
|
||
self.navigate(Route::Playlist {
|
||
owner_uid: owner,
|
||
kind,
|
||
title,
|
||
});
|
||
}
|
||
Err(e) => {
|
||
log::warn!("Create playlist failed: {}", e);
|
||
self.show_toast(t.toast_action_error());
|
||
}
|
||
},
|
||
ApiEvent::PlaylistRenamed {
|
||
owner_uid,
|
||
kind,
|
||
result,
|
||
} => match result {
|
||
Ok(pl) => {
|
||
if let Some(existing) = self
|
||
.user_playlists
|
||
.iter_mut()
|
||
.find(|p| p.owner_uid == owner_uid && p.kind == kind)
|
||
{
|
||
existing.title = pl.title.clone();
|
||
existing.revision = pl.revision;
|
||
}
|
||
if let Some(ref mut det) = self.current_playlist_detail {
|
||
if det.summary.owner_uid == owner_uid && det.summary.kind == kind {
|
||
det.summary.title = pl.title.clone();
|
||
det.summary.revision = pl.revision;
|
||
det.revision = pl.revision;
|
||
}
|
||
}
|
||
self.show_toast(t.toast_playlist_renamed(&pl.title));
|
||
}
|
||
Err(e) => {
|
||
log::warn!("Rename playlist failed: {}", e);
|
||
self.show_toast(t.toast_action_error());
|
||
}
|
||
},
|
||
ApiEvent::PlaylistDeleted {
|
||
owner_uid,
|
||
kind,
|
||
result,
|
||
} => match result {
|
||
Ok(()) => {
|
||
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(t.toast_playlist_deleted());
|
||
if matches!(&self.route, Route::Playlist { kind: k, .. } if k == &kind) {
|
||
self.collection_tab = CollectionTab::Playlists;
|
||
self.navigate(Route::Collection);
|
||
}
|
||
}
|
||
Err(e) => {
|
||
log::warn!("Delete playlist failed: {}", e);
|
||
self.show_toast(t.toast_action_error());
|
||
}
|
||
},
|
||
ApiEvent::PlaylistTracksChanged {
|
||
owner_uid,
|
||
kind,
|
||
revision,
|
||
toast_msg,
|
||
} => match revision {
|
||
Ok(new_rev) => {
|
||
if let Some(pl) = self
|
||
.user_playlists
|
||
.iter_mut()
|
||
.find(|p| p.owner_uid == owner_uid && p.kind == kind)
|
||
{
|
||
pl.revision = new_rev;
|
||
}
|
||
if let Some(ref mut det) = self.current_playlist_detail {
|
||
if det.summary.owner_uid == owner_uid && det.summary.kind == kind {
|
||
det.summary.revision = new_rev;
|
||
det.revision = new_rev;
|
||
}
|
||
}
|
||
self.show_toast(toast_msg);
|
||
}
|
||
Err(e) => {
|
||
log::warn!("Playlist change-relative failed: {}", e);
|
||
self.show_toast(t.toast_action_error());
|
||
}
|
||
},
|
||
ApiEvent::TrackDownloaded { track, result } => {
|
||
self.downloading_track_ids.remove(&track.id);
|
||
if self.download_batch_total > 0 {
|
||
self.download_batch_done =
|
||
(self.download_batch_done + 1).min(self.download_batch_total);
|
||
if self.downloading_track_ids.is_empty() {
|
||
self.download_batch_total = 0;
|
||
self.download_batch_done = 0;
|
||
}
|
||
}
|
||
if self.download_cancel.load(Ordering::Relaxed) {
|
||
return;
|
||
}
|
||
match result {
|
||
Ok(_) => {
|
||
self.downloaded_track_ids.insert(track.id.clone());
|
||
if !self
|
||
.config
|
||
.downloaded_tracks
|
||
.iter()
|
||
.any(|tr| tr.id == track.id)
|
||
{
|
||
self.config.downloaded_tracks.insert(0, track.clone());
|
||
self.save_config();
|
||
}
|
||
self.show_toast(t.toast_track_downloaded(&track.title));
|
||
}
|
||
Err(e) => {
|
||
log::warn!("Offline download failed for {}: {}", track.id, e);
|
||
self.show_toast(t.toast_download_error());
|
||
}
|
||
}
|
||
}
|
||
ApiEvent::UpdateCheckFinished(res) => match res {
|
||
Ok(Some((newer, url))) => {
|
||
self.available_update = Some((newer.clone(), url));
|
||
self.show_toast(t.toast_update_available(&newer));
|
||
}
|
||
Ok(None) => {
|
||
self.available_update = None;
|
||
self.show_toast(t.toast_latest_version());
|
||
}
|
||
Err(e) => {
|
||
log::warn!("Update check failed: {}", e);
|
||
self.show_toast(t.toast_update_check_failed());
|
||
}
|
||
},
|
||
}
|
||
}
|
||
|
||
/// Central action dispatcher for all Chrome, Overlays & Content Pages.
|
||
pub fn dispatch(&mut self, action: AppAction) {
|
||
let t = self.i18n();
|
||
match action {
|
||
AppAction::None => {}
|
||
AppAction::Navigate(route) => self.navigate(route),
|
||
AppAction::NavigateToCurrentContext => self.navigate_to_current_context(),
|
||
AppAction::NavigateCollectionTab(tab) => {
|
||
self.collection_tab = tab;
|
||
self.navigate(Route::Collection);
|
||
}
|
||
AppAction::SetForYouTab(tab) => {
|
||
self.for_you_tab = tab;
|
||
}
|
||
AppAction::GoBack => self.go_back(),
|
||
AppAction::GoForward => self.go_forward(),
|
||
AppAction::ToggleSidebarCollapse => {
|
||
self.config.sidebar_collapsed = !self.config.sidebar_collapsed;
|
||
self.save_config();
|
||
}
|
||
AppAction::OpenPin(pin) => match pin.kind.as_str() {
|
||
"likes" => self.navigate(Route::LikedTracks),
|
||
"album" => self.navigate(Route::Album {
|
||
id: pin.id,
|
||
title: pin.title,
|
||
}),
|
||
"artist" => self.navigate(Route::Artist {
|
||
id: pin.id,
|
||
name: pin.title,
|
||
}),
|
||
"wave" => {
|
||
let seeds: Vec<String> = pin
|
||
.id
|
||
.split(',')
|
||
.filter(|s| !s.is_empty())
|
||
.map(String::from)
|
||
.collect();
|
||
self.navigate(Route::MyVibe);
|
||
self.start_vibe_by_seeds(pin.title, seeds);
|
||
}
|
||
_ => {
|
||
let (owner, kind) = if let Some((o, k)) = pin.id.split_once(':') {
|
||
(o.to_string(), k.to_string())
|
||
} else {
|
||
(
|
||
pin.owner_uid.unwrap_or_else(|| "yamusic-daily".into()),
|
||
pin.id,
|
||
)
|
||
};
|
||
self.navigate(Route::Playlist {
|
||
owner_uid: owner,
|
||
kind,
|
||
title: pin.title,
|
||
});
|
||
}
|
||
},
|
||
AppAction::PlayWavePin(pin) => {
|
||
let seeds: Vec<String> = pin
|
||
.id
|
||
.split(',')
|
||
.filter(|s| !s.is_empty())
|
||
.map(String::from)
|
||
.collect();
|
||
let ctx_key = format!("vibe:{}", seeds.join(","));
|
||
if self.is_context_active(&ctx_key) {
|
||
self.toggle_play();
|
||
} else {
|
||
self.start_vibe_by_seeds(pin.title, seeds);
|
||
}
|
||
}
|
||
AppAction::OpenUrl(url) => open_url_in_browser(&url),
|
||
AppAction::OpenPromoUrl(url) => self.open_promo_url(&url),
|
||
|
||
// Playback & Queue
|
||
AppAction::TogglePlay => self.toggle_play(),
|
||
AppAction::Play => {
|
||
if self.audio.state.duration_ms.load(Ordering::Relaxed) == 0
|
||
&& !self.queue.is_empty()
|
||
{
|
||
self.start_playing_index(self.queue_index);
|
||
} else {
|
||
self.audio.play();
|
||
}
|
||
}
|
||
AppAction::Pause => {
|
||
self.play_paused = true;
|
||
self.audio.pause();
|
||
}
|
||
AppAction::Stop => self.audio.stop(),
|
||
AppAction::Prev => self.play_prev(),
|
||
AppAction::Next => self.play_next(),
|
||
AppAction::SeekMs(ms) => self.seek_ms(ms),
|
||
AppAction::SeekFraction(f) => self.seek_fraction(f),
|
||
AppAction::SetVolume(v) => {
|
||
self.config.volume = v.clamp(0.0, 1.0);
|
||
self.config.muted = self.config.volume < 0.005;
|
||
self.audio.set_volume(self.config.volume);
|
||
self.audio.set_muted(self.config.muted);
|
||
self.save_config();
|
||
}
|
||
AppAction::ToggleMute => {
|
||
self.config.muted = !self.config.muted;
|
||
self.audio.set_muted(self.config.muted);
|
||
self.save_config();
|
||
}
|
||
AppAction::ToggleShuffle => self.toggle_shuffle(),
|
||
AppAction::CycleRepeat => self.cycle_repeat(),
|
||
AppAction::PlayTracks {
|
||
tracks,
|
||
start_index,
|
||
context_name,
|
||
context_key,
|
||
is_vibe,
|
||
} => {
|
||
self.play_tracks(tracks, start_index, context_name, context_key, is_vibe);
|
||
}
|
||
AppAction::ToggleContextPlay {
|
||
tracks,
|
||
context_name,
|
||
context_key,
|
||
is_vibe,
|
||
} => {
|
||
self.toggle_context_play(tracks, context_name, context_key, is_vibe);
|
||
}
|
||
AppAction::PlayAlbum { id, title } => {
|
||
let ctx_key = format!("album:{}", id);
|
||
if self.is_context_active(&ctx_key) {
|
||
self.toggle_play();
|
||
} else {
|
||
let api = self.api.clone();
|
||
let tx = self.tx_api.clone();
|
||
let aid = id.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));
|
||
}
|
||
});
|
||
}
|
||
}
|
||
AppAction::PlayPlaylist {
|
||
owner_uid,
|
||
kind,
|
||
title,
|
||
} => {
|
||
let key = format!("playlist:{}:{}", owner_uid, kind);
|
||
if self.is_context_active(&key) {
|
||
self.toggle_play();
|
||
} else {
|
||
let api = self.api.clone();
|
||
let tx = self.tx_api.clone();
|
||
self.runtime.spawn(async move {
|
||
if let Ok(det) = api.fetch_playlist_detail(&owner_uid, &kind).await {
|
||
let _ = tx.send(ApiEvent::PlayPlaylistTracks(key, title, det.tracks));
|
||
}
|
||
});
|
||
}
|
||
}
|
||
AppAction::PlayArtist { id, name } => {
|
||
let ctx_key = format!("artist:{}", id);
|
||
if self.is_context_active(&ctx_key) {
|
||
self.toggle_play();
|
||
} else {
|
||
let api = self.api.clone();
|
||
let tx = self.tx_api.clone();
|
||
let aid = id.clone();
|
||
self.runtime.spawn(async move {
|
||
if let Ok(det) = api.fetch_artist_detail(&aid).await {
|
||
let _ = tx.send(ApiEvent::PlayArtistTracks(
|
||
aid,
|
||
name,
|
||
det.popular_tracks,
|
||
));
|
||
}
|
||
});
|
||
}
|
||
}
|
||
AppAction::PlayFavorites => {
|
||
let tracks = self.liked_tracks.clone();
|
||
if self.is_context_active("likes") {
|
||
self.toggle_play();
|
||
} else if !tracks.is_empty() {
|
||
self.play_tracks(
|
||
tracks,
|
||
0,
|
||
t.liked_playlist().to_string(),
|
||
"likes".into(),
|
||
false,
|
||
);
|
||
}
|
||
}
|
||
AppAction::JumpQueue(idx) => self.start_playing_index(idx),
|
||
AppAction::RemoveQueueAt(idx) => self.remove_queue_at(idx),
|
||
AppAction::MoveQueue { from, to } => self.move_queue(from, to),
|
||
AppAction::ClearQueue => self.clear_queue(),
|
||
AppAction::AddToQueue(tr) => self.add_to_queue(tr),
|
||
AppAction::PlayNext(tr) => self.play_next_track(tr),
|
||
AppAction::AddTracksToQueue(tracks) => self.add_tracks_to_queue(tracks),
|
||
AppAction::PlayTracksNext(tracks) => self.play_tracks_next(tracks),
|
||
|
||
// Vibe & Wheel
|
||
AppAction::ToggleMyVibe => self.toggle_my_vibe(),
|
||
AppAction::ResetContextToMyVibe => self.reset_context_to_my_vibe(),
|
||
AppAction::SelectVibeStation {
|
||
label,
|
||
hue,
|
||
mood,
|
||
activity,
|
||
seeds,
|
||
} => {
|
||
self.active_vibe_title = label.clone();
|
||
self.target_hue = hue;
|
||
self.config.vibe_mood = mood;
|
||
self.config.vibe_activity = activity;
|
||
self.save_config();
|
||
self.start_vibe_by_seeds(label, seeds);
|
||
}
|
||
AppAction::ActivateWheelItem(item) => self.activate_wheel_item(item),
|
||
AppAction::ReshuffleWheel => self.reshuffle_wheel(),
|
||
AppAction::StartVibeBySeeds { title, seeds }
|
||
| AppAction::StartVibeStation { title, seeds } => {
|
||
self.start_vibe_by_seeds(title, seeds);
|
||
}
|
||
AppAction::RefreshConcerts => self.refresh_concerts(),
|
||
AppAction::RefreshNonMusic => self.refresh_non_music(),
|
||
AppAction::ApplyVibeSettings {
|
||
mood,
|
||
activity,
|
||
character,
|
||
language,
|
||
} => {
|
||
self.config.vibe_mood = mood.clone();
|
||
self.config.vibe_activity = activity.clone();
|
||
self.config.vibe_character = character.clone();
|
||
self.config.vibe_language = language.clone();
|
||
self.save_config();
|
||
self.current_hue = match mood.as_deref() {
|
||
Some("active") => 0.04,
|
||
Some("fun") => 0.12,
|
||
Some("calm") => 0.56,
|
||
Some("sad") => 0.72,
|
||
_ => 0.12,
|
||
};
|
||
self.show_toast(t.toast_vibe_updated());
|
||
if self.api.has_token() {
|
||
let api = self.api.clone();
|
||
let tx = self.tx_api.clone();
|
||
self.runtime.spawn(async move {
|
||
if let Ok(tr) = api
|
||
.fetch_vibe_tracks(
|
||
mood.as_deref(),
|
||
activity.as_deref(),
|
||
character.as_deref(),
|
||
language.as_deref(),
|
||
)
|
||
.await
|
||
{
|
||
let _ = tx.send(ApiEvent::VibeTracksLoaded(tr, true));
|
||
}
|
||
});
|
||
}
|
||
}
|
||
|
||
// Likes, Dislikes & Pins
|
||
AppAction::ToggleLike(tr) => self.toggle_like(tr),
|
||
AppAction::ToggleDislike(tr) => self.toggle_dislike(tr),
|
||
AppAction::TogglePin {
|
||
kind,
|
||
id,
|
||
title,
|
||
subtitle,
|
||
cover_uri,
|
||
owner_uid,
|
||
} => {
|
||
self.toggle_pin(&kind, &id, &title, &subtitle, cover_uri, owner_uid);
|
||
}
|
||
AppAction::UnpinItem(pin) => self.unpin_item(pin),
|
||
|
||
// Favorites Filter & Search
|
||
AppAction::SelectFavoriteFilter(filter_id) => {
|
||
self.select_favorite_filter(filter_id);
|
||
}
|
||
AppAction::SetSearchQuery(q) => self.set_search_query(q),
|
||
AppAction::RunSearchNow(q) => {
|
||
self.search_query = q.clone();
|
||
self.search_debounce_deadline = None;
|
||
let trimmed = q.trim().to_string();
|
||
if !trimmed.is_empty() {
|
||
self.run_search(trimmed, self.search_filter);
|
||
}
|
||
}
|
||
AppAction::SetSearchFilter(f) => {
|
||
self.search_filter = f;
|
||
let q = self.search_query.trim().to_string();
|
||
if !q.is_empty() {
|
||
self.run_search(q, f);
|
||
}
|
||
}
|
||
AppAction::SetSearchBrowseTab(tab) => {
|
||
self.search_browse_tab = tab;
|
||
}
|
||
AppAction::ClearSearchHistory => {
|
||
self.config.search_history.clear();
|
||
self.save_config();
|
||
self.show_toast(t.toast_history_cleared());
|
||
if let Some(ref acc) = self.account {
|
||
let uid = acc.uid;
|
||
let api = self.api.clone();
|
||
self.runtime.spawn(async move {
|
||
let _ = api.clear_search_history(uid).await;
|
||
});
|
||
}
|
||
}
|
||
|
||
// Playlists CRUD & Modals
|
||
AppAction::OpenCreatePlaylistModal { initial_track } => {
|
||
self.playlist_modal = PlaylistModalState::Create {
|
||
title_draft: t.new_playlist_default().to_string(),
|
||
is_private: false,
|
||
initial_track,
|
||
};
|
||
}
|
||
AppAction::OpenRenamePlaylistModal {
|
||
owner_uid,
|
||
kind,
|
||
current_title,
|
||
} => {
|
||
self.playlist_modal = PlaylistModalState::Rename {
|
||
owner_uid,
|
||
kind,
|
||
title_draft: current_title,
|
||
};
|
||
}
|
||
AppAction::ClosePlaylistModal => {
|
||
self.playlist_modal = PlaylistModalState::None;
|
||
}
|
||
AppAction::CreatePlaylist {
|
||
title,
|
||
is_private,
|
||
initial_track,
|
||
} => {
|
||
self.playlist_modal = PlaylistModalState::None;
|
||
self.create_playlist(title, is_private, initial_track);
|
||
}
|
||
AppAction::RenamePlaylist {
|
||
owner_uid,
|
||
kind,
|
||
new_title,
|
||
} => {
|
||
self.playlist_modal = PlaylistModalState::None;
|
||
self.rename_playlist(owner_uid, kind, new_title);
|
||
}
|
||
AppAction::DeletePlaylist { owner_uid, kind } => {
|
||
self.delete_playlist(owner_uid, kind);
|
||
}
|
||
AppAction::AddTrackToPlaylist {
|
||
owner_uid,
|
||
kind,
|
||
track,
|
||
} => {
|
||
self.add_track_to_playlist(owner_uid, kind, track);
|
||
}
|
||
AppAction::RemoveTrackFromPlaylist {
|
||
owner_uid,
|
||
kind,
|
||
index,
|
||
} => {
|
||
self.remove_track_from_playlist(owner_uid, kind, index);
|
||
}
|
||
|
||
// Offline Downloads
|
||
AppAction::DownloadTrack(tr) => self.download_track(tr),
|
||
AppAction::DownloadTracks(tracks) => self.download_tracks(tracks),
|
||
AppAction::CancelDownload => self.cancel_downloads(),
|
||
AppAction::RemoveDownloadedTrack(id) => self.remove_downloaded_track(&id),
|
||
AppAction::RemoveDownloadedTracks(ids) => self.remove_downloaded_tracks(&ids),
|
||
|
||
// Share & Clipboard
|
||
AppAction::CopyToClipboard { text, toast_msg } => {
|
||
self.copy_to_clipboard(text, toast_msg);
|
||
}
|
||
AppAction::CopyTrackLink(tr) => {
|
||
let url = match &tr.album_id {
|
||
Some(aid) if !aid.is_empty() => {
|
||
format!("https://music.yandex.ru/album/{}/track/{}", aid, tr.id)
|
||
}
|
||
_ => format!("https://music.yandex.ru/track/{}", tr.id),
|
||
};
|
||
self.copy_to_clipboard(url, t.toast_link_copied("track"));
|
||
}
|
||
AppAction::CopyTrackEmbed(tr) => {
|
||
let html = format!(
|
||
"<iframe frameborder=\"0\" allow=\"clipboard-write\" style=\"border:none;width:614px;height:244px;\" width=\"614\" height=\"244\" src=\"https://music.yandex.ru/iframe/track/{}\"></iframe>",
|
||
tr.id
|
||
);
|
||
self.copy_to_clipboard(html, t.toast_html_copied().to_string());
|
||
}
|
||
AppAction::CopyEntityLink { kind, url } => {
|
||
self.copy_to_clipboard(url, t.toast_link_copied(&kind));
|
||
}
|
||
|
||
// Overlays & Modals
|
||
AppAction::ToggleRightDrawer(tab) => {
|
||
self.right_drawer = if self.right_drawer == tab {
|
||
RightDrawerTab::None
|
||
} else {
|
||
tab
|
||
};
|
||
if self.right_drawer == RightDrawerTab::Lyrics {
|
||
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);
|
||
}
|
||
}
|
||
}
|
||
}
|
||
AppAction::CloseRightDrawer => {
|
||
self.right_drawer = RightDrawerTab::None;
|
||
}
|
||
AppAction::ToggleFullscreen => {
|
||
self.fullscreen_open = !self.fullscreen_open;
|
||
if !self.fullscreen_open {
|
||
self.fullscreen_lyrics_open = false;
|
||
self.fullscreen_queue_open = false;
|
||
}
|
||
}
|
||
AppAction::SetFullscreen(open) => {
|
||
self.fullscreen_open = open;
|
||
if !open {
|
||
self.fullscreen_lyrics_open = false;
|
||
self.fullscreen_queue_open = false;
|
||
}
|
||
}
|
||
AppAction::OpenFullscreenSyncLyrics => {
|
||
self.open_fullscreen_sync_lyrics();
|
||
}
|
||
AppAction::OpenFullscreenQueue => {
|
||
self.open_fullscreen_queue();
|
||
}
|
||
AppAction::ToggleFullscreenLyrics => {
|
||
self.toggle_fullscreen_lyrics();
|
||
}
|
||
AppAction::ToggleFullscreenQueue => {
|
||
self.toggle_fullscreen_queue();
|
||
}
|
||
AppAction::SetVibeModalOpen(open) => {
|
||
self.vibe_modal_open = open;
|
||
}
|
||
AppAction::SetLoginModalOpen(open) => {
|
||
self.login_modal_open = open;
|
||
}
|
||
AppAction::SetEqPopoverOpen(open) => {
|
||
self.eq_popover_open = open;
|
||
}
|
||
AppAction::OpenTrackDetailModal(tr) => {
|
||
let tid = tr.id.clone();
|
||
let cached_from_current = self
|
||
.current_lyrics
|
||
.as_ref()
|
||
.filter(|l| l.track_id == tid && !l.lines.is_empty())
|
||
.cloned();
|
||
let already_in_modal = self
|
||
.modal_lyrics
|
||
.as_ref()
|
||
.map_or(false, |l| l.track_id == tid && !l.lines.is_empty());
|
||
if let Some(lyr) = cached_from_current {
|
||
self.modal_lyrics = Some(lyr);
|
||
} else if !already_in_modal {
|
||
self.modal_lyrics = None;
|
||
self.fetch_lyrics_for_track(&tr);
|
||
}
|
||
self.track_detail_modal = Some(tr);
|
||
}
|
||
AppAction::CloseTrackDetailModal => {
|
||
self.track_detail_modal = None;
|
||
}
|
||
AppAction::OpenWordsBigCard { track_id } => {
|
||
self.open_words_big_card(track_id);
|
||
}
|
||
AppAction::CloseWordsBigCard => {
|
||
self.words_big_card_open = false;
|
||
self.words_big_card_loading = false;
|
||
}
|
||
AppAction::SendWordsFeedback {
|
||
track_id,
|
||
card_id,
|
||
state,
|
||
} => {
|
||
self.send_words_feedback(track_id, card_id, state);
|
||
}
|
||
AppAction::DismissOverlays => {
|
||
self.fullscreen_open = false;
|
||
self.fullscreen_lyrics_open = false;
|
||
self.fullscreen_queue_open = false;
|
||
self.vibe_modal_open = false;
|
||
self.login_modal_open = false;
|
||
self.eq_popover_open = false;
|
||
self.playlist_modal = PlaylistModalState::None;
|
||
self.track_detail_modal = None;
|
||
self.words_big_card_open = false;
|
||
self.words_big_card_loading = false;
|
||
}
|
||
|
||
// Account, Settings & Lifecycle
|
||
AppAction::SetTheme(mode) => {
|
||
self.config.theme = mode;
|
||
self.save_config();
|
||
self.theme_dirty = true;
|
||
}
|
||
AppAction::SetLanguage(lang) => {
|
||
self.config.language = lang;
|
||
self.save_config();
|
||
self.api.set_language(lang.api_code());
|
||
self.clear_words_cache();
|
||
self.bootstrap_api();
|
||
self.ensure_words_for_current_track();
|
||
}
|
||
AppAction::ToggleLanguage => {
|
||
let next = if self.config.language.is_ru() {
|
||
Language::En
|
||
} else {
|
||
Language::Ru
|
||
};
|
||
self.config.language = next;
|
||
self.save_config();
|
||
self.api.set_language(next.api_code());
|
||
self.clear_words_cache();
|
||
self.bootstrap_api();
|
||
self.ensure_words_for_current_track();
|
||
}
|
||
AppAction::SetAudioQuality(q) => {
|
||
self.config.audio_quality = q;
|
||
self.save_config();
|
||
let label = q.label_for(self.config.language);
|
||
self.show_toast(t.toast_quality_changed(label));
|
||
}
|
||
AppAction::SetNormalizeLoudness(v) => {
|
||
self.config.normalize_loudness = v;
|
||
self.audio.set_normalize_loudness(v);
|
||
self.save_config();
|
||
}
|
||
AppAction::SetCrossfadeSecs(secs) => {
|
||
self.config.crossfade_secs = secs.clamp(0.0, 12.0);
|
||
self.audio.set_crossfade_secs(self.config.crossfade_secs);
|
||
self.save_config();
|
||
}
|
||
AppAction::SetAiContentReduction(v) => {
|
||
self.config.ai_content_reduction = v;
|
||
self.api.set_ai_content_reduction(v);
|
||
self.save_config();
|
||
if self.api.has_token() {
|
||
let api = self.api.clone();
|
||
self.runtime.spawn(async move {
|
||
let _ = api.update_account_settings(None, Some(v)).await;
|
||
});
|
||
}
|
||
}
|
||
AppAction::SetChildMode(v) => {
|
||
self.config.child_mode = v;
|
||
self.save_config();
|
||
if self.api.has_token() {
|
||
let api = self.api.clone();
|
||
self.runtime.spawn(async move {
|
||
let _ = api.update_account_settings(Some(v), None).await;
|
||
});
|
||
}
|
||
}
|
||
AppAction::SetCloseToTray(v) => {
|
||
self.config.close_to_tray = v;
|
||
self.save_config();
|
||
}
|
||
AppAction::UpdateEq { enabled, bands } => {
|
||
self.config.eq_enabled = enabled;
|
||
self.config.eq_bands_db = bands;
|
||
self.audio.set_eq(enabled, bands);
|
||
self.save_config();
|
||
}
|
||
AppAction::SetMaxCoverCache(cap) => {
|
||
self.config.max_cover_cache = cap.clamp(128, 1024);
|
||
self.cover_cache_capacity_dirty = true;
|
||
self.save_config();
|
||
}
|
||
AppAction::ClearCoverCache => {
|
||
self.clear_cover_cache_requested = true;
|
||
PerfTelemetry::trim_working_set();
|
||
self.show_toast(t.toast_cover_cache_cleared());
|
||
}
|
||
AppAction::TogglePerfHud(v) => {
|
||
self.config.show_perf_hud = v;
|
||
self.save_config();
|
||
}
|
||
AppAction::OpenOAuthBrowser => self.launch_oauth_login(),
|
||
AppAction::SubmitOAuthToken(raw) => self.submit_oauth_token(raw),
|
||
AppAction::Logout => {
|
||
self.config.oauth_token = None;
|
||
self.save_config();
|
||
self.api.set_token(None);
|
||
self.account = None;
|
||
self.clear_words_cache();
|
||
self.show_toast(t.toast_signed_out());
|
||
}
|
||
AppAction::CheckForUpdates => self.check_for_updates(),
|
||
AppAction::ShowToast(msg) => self.show_toast(msg),
|
||
}
|
||
}
|
||
}
|
||
|
||
// =============================================================================
|
||
// Pure RGB / HSL Color Helpers (Exact 5.129.0 16-Bucket Vibe Palette, Zero UI Deps)
|
||
// =============================================================================
|
||
|
||
pub fn parse_hex_rgb(hex: &str) -> Option<[u8; 3]> {
|
||
let s = hex.trim().trim_start_matches('#');
|
||
if s.len() != 6 {
|
||
return None;
|
||
}
|
||
let r = u8::from_str_radix(&s[0..2], 16).ok()?;
|
||
let g = u8::from_str_radix(&s[2..4], 16).ok()?;
|
||
let b = u8::from_str_radix(&s[4..6], 16).ok()?;
|
||
Some([r, g, b])
|
||
}
|
||
|
||
pub fn rgb_to_hue_f32(r: u8, g: u8, b: u8) -> f32 {
|
||
let rf = r as f32 / 255.0;
|
||
let gf = g as f32 / 255.0;
|
||
let bf = b as f32 / 255.0;
|
||
let max = rf.max(gf).max(bf);
|
||
let min = rf.min(gf).min(bf);
|
||
let delta = max - min;
|
||
if delta < 0.001 {
|
||
return 0.13;
|
||
}
|
||
let h = if (max - rf).abs() < 1e-5 {
|
||
((gf - bf) / delta) % 6.0
|
||
} else if (max - gf).abs() < 1e-5 {
|
||
(bf - rf) / delta + 2.0
|
||
} else {
|
||
(rf - gf) / delta + 4.0
|
||
};
|
||
let mut hue = h / 6.0;
|
||
if hue < 0.0 {
|
||
hue += 1.0;
|
||
}
|
||
hue
|
||
}
|
||
|
||
pub fn rgb_to_hsl_sl_f32(rgb: [u8; 3]) -> (f32, f32) {
|
||
let r = rgb[0] as f32 / 255.0;
|
||
let g = rgb[1] as f32 / 255.0;
|
||
let b = rgb[2] as f32 / 255.0;
|
||
let max = r.max(g).max(b);
|
||
let min = r.min(g).min(b);
|
||
let l = (max + min) * 0.5;
|
||
let d = max - min;
|
||
let sat = if d < 1e-5 {
|
||
0.0
|
||
} else if l > 0.5 {
|
||
d / (2.0 - max - min)
|
||
} else {
|
||
d / (max + min)
|
||
};
|
||
(sat, l)
|
||
}
|
||
|
||
/// Exact 5.129.0 `getVibePaletteColors` (`3684` mod `57496`): maps average RGB into 16 curated hue buckets
|
||
/// (or 5 lightness buckets for achromatic colors), fallback `slate` `#4F6C9B`.
|
||
pub fn vibe_bucket_primary_rgb(raw_rgb: Option<[u8; 3]>) -> [u8; 3] {
|
||
const SLATE: [u8; 3] = [0x4F, 0x6C, 0x9B];
|
||
let Some([r, g, b]) = raw_rgb else {
|
||
return SLATE;
|
||
};
|
||
let (sat, light) = rgb_to_hsl_sl_f32([r, g, b]);
|
||
if sat <= 0.001 {
|
||
let lp = light * 100.0;
|
||
return if lp < 22.0 {
|
||
[0x50, 0x35, 0xC0] // amethyst
|
||
} else if lp < 32.0 {
|
||
[0x16, 0x0C, 0xE8] // indigo
|
||
} else if lp < 42.0 {
|
||
[0x34, 0xC0, 0x3E] // clover
|
||
} else if lp < 51.0 {
|
||
[0xDB, 0x1A, 0x7D] // raspberry
|
||
} else {
|
||
[0x00, 0xB2, 0xCC] // aquamarine
|
||
};
|
||
}
|
||
let h = rgb_to_hue_f32(r, g, b) * 360.0;
|
||
if (2.0..20.0).contains(&h) {
|
||
[0xF5, 0x37, 0x00] // coral
|
||
} else if (20.0..65.0).contains(&h) {
|
||
[0xF5, 0x6E, 0x00] // tangerine
|
||
} else if (65.0..150.0).contains(&h) {
|
||
[0x34, 0xC0, 0x3E] // clover
|
||
} else if (150.0..165.0).contains(&h) {
|
||
[0x00, 0xC7, 0x89] // emerald
|
||
} else if (165.0..180.0).contains(&h) {
|
||
[0x00, 0xC7, 0xA6] // turquoise
|
||
} else if (180.0..190.0).contains(&h) {
|
||
[0x00, 0xB2, 0xCC] // aquamarine
|
||
} else if (190.0..205.0).contains(&h) {
|
||
[0x5C, 0x8E, 0x9B] // glacier
|
||
} else if (205.0..220.0).contains(&h) {
|
||
SLATE // slate
|
||
} else if (220.0..235.0).contains(&h) {
|
||
[0x0C, 0x41, 0xE8] // sapphire
|
||
} else if (235.0..250.0).contains(&h) {
|
||
[0x16, 0x0C, 0xE8] // indigo
|
||
} else if (250.0..260.0).contains(&h) {
|
||
[0x50, 0x35, 0xC0] // amethyst
|
||
} else if (260.0..270.0).contains(&h) {
|
||
[0x7C, 0x35, 0xC0] // plum
|
||
} else if (270.0..300.0).contains(&h) {
|
||
[0xBB, 0x1A, 0xDB] // orchid
|
||
} else if (300.0..330.0).contains(&h) {
|
||
[0xDB, 0x1A, 0x7D] // raspberry
|
||
} else if (330.0..340.0).contains(&h) {
|
||
[0xF5, 0x00, 0x7C] // fuchsia
|
||
} else {
|
||
[0xF5, 0x00, 0x2E] // carmine (340..360 or 0..2)
|
||
}
|
||
}
|
||
|
||
fn parse_semver_tuple(raw: &str) -> Option<(u32, u32, u32)> {
|
||
let trimmed = raw.trim().trim_start_matches(['v', 'V']);
|
||
let core = trimmed.split(['-', '+']).next()?.trim();
|
||
if core.is_empty() {
|
||
return None;
|
||
}
|
||
let mut parts = core.split('.');
|
||
let major = parts.next()?.parse::<u32>().ok()?;
|
||
let minor = match parts.next() {
|
||
Some(s) => s.parse::<u32>().ok()?,
|
||
None => 0,
|
||
};
|
||
let patch = match parts.next() {
|
||
Some(s) => s.parse::<u32>().ok()?,
|
||
None => 0,
|
||
};
|
||
Some((major, minor, patch))
|
||
}
|
||
|
||
/// Returns `true` iff `remote` is strictly newer than `current` by `(major, minor, patch)` semver comparison.
|
||
pub fn is_newer_version(remote: &str, current: &str) -> bool {
|
||
match (parse_semver_tuple(remote), parse_semver_tuple(current)) {
|
||
(Some(r), Some(c)) => r > c,
|
||
_ => false,
|
||
}
|
||
}
|
||
|
||
/// Normalize pinned items so only the signed-in user's own `kind == "3"` (`{my_uid}:3`)
|
||
/// collapses into system `kind: "likes", id: "likes"`, while friends' `"Мне нравится"` playlists
|
||
/// (`{friend_uid}:3`) are ALWAYS preserved as distinct `"playlist"` pins!
|
||
fn normalize_pins(pins: &mut Vec<PinnedItem>, my_uid: Option<u64>, ru: bool) {
|
||
if let Some(uid) = my_uid {
|
||
let my_likes_id = format!("{}:3", uid);
|
||
let likes_title = if ru { "Мне нравится" } else { "My Favorites" };
|
||
for p in pins.iter_mut() {
|
||
if p.kind == "playlist" && p.id == my_likes_id {
|
||
p.id = "likes".into();
|
||
p.kind = "likes".into();
|
||
p.cover_uri = None;
|
||
p.title = likes_title.into();
|
||
}
|
||
}
|
||
}
|
||
let mut seen: HashSet<(String, String)> = HashSet::new();
|
||
pins.retain(|p| seen.insert((p.kind.clone(), p.id.clone())));
|
||
}
|
||
|
||
#[cfg(test)]
|
||
mod tests {
|
||
use super::*;
|
||
|
||
#[test]
|
||
fn test_is_newer_version_semver() {
|
||
assert_eq!(APP_VERSION, env!("CARGO_PKG_VERSION"));
|
||
assert!(!is_newer_version("v0.1.0", "0.1.0"));
|
||
assert!(!is_newer_version("0.1.0", "0.1.0"));
|
||
assert!(is_newer_version("v0.1.1", "0.1.0"));
|
||
assert!(is_newer_version("v0.2.0", "0.1.0"));
|
||
assert!(is_newer_version("v1.0.0", "0.9.9"));
|
||
assert!(!is_newer_version("v0.0.9", "0.1.0"));
|
||
assert!(!is_newer_version("", "0.1.0"));
|
||
}
|
||
|
||
#[test]
|
||
fn test_normalize_pins_keeps_friends_favorites_playlist() {
|
||
let mut pins = vec![
|
||
PinnedItem {
|
||
id: "likes".into(),
|
||
kind: "likes".into(),
|
||
title: "Мне нравится".into(),
|
||
subtitle: "Плейлист".into(),
|
||
cover_uri: None,
|
||
owner_uid: Some("1001".into()),
|
||
},
|
||
PinnedItem {
|
||
id: "1001:3".into(),
|
||
kind: "playlist".into(),
|
||
title: "Мне нравится".into(),
|
||
subtitle: "Плейлист".into(),
|
||
cover_uri: None,
|
||
owner_uid: Some("1001".into()),
|
||
},
|
||
PinnedItem {
|
||
id: "2002:3".into(),
|
||
kind: "playlist".into(),
|
||
title: "Мне нравится".into(),
|
||
subtitle: "Плейлист".into(),
|
||
cover_uri: None,
|
||
owner_uid: Some("2002".into()),
|
||
},
|
||
];
|
||
normalize_pins(&mut pins, Some(1001), true);
|
||
assert_eq!(pins.len(), 2, "Own likes + friend's kind=3 likes must BOTH remain");
|
||
assert_eq!(pins[0].kind, "likes");
|
||
assert_eq!(pins[0].id, "likes");
|
||
assert_eq!(pins[1].kind, "playlist");
|
||
assert_eq!(pins[1].id, "2002:3");
|
||
assert_eq!(pins[1].owner_uid.as_deref(), Some("2002"));
|
||
}
|
||
}
|