style: apply cargo fmt across codebase

Automated formatting pass covering 79 Rust source files.
No logic changes -- only line wrapping, import ordering,
and match/closure reformatting.
This commit is contained in:
vicrodh committed 2026-02-20 00:14:58 -06:00
1 parent f9313c2d80
commit 3a297c0b2b
78 files changed
+4593 -2697

No files matched your search

+217 -88
View File
@@ -43,7 +43,8 @@ fn limit_quality_for_device(quality: Quality, max_sample_rate: Option<u32>) -> Q
Quality::UltraHiRes | Quality::HiRes => {
log::info!(
"[Quality Limit] Device max {}Hz, limiting {} to Lossless (44.1kHz)",
max_rate, quality.label()
max_rate,
quality.label()
);
Quality::Lossless
}
@@ -139,7 +140,11 @@ pub async fn play_track(
if let Some(file_path) = cached_path {
let path = std::path::Path::new(&file_path);
if path.exists() {
log::info!("[CACHE HIT] Track {} from OFFLINE cache: {:?}", track_id, path);
log::info!(
"[CACHE HIT] Track {} from OFFLINE cache: {:?}",
track_id,
path
);
// Read file and play
let audio_data = std::fs::read(path)
@@ -149,8 +154,15 @@ pub async fn play_track(
// Check if prefetch should be skipped (streaming_only mode)
let skip_prefetch = {
let guard = audio_settings.store.lock().map_err(|e| format!("Lock error: {}", e))?;
guard.as_ref().and_then(|s| s.get_settings().ok()).map(|s| s.streaming_only).unwrap_or(false)
let guard = audio_settings
.store
.lock()
.map_err(|e| format!("Lock error: {}", e))?;
guard
.as_ref()
.and_then(|s| s.get_settings().ok())
.map(|s| s.streaming_only)
.unwrap_or(false)
};
// Prefetch next track in background
@@ -171,13 +183,24 @@ pub async fn play_track(
// Check if track is in memory cache (L1)
if let Some(cached) = cache.get(track_id) {
log::info!("[CACHE HIT] Track {} from MEMORY cache ({} bytes) - instant playback", track_id, cached.size_bytes);
log::info!(
"[CACHE HIT] Track {} from MEMORY cache ({} bytes) - instant playback",
track_id,
cached.size_bytes
);
state.player.play_data(cached.data, track_id)?;
// Check if prefetch should be skipped (streaming_only mode)
let skip_prefetch = {
let guard = audio_settings.store.lock().map_err(|e| format!("Lock error: {}", e))?;
guard.as_ref().and_then(|s| s.get_settings().ok()).map(|s| s.streaming_only).unwrap_or(false)
let guard = audio_settings
.store
.lock()
.map_err(|e| format!("Lock error: {}", e))?;
guard
.as_ref()
.and_then(|s| s.get_settings().ok())
.map(|s| s.streaming_only)
.unwrap_or(false)
};
// Prefetch next track in background
@@ -195,7 +218,11 @@ pub async fn play_track(
// Check if track is in playback cache (L2 - disk)
if let Some(playback_cache) = cache.get_playback_cache() {
if let Some(audio_data) = playback_cache.get(track_id) {
log::info!("[CACHE HIT] Track {} from DISK cache ({} bytes) - instant playback", track_id, audio_data.len());
log::info!(
"[CACHE HIT] Track {} from DISK cache ({} bytes) - instant playback",
track_id,
audio_data.len()
);
// Promote back to memory cache
cache.insert(track_id, audio_data.clone());
@@ -204,8 +231,15 @@ pub async fn play_track(
// Check if prefetch should be skipped (streaming_only mode)
let skip_prefetch = {
let guard = audio_settings.store.lock().map_err(|e| format!("Lock error: {}", e))?;
guard.as_ref().and_then(|s| s.get_settings().ok()).map(|s| s.streaming_only).unwrap_or(false)
let guard = audio_settings
.store
.lock()
.map_err(|e| format!("Lock error: {}", e))?;
guard
.as_ref()
.and_then(|s| s.get_settings().ok())
.map(|s| s.streaming_only)
.unwrap_or(false)
};
// Prefetch next track in background
@@ -222,13 +256,23 @@ pub async fn play_track(
}
// Not in any cache - check if streaming is enabled
log::info!("Track {} not in any cache, fetching from network...", track_id);
log::info!(
"Track {} not in any cache, fetching from network...",
track_id
);
// Check streaming settings
let (stream_first_enabled, buffer_seconds, streaming_only) = {
let guard = audio_settings.store.lock().map_err(|e| format!("Lock error: {}", e))?;
let guard = audio_settings
.store
.lock()
.map_err(|e| format!("Lock error: {}", e))?;
match guard.as_ref().and_then(|s| s.get_settings().ok()) {
Some(settings) => (settings.stream_first_track, settings.stream_buffer_seconds, settings.streaming_only),
Some(settings) => (
settings.stream_first_track,
settings.stream_buffer_seconds,
settings.streaming_only,
),
None => {
log::warn!("Failed to get audio settings, using defaults");
(false, 3, false)
@@ -238,7 +282,9 @@ pub async fn play_track(
log::info!(
"[Playback Settings] stream_first: {}, streaming_only: {}, buffer: {}s",
stream_first_enabled, streaming_only, buffer_seconds
stream_first_enabled,
streaming_only,
buffer_seconds
);
let client = state.client.read().await;
@@ -253,7 +299,11 @@ pub async fn play_track(
if stream_first_enabled {
// Use streaming playback - start playing before full download
log::info!("[STREAMING] Track {} - streaming from network (cache_after: {})", track_id, !streaming_only);
log::info!(
"[STREAMING] Track {} - streaming from network (cache_after: {})",
track_id,
!streaming_only
);
// Get content length, audio info, and measured speed via HEAD request
let stream_info = get_stream_info(&stream_url.url).await?;
@@ -288,14 +338,29 @@ pub async fn play_track(
let content_len = stream_info.content_length;
let skip_cache = streaming_only;
tokio::spawn(async move {
match download_and_stream(&url, buffer_writer, track_id, cache_clone, content_len, skip_cache).await {
match download_and_stream(
&url,
buffer_writer,
track_id,
cache_clone,
content_len,
skip_cache,
)
.await
{
Ok(()) => {
if skip_cache {
log::info!("[STREAMING COMPLETE] Track {} - NOT cached (streaming_only mode)", track_id);
log::info!(
"[STREAMING COMPLETE] Track {} - NOT cached (streaming_only mode)",
track_id
);
} else {
log::info!("[STREAMING COMPLETE] Track {} - cached for instant replay", track_id);
log::info!(
"[STREAMING COMPLETE] Track {} - cached for instant replay",
track_id
);
}
},
}
Err(e) => log::error!("[STREAMING ERROR] Track {}: {}", track_id, e),
}
});
@@ -312,11 +377,17 @@ pub async fn play_track(
streaming_only,
);
return Ok(PlayTrackResult { format_id: Some(actual_format_id) });
return Ok(PlayTrackResult {
format_id: Some(actual_format_id),
});
}
// Standard download path (streaming disabled)
log::info!("[DOWNLOAD] Track {} - full download before playback (cache_after: {})", track_id, !streaming_only);
log::info!(
"[DOWNLOAD] Track {} - full download before playback (cache_after: {})",
track_id,
!streaming_only
);
// Download the audio
let audio_data = download_audio(&stream_url.url).await?;
@@ -327,7 +398,10 @@ pub async fn play_track(
cache.insert(track_id, audio_data.clone());
log::info!("[CACHED] Track {} stored in memory cache", track_id);
} else {
log::info!("[NOT CACHED] Track {} - streaming_only mode active", track_id);
log::info!(
"[NOT CACHED] Track {} - streaming_only mode active",
track_id
);
}
// Play it
@@ -347,7 +421,9 @@ pub async fn play_track(
streaming_only,
);
Ok(PlayTrackResult { format_id: Some(stream_url.format_id) })
Ok(PlayTrackResult {
format_id: Some(stream_url.format_id),
})
}
/// Prefetch a track into the in-memory cache without starting playback
@@ -390,7 +466,11 @@ pub async fn prefetch_track(
log::info!(
"Command: prefetch_track {} (quality_str={:?}, parsed={:?}, final={:?}, format_id={})",
track_id, quality, preferred_quality, final_quality, final_quality.id()
track_id,
quality,
preferred_quality,
final_quality,
final_quality.id()
);
let cache = state.audio_cache.clone();
@@ -519,14 +599,19 @@ async fn get_stream_info(url: &str) -> Result<StreamInfo, String> {
Err(e) => {
last_error = e.to_string();
if attempt < 2 {
log::warn!("HEAD request attempt {} failed: {}, retrying...", attempt + 1, e);
log::warn!(
"HEAD request attempt {} failed: {}, retrying...",
attempt + 1,
e
);
tokio::time::sleep(Duration::from_millis(100)).await;
}
}
}
}
let head_response = head_response.ok_or_else(|| format!("Failed HEAD request after 3 attempts: {}", last_error))?;
let head_response = head_response
.ok_or_else(|| format!("Failed HEAD request after 3 attempts: {}", last_error))?;
if !head_response.status().is_success() {
return Err(format!("HEAD request failed: {}", head_response.status()));
@@ -542,7 +627,7 @@ async fn get_stream_info(url: &str) -> Result<StreamInfo, String> {
// Download first ~64KB to probe audio format and measure speed
// This is enough for FLAC/M4A headers
let start_time = Instant::now();
let range_response = client
.get(url)
.header("User-Agent", "Mozilla/5.0")
@@ -551,7 +636,9 @@ async fn get_stream_info(url: &str) -> Result<StreamInfo, String> {
.await
.map_err(|e| format!("Failed range request: {}", e))?;
if !range_response.status().is_success() && range_response.status() != reqwest::StatusCode::PARTIAL_CONTENT {
if !range_response.status().is_success()
&& range_response.status() != reqwest::StatusCode::PARTIAL_CONTENT
{
return Err(format!("Range request failed: {}", range_response.status()));
}
@@ -589,8 +676,8 @@ async fn get_stream_info(url: &str) -> Result<StreamInfo, String> {
/// Extract sample rate, channels, and bit depth from audio file header
fn extract_audio_format_from_header(data: &[u8]) -> Result<(u32, u16, u32), String> {
use std::io::{BufReader, Cursor};
use rodio::Decoder;
use std::io::{BufReader, Cursor};
// Check if this is FLAC
if data.len() >= 4 && &data[0..4] == b"fLaC" {
@@ -599,7 +686,8 @@ fn extract_audio_format_from_header(data: &[u8]) -> Result<(u32, u16, u32), Stri
if data.len() >= 26 {
// STREAMINFO starts at byte 8
// Bytes 18-20: sample rate (20 bits) + channels (3 bits) + bits per sample (5 bits)
let sr_high = ((data[18] as u32) << 12) | ((data[19] as u32) << 4) | ((data[20] as u32) >> 4);
let sr_high =
((data[18] as u32) << 12) | ((data[19] as u32) << 4) | ((data[20] as u32) >> 4);
let sample_rate = sr_high;
let channels = ((data[20] >> 1) & 0x07) + 1;
// Bits per sample: 5 bits starting at bit 4 of byte 20
@@ -636,12 +724,19 @@ fn extract_audio_format_from_header(data: &[u8]) -> Result<(u32, u16, u32), Stri
}
}
impl symphonia::core::io::MediaSource for ProbeSource {
fn is_seekable(&self) -> bool { true }
fn byte_len(&self) -> Option<u64> { Some(self.len) }
fn is_seekable(&self) -> bool {
true
}
fn byte_len(&self) -> Option<u64> {
Some(self.len)
}
}
let len = data.len() as u64;
let source = Box::new(ProbeSource { inner: Cursor::new(data.to_vec()), len });
let source = Box::new(ProbeSource {
inner: Cursor::new(data.to_vec()),
len,
});
let mss = MediaSourceStream::new(source, Default::default());
let mut hint = Hint::new();
@@ -652,10 +747,16 @@ fn extract_audio_format_from_header(data: &[u8]) -> Result<(u32, u16, u32), Stri
..Default::default()
};
if let Ok(probed) = get_probe().format(&hint, mss, &format_opts, &MetadataOptions::default()) {
if let Ok(probed) =
get_probe().format(&hint, mss, &format_opts, &MetadataOptions::default())
{
if let Some(track) = probed.format.default_track() {
let sample_rate = track.codec_params.sample_rate.unwrap_or(44100);
let channels = track.codec_params.channels.map(|c| c.count() as u16).unwrap_or(2);
let channels = track
.codec_params
.channels
.map(|c| c.count() as u16)
.unwrap_or(2);
let bit_depth = track.codec_params.bits_per_sample.unwrap_or(16);
return Ok((sample_rate, channels, bit_depth));
}
@@ -674,7 +775,9 @@ fn extract_audio_format_from_header(data: &[u8]) -> Result<(u32, u16, u32), Stri
}
Err(_) => {
// Default fallback
log::warn!("Could not determine audio format, using defaults (44100Hz, stereo, 16-bit)");
log::warn!(
"Could not determine audio format, using defaults (44100Hz, stereo, 16-bit)"
);
Ok((44100, 2, 16))
}
}
@@ -690,8 +793,8 @@ async fn download_and_stream(
content_length: u64,
skip_cache: bool,
) -> Result<(), String> {
use std::time::{Duration, Instant};
use futures_util::StreamExt;
use std::time::{Duration, Instant};
let client = reqwest::Client::builder()
.timeout(Duration::from_secs(300)) // Longer timeout for streaming
@@ -699,8 +802,9 @@ async fn download_and_stream(
.build()
.map_err(|e| format!("Failed to create HTTP client: {}", e))?;
log::info!("Starting streaming cache for track {} ({:.2} MB total)",
track_id,
log::info!(
"Starting streaming cache for track {} ({:.2} MB total)",
track_id,
content_length as f64 / (1024.0 * 1024.0)
);
@@ -740,7 +844,7 @@ async fn download_and_stream(
let elapsed_total = start_time.elapsed().as_secs_f64();
let elapsed_interval = now.duration_since(last_log_time).as_secs_f64();
let bytes_this_interval = bytes_received - last_log_bytes;
// Current speed (MB/s)
let current_speed = (bytes_this_interval as f64 / elapsed_interval) / (1024.0 * 1024.0);
// Average speed
@@ -777,7 +881,7 @@ async fn download_and_stream(
let total_time = start_time.elapsed();
let avg_speed = (bytes_received as f64 / total_time.as_secs_f64()) / (1024.0 * 1024.0);
log::info!(
"Streaming cache complete: {:.2} MB in {:.1}s ({:.2} MB/s avg)",
bytes_received as f64 / (1024.0 * 1024.0),
@@ -850,7 +954,11 @@ fn spawn_prefetch(
// Skip local tracks - they don't need prefetching from Qobuz
if track.is_local {
log::debug!("Skipping prefetch for local track: {} - {}", track_id, track_title);
log::debug!(
"Skipping prefetch for local track: {} - {}",
track_id,
track_title
);
continue;
}
@@ -983,7 +1091,11 @@ pub async fn play_next_gapless(
// Check memory cache (L1)
let cache = state.audio_cache.clone();
if let Some(cached) = cache.get(track_id) {
log::info!("[GAPLESS] Track {} from MEMORY cache ({} bytes)", track_id, cached.size_bytes);
log::info!(
"[GAPLESS] Track {} from MEMORY cache ({} bytes)",
track_id,
cached.size_bytes
);
state.player.play_next(cached.data, track_id)?;
return Ok(true);
}
@@ -991,13 +1103,20 @@ pub async fn play_next_gapless(
// Check playback cache (L2 - disk)
if let Some(playback_cache) = cache.get_playback_cache() {
if let Some(audio_data) = playback_cache.get(track_id) {
log::info!("[GAPLESS] Track {} from DISK cache ({} bytes)", track_id, audio_data.len());
log::info!(
"[GAPLESS] Track {} from DISK cache ({} bytes)",
track_id,
audio_data.len()
);
state.player.play_next(audio_data, track_id)?;
return Ok(true);
}
}
log::info!("[GAPLESS] Track {} not in any cache, gapless not possible", track_id);
log::info!(
"[GAPLESS] Track {} not in any cache, gapless not possible",
track_id
);
Ok(false)
}
@@ -1043,10 +1162,9 @@ pub fn seek(position: u64, state: State<'_, AppState>) -> Result<(), String> {
// Update MPRIS with new position
let playback_state = state.player.get_state().unwrap_or_default();
state.media_controls.set_playback_with_progress(
playback_state.is_playing,
position,
);
state
.media_controls
.set_playback_with_progress(playback_state.is_playing, position);
result
}
@@ -1057,10 +1175,9 @@ pub fn get_playback_state(state: State<'_, AppState>) -> Result<PlaybackState, S
let playback_state = state.player.get_state()?;
// Update MPRIS with current progress (called every ~500ms from frontend)
state.media_controls.set_playback_with_progress(
playback_state.is_playing,
playback_state.position,
);
state
.media_controls
.set_playback_with_progress(playback_state.is_playing, playback_state.position);
Ok(playback_state)
}
@@ -1068,10 +1185,10 @@ pub fn get_playback_state(state: State<'_, AppState>) -> Result<PlaybackState, S
/// Audio device information
#[derive(serde::Serialize)]
pub struct AudioDevice {
pub name: String, // Technical name (internal use)
pub display_name: String, // Friendly name for UI
pub name: String, // Technical name (internal use)
pub display_name: String, // Friendly name for UI
pub is_default: bool,
pub device_type: Option<String>, // "USB", "PCI", "HDMI", etc.
pub device_type: Option<String>, // "USB", "PCI", "HDMI", etc.
}
/// Get friendly device names from PipeWire/PulseAudio
@@ -1105,7 +1222,10 @@ fn get_pipewire_device_descriptions() -> std::collections::HashMap<String, Strin
}
}
log::info!("Found {} device descriptions from PipeWire/PulseAudio", map.len());
log::info!(
"Found {} device descriptions from PipeWire/PulseAudio",
map.len()
);
map
}
@@ -1123,9 +1243,7 @@ pub fn get_audio_devices() -> Result<Vec<AudioDevice>, String> {
let host = rodio::cpal::default_host();
let default_device_name = host
.default_output_device()
.and_then(|d| d.name().ok());
let default_device_name = host.default_output_device().and_then(|d| d.name().ok());
// Get friendly names from PipeWire/PulseAudio
let friendly_names = get_pipewire_device_descriptions();
@@ -1135,20 +1253,20 @@ pub fn get_audio_devices() -> Result<Vec<AudioDevice>, String> {
.map_err(|e| format!("Failed to enumerate devices: {}", e))?
.filter_map(|device| {
device.name().ok().map(|name| {
let is_default = default_device_name.as_ref().map(|d| d == &name).unwrap_or(false);
let is_default = default_device_name
.as_ref()
.map(|d| d == &name)
.unwrap_or(false);
// Try to get friendly name from PipeWire/PulseAudio
let display_name = friendly_names
.get(&name)
.cloned()
.unwrap_or_else(|| {
// Fallback: clean up technical name slightly
name.replace("alsa_output.", "")
.replace("_", " ")
.replace("pro-output", "")
.trim()
.to_string()
});
let display_name = friendly_names.get(&name).cloned().unwrap_or_else(|| {
// Fallback: clean up technical name slightly
name.replace("alsa_output.", "")
.replace("_", " ")
.replace("pro-output", "")
.trim()
.to_string()
});
// Detect device type from technical name
let device_type = if name.contains("usb") || name.contains("USB") {
@@ -1221,7 +1339,10 @@ pub fn reinit_audio_device(
if let Ok(guard) = audio_settings_state.store.lock() {
if let Some(store) = guard.as_ref() {
if let Ok(fresh_settings) = store.get_settings() {
log::info!("Reloading audio settings before reinit (backend_type: {:?})", fresh_settings.backend_type);
log::info!(
"Reloading audio settings before reinit (backend_type: {:?})",
fresh_settings.backend_type
);
let _ = state.player.reload_settings(fresh_settings);
}
}
@@ -1255,9 +1376,7 @@ pub fn get_pipewire_sinks() -> Result<Vec<PipewireSink>, String> {
let host = rodio::cpal::default_host();
// Get default device name from CPAL
let default_device_name = host
.default_output_device()
.and_then(|d| d.name().ok());
let default_device_name = host.default_output_device().and_then(|d| d.name().ok());
log::info!("CPAL default device: {:?}", default_device_name);
@@ -1269,10 +1388,14 @@ pub fn get_pipewire_sinks() -> Result<Vec<PipewireSink>, String> {
.filter_map(|(idx, device)| {
match device.name() {
Ok(name) => {
let is_default = default_device_name.as_ref().map(|d| d == &name).unwrap_or(false);
let is_default = default_device_name
.as_ref()
.map(|d| d == &name)
.unwrap_or(false);
// Get detailed device info for logging
let configs_info = device.supported_output_configs()
let configs_info = device
.supported_output_configs()
.ok()
.map(|configs| {
let config_strs: Vec<String> = configs
@@ -1283,8 +1406,13 @@ pub fn get_pipewire_sinks() -> Result<Vec<PipewireSink>, String> {
})
.unwrap_or_else(|| "no configs".to_string());
log::info!(" [{}] Device: '{}' (default: {}) - Configs: {}",
idx, name, is_default, configs_info);
log::info!(
" [{}] Device: '{}' (default: {}) - Configs: {}",
idx,
name,
is_default,
configs_info
);
// CRITICAL: Use CPAL device name as both name and description
// This ensures the name we save is the exact name CPAL can find later
@@ -1319,16 +1447,17 @@ pub fn get_pipewire_sinks() -> Result<Vec<PipewireSink>, String> {
let host = rodio::cpal::default_host();
let default_device_name = host
.default_output_device()
.and_then(|d| d.name().ok());
let default_device_name = host.default_output_device().and_then(|d| d.name().ok());
let sinks: Vec<PipewireSink> = host
.output_devices()
.map_err(|e| format!("Failed to enumerate devices: {}", e))?
.filter_map(|device| {
device.name().ok().map(|name| {
let is_default = default_device_name.as_ref().map(|d| d == &name).unwrap_or(false);
let is_default = default_device_name
.as_ref()
.map(|d| d == &name)
.unwrap_or(false);
PipewireSink {
name: name.clone(),
description: name, // On Mac/Windows, name is usually descriptive enough
@@ -1378,17 +1507,17 @@ pub fn set_pipewire_default_sink(_sink_name: String) -> Result<(), String> {
#[tauri::command]
pub fn debug_get_cpal_devices() -> Result<Vec<String>, String> {
use rodio::cpal::traits::{DeviceTrait, HostTrait};
log::info!("Command: debug_get_cpal_devices");
let host = rodio::cpal::default_host();
let devices: Vec<String> = host
.output_devices()
.map_err(|e| format!("Failed to enumerate devices: {}", e))?
.filter_map(|device| device.name().ok())
.collect();
log::info!("CPAL devices: {:?}", devices);
Ok(devices)
}
+162 -49
View File
@@ -2,7 +2,11 @@
use tauri::State;
use crate::api::{endpoints, endpoints::paths, Album, Artist, ArtistAlbums, DiscoverAlbum, DiscoverData, DiscoverResponse, DiscoverPlaylistsResponse, LabelDetail, PageArtistResponse, Playlist, PlaylistTag, ReleasesGridResponse, SearchResultsPage, Track, TracksContainer};
use crate::api::{
endpoints, endpoints::paths, Album, Artist, ArtistAlbums, DiscoverAlbum, DiscoverData,
DiscoverPlaylistsResponse, DiscoverResponse, LabelDetail, PageArtistResponse, Playlist,
PlaylistTag, ReleasesGridResponse, SearchResultsPage, Track, TracksContainer,
};
use crate::api_cache::ApiCacheState;
use crate::artist_blacklist::BlacklistState;
use crate::AppState;
@@ -39,18 +43,28 @@ pub async fn search_albums(
let mut results = {
let client = state.client.read().await;
client
.search_albums(&query, limit.unwrap_or(20), offset.unwrap_or(0), search_type.as_deref())
.search_albums(
&query,
limit.unwrap_or(20),
offset.unwrap_or(0),
search_type.as_deref(),
)
.await
.map_err(|e| e.to_string())?
};
// Filter out albums from blacklisted artists
let original_count = results.items.len();
results.items.retain(|album| !blacklist_state.is_blacklisted(album.artist.id));
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!("[Blacklist] Filtered {} albums from search results", filtered_count);
log::debug!(
"[Blacklist] Filtered {} albums from search results",
filtered_count
);
results.total = results.total.saturating_sub(filtered_count as u32);
}
@@ -69,7 +83,12 @@ pub async fn search_tracks(
let mut results = {
let client = state.client.read().await;
client
.search_tracks(&query, limit.unwrap_or(20), offset.unwrap_or(0), search_type.as_deref())
.search_tracks(
&query,
limit.unwrap_or(20),
offset.unwrap_or(0),
search_type.as_deref(),
)
.await
.map_err(|e| e.to_string())?
};
@@ -86,7 +105,10 @@ pub async fn search_tracks(
let filtered_count = original_count - results.items.len();
if filtered_count > 0 {
log::debug!("[Blacklist] Filtered {} tracks from search results", filtered_count);
log::debug!(
"[Blacklist] Filtered {} tracks from search results",
filtered_count
);
// Adjust total to reflect filtered count (approximate)
results.total = results.total.saturating_sub(filtered_count as u32);
}
@@ -106,18 +128,28 @@ pub async fn search_artists(
let mut results = {
let client = state.client.read().await;
client
.search_artists(&query, limit.unwrap_or(20), offset.unwrap_or(0), search_type.as_deref())
.search_artists(
&query,
limit.unwrap_or(20),
offset.unwrap_or(0),
search_type.as_deref(),
)
.await
.map_err(|e| e.to_string())?
};
// Filter out blacklisted artists
let original_count = results.items.len();
results.items.retain(|artist| !blacklist_state.is_blacklisted(artist.id));
results
.items
.retain(|artist| !blacklist_state.is_blacklisted(artist.id));
let filtered_count = original_count - results.items.len();
if filtered_count > 0 {
log::debug!("[Blacklist] Filtered {} artists from search results", filtered_count);
log::debug!(
"[Blacklist] Filtered {} artists from search results",
filtered_count
);
results.total = results.total.saturating_sub(filtered_count as u32);
}
@@ -141,13 +173,15 @@ pub async fn search_all(
client
.get_http()
.get(&url)
.header("X-App-Id", client.app_id().await.map_err(|e| e.to_string())?)
.header("X-User-Auth-Token", client.auth_token().await.map_err(|e| e.to_string())?)
.query(&[
("query", query.as_str()),
("limit", "30"),
("offset", "0"),
])
.header(
"X-App-Id",
client.app_id().await.map_err(|e| e.to_string())?,
)
.header(
"X-User-Auth-Token",
client.auth_token().await.map_err(|e| e.to_string())?,
)
.query(&[("query", query.as_str()), ("limit", "30"), ("offset", "0")])
.send()
.await
.map_err(|e| format!("Request failed: {}", e))?
@@ -160,25 +194,45 @@ pub async fn search_all(
let albums: SearchResultsPage<Album> = response
.get("albums")
.and_then(|v| serde_json::from_value(v.clone()).ok())
.unwrap_or_else(|| SearchResultsPage { items: vec![], total: 0, offset: 0, limit: 30 });
.unwrap_or_else(|| SearchResultsPage {
items: vec![],
total: 0,
offset: 0,
limit: 30,
});
// Parse tracks
let mut tracks: SearchResultsPage<Track> = response
.get("tracks")
.and_then(|v| serde_json::from_value(v.clone()).ok())
.unwrap_or_else(|| SearchResultsPage { items: vec![], total: 0, offset: 0, limit: 30 });
.unwrap_or_else(|| SearchResultsPage {
items: vec![],
total: 0,
offset: 0,
limit: 30,
});
// Parse artists
let mut artists: SearchResultsPage<Artist> = response
.get("artists")
.and_then(|v| serde_json::from_value(v.clone()).ok())
.unwrap_or_else(|| SearchResultsPage { items: vec![], total: 0, offset: 0, limit: 30 });
.unwrap_or_else(|| SearchResultsPage {
items: vec![],
total: 0,
offset: 0,
limit: 30,
});
// Parse playlists
let playlists: SearchResultsPage<Playlist> = response
.get("playlists")
.and_then(|v| serde_json::from_value(v.clone()).ok())
.unwrap_or_else(|| SearchResultsPage { items: vec![], total: 0, offset: 0, limit: 30 });
.unwrap_or_else(|| SearchResultsPage {
items: vec![],
total: 0,
offset: 0,
limit: 30,
});
// Parse most_popular - find the first non-blacklisted item
let most_popular: Option<MostPopularItem> = response
@@ -245,7 +299,9 @@ pub async fn search_all(
// Filter albums from blacklisted artists
let original_album_count = albums.items.len();
let mut albums = albums;
albums.items.retain(|album| !blacklist_state.is_blacklisted(album.artist.id));
albums
.items
.retain(|album| !blacklist_state.is_blacklisted(album.artist.id));
let filtered_albums = original_album_count - albums.items.len();
if filtered_albums > 0 {
albums.total = albums.total.saturating_sub(filtered_albums as u32);
@@ -267,7 +323,9 @@ pub async fn search_all(
// Filter blacklisted artists
let original_artist_count = artists.items.len();
artists.items.retain(|artist| !blacklist_state.is_blacklisted(artist.id));
artists
.items
.retain(|artist| !blacklist_state.is_blacklisted(artist.id));
let filtered_artists = original_artist_count - artists.items.len();
if filtered_artists > 0 {
artists.total = artists.total.saturating_sub(filtered_artists as u32);
@@ -302,7 +360,9 @@ pub async fn get_album(
// Check cache first
{
let guard__ = cache_state.cache.lock().await;
let cache = guard__.as_ref().ok_or("No active session - please log in")?;
let cache = guard__
.as_ref()
.ok_or("No active session - please log in")?;
match cache.get_album(&album_id, None) {
Ok(Some(cached_data)) => {
log::debug!("Cache hit for album {}", album_id);
@@ -320,13 +380,18 @@ pub async fn get_album(
log::debug!("Cache miss for album {}, fetching from API", album_id);
let album = {
let client = state.client.read().await;
client.get_album(&album_id).await.map_err(|e| e.to_string())?
client
.get_album(&album_id)
.await
.map_err(|e| e.to_string())?
};
// Cache the result
{
let guard__ = cache_state.cache.lock().await;
let cache = guard__.as_ref().ok_or("No active session - please log in")?;
let cache = guard__
.as_ref()
.ok_or("No active session - please log in")?;
let json = serde_json::to_string(&album)
.map_err(|e| format!("Failed to serialize album: {}", e))?;
let _ = cache.set_album(&album_id, &json);
@@ -347,7 +412,12 @@ pub async fn get_featured_albums(
let result = {
let client = state.client.read().await;
client
.get_featured_albums(&featured_type, limit.unwrap_or(12), offset.unwrap_or(0), genre_id)
.get_featured_albums(
&featured_type,
limit.unwrap_or(12),
offset.unwrap_or(0),
genre_id,
)
.await
.map_err(|e| e.to_string())?
};
@@ -363,7 +433,9 @@ pub async fn get_track(
// Check cache first
{
let guard__ = cache_state.cache.lock().await;
let cache = guard__.as_ref().ok_or("No active session - please log in")?;
let cache = guard__
.as_ref()
.ok_or("No active session - please log in")?;
match cache.get_track(track_id, None) {
Ok(Some(cached_data)) => {
log::debug!("Cache hit for track {}", track_id);
@@ -381,13 +453,18 @@ pub async fn get_track(
log::debug!("Cache miss for track {}, fetching from API", track_id);
let track = {
let client = state.client.read().await;
client.get_track(track_id).await.map_err(|e| e.to_string())?
client
.get_track(track_id)
.await
.map_err(|e| e.to_string())?
};
// Cache the result
{
let guard__ = cache_state.cache.lock().await;
let cache = guard__.as_ref().ok_or("No active session - please log in")?;
let cache = guard__
.as_ref()
.ok_or("No active session - please log in")?;
let json = serde_json::to_string(&track)
.map_err(|e| format!("Failed to serialize track: {}", e))?;
let _ = cache.set_track(track_id, &json);
@@ -414,7 +491,9 @@ pub async fn get_artist(
// Check cache first
{
let guard__ = cache_state.cache.lock().await;
let cache = guard__.as_ref().ok_or("No active session - please log in")?;
let cache = guard__
.as_ref()
.ok_or("No active session - please log in")?;
if let Some(cached_data) = cache.get_artist(artist_id, &locale, None)? {
log::debug!("Cache hit for artist {} (locale: {})", artist_id, locale);
return serde_json::from_str(&cached_data)
@@ -423,7 +502,11 @@ pub async fn get_artist(
}
// Cache miss - fetch from API
log::debug!("Cache miss for artist {} (locale: {}), fetching from API", artist_id, locale);
log::debug!(
"Cache miss for artist {} (locale: {}), fetching from API",
artist_id,
locale
);
let client = state.client.read().await;
let artist = client
.get_artist(artist_id, true)
@@ -433,7 +516,9 @@ pub async fn get_artist(
// Cache the result
{
let guard__ = cache_state.cache.lock().await;
let cache = guard__.as_ref().ok_or("No active session - please log in")?;
let cache = guard__
.as_ref()
.ok_or("No active session - please log in")?;
let json = serde_json::to_string(&artist)
.map_err(|e| format!("Failed to serialize artist: {}", e))?;
cache.set_artist(artist_id, &locale, &json)?;
@@ -458,16 +543,26 @@ pub async fn get_artist_basic(
// Check cache first (reuse same cache - basic response works for both)
{
let guard__ = cache_state.cache.lock().await;
let cache = guard__.as_ref().ok_or("No active session - please log in")?;
let cache = guard__
.as_ref()
.ok_or("No active session - please log in")?;
if let Some(cached_data) = cache.get_artist(artist_id, &locale, None)? {
log::debug!("Cache hit for artist_basic {} (locale: {})", artist_id, locale);
log::debug!(
"Cache hit for artist_basic {} (locale: {})",
artist_id,
locale
);
return serde_json::from_str(&cached_data)
.map_err(|e| format!("Failed to parse cached artist: {}", e));
}
}
// Cache miss - fetch from API (without albums - much faster)
log::debug!("Cache miss for artist_basic {} (locale: {}), fetching from API", artist_id, locale);
log::debug!(
"Cache miss for artist_basic {} (locale: {}), fetching from API",
artist_id,
locale
);
let artist = {
let client = state.client.read().await;
client
@@ -479,7 +574,9 @@ pub async fn get_artist_basic(
// Cache the result
{
let guard__ = cache_state.cache.lock().await;
let cache = guard__.as_ref().ok_or("No active session - please log in")?;
let cache = guard__
.as_ref()
.ok_or("No active session - please log in")?;
let json = serde_json::to_string(&artist)
.map_err(|e| format!("Failed to serialize artist: {}", e))?;
cache.set_artist(artist_id, &locale, &json)?;
@@ -577,7 +674,9 @@ pub async fn get_similar_artists(
// Filter out blacklisted artists
let original_count = results.items.len();
results.items.retain(|artist| !blacklist_state.is_blacklisted(artist.id));
results
.items
.retain(|artist| !blacklist_state.is_blacklisted(artist.id));
let filtered_count = original_count - results.items.len();
if filtered_count > 0 {
@@ -638,7 +737,10 @@ pub async fn get_genres(
}
// Cache miss - fetch from API
log::debug!("Cache miss for genres parent_id={:?}, fetching from API", parent_id);
log::debug!(
"Cache miss for genres parent_id={:?}, fetching from API",
parent_id
);
let client = state.client.read().await;
let genres = client
.get_genres(parent_id)
@@ -685,7 +787,13 @@ pub async fn get_discover_playlists(
offset: Option<u32>,
state: State<'_, AppState>,
) -> Result<DiscoverPlaylistsResponse, String> {
log::debug!("Command: get_discover_playlists tag={:?} genre_ids={:?} limit={:?} offset={:?}", tag, genre_ids, limit, offset);
log::debug!(
"Command: get_discover_playlists tag={:?} genre_ids={:?} limit={:?} offset={:?}",
tag,
genre_ids,
limit,
offset
);
let client = state.client.read().await;
client
@@ -696,14 +804,9 @@ pub async fn get_discover_playlists(
/// Get playlist tags (localized names from /playlist/getTags)
#[tauri::command]
pub async fn get_playlist_tags(
state: State<'_, AppState>,
) -> Result<Vec<PlaylistTag>, String> {
pub async fn get_playlist_tags(state: State<'_, AppState>) -> Result<Vec<PlaylistTag>, String> {
let client = state.client.read().await;
client
.get_playlist_tags()
.await
.map_err(|e| e.to_string())
client.get_playlist_tags().await.map_err(|e| e.to_string())
}
/// Get discover albums from a browse endpoint (newReleases, idealDiscography, mostStreamed)
@@ -727,12 +830,19 @@ pub async fn get_discover_albums(
log::debug!(
"Command: get_discover_albums type={} offset={:?} limit={:?}",
endpoint_type, offset, limit
endpoint_type,
offset,
limit
);
let client = state.client.read().await;
client
.get_discover_albums(endpoint, genre_ids, offset.unwrap_or(0), limit.unwrap_or(50))
.get_discover_albums(
endpoint,
genre_ids,
offset.unwrap_or(0),
limit.unwrap_or(50),
)
.await
.map_err(|e| e.to_string())
}
@@ -765,7 +875,10 @@ pub async fn get_releases_grid(
) -> Result<ReleasesGridResponse, String> {
log::debug!(
"Command: get_releases_grid {} type={} limit={:?} offset={:?}",
artist_id, release_type, limit, offset
artist_id,
release_type,
limit,
offset
);
let client = state.client.read().await;
+2 -7
View File
@@ -48,10 +48,7 @@ pub fn get_last_user_id() -> Option<u64> {
///
/// This is a legacy command - now delegates to session_lifecycle::activate_session().
#[tauri::command]
pub async fn activate_user_session(
app: tauri::AppHandle,
user_id: u64,
) -> Result<(), String> {
pub async fn activate_user_session(app: tauri::AppHandle, user_id: u64) -> Result<(), String> {
log::info!("[Legacy] activate_user_session called - delegating to session_lifecycle");
crate::session_lifecycle::activate_session(&app, user_id).await
}
@@ -61,9 +58,7 @@ pub async fn activate_user_session(
/// Tears down all per-user stores, closing database connections.
/// This is a legacy command - now delegates to session_lifecycle::deactivate_session().
#[tauri::command]
pub async fn deactivate_user_session(
app: tauri::AppHandle,
) -> Result<(), String> {
pub async fn deactivate_user_session(app: tauri::AppHandle) -> Result<(), String> {
log::info!("[Legacy] deactivate_user_session called - delegating to session_lifecycle");
crate::session_lifecycle::deactivate_session(&app).await
}