feat(playlist-import): concurrent matching with progress reporting

Replace sequential track matching with buffer_unordered(8) for 8
concurrent Qobuz API calls, reducing import time ~8x. Add real-time
progress events (import:progress, import:phase) emitted from Rust
backend and consumed by frontend via Tauri event listeners.

Frontend shows progress bar, matching status text, and current track
name during import. Individual search failures are now logged and
skipped instead of aborting the entire import.
This commit is contained in:
vicrodh committed 2026-02-09 17:53:04 -06:00
1 parent a46a422a04
commit 9fdd1dd0df
10 files changed
+278 -37

No files matched your search

@@ -20,6 +20,7 @@ pub async fn playlist_import_preview(
#[tauri::command] #[tauri::command]
pub async fn playlist_import_execute( pub async fn playlist_import_execute(
app: tauri::AppHandle,
url: String, url: String,
name_override: Option<String>, name_override: Option<String>,
is_public: Option<bool>, is_public: Option<bool>,
@@ -33,6 +34,7 @@ pub async fn playlist_import_execute(
&client, &client,
name_override.as_deref(), name_override.as_deref(),
is_public.unwrap_or(false), is_public.unwrap_or(false),
&app,
) )
.await .await
.map_err(|e| e.to_string()) .map_err(|e| e.to_string())
+29 -3
View File
@@ -1,9 +1,11 @@
//! Orchestrates playlist import //! Orchestrates playlist import
use tauri::{AppHandle, Emitter};
use crate::api::QobuzClient; use crate::api::QobuzClient;
use crate::playlist_import::errors::PlaylistImportError; use crate::playlist_import::errors::PlaylistImportError;
use crate::playlist_import::match_qobuz::match_tracks; use crate::playlist_import::match_qobuz::match_tracks;
use crate::playlist_import::models::{ImportPlaylist, ImportSummary}; use crate::playlist_import::models::{ImportPlaylist, ImportProgress, ImportSummary};
use crate::playlist_import::providers::{detect_provider, fetch_playlist}; use crate::playlist_import::providers::{detect_provider, fetch_playlist};
const ADD_CHUNK_SIZE: usize = 50; const ADD_CHUNK_SIZE: usize = 50;
@@ -20,9 +22,13 @@ pub async fn import_public_playlist(
client: &QobuzClient, client: &QobuzClient,
name_override: Option<&str>, name_override: Option<&str>,
is_public: bool, is_public: bool,
app: &AppHandle,
) -> Result<ImportSummary, PlaylistImportError> { ) -> Result<ImportSummary, PlaylistImportError> {
let playlist = preview_public_playlist(url).await?; let playlist = preview_public_playlist(url).await?;
let matches = match_tracks(client, &playlist.tracks).await?;
// Phase: matching
let _ = app.emit("import:phase", serde_json::json!({ "phase": "matching" }));
let matches = match_tracks(client, &playlist.tracks, app).await?;
let mut matched_track_ids = Vec::new(); let mut matched_track_ids = Vec::new();
let mut seen = std::collections::HashSet::new(); let mut seen = std::collections::HashSet::new();
@@ -41,6 +47,9 @@ pub async fn import_public_playlist(
let mut qobuz_playlist_id = None; let mut qobuz_playlist_id = None;
if !matched_track_ids.is_empty() { if !matched_track_ids.is_empty() {
// Phase: creating
let _ = app.emit("import:phase", serde_json::json!({ "phase": "creating" }));
let name = name_override.unwrap_or(&playlist.name); let name = name_override.unwrap_or(&playlist.name);
let description = playlist let description = playlist
.description .description
@@ -54,11 +63,28 @@ pub async fn import_public_playlist(
qobuz_playlist_id = Some(created.id); qobuz_playlist_id = Some(created.id);
for chunk in matched_track_ids.chunks(ADD_CHUNK_SIZE) { // Phase: adding
let _ = app.emit("import:phase", serde_json::json!({ "phase": "adding" }));
let chunks: Vec<&[u64]> = matched_track_ids.chunks(ADD_CHUNK_SIZE).collect();
let total_chunks = chunks.len() as u32;
for (i, chunk) in chunks.iter().enumerate() {
client client
.add_tracks_to_playlist(created.id, chunk) .add_tracks_to_playlist(created.id, chunk)
.await .await
.map_err(|e| PlaylistImportError::Qobuz(e.to_string()))?; .map_err(|e| PlaylistImportError::Qobuz(e.to_string()))?;
let _ = app.emit(
"import:progress",
ImportProgress {
phase: "adding".to_string(),
current: (i as u32) + 1,
total: total_chunks,
matched_so_far: matched_count,
current_track: None,
},
);
} }
} }
+106 -28
View File
@@ -1,52 +1,130 @@
//! Match imported tracks to Qobuz catalog //! Match imported tracks to Qobuz catalog
use std::sync::atomic::{AtomicU32, Ordering};
use std::sync::Arc;
use futures_util::stream::{self, StreamExt};
use tauri::{AppHandle, Emitter};
use crate::api::models::Track; use crate::api::models::Track;
use crate::api::QobuzClient; use crate::api::QobuzClient;
use crate::playlist_import::errors::PlaylistImportError; use crate::playlist_import::errors::PlaylistImportError;
use crate::playlist_import::models::{ImportTrack, TrackMatch}; use crate::playlist_import::models::{ImportProgress, ImportTrack, TrackMatch};
const SEARCH_LIMIT: u32 = 20; const SEARCH_LIMIT: u32 = 20;
const TITLE_WEIGHT: f32 = 0.6; const TITLE_WEIGHT: f32 = 0.6;
const ARTIST_WEIGHT: f32 = 0.3; const ARTIST_WEIGHT: f32 = 0.3;
const ALBUM_WEIGHT: f32 = 0.1; const ALBUM_WEIGHT: f32 = 0.1;
const MIN_SCORE: f32 = 0.65; const MIN_SCORE: f32 = 0.65;
const CONCURRENCY: usize = 8;
pub async fn match_tracks( pub async fn match_tracks(
client: &QobuzClient, client: &QobuzClient,
tracks: &[ImportTrack], tracks: &[ImportTrack],
app: &AppHandle,
) -> Result<Vec<TrackMatch>, PlaylistImportError> { ) -> Result<Vec<TrackMatch>, PlaylistImportError> {
let mut results = Vec::new(); let total = tracks.len() as u32;
let matched_counter = Arc::new(AtomicU32::new(0));
let completed_counter = Arc::new(AtomicU32::new(0));
for track in tracks { // Pre-allocate results vector with None slots
let query = format!("{} {}", track.artist, track.title); let results: Arc<tokio::sync::Mutex<Vec<Option<TrackMatch>>>> =
let search = client Arc::new(tokio::sync::Mutex::new(vec![None; tracks.len()]));
.search_tracks(&query, SEARCH_LIMIT, 0, None)
.await
.map_err(|e| PlaylistImportError::Qobuz(e.to_string()))?;
let (best, score) = select_best_match(track, &search.items); let owned_tracks: Vec<(usize, ImportTrack)> = tracks.iter().enumerate().map(|(i, tr)| (i, tr.clone())).collect();
let match_entry = match best { stream::iter(owned_tracks)
Some(candidate) if score >= MIN_SCORE => TrackMatch { .map(|(idx, track)| {
source: track.clone(), let client = client.clone();
qobuz_track_id: Some(candidate.id), let app = app.clone();
qobuz_title: Some(candidate.title.clone()), let matched_counter = Arc::clone(&matched_counter);
qobuz_artist: candidate.performer.as_ref().map(|a| a.name.clone()), let completed_counter = Arc::clone(&completed_counter);
score, let results = Arc::clone(&results);
},
_ => TrackMatch {
source: track.clone(),
qobuz_track_id: None,
qobuz_title: None,
qobuz_artist: None,
score,
},
};
results.push(match_entry); async move {
} let query = format!("{} {}", track.artist, track.title);
let search_result = client
.search_tracks(&query, SEARCH_LIMIT, 0, None)
.await;
Ok(results) let match_entry = match search_result {
Ok(search) => {
let (best, score) = select_best_match(&track, &search.items);
match best {
Some(candidate) if score >= MIN_SCORE => {
matched_counter.fetch_add(1, Ordering::Relaxed);
TrackMatch {
source: track.clone(),
qobuz_track_id: Some(candidate.id),
qobuz_title: Some(candidate.title.clone()),
qobuz_artist: candidate
.performer
.as_ref()
.map(|a| a.name.clone()),
score,
}
}
_ => TrackMatch {
source: track.clone(),
qobuz_track_id: None,
qobuz_title: None,
qobuz_artist: None,
score,
},
}
}
Err(e) => {
log::warn!(
"Search failed for '{}' - '{}': {}",
track.artist,
track.title,
e
);
TrackMatch {
source: track.clone(),
qobuz_track_id: None,
qobuz_title: None,
qobuz_artist: None,
score: 0.0,
}
}
};
// Store result at correct index
{
let mut res = results.lock().await;
res[idx] = Some(match_entry);
}
let current = completed_counter.fetch_add(1, Ordering::Relaxed) + 1;
let matched = matched_counter.load(Ordering::Relaxed);
let current_track = Some(format!("{} - {}", track.artist, track.title));
let _ = app.emit(
"import:progress",
ImportProgress {
phase: "matching".to_string(),
current,
total,
matched_so_far: matched,
current_track,
},
);
}
})
.buffer_unordered(CONCURRENCY)
.collect::<Vec<()>>()
.await;
// Extract results in order
let locked = results.lock().await;
let ordered: Vec<TrackMatch> = locked
.iter()
.map(|slot| slot.clone().expect("All slots should be filled"))
.collect();
Ok(ordered)
} }
fn select_best_match<'a>(track: &ImportTrack, candidates: &'a [Track]) -> (Option<&'a Track>, f32) { fn select_best_match<'a>(track: &ImportTrack, candidates: &'a [Track]) -> (Option<&'a Track>, f32) {
+1 -1
View File
@@ -8,5 +8,5 @@ pub mod providers;
pub use errors::PlaylistImportError; pub use errors::PlaylistImportError;
pub use importer::{import_public_playlist, preview_public_playlist}; pub use importer::{import_public_playlist, preview_public_playlist};
pub use models::{ImportPlaylist, ImportProvider, ImportSummary, ImportTrack, TrackMatch}; pub use models::{ImportPlaylist, ImportProgress, ImportProvider, ImportSummary, ImportTrack, TrackMatch};
pub use providers::ProviderCredentials; pub use providers::ProviderCredentials;
+9
View File
@@ -60,3 +60,12 @@ pub struct ImportSummary {
pub qobuz_playlist_id: Option<u64>, pub qobuz_playlist_id: Option<u64>,
pub matches: Vec<TrackMatch>, pub matches: Vec<TrackMatch>,
} }
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ImportProgress {
pub phase: String,
pub current: u32,
pub total: u32,
pub matched_so_far: u32,
pub current_track: Option<String>,
}
+107 -1
View File
@@ -1,5 +1,6 @@
<script lang="ts"> <script lang="ts">
import { invoke } from '@tauri-apps/api/core'; import { invoke } from '@tauri-apps/api/core';
import { listen, type UnlistenFn } from '@tauri-apps/api/event';
import { X, CloudOff } from 'lucide-svelte'; import { X, CloudOff } from 'lucide-svelte';
import { showToast } from '$lib/stores/toastStore'; import { showToast } from '$lib/stores/toastStore';
import { t } from '$lib/i18n'; import { t } from '$lib/i18n';
@@ -57,6 +58,8 @@
let isOffline = $state(checkIsOffline()); let isOffline = $state(checkIsOffline());
let importCompleted = $state(false); let importCompleted = $state(false);
let lastImportedUrl = $state(''); let lastImportedUrl = $state('');
let importProgress = $state<{ phase: string; current: number; total: number; matched_so_far: number; current_track: string | null } | null>(null);
let importPhase = $state<string | null>(null);
// Preview + customization state // Preview + customization state
let preview = $state<ImportPlaylist | null>(null); let preview = $state<ImportPlaylist | null>(null);
@@ -106,6 +109,8 @@
logEntries = []; logEntries = [];
importCompleted = false; importCompleted = false;
lastImportedUrl = ''; lastImportedUrl = '';
importProgress = null;
importPhase = null;
preview = null; preview = null;
previewUrl = ''; previewUrl = '';
customName = ''; customName = '';
@@ -187,9 +192,57 @@
loading = true; loading = true;
error = null; error = null;
importProgress = null;
importPhase = null;
let unlistenProgress: UnlistenFn | null = null;
let unlistenPhase: UnlistenFn | null = null;
let lastLoggedPercent = -1;
try { try {
pushLog('Matching tracks in Qobuz\u2122...'); // Set up event listeners before invoking
unlistenProgress = await listen<{ phase: string; current: number; total: number; matched_so_far: number; current_track: string | null }>('import:progress', (event) => {
importProgress = event.payload;
if (event.payload.phase === 'matching' && event.payload.total > 0) {
const pct = Math.floor((event.payload.current / event.payload.total) * 100);
// Log at every 5% milestone
if (pct >= lastLoggedPercent + 5) {
lastLoggedPercent = pct;
pushLog(
$t('playlistImport.matchingTracks', {
values: {
current: event.payload.current.toLocaleString(),
total: event.payload.total.toLocaleString(),
matched: event.payload.matched_so_far.toLocaleString()
}
})
);
}
} else if (event.payload.phase === 'adding') {
pushLog(
$t('playlistImport.addingProgress', {
values: {
current: event.payload.current,
total: event.payload.total
}
})
);
}
});
unlistenPhase = await listen<{ phase: string }>('import:phase', (event) => {
importPhase = event.payload.phase;
if (event.payload.phase === 'matching') {
pushLog($t('playlistImport.matchingPhase'));
} else if (event.payload.phase === 'creating') {
pushLog($t('playlistImport.creatingPhase'), 'success');
} else if (event.payload.phase === 'adding') {
pushLog($t('playlistImport.addingPhase'));
}
});
const nameOverride = customName.trim() !== preview.name ? customName.trim() || null : null; const nameOverride = customName.trim() !== preview.name ? customName.trim() || null : null;
const result = await invoke<ImportSummary>('playlist_import_execute', { const result = await invoke<ImportSummary>('playlist_import_execute', {
url: previewUrl, url: previewUrl,
@@ -223,6 +276,8 @@
showToast($t('toast.playlistImportFailed'), 'error'); showToast($t('toast.playlistImportFailed'), 'error');
} finally { } finally {
loading = false; loading = false;
unlistenProgress?.();
unlistenPhase?.();
} }
} }
@@ -352,6 +407,26 @@
<span class="spinner" aria-hidden="true"></span> <span class="spinner" aria-hidden="true"></span>
{/if} {/if}
</div> </div>
{#if importProgress && importProgress.total > 0 && loading}
<div class="progress-bar-container">
<div
class="progress-bar-fill"
style="width: {Math.min(100, (importProgress.current / importProgress.total) * 100)}%"
></div>
</div>
<div class="progress-status">
{$t('playlistImport.matchingTracks', {
values: {
current: importProgress.current.toLocaleString(),
total: importProgress.total.toLocaleString(),
matched: importProgress.matched_so_far.toLocaleString()
}
})}
</div>
{#if importProgress.current_track}
<div class="progress-current-track">{importProgress.current_track}</div>
{/if}
{/if}
<ul class="progress-log"> <ul class="progress-log">
{#each logEntries as entry} {#each logEntries as entry}
<li class={`log-item ${entry.status}`}>{entry.message}</li> <li class={`log-item ${entry.status}`}>{entry.message}</li>
@@ -605,6 +680,37 @@
margin-bottom: 10px; margin-bottom: 10px;
} }
.progress-bar-container {
width: 100%;
height: 6px;
background: var(--alpha-8);
border-radius: 3px;
overflow: hidden;
margin-bottom: 8px;
}
.progress-bar-fill {
height: 100%;
background: var(--accent-primary);
border-radius: 3px;
transition: width 200ms ease;
}
.progress-status {
font-size: 12px;
color: var(--text-secondary);
margin-bottom: 4px;
}
.progress-current-track {
font-size: 11px;
color: var(--text-muted);
white-space: nowrap;
overflow: hidden;
text-overflow: ellipsis;
margin-bottom: 10px;
}
.progress-log { .progress-log {
list-style: none; list-style: none;
padding: 0; padding: 0;
+6 -1
View File
@@ -1318,6 +1318,11 @@
"summary": "Zusammenfassung", "summary": "Zusammenfassung",
"playlistLabel": "Playlist: {name}", "playlistLabel": "Playlist: {name}",
"tracksMatched": "Titel zugeordnet: {matched} / {total}", "tracksMatched": "Titel zugeordnet: {matched} / {total}",
"skipped": "Übersprungen: {count}" "skipped": "Übersprungen: {count}",
"matchingTracks": "Titel abgleichen: {current} / {total} ({matched} gefunden)",
"matchingPhase": "Qobuz-Katalog durchsuchen...",
"creatingPhase": "Playlist erstellen...",
"addingPhase": "Titel zur Playlist hinzufugen...",
"addingProgress": "Titel hinzufugen: {current} / {total}"
} }
} }
+6 -1
View File
@@ -1520,6 +1520,11 @@
"summary": "Summary", "summary": "Summary",
"playlistLabel": "Playlist: {name}", "playlistLabel": "Playlist: {name}",
"tracksMatched": "Tracks matched: {matched} / {total}", "tracksMatched": "Tracks matched: {matched} / {total}",
"skipped": "Skipped: {count}" "skipped": "Skipped: {count}",
"matchingTracks": "Matching tracks: {current} / {total} ({matched} found)",
"matchingPhase": "Searching Qobuz catalog...",
"creatingPhase": "Creating playlist...",
"addingPhase": "Adding tracks to playlist...",
"addingProgress": "Adding tracks: {current} / {total}"
} }
} }
+6 -1
View File
@@ -1520,6 +1520,11 @@
"summary": "Resumen", "summary": "Resumen",
"playlistLabel": "Playlist: {name}", "playlistLabel": "Playlist: {name}",
"tracksMatched": "Tracks encontrados: {matched} / {total}", "tracksMatched": "Tracks encontrados: {matched} / {total}",
"skipped": "Omitidos: {count}" "skipped": "Omitidos: {count}",
"matchingTracks": "Buscando tracks: {current} / {total} ({matched} encontrados)",
"matchingPhase": "Buscando en el catalogo de Qobuz...",
"creatingPhase": "Creando playlist...",
"addingPhase": "Agregando tracks a la playlist...",
"addingProgress": "Agregando tracks: {current} / {total}"
} }
} }
+6 -1
View File
@@ -1318,6 +1318,11 @@
"summary": "Resume", "summary": "Resume",
"playlistLabel": "Playlist : {name}", "playlistLabel": "Playlist : {name}",
"tracksMatched": "Titres trouves : {matched} / {total}", "tracksMatched": "Titres trouves : {matched} / {total}",
"skipped": "Ignores : {count}" "skipped": "Ignores : {count}",
"matchingTracks": "Recherche des titres : {current} / {total} ({matched} trouves)",
"matchingPhase": "Recherche dans le catalogue Qobuz...",
"creatingPhase": "Creation de la playlist...",
"addingPhase": "Ajout des titres a la playlist...",
"addingProgress": "Ajout des titres : {current} / {total}"
} }
} }