diff --git a/crates/qbz-core/src/core.rs b/crates/qbz-core/src/core.rs index 2ac693dee..4c2c7dd79 100644 --- a/crates/qbz-core/src/core.rs +++ b/crates/qbz-core/src/core.rs @@ -157,12 +157,13 @@ impl QbzCore { query: &str, limit: u32, offset: u32, + search_type: Option<&str>, ) -> Result, CoreError> { let client = self.client.read().await; let client = client.as_ref().ok_or(CoreError::NotInitialized)?; client - .search_albums(query, limit, offset, None) + .search_albums(query, limit, offset, search_type) .await .map_err(CoreError::Api) } @@ -173,12 +174,13 @@ impl QbzCore { query: &str, limit: u32, offset: u32, + search_type: Option<&str>, ) -> Result, CoreError> { let client = self.client.read().await; let client = client.as_ref().ok_or(CoreError::NotInitialized)?; client - .search_tracks(query, limit, offset, None) + .search_tracks(query, limit, offset, search_type) .await .map_err(CoreError::Api) } @@ -189,12 +191,13 @@ impl QbzCore { query: &str, limit: u32, offset: u32, + search_type: Option<&str>, ) -> Result, CoreError> { let client = self.client.read().await; let client = client.as_ref().ok_or(CoreError::NotInitialized)?; client - .search_artists(query, limit, offset, None) + .search_artists(query, limit, offset, search_type) .await .map_err(CoreError::Api) } diff --git a/src-tauri/src/commands_v2.rs b/src-tauri/src/commands_v2.rs index fe795da98..3bb5df093 100644 --- a/src-tauri/src/commands_v2.rs +++ b/src-tauri/src/commands_v2.rs @@ -2,12 +2,18 @@ //! //! These commands use QbzCore via CoreBridge instead of the old AppState. //! They coexist with the old commands during migration. +//! +//! For playback commands, we use a bridge pattern: +//! - CoreBridge for Qobuz API (get stream URL) +//! - AppState.player for actual audio playback (until player moves to qbz-player crate) use tauri::State; use qbz_models::{Album, Artist, QueueState, RepeatMode, SearchResultsPage, Track, UserSession}; +use crate::artist_blacklist::BlacklistState; use crate::core_bridge::CoreBridgeState; +use crate::AppState; // ==================== Auth Commands (V2) ==================== @@ -85,38 +91,89 @@ pub async fn v2_clear_queue( /// Search for albums (V2 - uses QbzCore) #[tauri::command] +#[allow(non_snake_case)] pub async fn v2_search_albums( query: String, limit: u32, offset: u32, + searchType: Option, bridge: State<'_, CoreBridgeState>, + blacklist_state: State<'_, BlacklistState>, ) -> Result, String> { let bridge = bridge.get().await; - bridge.search_albums(&query, limit, offset).await + let mut results = bridge.search_albums(&query, limit, offset, searchType.as_deref()).await?; + + // Filter out albums from blacklisted artists + let original_count = results.items.len(); + results.items.retain(|album| !blacklist_state.is_blacklisted(album.artist.id)); + + let filtered_count = original_count - results.items.len(); + if filtered_count > 0 { + log::debug!("[V2/Blacklist] Filtered {} albums from search results", filtered_count); + results.total = results.total.saturating_sub(filtered_count as u32); + } + + Ok(results) } /// Search for tracks (V2 - uses QbzCore) #[tauri::command] +#[allow(non_snake_case)] pub async fn v2_search_tracks( query: String, limit: u32, offset: u32, + searchType: Option, bridge: State<'_, CoreBridgeState>, + blacklist_state: State<'_, BlacklistState>, ) -> Result, String> { let bridge = bridge.get().await; - bridge.search_tracks(&query, limit, offset).await + let mut results = bridge.search_tracks(&query, limit, offset, searchType.as_deref()).await?; + + // Filter out tracks from blacklisted artists + let original_count = results.items.len(); + results.items.retain(|track| { + if let Some(ref performer) = track.performer { + !blacklist_state.is_blacklisted(performer.id) + } else { + true // Keep tracks without performer info + } + }); + + let filtered_count = original_count - results.items.len(); + if filtered_count > 0 { + log::debug!("[V2/Blacklist] Filtered {} tracks from search results", filtered_count); + results.total = results.total.saturating_sub(filtered_count as u32); + } + + Ok(results) } /// Search for artists (V2 - uses QbzCore) #[tauri::command] +#[allow(non_snake_case)] pub async fn v2_search_artists( query: String, limit: u32, offset: u32, + searchType: Option, bridge: State<'_, CoreBridgeState>, + blacklist_state: State<'_, BlacklistState>, ) -> Result, String> { let bridge = bridge.get().await; - bridge.search_artists(&query, limit, offset).await + let mut results = bridge.search_artists(&query, limit, offset, searchType.as_deref()).await?; + + // Filter out blacklisted artists + let original_count = results.items.len(); + results.items.retain(|artist| !blacklist_state.is_blacklisted(artist.id)); + + let filtered_count = original_count - results.items.len(); + if filtered_count > 0 { + log::debug!("[V2/Blacklist] Filtered {} artists from search results", filtered_count); + results.total = results.total.saturating_sub(filtered_count as u32); + } + + Ok(results) } // ==================== Catalog Commands (V2) ==================== @@ -153,3 +210,66 @@ pub async fn v2_get_artist( let bridge = bridge.get().await; bridge.get_artist(artistId).await } + +// ==================== Playback Commands (V2) ==================== +// +// These commands use AppState.player for actual playback (bridge pattern). +// Eventually the player should move to qbz-player crate, but for now +// we keep it in src-tauri and bridge to it. + +/// Pause playback (V2) +#[tauri::command] +pub async fn v2_pause_playback( + state: State<'_, AppState>, +) -> Result<(), String> { + state.player.pause() +} + +/// Resume playback (V2) +#[tauri::command] +pub async fn v2_resume_playback( + state: State<'_, AppState>, +) -> Result<(), String> { + state.player.resume() +} + +/// Stop playback (V2) +#[tauri::command] +pub async fn v2_stop_playback( + state: State<'_, AppState>, +) -> Result<(), String> { + state.player.stop() +} + +/// Seek to position in seconds (V2) +#[tauri::command] +pub async fn v2_seek( + position: u64, + state: State<'_, AppState>, +) -> Result<(), String> { + state.player.seek(position) +} + +/// Set volume (0.0 - 1.0) (V2) +#[tauri::command] +pub async fn v2_set_volume( + volume: f32, + state: State<'_, AppState>, +) -> Result<(), String> { + state.player.set_volume(volume) +} + +/// Get current playback state (V2) +#[tauri::command] +pub async fn v2_get_playback_state( + state: State<'_, AppState>, +) -> Result { + let player_state = &state.player.state; + Ok(crate::player::PlaybackState { + is_playing: player_state.is_playing(), + position: player_state.current_position(), + duration: player_state.duration(), + track_id: player_state.current_track_id(), + volume: player_state.volume(), + }) +} diff --git a/src-tauri/src/core_bridge.rs b/src-tauri/src/core_bridge.rs index 0207d1e83..9ce76c62e 100644 --- a/src-tauri/src/core_bridge.rs +++ b/src-tauri/src/core_bridge.rs @@ -83,9 +83,10 @@ impl CoreBridge { query: &str, limit: u32, offset: u32, + search_type: Option<&str>, ) -> Result, String> { self.core - .search_albums(query, limit, offset) + .search_albums(query, limit, offset, search_type) .await .map_err(|e| e.to_string()) } @@ -96,9 +97,10 @@ impl CoreBridge { query: &str, limit: u32, offset: u32, + search_type: Option<&str>, ) -> Result, String> { self.core - .search_tracks(query, limit, offset) + .search_tracks(query, limit, offset, search_type) .await .map_err(|e| e.to_string()) } @@ -109,9 +111,10 @@ impl CoreBridge { query: &str, limit: u32, offset: u32, + search_type: Option<&str>, ) -> Result, String> { self.core - .search_artists(query, limit, offset) + .search_artists(query, limit, offset, search_type) .await .map_err(|e| e.to_string()) } diff --git a/src-tauri/src/lib.rs b/src-tauri/src/lib.rs index 16c62f291..7053dac6b 100644 --- a/src-tauri/src/lib.rs +++ b/src-tauri/src/lib.rs @@ -1061,6 +1061,13 @@ pub fn run() { commands_v2::v2_get_album, commands_v2::v2_get_track, commands_v2::v2_get_artist, + // Playback + commands_v2::v2_pause_playback, + commands_v2::v2_resume_playback, + commands_v2::v2_stop_playback, + commands_v2::v2_seek, + commands_v2::v2_set_volume, + commands_v2::v2_get_playback_state, ]) .run(tauri::generate_context!()) .expect("error while running tauri application"); diff --git a/src-tauri/src/tauri_adapter.rs b/src-tauri/src/tauri_adapter.rs index 75ecc32dc..208887a64 100644 --- a/src-tauri/src/tauri_adapter.rs +++ b/src-tauri/src/tauri_adapter.rs @@ -1,6 +1,12 @@ //! Tauri Frontend Adapter //! //! Implements FrontendAdapter for Tauri, emitting events to the frontend via Tauri's event system. +//! +//! MIGRATION NOTE: During the V2 migration, this adapter emits BOTH: +//! - "core-event" (new unified event channel for V2 architecture) +//! - Legacy event names ("playback:state", etc.) for backwards compatibility +//! +//! Once frontend is fully migrated to listen on "core-event", legacy emissions can be removed. use async_trait::async_trait; use qbz_models::{CoreEvent, FrontendAdapter}; @@ -9,6 +15,7 @@ use tauri::{AppHandle, Emitter}; /// Tauri implementation of FrontendAdapter /// /// Emits CoreEvents to the Svelte frontend via Tauri's event system. +/// During migration, emits both new and legacy event formats. #[derive(Clone)] pub struct TauriAdapter { app_handle: AppHandle, @@ -19,6 +26,62 @@ impl TauriAdapter { pub fn new(app_handle: AppHandle) -> Self { Self { app_handle } } + + /// Emit legacy event for backwards compatibility during migration + fn emit_legacy_event(&self, event: &CoreEvent) { + // Map CoreEvent variants to legacy event names + match event { + CoreEvent::PlaybackStateChanged { state: _ } => { + // Legacy "playback:state" expects PlaybackEvent format + // The full legacy polling loop in lib.rs handles this event + // Once we migrate the polling loop to use CoreEvent, we can emit here + log::trace!("[Legacy] PlaybackStateChanged -> handled by polling loop"); + } + CoreEvent::QueueUpdated { state } => { + if let Err(e) = self.app_handle.emit("queue:updated", state) { + log::error!("Failed to emit legacy queue:updated: {}", e); + } + } + CoreEvent::ShuffleChanged { enabled } => { + if let Err(e) = self.app_handle.emit("queue:shuffle-changed", enabled) { + log::error!("Failed to emit legacy queue:shuffle-changed: {}", e); + } + } + CoreEvent::RepeatModeChanged { mode } => { + let mode_str = match mode { + qbz_models::RepeatMode::Off => "off", + qbz_models::RepeatMode::All => "all", + qbz_models::RepeatMode::One => "one", + }; + if let Err(e) = self.app_handle.emit("queue:repeat-changed", mode_str) { + log::error!("Failed to emit legacy queue:repeat-changed: {}", e); + } + } + CoreEvent::LoggedIn { session } => { + if let Err(e) = self.app_handle.emit("auth:logged-in", session) { + log::error!("Failed to emit legacy auth:logged-in: {}", e); + } + } + CoreEvent::LoggedOut => { + if let Err(e) = self.app_handle.emit("auth:logged-out", ()) { + log::error!("Failed to emit legacy auth:logged-out: {}", e); + } + } + CoreEvent::Error { code, message, recoverable } => { + #[derive(serde::Serialize, Clone)] + struct LegacyError<'a> { + code: &'a str, + message: &'a str, + recoverable: bool, + } + if let Err(e) = self.app_handle.emit("error", LegacyError { code, message, recoverable: *recoverable }) { + log::error!("Failed to emit legacy error: {}", e); + } + } + // Other events don't have legacy equivalents (or are handled by polling loop) + _ => {} + } + } } #[async_trait] @@ -27,22 +90,32 @@ impl FrontendAdapter for TauriAdapter { /// /// Events are serialized to JSON and sent via Tauri's event system. /// The frontend listens on "core-event" channel. + /// + /// MIGRATION: Also emits legacy events for backwards compatibility. async fn on_event(&self, event: CoreEvent) { - // Emit to frontend via Tauri event system + // Emit new unified event if let Err(e) = self.app_handle.emit("core-event", &event) { log::error!("Failed to emit core event: {}", e); } - // Also log for debugging + // Also emit legacy event for backwards compatibility + self.emit_legacy_event(&event); + + // Debug logging log::trace!("CoreEvent emitted: {:?}", event); } async fn on_ready(&self) { log::info!("QBZ Core is ready"); - // Could emit a ready event to frontend if needed + if let Err(e) = self.app_handle.emit("core:ready", ()) { + log::error!("Failed to emit core:ready: {}", e); + } } async fn on_shutdown(&self) { log::info!("QBZ Core is shutting down"); + if let Err(e) = self.app_handle.emit("core:shutdown", ()) { + log::error!("Failed to emit core:shutdown: {}", e); + } } } diff --git a/src/lib/components/TrackReplacementModal.svelte b/src/lib/components/TrackReplacementModal.svelte index c1954c7f2..496e6f430 100644 --- a/src/lib/components/TrackReplacementModal.svelte +++ b/src/lib/components/TrackReplacementModal.svelte @@ -70,9 +70,10 @@ loading = true; searched = true; try { - const response = await invoke('search_tracks', { + const response = await invoke('v2_search_tracks', { query: searchQuery.trim(), - limit: 20 + limit: 20, + offset: 0 }); // Filter out non-streamable tracks results = response.items.filter(trk => trk.streamable !== false); diff --git a/src/lib/components/views/ArtistDetailView.svelte b/src/lib/components/views/ArtistDetailView.svelte index 157f8777e..9234e5dec 100644 --- a/src/lib/components/views/ArtistDetailView.svelte +++ b/src/lib/components/views/ArtistDetailView.svelte @@ -633,7 +633,7 @@ tracksLoading = true; try { // Search for tracks by artist name - const results = await invoke('search_tracks', { + const results = await invoke('v2_search_tracks', { query: artist.name, limit: 30, offset: 0 @@ -726,7 +726,7 @@ async function navigateToRelatedArtist(name: string) { try { // Search for the artist on Qobuz - const results = await invoke<{ artists?: { items: QobuzArtist[] } }>('search_artists', { + const results = await invoke<{ artists?: { items: QobuzArtist[] } }>('v2_search_artists', { query: name, limit: 5 }); diff --git a/src/lib/components/views/HomeView.svelte b/src/lib/components/views/HomeView.svelte index 89546109e..57794d808 100644 --- a/src/lib/components/views/HomeView.svelte +++ b/src/lib/components/views/HomeView.svelte @@ -439,7 +439,7 @@ for (let i = 0; i < uncachedIds.length; i += BATCH_SIZE) { const batch = uncachedIds.slice(i, i + BATCH_SIZE); const results = await Promise.allSettled( - batch.map(albumId => invoke('get_album', { albumId })) + batch.map(albumId => invoke('v2_get_album', { albumId })) ); for (const result of results) { @@ -474,7 +474,7 @@ for (let i = 0; i < uncachedIds.length; i += BATCH_SIZE) { const batch = uncachedIds.slice(i, i + BATCH_SIZE); const results = await Promise.allSettled( - batch.map(trackId => invoke('get_track', { trackId })) + batch.map(trackId => invoke('v2_get_track', { trackId })) ); for (const result of results) { diff --git a/src/lib/components/views/LocalLibraryView.svelte b/src/lib/components/views/LocalLibraryView.svelte index f69e01c7f..716a7c92d 100644 --- a/src/lib/components/views/LocalLibraryView.svelte +++ b/src/lib/components/views/LocalLibraryView.svelte @@ -2699,7 +2699,7 @@ const query = name.trim(); if (!query) return null; - const results = await invoke>('search_artists', { + const results = await invoke>('v2_search_artists', { query, limit: 5, offset: 0 @@ -2845,7 +2845,7 @@ try { // Only use Qobuz - Discogs causes too many issues with rate limiting - const results = await invoke>('search_artists', { + const results = await invoke>('v2_search_artists', { query: name.trim(), limit: 3, offset: 0 diff --git a/src/lib/components/views/SearchView.svelte b/src/lib/components/views/SearchView.svelte index ac35f8032..9681dff09 100644 --- a/src/lib/components/views/SearchView.svelte +++ b/src/lib/components/views/SearchView.svelte @@ -503,7 +503,7 @@ loadAllAlbumDownloadStatuses(allResults.albums.items); // fire-and-forget } } else if (activeTab === 'albums') { - const results = await invoke>('search_albums', { + const results = await invoke>('v2_search_albums', { query: searchQuery, limit: PAGE_SIZE, offset: 0, @@ -517,7 +517,7 @@ loadAllAlbumDownloadStatuses(albumResults.items); // fire-and-forget } } else if (activeTab === 'tracks') { - const results = await invoke>('search_tracks', { + const results = await invoke>('v2_search_tracks', { query: searchQuery, limit: PAGE_SIZE, offset: 0, @@ -527,7 +527,7 @@ trackResults = results; console.log('Track results:', trackResults); } else if (activeTab === 'artists') { - const results = await invoke>('search_artists', { + const results = await invoke>('v2_search_artists', { query: searchQuery, limit: PAGE_SIZE, offset: 0, @@ -569,7 +569,7 @@ try { if (activeTab === 'albums' && albumResults && hasMoreAlbums) { const newOffset = albumResults.offset + albumResults.items.length; - const moreResults = await invoke>('search_albums', { + const moreResults = await invoke>('v2_search_albums', { query: query.trim(), limit: PAGE_SIZE, offset: newOffset, @@ -583,7 +583,7 @@ loadAllAlbumDownloadStatuses(moreResults.items); // fire-and-forget } else if (activeTab === 'tracks' && trackResults && hasMoreTracks) { const newOffset = trackResults.offset + trackResults.items.length; - const moreResults = await invoke>('search_tracks', { + const moreResults = await invoke>('v2_search_tracks', { query: query.trim(), limit: PAGE_SIZE, offset: newOffset, @@ -596,7 +596,7 @@ }; } else if (activeTab === 'artists' && artistResults && hasMoreArtists) { const newOffset = artistResults.offset + artistResults.items.length; - const moreResults = await invoke>('search_artists', { + const moreResults = await invoke>('v2_search_artists', { query: query.trim(), limit: PAGE_SIZE, offset: newOffset, diff --git a/src/routes/+page.svelte b/src/routes/+page.svelte index 78953e0f1..3043bbe47 100644 --- a/src/routes/+page.svelte +++ b/src/routes/+page.svelte @@ -630,7 +630,7 @@ async function handleAlbumClick(albumId: string) { try { showToast($t('toast.loadingAlbum'), 'info'); - const album = await invoke('get_album', { albumId }); + const album = await invoke('v2_get_album', { albumId }); const converted = convertQobuzAlbum(album); @@ -934,7 +934,7 @@ async function fetchAlbumDetail(albumId: string): Promise { try { - const album = await invoke('get_album', { albumId }); + const album = await invoke('v2_get_album', { albumId }); return convertQobuzAlbum(album); } catch (err) { console.error('Failed to load album:', err); @@ -2041,7 +2041,7 @@ async function reDownloadAlbumById(albumId: string) { try { - const album = await invoke('get_album', { albumId }); + const album = await invoke('v2_get_album', { albumId }); if (!album || !album.tracks || album.tracks.data.length === 0) { showToast($t('toast.failedLoadAlbumRefresh'), 'error'); return; @@ -2383,7 +2383,7 @@ // Fetch full track info from Qobuz to get albumId, artistId, and quality try { - const fullTrack = await invoke('get_track', { trackId: track.id }); + const fullTrack = await invoke('v2_get_track', { trackId: track.id }); const artwork = fullTrack.album?.image?.large || fullTrack.album?.image?.thumbnail || track.artwork_url || ''; const quality = fullTrack.hires_streamable ? `${fullTrack.maximum_bit_depth ?? 24}/${fullTrack.maximum_sampling_rate ?? 96}`