From fa784df62e6da2478601f689b2c77260829facb2 Mon Sep 17 00:00:00 2001 From: vicrodh <103399283+vicrodh@users.noreply.github.com> Date: Mon, 9 Feb 2026 21:56:15 -0600 Subject: [PATCH] feat(playlist): progressive loading via track_ids + track/getList Replace monolithic get_playlist call with two-phase approach: - Phase 1: playlist/get?extra=track_ids returns metadata + all track IDs in a single lightweight call (~50KB vs ~5MB) - Phase 2: track/getList fetches full details in batches of 50, 4 concurrent groups, with tracks rendering progressively Backend changes: - Add TRACK_GET_LIST endpoint and PlaylistWithTrackIds model - Add get_playlist_track_ids and get_tracks_batch API client methods - Add corresponding Tauri commands - Update remove_tracks_from_playlist to accept either playlist_track_ids or regular track_ids (resolves internally) Frontend changes: - Rewrite loadPlaylist() for two-phase progressive loading - Show playlist header + placeholder tracks after Phase 1 (~0.5s) - Fill in full track details as batches arrive - Add placeholder track row CSS (gray bars, no shimmer) - Use Qobuz pre-made collage images from playlist metadata - Update track removal to handle missing playlist_track_id --- src-tauri/src/api/client.rs | 48 +++ src-tauri/src/api/endpoints.rs | 1 + src-tauri/src/api/models.rs | 27 ++ src-tauri/src/commands/playlist.rs | 102 +++++- src-tauri/src/lib.rs | 2 + .../views/PlaylistDetailView.svelte | 332 ++++++++++++++---- 6 files changed, 429 insertions(+), 83 deletions(-) diff --git a/src-tauri/src/api/client.rs b/src-tauri/src/api/client.rs index 213c808a1..b0f3c700b 100644 --- a/src-tauri/src/api/client.rs +++ b/src-tauri/src/api/client.rs @@ -746,6 +746,54 @@ impl QobuzClient { Ok(serde_json::from_value(response)?) } + /// Get playlist metadata + ordered track IDs (lightweight, no full Track objects). + /// Uses `playlist/get?extra=track_ids` which returns the playlist with a flat + /// array of track IDs instead of nested Track objects. + pub async fn get_playlist_track_ids(&self, playlist_id: u64) -> Result { + let url = endpoints::build_url(paths::PLAYLIST_GET); + let http_response = self + .http + .get(&url) + .headers(self.api_headers().await?) + .query(&[ + ("playlist_id", playlist_id.to_string()), + ("extra", "track_ids".to_string()), + ]) + .send() + .await?; + log::debug!("[API] get_playlist_track_ids({}) status={}", playlist_id, http_response.status()); + let response: Value = http_response.json().await?; + let result: PlaylistWithTrackIds = serde_json::from_value(response)?; + log::info!( + "[API] get_playlist_track_ids({}) — {} track IDs", + playlist_id, + result.track_ids.len() + ); + Ok(result) + } + + /// Fetch full Track objects for a batch of track IDs (max 50 per call). + /// Uses the `track/getList` endpoint. + pub async fn get_tracks_batch(&self, track_ids: &[u64]) -> Result> { + let url = endpoints::build_url(paths::TRACK_GET_LIST); + let ids_csv = track_ids.iter().map(|id| id.to_string()).collect::>().join(","); + let http_response = self + .http + .get(&url) + .headers(self.api_headers().await?) + .query(&[("track_ids", ids_csv.as_str())]) + .send() + .await?; + log::debug!("[API] get_tracks_batch({} IDs) status={}", track_ids.len(), http_response.status()); + let value: Value = http_response.json().await?; + let items = value + .get("tracks") + .and_then(|t| t.get("items")) + .ok_or_else(|| ApiError::ApiResponse("Missing tracks.items in getList response".to_string()))?; + let tracks: Vec = serde_json::from_value(items.clone())?; + Ok(tracks) + } + /// Get playlist by ID (paginates automatically to fetch all tracks) /// /// After the first page, remaining pages are fetched concurrently diff --git a/src-tauri/src/api/endpoints.rs b/src-tauri/src/api/endpoints.rs index 3d231f7ce..2e43ac120 100644 --- a/src-tauri/src/api/endpoints.rs +++ b/src-tauri/src/api/endpoints.rs @@ -9,6 +9,7 @@ pub mod paths { // Track pub const TRACK_GET: &str = "/track/get"; + pub const TRACK_GET_LIST: &str = "/track/getList"; pub const TRACK_SEARCH: &str = "/track/search"; pub const TRACK_GET_FILE_URL: &str = "/track/getFileUrl"; diff --git a/src-tauri/src/api/models.rs b/src-tauri/src/api/models.rs index f85fb0878..493f3e2cd 100644 --- a/src-tauri/src/api/models.rs +++ b/src-tauri/src/api/models.rs @@ -254,6 +254,33 @@ pub struct PlaylistGenre { pub slug: Option, } +/// Lightweight playlist response with track IDs only (no full Track objects). +/// Returned by `playlist/get?extra=track_ids`. +#[derive(Debug, Clone, Serialize, Deserialize)] +pub struct PlaylistWithTrackIds { + #[serde(default)] + pub id: u64, + #[serde(default)] + pub name: String, + pub description: Option, + #[serde(default)] + pub owner: PlaylistOwner, + pub images: Option>, + #[serde(default)] + pub tracks_count: u32, + #[serde(default)] + pub duration: u32, + #[serde(default)] + pub is_public: bool, + #[serde(default)] + pub track_ids: Vec, + pub genres: Option>, + pub images150: Option>, + pub images300: Option>, + pub slug: Option, + pub users_count: Option, +} + /// Result of checking for duplicate tracks in a playlist #[derive(Debug, Clone, Serialize, Deserialize)] pub struct PlaylistDuplicateResult { diff --git a/src-tauri/src/commands/playlist.rs b/src-tauri/src/commands/playlist.rs index fc46225b1..a2070eeea 100644 --- a/src-tauri/src/commands/playlist.rs +++ b/src-tauri/src/commands/playlist.rs @@ -3,7 +3,7 @@ use serde::Serialize; use tauri::State; -use crate::api::models::{Playlist, PlaylistDuplicateResult, SearchResultsPage, Track}; +use crate::api::models::{Playlist, PlaylistDuplicateResult, PlaylistWithTrackIds, SearchResultsPage, Track}; use crate::api::performers::{parse_performers, Performer}; use crate::AppState; @@ -57,6 +57,47 @@ pub async fn get_playlist( result } +/// Get playlist metadata + ordered track IDs (lightweight, no full track data) +#[tauri::command] +pub async fn get_playlist_track_ids( + playlist_id: u64, + state: State<'_, AppState>, +) -> Result { + let cmd_start = std::time::Instant::now(); + log::debug!("Command: get_playlist_track_ids {}", playlist_id); + + let client = state.client.lock().await; + let result = client + .get_playlist_track_ids(playlist_id) + .await + .map_err(|e| format!("Failed to get playlist track IDs: {}", e)); + + let elapsed = cmd_start.elapsed(); + log::info!( + "Command: get_playlist_track_ids {} — {:.1}ms, {} IDs", + playlist_id, + elapsed.as_secs_f64() * 1000.0, + result.as_ref().map(|p| p.track_ids.len()).unwrap_or(0) + ); + + result +} + +/// Fetch full track details for a batch of track IDs (max 50) +#[tauri::command] +pub async fn get_tracks_batch( + track_ids: Vec, + state: State<'_, AppState>, +) -> Result, String> { + log::debug!("Command: get_tracks_batch ({} IDs)", track_ids.len()); + + let client = state.client.lock().await; + client + .get_tracks_batch(&track_ids) + .await + .map_err(|e| format!("Failed to get tracks batch: {}", e)) +} + /// Check for duplicate tracks in a playlist #[tauri::command] pub async fn check_playlist_duplicates( @@ -166,20 +207,65 @@ pub async fn add_tracks_to_playlist( .map_err(|e| format!("Failed to add tracks to playlist: {}", e)) } -/// Remove tracks from a playlist +/// Remove tracks from a playlist. +/// Accepts either playlist_track_ids (direct Qobuz IDs) or regular track_ids. +/// When track_ids are provided (and playlist_track_ids is empty), resolves them +/// by fetching the full playlist to find the corresponding playlist_track_ids. #[tauri::command] pub async fn remove_tracks_from_playlist( playlist_id: u64, - playlist_track_ids: Vec, + #[allow(unused_variables)] + playlist_track_ids: Option>, + track_ids: Option>, state: State<'_, AppState>, ) -> Result<(), String> { - log::info!("Command: remove_tracks_from_playlist {} ({} tracks)", playlist_id, playlist_track_ids.len()); + let ptids = playlist_track_ids.unwrap_or_default(); + let tids = track_ids.unwrap_or_default(); + log::info!( + "Command: remove_tracks_from_playlist {} (playlist_track_ids={}, track_ids={})", + playlist_id, ptids.len(), tids.len() + ); let client = state.client.lock().await; - client - .remove_tracks_from_playlist(playlist_id, &playlist_track_ids) - .await - .map_err(|e| format!("Failed to remove tracks from playlist: {}", e)) + + // If we have direct playlist_track_ids, use them + if !ptids.is_empty() { + return client + .remove_tracks_from_playlist(playlist_id, &ptids) + .await + .map_err(|e| format!("Failed to remove tracks from playlist: {}", e)); + } + + // Otherwise resolve track_ids → playlist_track_ids via full playlist fetch + if !tids.is_empty() { + let playlist = client + .get_playlist(playlist_id) + .await + .map_err(|e| format!("Failed to fetch playlist for track ID resolution: {}", e))?; + + let track_id_set: std::collections::HashSet = tids.into_iter().collect(); + let resolved_ptids: Vec = playlist + .tracks + .map(|tc| { + tc.items + .into_iter() + .filter(|track| track_id_set.contains(&track.id)) + .filter_map(|track| track.playlist_track_id) + .collect() + }) + .unwrap_or_default(); + + if resolved_ptids.is_empty() { + return Err("Could not resolve any track IDs to playlist track IDs".to_string()); + } + + return client + .remove_tracks_from_playlist(playlist_id, &resolved_ptids) + .await + .map_err(|e| format!("Failed to remove tracks from playlist: {}", e)); + } + + Err("Either playlist_track_ids or track_ids must be provided".to_string()) } /// Update playlist metadata diff --git a/src-tauri/src/lib.rs b/src-tauri/src/lib.rs index 56af2bf3c..2983eb336 100644 --- a/src-tauri/src/lib.rs +++ b/src-tauri/src/lib.rs @@ -565,6 +565,8 @@ pub fn run() { // Playlist commands commands::get_user_playlists, commands::get_playlist, + commands::get_playlist_track_ids, + commands::get_tracks_batch, commands::check_playlist_duplicates, commands::search_playlists, commands::create_playlist, diff --git a/src/lib/components/views/PlaylistDetailView.svelte b/src/lib/components/views/PlaylistDetailView.svelte index a4a145a21..c5837281e 100644 --- a/src/lib/components/views/PlaylistDetailView.svelte +++ b/src/lib/components/views/PlaylistDetailView.svelte @@ -57,6 +57,20 @@ tracks?: { items: PlaylistTrack[]; total: number }; } + interface PlaylistWithTrackIds { + id: number; + name: string; + description?: string; + owner: { id: number; name: string }; + images?: string[]; + tracks_count: number; + duration: number; + is_public: boolean; + track_ids: number[]; + images150?: string[]; + images300?: string[]; + } + interface DisplayTrack { id: number; number: number; @@ -234,6 +248,7 @@ let loading = $state(true); let spinnerFading = $state(false); let error = $state(null); + let tracksLoadedCount = $state(0); // Progressive loading: how many tracks have full data let scrollContainer: HTMLDivElement | null = $state(null); // Virtual scrolling for track list @@ -523,11 +538,43 @@ } } + /** Convert a raw PlaylistTrack from the API into a DisplayTrack */ + function mapPlaylistTrack(track: PlaylistTrack, idx: number): DisplayTrack { + return { + id: track.id, + number: idx + 1, + title: track.title, + artist: track.performer?.name, + album: track.album?.title, + albumArt: track.album?.image?.large || track.album?.image?.thumbnail || track.album?.image?.small, + albumId: track.album?.id, + artistId: track.performer?.id, + duration: formatDuration(track.duration), + durationSeconds: track.duration, + hires: track.hires, + bitDepth: track.maximum_bit_depth, + samplingRate: track.maximum_sampling_rate, + isrc: track.isrc, + playlistTrackId: track.playlist_track_id, + label: track.album?.label?.name, + addedIndex: idx, + streamable: track.streamable, + }; + } + + /** + * Progressive playlist loading: + * Phase 1: get_playlist_track_ids → metadata + ordered track ID array (instant, ~50KB) + * Phase 2: get_tracks_batch × N → full track details in batches of 50 + * + * For pending playlists (negative ID), the old single-call path is kept. + */ async function loadPlaylist() { const _t0 = performance.now(); console.log(`[Perf] loadPlaylist() START`); loading = true; error = null; + tracksLoadedCount = 0; try { // Check if this is a pending playlist (negative ID) if (playlistId < 0) { @@ -560,24 +607,8 @@ trackIds: pending.trackIds }); - tracks = qobuzTracks.map((t, idx) => ({ - id: t.id, - number: idx + 1, - title: t.title, - artist: t.performer?.name, - album: t.album?.title, - albumArt: t.album?.image?.large || t.album?.image?.thumbnail || t.album?.image?.small, - albumId: t.album?.id, - artistId: t.performer?.id, - duration: formatDuration(t.duration), - durationSeconds: t.duration, - hires: t.hires, - bitDepth: t.maximum_bit_depth, - samplingRate: t.maximum_sampling_rate, - isrc: t.isrc, - label: t.album?.label?.name, - addedIndex: idx, - })); + tracks = qobuzTracks.map((track, idx) => mapPlaylistTrack(track, idx)); + tracksLoadedCount = tracks.length; // Update duration playlist.duration = qobuzTracks.reduce((sum, track) => sum + track.duration, 0); @@ -589,35 +620,88 @@ tracks = []; } } else { - // Regular playlist - use existing command - console.log(`[Perf] invoke get_playlist START (+${(performance.now() - _t0).toFixed(1)}ms)`); - const result = await invoke('get_playlist', { playlistId }); - console.log(`[Perf] invoke get_playlist DONE (+${(performance.now() - _t0).toFixed(1)}ms) — ${result.tracks?.items?.length ?? 0} items from API`); - playlist = result; + // === Progressive loading for regular playlists === - if (result.tracks?.items) { - const mapStart = performance.now(); - tracks = result.tracks.items.map((t, idx) => ({ - id: t.id, - number: idx + 1, - title: t.title, - artist: t.performer?.name, - album: t.album?.title, - albumArt: t.album?.image?.large || t.album?.image?.thumbnail || t.album?.image?.small, - albumId: t.album?.id, - artistId: t.performer?.id, - duration: formatDuration(t.duration), - durationSeconds: t.duration, - hires: t.hires, - bitDepth: t.maximum_bit_depth, - samplingRate: t.maximum_sampling_rate, - isrc: t.isrc, - playlistTrackId: t.playlist_track_id, - label: t.album?.label?.name, - addedIndex: idx, - streamable: t.streamable, - })); - console.log(`[Perf] tracks.map() ${tracks.length} items: ${(performance.now() - mapStart).toFixed(1)}ms`); + // Phase 1: Get metadata + track IDs (lightweight, ~50KB even for 2000 tracks) + console.log(`[Perf] invoke get_playlist_track_ids START (+${(performance.now() - _t0).toFixed(1)}ms)`); + const meta = await invoke('get_playlist_track_ids', { playlistId }); + console.log(`[Perf] invoke get_playlist_track_ids DONE (+${(performance.now() - _t0).toFixed(1)}ms) — ${meta.track_ids.length} IDs`); + + // Set playlist metadata immediately (header renders instantly) + playlist = { + id: meta.id, + name: meta.name, + description: meta.description || undefined, + owner: meta.owner, + images: meta.images300 ?? meta.images150 ?? meta.images, + tracks_count: meta.tracks_count, + duration: meta.duration, + is_public: meta.is_public, + }; + + const allTrackIds = meta.track_ids; + + // Create placeholder DisplayTrack entries (minimal objects, low proxy cost) + tracks = allTrackIds.map((trackId, idx) => ({ + id: trackId, + number: idx + 1, + title: '', // Empty title = placeholder + duration: '', + durationSeconds: 0, + addedIndex: idx, + })); + + // Show header + placeholders immediately (hide spinner before Phase 2) + spinnerFading = true; + setTimeout(() => { + loading = false; + spinnerFading = false; + requestAnimationFrame(() => { + if (scrollContainer) { + trackListViewHeight = scrollContainer.clientHeight; + } + trackListScrollTop = 0; + }); + }, 100); + + // Phase 2: Fetch full track data in batches of 50, 4 concurrent + const BATCH_SIZE = 50; + const CONCURRENCY = 4; + const batches: number[][] = []; + for (let i = 0; i < allTrackIds.length; i += BATCH_SIZE) { + batches.push(allTrackIds.slice(i, i + BATCH_SIZE)); + } + + console.log(`[Perf] progressive load: ${batches.length} batches of ${BATCH_SIZE} (+${(performance.now() - _t0).toFixed(1)}ms)`); + + // Process batches in groups of CONCURRENCY + for (let g = 0; g < batches.length; g += CONCURRENCY) { + const group = batches.slice(g, g + CONCURRENCY); + const groupStartIdx = g * BATCH_SIZE; + + const results = await Promise.all( + group.map(batch => + invoke('get_tracks_batch', { trackIds: batch }) + .catch(err => { + console.warn('[Perf] batch fetch failed:', err); + return [] as PlaylistTrack[]; + }) + ) + ); + + // Merge results into tracks array (in-place update by index) + let offset = groupStartIdx; + for (const batchTracks of results) { + for (const apiTrack of batchTracks) { + if (offset < tracks.length) { + tracks[offset] = mapPlaylistTrack(apiTrack, offset); + } + offset++; + } + } + + tracksLoadedCount = Math.min(offset, allTrackIds.length); + console.log(`[Perf] loaded ${tracksLoadedCount}/${allTrackIds.length} tracks (+${(performance.now() - _t0).toFixed(1)}ms)`); } } } catch (err) { @@ -626,24 +710,28 @@ } finally { console.log(`[Perf] loadPlaylist() try/catch done (+${(performance.now() - _t0).toFixed(1)}ms)`); if (playlist) { - console.log(`[Perf] "${playlist.name}" — ${tracks.length} tracks`); + console.log(`[Perf] "${playlist.name}" — ${tracks.length} tracks (${tracksLoadedCount} loaded)`); + } + // For progressive loading (positive ID), loading was already set to false + // after Phase 1. Only handle the spinner for pending playlists and errors. + if (loading) { + spinnerFading = true; + console.log(`[Perf] spinnerFading=true, scheduling loading=false in 200ms (+${(performance.now() - _t0).toFixed(1)}ms)`); + const finalT0 = _t0; + setTimeout(() => { + console.log(`[Perf] loading=false NOW (+${(performance.now() - finalT0).toFixed(1)}ms)`); + loading = false; + spinnerFading = false; + // After content mounts, ensure virtual scroll has correct dimensions + requestAnimationFrame(() => { + console.log(`[Perf] rAF after mount (+${(performance.now() - finalT0).toFixed(1)}ms) — RENDER COMPLETE`); + if (scrollContainer) { + trackListViewHeight = scrollContainer.clientHeight; + } + trackListScrollTop = 0; + }); + }, 200); } - spinnerFading = true; - console.log(`[Perf] spinnerFading=true, scheduling loading=false in 200ms (+${(performance.now() - _t0).toFixed(1)}ms)`); - const finalT0 = _t0; - setTimeout(() => { - console.log(`[Perf] loading=false NOW (+${(performance.now() - finalT0).toFixed(1)}ms)`); - loading = false; - spinnerFading = false; - // After content mounts, ensure virtual scroll has correct dimensions - requestAnimationFrame(() => { - console.log(`[Perf] rAF after mount (+${(performance.now() - finalT0).toFixed(1)}ms) — RENDER COMPLETE`); - if (scrollContainer) { - trackListViewHeight = scrollContainer.clientHeight; - } - trackListScrollTop = 0; - }); - }, 200); } } @@ -1376,13 +1464,21 @@ await loadLocalTracks(); notifyParentOfCounts(); } else if (track.playlistTrackId) { - // Remove Qobuz track using playlist_track_id + // Remove Qobuz track using playlist_track_id (available from full playlist load) await invoke('remove_tracks_from_playlist', { playlistId, playlistTrackIds: [track.playlistTrackId] }); await loadPlaylist(); notifyParentOfCounts(); + } else { + // Progressive loading path: no playlist_track_id available, resolve by track ID + await invoke('remove_tracks_from_playlist', { + playlistId, + trackIds: [track.id] + }); + await loadPlaylist(); + notifyParentOfCounts(); } // Notify parent to refresh sidebar counts onPlaylistUpdated?.(); @@ -1414,8 +1510,8 @@ } async function handleTrackReplacement(newTrack: ReplacementTrack) { - if (!trackToReplace || !trackToReplace.playlistTrackId) { - console.error('No track to replace or missing playlist_track_id'); + if (!trackToReplace) { + console.error('No track to replace'); return; } @@ -1423,11 +1519,18 @@ // Get the current position of the track being replaced const currentIndex = displayTracks.findIndex(trk => trk.id === trackToReplace!.id); - // Remove the old track - await invoke('remove_tracks_from_playlist', { - playlistId, - playlistTrackIds: [trackToReplace.playlistTrackId] - }); + // Remove the old track (supports both playlist_track_id and track_id resolution) + if (trackToReplace.playlistTrackId) { + await invoke('remove_tracks_from_playlist', { + playlistId, + playlistTrackIds: [trackToReplace.playlistTrackId] + }); + } else { + await invoke('remove_tracks_from_playlist', { + playlistId, + trackIds: [trackToReplace.id] + }); + } // Add the new track await invoke('add_tracks_to_playlist', { @@ -1765,10 +1868,14 @@ {:else}
- trk.albumArt).filter((a): a is string => !!a)} - size={200} - /> + {#if playlist.images && playlist.images.length > 0} + {playlist.name} + {:else} + trk.albumArt).filter((a): a is string => !!a)} + size={200} + /> + {/if}
@@ -2824,4 +2947,63 @@ border-color: var(--alpha-20); } + /* Playlist API image (pre-made collage from Qobuz) */ + .playlist-api-image { + border-radius: 8px; + object-fit: cover; + display: block; + } + + /* Placeholder track rows (progressive loading) */ + .placeholder-track { + display: flex; + align-items: center; + gap: 12px; + padding: 0 16px; + position: absolute; + left: 0; + right: 0; + } + + .placeholder-number { + width: 32px; + text-align: right; + font-size: 13px; + color: var(--text-tertiary, rgba(255, 255, 255, 0.3)); + flex-shrink: 0; + } + + .placeholder-bars { + display: flex; + flex-direction: column; + gap: 6px; + flex: 1; + min-width: 0; + } + + .placeholder-bar { + height: 10px; + border-radius: 4px; + background: var(--alpha-08, rgba(255, 255, 255, 0.08)); + } + + .placeholder-bar.title-bar { + width: 45%; + } + + .placeholder-bar.artist-bar { + width: 30%; + height: 8px; + } + + .placeholder-bar.album-bar { + width: 120px; + flex-shrink: 0; + } + + .placeholder-bar.duration-bar { + width: 40px; + flex-shrink: 0; + } +