refactor(backend): rename module and APIs for compliance

- Renamed download_cache module to offline_cache
- Updated Tauri command names (e.g., cache_track_for_offline)
- Updated event names (offline:caching_started, etc.)
- Updated library database function names
- Updated frontend invoke calls to use new command names
This commit is contained in:
vicrodh committed 2026-01-23 12:14:39 -06:00
1 parent 84a2164079
commit 6d5d264778
15 files changed
+348 -343

No files matched your search

+747
View File
@@ -0,0 +1,747 @@
//! Tauri commands for offline cache functionality
use std::sync::Arc;
use tauri::{AppHandle, Emitter, State};
use crate::api::models::Quality;
use crate::AppState;
use crate::offline_cache::path_validator::{self, PathValidationResult};
use crate::offline_cache::{OfflineCacheDb, OfflineCacheState};
use crate::offline_cache::metadata::{fetch_complete_metadata, write_flac_tags, embed_artwork, organize_cached_file, save_album_artwork};
use super::{
CachedTrackInfo, OfflineCacheStats, OfflineCacheStatus,
TrackCacheInfo,
};
/// Post-process a cached track: fetch metadata, tag FLAC, embed artwork, organize files
async fn post_process_cached_track(
track_id: u64,
current_path: &str,
offline_root: &str,
qobuz_client: &crate::api::QobuzClient,
library_db: Arc<tokio::sync::Mutex<crate::library::database::LibraryDatabase>>,
) -> Result<String, String> {
log::info!("Post-processing cached track {}", track_id);
// 1. Fetch complete metadata from Qobuz
let metadata = fetch_complete_metadata(track_id, qobuz_client).await?;
// 2. Write FLAC tags
write_flac_tags(current_path, &metadata)
.map_err(|e| format!("Failed to write tags: {}", e))?;
// 3. Embed artwork if available
if let Some(artwork_url) = &metadata.artwork_url {
if let Err(e) = embed_artwork(current_path, artwork_url).await {
log::warn!("Failed to embed artwork for track {}: {}", track_id, e);
}
}
// 4. Organize file into artist/album structure
let new_path = organize_cached_file(track_id, current_path, offline_root, &metadata)?;
// 5. Download and save album cover art as cover.jpg
let artwork_path = if let Some(artwork_url) = &metadata.artwork_url {
// Extract album directory from the new_path
if let Some(parent_dir) = std::path::Path::new(&new_path).parent() {
match save_album_artwork(parent_dir, artwork_url).await {
Ok(_) => {
let cover_path = parent_dir.join("cover.jpg").to_string_lossy().to_string();
log::info!("Album artwork saved for track {}: {}", track_id, cover_path);
Some(cover_path)
},
Err(e) => {
log::warn!("Failed to save album artwork for track {}: {}", track_id, e);
None
}
}
} else {
None
}
} else {
log::warn!("No artwork URL available for track {}", track_id);
None
};
// 6. Extract audio properties from FLAC file
use lofty::AudioFile;
let (bit_depth, sample_rate) = match lofty::read_from_path(&new_path) {
Ok(tagged_file) => {
let properties = tagged_file.properties();
let bit_depth = properties.bit_depth().map(|bd| bd as u32);
let sample_rate = properties.sample_rate().map(|sr| sr as f64);
(bit_depth, sample_rate)
}
Err(e) => {
log::warn!("Failed to read audio properties for track {}: {}", track_id, e);
(None, None)
}
};
// 7. ALWAYS insert into local library DB (visibility controlled by toggle)
let lib_guard = library_db.lock().await;
// Generate album_group_key: album|album_artist
let album_artist = metadata.album_artist.as_ref().unwrap_or(&metadata.artist);
let album_group_key = format!("{}|{}", metadata.album, album_artist);
match lib_guard.insert_qobuz_cached_track_with_grouping(
track_id,
&metadata.title,
&metadata.artist,
Some(&metadata.album),
metadata.album_artist.as_deref(),
metadata.track_number,
metadata.disc_number,
metadata.year,
metadata.duration_secs,
&new_path,
&album_group_key,
&metadata.album,
bit_depth,
sample_rate,
artwork_path.as_deref(),
) {
Ok(_) => log::info!("Track {} inserted to local library DB with group key: {}, artwork: {:?}", track_id, album_group_key, artwork_path),
Err(e) => log::error!("Failed to insert track {} to library DB: {}", track_id, e),
}
log::info!("Track {} organized to: {}", track_id, new_path);
Ok(new_path)
}
/// Cache a track for offline playback
#[tauri::command]
pub async fn cache_track_for_offline(
track_id: u64,
title: String,
artist: String,
album: Option<String>,
album_id: Option<String>,
duration_secs: u64,
quality: String,
bit_depth: Option<u32>,
sample_rate: Option<f64>,
state: State<'_, AppState>,
cache_state: State<'_, OfflineCacheState>,
library_state: State<'_, crate::library::commands::LibraryState>,
app_handle: AppHandle,
) -> Result<(), String> {
log::info!("Command: cache_track_for_offline {} - {} by {}", track_id, title, artist);
let track_info = TrackCacheInfo {
track_id,
title,
artist,
album,
album_id,
duration_secs,
quality,
bit_depth,
sample_rate,
};
// Determine file path (we'll use flac as default format)
let file_path = cache_state.track_file_path(track_id, "flac");
let file_path_str = file_path.to_string_lossy().to_string();
// Insert into database as queued
{
let db = cache_state.db.lock().await;
db.insert_track(&track_info, &file_path_str)?;
}
// Clone what we need for the spawn
let client = state.client.clone();
let fetcher = cache_state.fetcher.clone();
let db = cache_state.db.clone();
let offline_root = cache_state.get_cache_path();
let library_db = library_state.db.clone();
let app = app_handle.clone();
let semaphore = cache_state.cache_semaphore.clone();
// Spawn caching task
tokio::spawn(async move {
let _permit = match semaphore.acquire_owned().await {
Ok(permit) => permit,
Err(err) => {
log::error!("Failed to acquire cache slot for track {}: {}", track_id, err);
let db_guard = db.lock().await;
let _ = db_guard.update_status(
track_id,
OfflineCacheStatus::Failed,
Some("Failed to start caching"),
);
let _ = app.emit("offline:caching_failed", serde_json::json!({
"trackId": track_id,
"error": "Failed to acquire cache slot"
}));
return;
}
};
// Update status to caching
{
let db_guard = db.lock().await;
let _ = db_guard.update_status(track_id, OfflineCacheStatus::Downloading, None);
}
let _ = app.emit("offline:caching_started", serde_json::json!({
"trackId": track_id
}));
// Get stream URL with highest quality available
let stream_url = {
let client_guard = client.lock().await;
client_guard
.get_stream_url_with_fallback(track_id, Quality::UltraHiRes)
.await
};
let url = match stream_url {
Ok(s) => s.url,
Err(e) => {
log::error!("Failed to get stream URL for track {}: {}", track_id, e);
let db_guard = db.lock().await;
let _ = db_guard.update_status(
track_id,
OfflineCacheStatus::Failed,
Some(&format!("Failed to get stream URL: {}", e)),
);
let _ = app.emit("offline:caching_failed", serde_json::json!({
"trackId": track_id,
"error": e.to_string()
}));
return;
}
};
// Fetch and cache the file
match fetcher
.fetch_to_file(&url, &file_path, track_id, Some(&app))
.await
{
Ok(size) => {
log::info!("Caching complete for track {}: {} bytes", track_id, size);
{
let db_guard = db.lock().await;
let _ = db_guard.mark_complete(track_id, size);
}
let _ = app.emit("offline:caching_completed", serde_json::json!({
"trackId": track_id,
"size": size
}));
// Post-processing: metadata, tagging, artwork, organization
log::info!("Starting post-processing for cached track {}", track_id);
let file_path_str = file_path.to_string_lossy().to_string();
let qobuz_client = client.lock().await;
match post_process_cached_track(
track_id,
&file_path_str,
&offline_root,
&*qobuz_client,
library_db.clone(),
).await {
Ok(new_path) => {
// Update database with new path
let db_guard = db.lock().await;
if let Err(e) = db_guard.update_file_path(track_id, &new_path) {
log::error!("Failed to update path for track {}: {}", track_id, e);
}
let _ = app.emit("offline:caching_processed", serde_json::json!({
"trackId": track_id,
"path": new_path
}));
}
Err(e) => {
log::error!("Post-processing failed for cached track {}: {}", track_id, e);
// File still exists and is playable, just not organized
}
}
}
Err(e) => {
log::error!("Caching failed for track {}: {}", track_id, e);
let db_guard = db.lock().await;
let _ = db_guard.update_status(track_id, OfflineCacheStatus::Failed, Some(&e));
let _ = app.emit("offline:caching_failed", serde_json::json!({
"trackId": track_id,
"error": e
}));
}
}
});
Ok(())
}
/// Check if a track is cached and ready for playback
#[tauri::command]
pub async fn is_track_cached(
track_id: u64,
cache_state: State<'_, OfflineCacheState>,
) -> Result<bool, String> {
let db = cache_state.db.lock().await;
db.is_cached(track_id)
}
/// Get the local file path for a cached track
#[tauri::command]
pub async fn get_cached_track_path(
track_id: u64,
cache_state: State<'_, OfflineCacheState>,
) -> Result<Option<String>, String> {
let db = cache_state.db.lock().await;
db.get_file_path(track_id)
}
/// Get info about a specific cached track
#[tauri::command]
pub async fn get_cached_track(
track_id: u64,
cache_state: State<'_, OfflineCacheState>,
) -> Result<Option<CachedTrackInfo>, String> {
let db = cache_state.db.lock().await;
db.get_track(track_id)
}
/// Get all cached tracks
#[tauri::command]
pub async fn get_cached_tracks(
cache_state: State<'_, OfflineCacheState>,
) -> Result<Vec<CachedTrackInfo>, String> {
let db = cache_state.db.lock().await;
db.get_all_tracks()
}
/// Get offline cache statistics
#[tauri::command]
pub async fn get_offline_cache_stats(
cache_state: State<'_, OfflineCacheState>,
) -> Result<OfflineCacheStats, String> {
let db = cache_state.db.lock().await;
let limit = *cache_state.limit_bytes.lock().await;
db.get_stats(&cache_state.get_cache_path(), limit)
}
/// Remove a track from the offline cache
#[tauri::command]
pub async fn remove_cached_track(
track_id: u64,
cache_state: State<'_, OfflineCacheState>,
library_state: State<'_, crate::library::commands::LibraryState>,
) -> Result<(), String> {
log::info!("Command: remove_cached_track {}", track_id);
let db = cache_state.db.lock().await;
// Get file path and delete from DB
if let Some(file_path) = db.delete_track(track_id)? {
// Delete the actual file
let path = std::path::Path::new(&file_path);
if path.exists() {
std::fs::remove_file(path)
.map_err(|e| format!("Failed to delete file: {}", e))?;
}
}
drop(db);
// Also remove from library if it was added
let library_db = library_state.db.lock().await;
let _ = library_db.remove_qobuz_cached_track(track_id);
Ok(())
}
/// Clear entire offline cache
#[tauri::command]
pub async fn clear_offline_cache(
cache_state: State<'_, OfflineCacheState>,
library_state: State<'_, crate::library::commands::LibraryState>,
) -> Result<(), String> {
log::info!("Command: clear_offline_cache");
purge_all_cached_files(cache_state.inner(), library_state.inner()).await
}
/// Clear entire offline cache (internal helper)
pub async fn purge_all_cached_files(
cache_state: &OfflineCacheState,
library_state: &crate::library::commands::LibraryState,
) -> Result<(), String> {
let db = cache_state.db.lock().await;
// Get all file paths and clear DB
let paths = db.clear_all()?;
drop(db);
// Delete all files
for path in paths {
let p = std::path::Path::new(&path);
if p.exists() {
let _ = std::fs::remove_file(p);
}
}
// Also clear the tracks directory
let tracks_dir = cache_state.cache_dir.join("tracks");
if tracks_dir.exists() {
if let Ok(entries) = std::fs::read_dir(&tracks_dir) {
for entry in entries.flatten() {
let _ = std::fs::remove_file(entry.path());
}
}
}
// Remove all Qobuz cached tracks from library
let library_db = library_state.db.lock().await;
let removed_count = library_db
.remove_all_qobuz_cached_tracks()
.map_err(|e| format!("Failed to remove cached tracks from library: {}", e))?;
log::info!("Removed {} Qobuz cached tracks from library", removed_count);
Ok(())
}
/// Set cache size limit
#[tauri::command]
pub async fn set_offline_cache_limit(
limit_mb: Option<u64>,
cache_state: State<'_, OfflineCacheState>,
) -> Result<(), String> {
log::info!("Command: set_offline_cache_limit {:?} MB", limit_mb);
let limit_bytes = limit_mb.map(|mb| mb * 1024 * 1024);
let mut limit = cache_state.limit_bytes.lock().await;
*limit = limit_bytes;
// Check if we need to evict
if let Some(limit_bytes) = limit_bytes {
drop(limit);
evict_if_needed(&cache_state, limit_bytes).await?;
}
Ok(())
}
/// Open the cache folder in the system file manager
#[tauri::command]
pub async fn open_offline_cache_folder(
cache_state: State<'_, OfflineCacheState>,
) -> Result<(), String> {
log::info!("Command: open_offline_cache_folder");
let path = cache_state.cache_dir.clone();
// Ensure directory exists
std::fs::create_dir_all(&path)
.map_err(|e| format!("Failed to create cache directory: {}", e))?;
// Open with system file manager
open::that(&path).map_err(|e| format!("Failed to open folder: {}", e))?;
Ok(())
}
/// Open the folder containing a specific album in the system file manager
#[tauri::command]
pub async fn open_album_folder(
album_id: String,
cache_state: State<'_, OfflineCacheState>,
) -> Result<(), String> {
log::info!("Command: open_album_folder for album_id: {}", album_id);
let db = cache_state.db.lock().await;
// Get tracks for this album
let tracks = db.get_all_tracks()?;
let album_tracks: Vec<_> = tracks
.into_iter()
.filter(|t| t.album_id.as_deref() == Some(&album_id))
.collect();
if album_tracks.is_empty() {
return Err("No cached tracks found for this album".to_string());
}
// Get the first track's path and extract the album directory
let first_track_id = album_tracks[0].track_id;
let file_path = db.get_file_path(first_track_id)?
.ok_or_else(|| "Track file path not found".to_string())?;
let track_path = std::path::Path::new(&file_path);
let album_dir = track_path
.parent()
.ok_or_else(|| "Could not determine album folder".to_string())?;
if !album_dir.exists() {
return Err("Album folder does not exist".to_string());
}
// Open with system file manager
open::that(album_dir).map_err(|e| format!("Failed to open folder: {}", e))?;
Ok(())
}
/// Open the folder containing a specific track in the system file manager
#[tauri::command]
pub async fn open_track_folder(
track_id: u64,
cache_state: State<'_, OfflineCacheState>,
) -> Result<(), String> {
log::info!("Command: open_track_folder for track_id: {}", track_id);
let db = cache_state.db.lock().await;
// Get the track's file path
let file_path = db.get_file_path(track_id)?
.ok_or_else(|| "Track file path not found - track may not be cached".to_string())?;
let track_path = std::path::Path::new(&file_path);
let track_dir = track_path
.parent()
.ok_or_else(|| "Could not determine track folder".to_string())?;
if !track_dir.exists() {
return Err("Track folder does not exist".to_string());
}
// Open with system file manager
open::that(track_dir).map_err(|e| format!("Failed to open folder: {}", e))?;
Ok(())
}
/// Check if an album is fully cached (all tracks ready)
#[tauri::command]
pub async fn check_album_fully_cached(
album_id: String,
cache_state: State<'_, OfflineCacheState>,
) -> Result<bool, String> {
let db = cache_state.db.lock().await;
// Get all tracks for this album
let tracks = db.get_all_tracks()?;
let album_tracks: Vec<_> = tracks
.into_iter()
.filter(|t| t.album_id.as_deref() == Some(&album_id))
.collect();
if album_tracks.is_empty() {
return Ok(false);
}
// Check if all tracks are ready
for track in album_tracks {
if track.status != crate::offline_cache::OfflineCacheStatus::Ready {
return Ok(false);
}
}
Ok(true)
}
/// Evict tracks if cache exceeds limit (LRU policy)
async fn evict_if_needed(
cache_state: &OfflineCacheState,
limit_bytes: u64,
) -> Result<(), String> {
let db = cache_state.db.lock().await;
let stats = db.get_stats(&cache_state.get_cache_path(), Some(limit_bytes))?;
if stats.total_size_bytes <= limit_bytes {
return Ok(());
}
let bytes_to_free = stats.total_size_bytes - limit_bytes;
log::info!(
"Cache exceeds limit ({} > {}), need to free {} bytes",
stats.total_size_bytes,
limit_bytes,
bytes_to_free
);
let tracks_to_evict = db.get_tracks_for_eviction(bytes_to_free)?;
for (track_id, file_path) in tracks_to_evict {
log::info!("Evicting track {} from cache", track_id);
// Delete from DB
db.delete_track(track_id)?;
// Delete file
let path = std::path::Path::new(&file_path);
if path.exists() {
let _ = std::fs::remove_file(path);
}
}
Ok(())
}
// Path management commands
#[tauri::command]
pub async fn check_offline_root_mounted(
cache_state: State<'_, OfflineCacheState>,
) -> Result<bool, String> {
log::info!("Command: check_offline_root_mounted");
let root_path = cache_state.cache_dir.to_string_lossy().to_string();
super::path_validator::is_offline_root_available(&root_path)
}
#[tauri::command]
pub async fn validate_offline_path(path: String) -> Result<super::path_validator::PathValidationResult, String> {
log::info!("Command: validate_offline_path: {}", path);
super::path_validator::validate_path(&path)
}
#[tauri::command]
pub async fn move_offline_cache_to_path(
new_path: String,
cache_state: State<'_, OfflineCacheState>,
) -> Result<super::path_validator::MoveReport, String> {
log::info!("Command: move_offline_cache_to_path: {}", new_path);
let old_path = cache_state.cache_dir.to_string_lossy().to_string();
super::path_validator::move_cached_files_to_new_path(&old_path, &new_path)
}
/// Detect legacy cached files (numeric FLAC files)
#[tauri::command]
pub async fn detect_legacy_cached_files(
cache_state: State<'_, OfflineCacheState>,
) -> Result<super::MigrationStatus, String> {
log::info!("Command: detect_legacy_cached_files");
let tracks_dir = cache_state.cache_dir.join("tracks");
match super::detect_legacy_cached_files(&tracks_dir) {
Ok(track_ids) => {
Ok(super::MigrationStatus {
has_legacy_files: !track_ids.is_empty(),
total_tracks: track_ids.len(),
..Default::default()
})
}
Err(e) => Err(e),
}
}
/// Start migration of legacy cached files
#[tauri::command]
pub async fn start_legacy_migration(
state: State<'_, AppState>,
cache_state: State<'_, OfflineCacheState>,
library_state: State<'_, crate::library::commands::LibraryState>,
app_handle: AppHandle,
) -> Result<(), String> {
log::info!("Command: start_legacy_migration");
let tracks_dir = cache_state.cache_dir.join("tracks");
let track_ids = super::detect_legacy_cached_files(&tracks_dir)?;
if track_ids.is_empty() {
return Err("No legacy cached files found".to_string());
}
let offline_root = cache_state.get_cache_path();
let qobuz_client = state.client.clone();
let library_db = library_state.db.clone();
let app_complete = app_handle.clone();
// Spawn migration task
tokio::spawn(async move {
let status = super::migrate_legacy_cached_files(
track_ids,
tracks_dir,
offline_root,
qobuz_client,
library_db,
).await;
let _ = app_complete.emit("migration:complete", status);
});
Ok(())
}
/// Sync cached tracks to library database
/// This ensures all ready cached tracks appear in the library with source='qobuz_cached'
#[tauri::command]
pub async fn sync_offline_cache_to_library(
cache_state: State<'_, OfflineCacheState>,
library_state: State<'_, crate::library::commands::LibraryState>,
) -> Result<SyncResult, String> {
log::info!("Command: sync_offline_cache_to_library");
let cache_db = cache_state.db.lock().await;
let library_db = library_state.db.lock().await;
// Get all ready tracks from offline cache
let ready_tracks = cache_db.get_ready_tracks_for_sync()?;
let mut synced = 0;
let mut already_present = 0;
let mut errors = 0;
for track in ready_tracks {
// Check if track already exists in library
match library_db.track_exists_by_qobuz_id(track.track_id) {
Ok(true) => {
already_present += 1;
}
Ok(false) => {
// Insert into library with basic metadata
match library_db.insert_qobuz_cached_track_direct(
track.track_id,
&track.title,
&track.artist,
track.album.as_deref(),
track.duration_secs,
&track.file_path,
track.bit_depth,
track.sample_rate,
) {
Ok(_) => {
log::info!("Synced track {} to library: {}", track.track_id, track.title);
synced += 1;
}
Err(e) => {
log::error!("Failed to sync track {}: {}", track.track_id, e);
errors += 1;
}
}
}
Err(e) => {
log::error!("Failed to check if track {} exists: {}", track.track_id, e);
errors += 1;
}
}
}
log::info!(
"Sync complete: {} synced, {} already present, {} errors",
synced, already_present, errors
);
Ok(SyncResult {
synced,
already_present,
errors,
})
}
/// Result of syncing downloads to library
#[derive(Debug, Clone, serde::Serialize)]
#[serde(rename_all = "camelCase")]
pub struct SyncResult {
pub synced: u32,
pub already_present: u32,
pub errors: u32,
}
+375
View File
@@ -0,0 +1,375 @@
//! SQLite database for offline cache index
use rusqlite::{Connection, params};
use std::path::Path;
use super::{CachedTrackInfo, OfflineCacheStats, OfflineCacheStatus, ReadyTrackForSync, TrackCacheInfo};
/// Database wrapper for cached tracks index
pub struct OfflineCacheDb {
conn: Connection,
}
impl OfflineCacheDb {
/// Open or create the database
pub fn new(path: &Path) -> Result<Self, String> {
let conn = Connection::open(path)
.map_err(|e| format!("Failed to open offline cache database: {}", e))?;
let db = Self { conn };
db.init_schema()?;
Ok(db)
}
/// Get reference to the connection (for direct queries)
pub fn conn(&self) -> &Connection {
&self.conn
}
/// Initialize database schema
fn init_schema(&self) -> Result<(), String> {
self.conn.execute_batch(
"
CREATE TABLE IF NOT EXISTS cached_tracks (
id INTEGER PRIMARY KEY AUTOINCREMENT,
track_id INTEGER UNIQUE NOT NULL,
title TEXT NOT NULL,
artist TEXT NOT NULL,
album TEXT,
album_id TEXT,
duration_secs INTEGER NOT NULL,
file_path TEXT NOT NULL,
file_size_bytes INTEGER NOT NULL DEFAULT 0,
format TEXT NOT NULL DEFAULT 'flac',
quality TEXT,
bit_depth INTEGER,
sample_rate REAL,
artwork_path TEXT,
status TEXT NOT NULL DEFAULT 'queued',
progress_percent INTEGER NOT NULL DEFAULT 0,
error_message TEXT,
created_at TEXT NOT NULL DEFAULT (datetime('now')),
last_accessed_at TEXT NOT NULL DEFAULT (datetime('now'))
);
CREATE INDEX IF NOT EXISTS idx_track_id ON cached_tracks(track_id);
CREATE INDEX IF NOT EXISTS idx_status ON cached_tracks(status);
CREATE INDEX IF NOT EXISTS idx_last_accessed ON cached_tracks(last_accessed_at);
"
).map_err(|e| format!("Failed to initialize database schema: {}", e))?;
Ok(())
}
/// Insert a new track to cache for offline
pub fn insert_track(&self, info: &TrackCacheInfo, file_path: &str) -> Result<(), String> {
self.conn.execute(
"INSERT OR REPLACE INTO cached_tracks
(track_id, title, artist, album, album_id, duration_secs, file_path, quality, bit_depth, sample_rate, status, progress_percent, created_at, last_accessed_at)
VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8, ?9, ?10, 'queued', 0, datetime('now'), datetime('now'))",
params![
info.track_id as i64,
info.title,
info.artist,
info.album,
info.album_id,
info.duration_secs as i64,
file_path,
info.quality,
info.bit_depth.map(|v| v as i64),
info.sample_rate,
],
).map_err(|e| format!("Failed to insert track: {}", e))?;
Ok(())
}
/// Update track status
pub fn update_status(&self, track_id: u64, status: OfflineCacheStatus, error: Option<&str>) -> Result<(), String> {
self.conn.execute(
"UPDATE cached_tracks SET status = ?1, error_message = ?2 WHERE track_id = ?3",
params![status.as_str(), error, track_id as i64],
).map_err(|e| format!("Failed to update status: {}", e))?;
Ok(())
}
/// Update caching progress
pub fn update_progress(&self, track_id: u64, progress: u8, size_bytes: u64) -> Result<(), String> {
self.conn.execute(
"UPDATE cached_tracks SET progress_percent = ?1, file_size_bytes = ?2 WHERE track_id = ?3",
params![progress as i64, size_bytes as i64, track_id as i64],
).map_err(|e| format!("Failed to update progress: {}", e))?;
Ok(())
}
/// Mark caching as complete
pub fn mark_complete(&self, track_id: u64, file_size: u64) -> Result<(), String> {
self.conn.execute(
"UPDATE cached_tracks SET status = 'ready', progress_percent = 100, file_size_bytes = ?1, last_accessed_at = datetime('now') WHERE track_id = ?2",
params![file_size as i64, track_id as i64],
).map_err(|e| format!("Failed to mark complete: {}", e))?;
Ok(())
}
/// Update last accessed time (for LRU)
pub fn touch(&self, track_id: u64) -> Result<(), String> {
self.conn.execute(
"UPDATE cached_tracks SET last_accessed_at = datetime('now') WHERE track_id = ?1",
params![track_id as i64],
).map_err(|e| format!("Failed to update access time: {}", e))?;
Ok(())
}
/// Check if a track is cached and ready
pub fn is_cached(&self, track_id: u64) -> Result<bool, String> {
let count: i64 = self.conn.query_row(
"SELECT COUNT(*) FROM cached_tracks WHERE track_id = ?1 AND status = 'ready'",
params![track_id as i64],
|row| row.get(0),
).map_err(|e| format!("Failed to check cache: {}", e))?;
Ok(count > 0)
}
/// Get file path for a cached track
pub fn get_file_path(&self, track_id: u64) -> Result<Option<String>, String> {
let result = self.conn.query_row(
"SELECT file_path FROM cached_tracks WHERE track_id = ?1 AND status = 'ready'",
params![track_id as i64],
|row| row.get(0),
);
match result {
Ok(path) => Ok(Some(path)),
Err(rusqlite::Error::QueryReturnedNoRows) => Ok(None),
Err(e) => Err(format!("Failed to get file path: {}", e)),
}
}
/// Get all ready (cached) tracks with their file paths for syncing to library
pub fn get_ready_tracks_for_sync(&self) -> Result<Vec<ReadyTrackForSync>, String> {
let mut stmt = self.conn.prepare(
"SELECT track_id, title, artist, album, duration_secs, file_path, bit_depth, sample_rate
FROM cached_tracks WHERE status = 'ready'"
).map_err(|e| format!("Failed to prepare query: {}", e))?;
let tracks = stmt.query_map([], |row| {
Ok(ReadyTrackForSync {
track_id: row.get::<_, i64>(0)? as u64,
title: row.get(1)?,
artist: row.get(2)?,
album: row.get(3)?,
duration_secs: row.get::<_, i64>(4)? as u64,
file_path: row.get(5)?,
bit_depth: row.get::<_, Option<i64>>(6)?.map(|v| v as u32),
sample_rate: row.get(7)?,
})
}).map_err(|e| format!("Failed to query tracks: {}", e))?;
let mut result = Vec::new();
for track in tracks {
result.push(track.map_err(|e| format!("Failed to read track: {}", e))?);
}
Ok(result)
}
/// Get track info
pub fn get_track(&self, track_id: u64) -> Result<Option<CachedTrackInfo>, String> {
let result = self.conn.query_row(
"SELECT track_id, title, artist, album, album_id, duration_secs, file_size_bytes, quality, bit_depth, sample_rate, status, progress_percent, error_message, created_at, last_accessed_at
FROM cached_tracks WHERE track_id = ?1",
params![track_id as i64],
|row| {
Ok(CachedTrackInfo {
track_id: row.get::<_, i64>(0)? as u64,
title: row.get(1)?,
artist: row.get(2)?,
album: row.get(3)?,
album_id: row.get(4)?,
duration_secs: row.get::<_, i64>(5)? as u64,
file_size_bytes: row.get::<_, i64>(6)? as u64,
quality: row.get::<_, Option<String>>(7)?.unwrap_or_default(),
bit_depth: row.get::<_, Option<i64>>(8)?.map(|v| v as u32),
sample_rate: row.get(9)?,
status: OfflineCacheStatus::from_str(&row.get::<_, String>(10)?),
progress_percent: row.get::<_, i64>(11)? as u8,
error_message: row.get(12)?,
created_at: row.get(13)?,
last_accessed_at: row.get(14)?,
})
},
);
match result {
Ok(info) => Ok(Some(info)),
Err(rusqlite::Error::QueryReturnedNoRows) => Ok(None),
Err(e) => Err(format!("Failed to get track: {}", e)),
}
}
/// Get all cached tracks
pub fn get_all_tracks(&self) -> Result<Vec<CachedTrackInfo>, String> {
let mut stmt = self.conn.prepare(
"SELECT track_id, title, artist, album, album_id, duration_secs, file_size_bytes, quality, bit_depth, sample_rate, status, progress_percent, error_message, created_at, last_accessed_at
FROM cached_tracks ORDER BY last_accessed_at DESC"
).map_err(|e| format!("Failed to prepare query: {}", e))?;
let tracks = stmt.query_map([], |row| {
Ok(CachedTrackInfo {
track_id: row.get::<_, i64>(0)? as u64,
title: row.get(1)?,
artist: row.get(2)?,
album: row.get(3)?,
album_id: row.get(4)?,
duration_secs: row.get::<_, i64>(5)? as u64,
file_size_bytes: row.get::<_, i64>(6)? as u64,
quality: row.get::<_, Option<String>>(7)?.unwrap_or_default(),
bit_depth: row.get::<_, Option<i64>>(8)?.map(|v| v as u32),
sample_rate: row.get(9)?,
status: OfflineCacheStatus::from_str(&row.get::<_, String>(10)?),
progress_percent: row.get::<_, i64>(11)? as u8,
error_message: row.get(12)?,
created_at: row.get(13)?,
last_accessed_at: row.get(14)?,
})
}).map_err(|e| format!("Failed to query tracks: {}", e))?;
let mut result = Vec::new();
for track in tracks {
result.push(track.map_err(|e| format!("Failed to read track: {}", e))?);
}
Ok(result)
}
/// Delete a track from cache
pub fn delete_track(&self, track_id: u64) -> Result<Option<String>, String> {
// Get file path before deleting
let file_path: Option<String> = self.conn.query_row(
"SELECT file_path FROM cached_tracks WHERE track_id = ?1",
params![track_id as i64],
|row| row.get(0),
).ok();
self.conn.execute(
"DELETE FROM cached_tracks WHERE track_id = ?1",
params![track_id as i64],
).map_err(|e| format!("Failed to delete track: {}", e))?;
Ok(file_path)
}
/// Get statistics
pub fn get_stats(&self, cache_path: &str, limit_bytes: Option<u64>) -> Result<OfflineCacheStats, String> {
let total_tracks: i64 = self.conn.query_row(
"SELECT COUNT(*) FROM cached_tracks",
[],
|row| row.get(0),
).map_err(|e| format!("Failed to count tracks: {}", e))?;
let ready_tracks: i64 = self.conn.query_row(
"SELECT COUNT(*) FROM cached_tracks WHERE status = 'ready'",
[],
|row| row.get(0),
).map_err(|e| format!("Failed to count ready tracks: {}", e))?;
let downloading_tracks: i64 = self.conn.query_row(
"SELECT COUNT(*) FROM cached_tracks WHERE status = 'downloading' OR status = 'queued'",
[],
|row| row.get(0),
).map_err(|e| format!("Failed to count downloading tracks: {}", e))?;
let failed_tracks: i64 = self.conn.query_row(
"SELECT COUNT(*) FROM cached_tracks WHERE status = 'failed'",
[],
|row| row.get(0),
).map_err(|e| format!("Failed to count failed tracks: {}", e))?;
let total_size: i64 = self.conn.query_row(
"SELECT COALESCE(SUM(file_size_bytes), 0) FROM cached_tracks WHERE status = 'ready'",
[],
|row| row.get(0),
).map_err(|e| format!("Failed to sum sizes: {}", e))?;
Ok(OfflineCacheStats {
total_tracks: total_tracks as usize,
ready_tracks: ready_tracks as usize,
downloading_tracks: downloading_tracks as usize,
failed_tracks: failed_tracks as usize,
total_size_bytes: total_size as u64,
limit_bytes,
cache_path: cache_path.to_string(),
})
}
/// Get tracks to evict (LRU order) to free up space
pub fn get_tracks_for_eviction(&self, bytes_to_free: u64) -> Result<Vec<(u64, String)>, String> {
let mut stmt = self.conn.prepare(
"SELECT track_id, file_path, file_size_bytes FROM cached_tracks
WHERE status = 'ready'
ORDER BY last_accessed_at ASC"
).map_err(|e| format!("Failed to prepare eviction query: {}", e))?;
let mut result = Vec::new();
let mut freed = 0u64;
let rows = stmt.query_map([], |row| {
Ok((
row.get::<_, i64>(0)? as u64,
row.get::<_, String>(1)?,
row.get::<_, i64>(2)? as u64,
))
}).map_err(|e| format!("Failed to query for eviction: {}", e))?;
for row in rows {
if freed >= bytes_to_free {
break;
}
let (track_id, file_path, size) = row.map_err(|e| format!("Failed to read row: {}", e))?;
result.push((track_id, file_path));
freed += size;
}
Ok(result)
}
/// Clear all entries
pub fn clear_all(&self) -> Result<Vec<String>, String> {
// Get all file paths first
let mut stmt = self.conn.prepare("SELECT file_path FROM cached_tracks")
.map_err(|e| format!("Failed to prepare query: {}", e))?;
let paths: Vec<String> = stmt.query_map([], |row| row.get(0))
.map_err(|e| format!("Failed to query paths: {}", e))?
.filter_map(|r| r.ok())
.collect();
self.conn.execute("DELETE FROM cached_tracks", [])
.map_err(|e| format!("Failed to clear database: {}", e))?;
Ok(paths)
}
/// Update file path for a track (after organizing)
pub fn update_file_path(&self, track_id: u64, new_path: &str) -> Result<(), String> {
self.conn.execute(
"UPDATE cached_tracks SET file_path = ?1 WHERE track_id = ?2",
params![new_path, track_id as i64],
).map_err(|e| format!("Failed to update file path: {}", e))?;
Ok(())
}
/// Update artwork path for a track
pub fn update_artwork_path(&self, track_id: u64, artwork_path: &str) -> Result<(), String> {
self.conn.execute(
"UPDATE cached_tracks SET artwork_path = ?1 WHERE track_id = ?2",
params![artwork_path, track_id as i64],
).map_err(|e| format!("Failed to update artwork path: {}", e))?;
Ok(())
}
}
+163
View File
@@ -0,0 +1,163 @@
//! Stream fetcher for caching tracks to disk
use std::io::Write;
use std::path::Path;
use std::time::Duration;
use tauri::{AppHandle, Emitter};
use super::{CacheProgress, OfflineCacheStatus};
/// StreamFetcher handles fetching audio streams and caching them to disk
pub struct StreamFetcher {
client: reqwest::Client,
}
impl StreamFetcher {
pub fn new() -> Self {
let client = reqwest::Client::builder()
.timeout(Duration::from_secs(300)) // 5 minute timeout for large files
.connect_timeout(Duration::from_secs(15))
.build()
.expect("Failed to create HTTP client");
Self { client }
}
/// Fetch a stream and cache it to disk with progress updates
pub async fn fetch_to_file(
&self,
url: &str,
dest_path: &Path,
track_id: u64,
app_handle: Option<&AppHandle>,
) -> Result<u64, String> {
log::info!("Caching track {} to {:?}", track_id, dest_path);
// Create parent directories if needed
if let Some(parent) = dest_path.parent() {
std::fs::create_dir_all(parent)
.map_err(|e| format!("Failed to create directory: {}", e))?;
}
// Start fetching
let response = self
.client
.get(url)
.header("User-Agent", "Mozilla/5.0")
.send()
.await
.map_err(|e| format!("Failed to start fetch: {}", e))?;
if !response.status().is_success() {
return Err(format!("HTTP error: {}", response.status()));
}
let total_size = response.content_length();
log::info!(
"Caching started for track {}, total size: {:?} bytes",
track_id,
total_size
);
// Create temp file for caching
let temp_path = dest_path.with_extension("tmp");
let mut file = std::fs::File::create(&temp_path)
.map_err(|e| format!("Failed to create temp file: {}", e))?;
let mut cached: u64 = 0;
let mut last_progress: u8 = 0;
// Stream the response body
let mut stream = response.bytes_stream();
use futures_util::StreamExt;
while let Some(chunk_result) = stream.next().await {
let chunk = chunk_result.map_err(|e| format!("Fetch error: {}", e))?;
file.write_all(&chunk)
.map_err(|e| format!("Failed to write chunk: {}", e))?;
cached += chunk.len() as u64;
// Calculate progress
let progress = if let Some(total) = total_size {
((cached as f64 / total as f64) * 100.0) as u8
} else {
// If we don't know total size, report bytes cached
0
};
// Emit progress event every 2% change
if progress != last_progress && (progress - last_progress >= 2 || progress == 100) {
last_progress = progress;
if let Some(app) = app_handle {
let _ = app.emit(
"offline:caching_progress",
CacheProgress {
track_id,
progress_percent: progress,
bytes_downloaded: cached,
total_bytes: total_size,
status: OfflineCacheStatus::Downloading,
},
);
}
log::debug!(
"Caching progress for track {}: {}% ({}/{:?} bytes)",
track_id,
progress,
cached,
total_size
);
}
}
// Ensure all data is written
file.flush()
.map_err(|e| format!("Failed to flush file: {}", e))?;
drop(file);
// Move temp file to final destination
std::fs::rename(&temp_path, dest_path)
.map_err(|e| format!("Failed to move temp file: {}", e))?;
log::info!(
"Caching complete for track {}: {} bytes",
track_id,
cached
);
Ok(cached)
}
/// Fetch to memory (for smaller files or streaming)
pub async fn fetch_to_memory(&self, url: &str) -> Result<Vec<u8>, String> {
let response = self
.client
.get(url)
.header("User-Agent", "Mozilla/5.0")
.send()
.await
.map_err(|e| format!("Failed to fetch: {}", e))?;
if !response.status().is_success() {
return Err(format!("HTTP error: {}", response.status()));
}
let bytes = response
.bytes()
.await
.map_err(|e| format!("Failed to read bytes: {}", e))?;
Ok(bytes.to_vec())
}
}
impl Default for StreamFetcher {
fn default() -> Self {
Self::new()
}
}
+371
View File
@@ -0,0 +1,371 @@
//! Metadata fetching and FLAC tagging for cached tracks
//!
//! Handles complete metadata retrieval from Qobuz API and writing to FLAC tags.
use serde::{Deserialize, Serialize};
use lofty::{
Accessor, AudioFile, ItemKey, Picture, PictureType, Tag, TagExt, TaggedFileExt,
};
use std::path::Path;
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct CompleteTrackMetadata {
pub track_id: u64,
pub title: String,
pub artist: String,
pub album: String,
pub album_artist: Option<String>,
pub track_number: Option<u32>,
pub disc_number: Option<u32>,
pub year: Option<u32>,
pub genre: Option<String>,
pub isrc: Option<String>,
pub label: Option<String>,
pub copyright: Option<String>,
pub composer: Option<String>,
pub duration_secs: u64,
pub artwork_url: Option<String>,
}
/// Fetch complete metadata for a track from Qobuz API
pub async fn fetch_complete_metadata(
track_id: u64,
qobuz_client: &crate::api::QobuzClient,
) -> Result<CompleteTrackMetadata, String> {
log::info!("Fetching complete metadata for track {}", track_id);
let track = qobuz_client
.get_track(track_id)
.await
.map_err(|e| format!("Failed to fetch track: {}", e))?;
let album = if let Some(album_obj) = &track.album {
qobuz_client
.get_album(&album_obj.id)
.await
.ok()
} else {
None
};
let album_artist = album
.as_ref()
.map(|a| a.artist.name.clone())
.or_else(|| track.performer.as_ref().map(|p| p.name.clone()));
let genre = album
.as_ref()
.and_then(|a| a.genre.as_ref())
.map(|g| g.name.clone());
let label = album
.as_ref()
.and_then(|a| a.label.as_ref())
.map(|l| l.name.clone());
let year = album
.as_ref()
.and_then(|a| a.release_date_original.as_ref())
.and_then(|date_str| {
// Parse YYYY-MM-DD or YYYY format
date_str.split('-').next()
.and_then(|year_str| year_str.parse::<u32>().ok())
});
let artwork_url = album
.as_ref()
.and_then(|a| a.image.large.clone())
.or_else(|| {
track.album.as_ref()
.and_then(|a| a.image.large.clone())
});
Ok(CompleteTrackMetadata {
track_id,
title: track.title,
artist: track.performer.as_ref().map(|p| p.name.clone()).unwrap_or_default(),
album: track.album.as_ref().map(|a| a.title.clone()).unwrap_or_default(),
album_artist,
track_number: Some(track.track_number),
disc_number: track.media_number,
year,
genre,
isrc: track.isrc.clone(),
label,
copyright: None, // Qobuz API doesn't provide copyright in album model
composer: None, // Qobuz API doesn't provide composer in track model
duration_secs: track.duration as u64,
artwork_url,
})
}
/// Write metadata tags to a FLAC file
pub fn write_flac_tags(
file_path: &str,
metadata: &CompleteTrackMetadata,
) -> Result<(), String> {
log::info!("Writing FLAC tags to: {}", file_path);
let path = Path::new(file_path);
let mut tagged_file = lofty::read_from_path(path)
.map_err(|e| format!("Failed to read FLAC file: {}", e))?;
let tag = match tagged_file.primary_tag_mut() {
Some(primary_tag) => primary_tag,
None => {
let tag_type = tagged_file.primary_tag_type();
tagged_file.insert_tag(Tag::new(tag_type));
tagged_file.primary_tag_mut().unwrap()
}
};
// Clear existing tags
tag.clear();
// Write standard Vorbis comments
tag.set_title(metadata.title.clone());
tag.set_artist(metadata.artist.clone());
tag.set_album(metadata.album.clone());
if let Some(album_artist) = &metadata.album_artist {
tag.insert_text(ItemKey::AlbumArtist, album_artist.clone());
}
if let Some(track_number) = metadata.track_number {
tag.set_track(track_number);
}
if let Some(disc_number) = metadata.disc_number {
tag.set_disk(disc_number);
}
if let Some(year) = metadata.year {
tag.set_year(year);
}
if let Some(genre) = &metadata.genre {
tag.set_genre(genre.clone());
}
if let Some(isrc) = &metadata.isrc {
tag.insert_text(ItemKey::Unknown("ISRC".to_string()), isrc.clone());
}
if let Some(label) = &metadata.label {
tag.insert_text(ItemKey::Label, label.clone());
}
if let Some(copyright) = &metadata.copyright {
tag.insert_text(ItemKey::CopyrightMessage, copyright.clone());
}
if let Some(composer) = &metadata.composer {
tag.insert_text(ItemKey::Composer, composer.clone());
}
// Save tags
tagged_file
.save_to_path(path)
.map_err(|e| format!("Failed to save tags: {}", e))?;
Ok(())
}
/// Download and embed artwork in FLAC file
pub async fn embed_artwork(
file_path: &str,
artwork_url: &str,
) -> Result<(), String> {
log::info!("Embedding artwork from: {}", artwork_url);
// Download artwork
let response = reqwest::get(artwork_url)
.await
.map_err(|e| format!("Failed to download artwork: {}", e))?;
let artwork_bytes = response
.bytes()
.await
.map_err(|e| format!("Failed to read artwork bytes: {}", e))?;
// Determine MIME type from URL
let mime_type = if artwork_url.contains(".jpg") || artwork_url.contains(".jpeg") {
lofty::MimeType::Jpeg
} else if artwork_url.contains(".png") {
lofty::MimeType::Png
} else {
lofty::MimeType::Jpeg // Default to JPEG
};
// Create picture
let picture = Picture::new_unchecked(
PictureType::CoverFront,
Some(mime_type),
None,
artwork_bytes.to_vec(),
);
// Read file
let path = Path::new(file_path);
let mut tagged_file = lofty::read_from_path(path)
.map_err(|e| format!("Failed to read FLAC file: {}", e))?;
// Add picture to primary tag
if let Some(tag) = tagged_file.primary_tag_mut() {
tag.push_picture(picture);
} else {
let tag_type = tagged_file.primary_tag_type();
let mut tag = Tag::new(tag_type);
tag.push_picture(picture);
tagged_file.insert_tag(tag);
}
// Save
tagged_file
.save_to_path(path)
.map_err(|e| format!("Failed to save artwork: {}", e))?;
Ok(())
}
/// Sanitize filename to be ASCII-safe and filesystem-compatible
pub fn sanitize_filename(name: &str) -> String {
// Remove or replace invalid characters
let invalid_chars = ['/', '\\', ':', '*', '?', '"', '<', '>', '|'];
let mut sanitized = name
.chars()
.map(|c| {
if invalid_chars.contains(&c) {
'-'
} else if c.is_ascii() || c.is_alphanumeric() {
c
} else {
'-'
}
})
.collect::<String>();
// Replace multiple consecutive dashes with single dash
while sanitized.contains("--") {
sanitized = sanitized.replace("--", "-");
}
// Trim dashes and whitespace from ends
sanitized = sanitized.trim_matches('-').trim().to_string();
// Limit length to 200 chars (leaving room for extension and path)
if sanitized.len() > 200 {
sanitized.truncate(200);
sanitized = sanitized.trim_matches('-').trim().to_string();
}
// If empty after sanitization, use fallback
if sanitized.is_empty() {
sanitized = "track".to_string();
}
sanitized
}
/// Download and save album cover art as a file
pub async fn save_album_artwork(
album_dir: &Path,
artwork_url: &str,
) -> Result<(), String> {
log::info!("Downloading album artwork to: {:?}", album_dir);
let cover_path = album_dir.join("cover.jpg");
// Skip if cover already exists
if cover_path.exists() {
log::debug!("Cover art already exists at {:?}", cover_path);
return Ok(());
}
// Download artwork
let response = reqwest::get(artwork_url)
.await
.map_err(|e| format!("Failed to download album artwork: {}", e))?;
let artwork_bytes = response
.bytes()
.await
.map_err(|e| format!("Failed to read album artwork bytes: {}", e))?;
// Write to file
std::fs::write(&cover_path, artwork_bytes)
.map_err(|e| format!("Failed to write cover.jpg: {}", e))?;
log::info!("Album artwork saved to: {:?}", cover_path);
Ok(())
}
/// Organize cached file into proper folder structure
pub fn organize_cached_file(
track_id: u64,
temp_path: &str,
root_dir: &str,
metadata: &CompleteTrackMetadata,
) -> Result<String, String> {
log::info!("Organizing cached file for track {}", track_id);
let temp = Path::new(temp_path);
let root = Path::new(root_dir);
// Build target path: <root>/<artist>/<album>/[Disc N/]NN - Title.flac
let artist_dir = sanitize_filename(&metadata.album_artist.as_ref().unwrap_or(&metadata.artist));
let album_dir = sanitize_filename(&metadata.album);
let mut target_dir = root.join(&artist_dir).join(&album_dir);
// Add disc subfolder if multi-disc
if let Some(disc) = metadata.disc_number {
if disc > 1 {
target_dir = target_dir.join(format!("Disc {}", disc));
}
}
// Create directory structure
std::fs::create_dir_all(&target_dir)
.map_err(|e| format!("Failed to create directories: {}", e))?;
// Build filename: NN - Title.flac
let track_num = metadata.track_number.unwrap_or(0);
let title_clean = sanitize_filename(&metadata.title);
let filename = if track_num > 0 {
format!("{:02} - {}.flac", track_num, title_clean)
} else {
format!("{}.flac", title_clean)
};
let target_path = target_dir.join(&filename);
// Handle filename conflicts
let final_path = if target_path.exists() {
let mut counter = 2;
loop {
let alt_filename = if track_num > 0 {
format!("{:02} - {} ({}).flac", track_num, title_clean, counter)
} else {
format!("{} ({}).flac", title_clean, counter)
};
let alt_path = target_dir.join(&alt_filename);
if !alt_path.exists() {
break alt_path;
}
counter += 1;
if counter > 100 {
return Err("Too many filename conflicts".to_string());
}
}
} else {
target_path
};
// Move file
std::fs::rename(temp, &final_path)
.map_err(|e| format!("Failed to move file: {}", e))?;
Ok(final_path.to_string_lossy().to_string())
}
+228
View File
@@ -0,0 +1,228 @@
//! Legacy cached file migration service
//!
//! Handles migration of old numeric-named FLAC files to new organized structure
use std::path::{Path, PathBuf};
use std::sync::Arc;
use serde::Serialize;
use tokio::sync::Mutex;
use crate::api::QobuzClient;
use crate::library::database::LibraryDatabase;
use super::metadata::{fetch_complete_metadata, write_flac_tags, embed_artwork, organize_cached_file, save_album_artwork};
#[derive(Default, Serialize, Clone, Debug)]
pub struct MigrationStatus {
pub has_legacy_files: bool,
pub total_tracks: usize,
pub processed: usize,
pub successful: usize,
pub failed: usize,
pub in_progress: bool,
pub completed: bool,
pub errors: Vec<MigrationError>,
}
#[derive(Serialize, Clone, Debug)]
pub struct MigrationError {
pub track_id: u64,
pub error_message: String,
}
/// Detect legacy cached files (numeric FLAC files in tracks/ folder)
pub fn detect_legacy_cached_files(tracks_dir: &Path) -> Result<Vec<u64>, String> {
log::info!("Scanning for legacy cached files in: {}", tracks_dir.display());
if !tracks_dir.exists() {
return Ok(Vec::new());
}
let mut track_ids = Vec::new();
match std::fs::read_dir(tracks_dir) {
Ok(entries) => {
for entry in entries.flatten() {
let path = entry.path();
// Only process FLAC files
if path.extension().and_then(|s| s.to_str()) != Some("flac") {
continue;
}
// Check if filename is purely numeric (track_id)
if let Some(filename) = path.file_stem().and_then(|s| s.to_str()) {
if let Ok(track_id) = filename.parse::<u64>() {
track_ids.push(track_id);
log::debug!("Found legacy track: {}", track_id);
}
}
}
}
Err(e) => {
return Err(format!("Failed to read tracks directory: {}", e));
}
}
log::info!("Found {} legacy cached files", track_ids.len());
Ok(track_ids)
}
/// Migrate a single legacy cached track
async fn migrate_single_track(
track_id: u64,
legacy_path: PathBuf,
offline_root: &str,
qobuz_client: &QobuzClient,
library_db: Arc<Mutex<LibraryDatabase>>,
) -> Result<String, String> {
log::info!("Migrating track {}", track_id);
// 1. Fetch complete metadata from Qobuz
let metadata = fetch_complete_metadata(track_id, qobuz_client).await?;
// 2. Write FLAC tags
let legacy_path_str = legacy_path.to_string_lossy().to_string();
write_flac_tags(&legacy_path_str, &metadata)
.map_err(|e| format!("Failed to write tags: {}", e))?;
// 3. Embed artwork if available
if let Some(artwork_url) = &metadata.artwork_url {
if let Err(e) = embed_artwork(&legacy_path_str, artwork_url).await {
log::warn!("Failed to embed artwork for track {}: {}", track_id, e);
}
}
// 4. Organize file into artist/album structure
let new_path = organize_cached_file(track_id, &legacy_path_str, offline_root, &metadata)?;
// 5. Save album artwork as cover.jpg
let artwork_path = if let Some(artwork_url) = &metadata.artwork_url {
if let Some(parent_dir) = std::path::Path::new(&new_path).parent() {
match save_album_artwork(parent_dir, artwork_url).await {
Ok(_) => Some(parent_dir.join("cover.jpg").to_string_lossy().to_string()),
Err(e) => {
log::warn!("Failed to save album artwork for track {}: {}", track_id, e);
None
}
}
} else {
None
}
} else {
None
};
// 6. Extract audio properties from FLAC file
use lofty::AudioFile;
let (bit_depth, sample_rate) = match lofty::read_from_path(&new_path) {
Ok(tagged_file) => {
let properties = tagged_file.properties();
let bit_depth = properties.bit_depth().map(|bd| bd as u32);
let sample_rate = properties.sample_rate().map(|sr| sr as f64);
(bit_depth, sample_rate)
}
Err(e) => {
log::warn!("Failed to read audio properties for track {}: {}", track_id, e);
(None, None)
}
};
// 7. Insert into local library DB
let lib_guard = library_db.lock().await;
let album_artist = metadata.album_artist.as_ref().unwrap_or(&metadata.artist);
let album_group_key = format!("{}|{}", metadata.album, album_artist);
lib_guard.insert_qobuz_cached_track_with_grouping(
track_id,
&metadata.title,
&metadata.artist,
Some(&metadata.album),
metadata.album_artist.as_deref(),
metadata.track_number,
metadata.disc_number,
metadata.year,
metadata.duration_secs,
&new_path,
&album_group_key,
&metadata.album,
bit_depth,
sample_rate,
artwork_path.as_deref(),
)
.map_err(|e| format!("Failed to insert to library DB: {}", e))?;
log::info!("Track {} migrated successfully to: {}", track_id, new_path);
Ok(new_path)
}
/// Migrate all legacy cached files
pub async fn migrate_legacy_cached_files(
track_ids: Vec<u64>,
tracks_dir: PathBuf,
offline_root: String,
qobuz_client: Arc<Mutex<QobuzClient>>,
library_db: Arc<Mutex<LibraryDatabase>>,
) -> MigrationStatus {
let total = track_ids.len();
let mut status = MigrationStatus {
has_legacy_files: true,
total_tracks: total,
in_progress: true,
..Default::default()
};
for track_id in track_ids {
let legacy_path = tracks_dir.join(format!("{}.flac", track_id));
if !legacy_path.exists() {
log::warn!("Legacy file not found: {}", legacy_path.display());
status.processed += 1;
continue;
}
// Lock client for this migration
let client_guard = qobuz_client.lock().await;
match migrate_single_track(
track_id,
legacy_path.clone(),
&offline_root,
&*client_guard,
library_db.clone(),
).await {
Ok(_) => {
status.successful += 1;
// Delete legacy file after successful migration
if let Err(e) = std::fs::remove_file(&legacy_path) {
log::warn!("Failed to delete legacy file {}: {}", legacy_path.display(), e);
}
}
Err(e) => {
status.failed += 1;
status.errors.push(MigrationError {
track_id,
error_message: e,
});
log::error!("Failed to migrate track {}: {}", track_id, status.errors.last().unwrap().error_message);
}
}
drop(client_guard);
status.processed += 1;
}
status.in_progress = false;
status.completed = true;
log::info!(
"Migration complete: {}/{} successful, {} failed",
status.successful,
total,
status.failed
);
status
}
+189
View File
@@ -0,0 +1,189 @@
//! Offline cache module for temporary playback data
//!
//! Provides persistent disk-based caching for audio tracks:
//! - SQLite index for track metadata
//! - File-based storage for audio data
//! - LRU eviction with configurable limits
//! - Progress events for UI updates
pub mod commands;
pub mod db;
pub mod downloader;
pub mod path_validator;
pub mod metadata;
pub mod migration;
use std::path::PathBuf;
use std::sync::Arc;
use tokio::sync::{Mutex, Semaphore};
use serde::{Deserialize, Serialize};
pub use db::OfflineCacheDb;
pub use downloader::StreamFetcher;
pub use path_validator::{is_offline_root_available, validate_path, PathStatus};
pub use metadata::{CompleteTrackMetadata, sanitize_filename};
pub use migration::{MigrationStatus, MigrationError, detect_legacy_cached_files, migrate_legacy_cached_files};
/// Cache status for a track in offline storage
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum OfflineCacheStatus {
Queued,
Downloading,
Ready,
Failed,
}
impl OfflineCacheStatus {
pub fn as_str(&self) -> &'static str {
match self {
Self::Queued => "queued",
Self::Downloading => "downloading",
Self::Ready => "ready",
Self::Failed => "failed",
}
}
pub fn from_str(s: &str) -> Self {
match s {
"queued" => Self::Queued,
"downloading" => Self::Downloading,
"ready" => Self::Ready,
"failed" => Self::Failed,
_ => Self::Failed,
}
}
}
/// Information about a cached track
#[derive(Debug, Clone, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct CachedTrackInfo {
pub track_id: u64,
pub title: String,
pub artist: String,
pub album: Option<String>,
pub album_id: Option<String>,
pub duration_secs: u64,
pub file_size_bytes: u64,
pub quality: String,
pub bit_depth: Option<u32>,
pub sample_rate: Option<f64>,
pub status: OfflineCacheStatus,
pub progress_percent: u8,
pub error_message: Option<String>,
pub created_at: String,
pub last_accessed_at: String,
}
/// Minimal track info for syncing to library
#[derive(Debug, Clone)]
pub struct ReadyTrackForSync {
pub track_id: u64,
pub title: String,
pub artist: String,
pub album: Option<String>,
pub duration_secs: u64,
pub file_path: String,
pub bit_depth: Option<u32>,
pub sample_rate: Option<f64>,
}
/// Statistics about the offline cache
#[derive(Debug, Clone, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct OfflineCacheStats {
pub total_tracks: usize,
pub ready_tracks: usize,
pub downloading_tracks: usize,
pub failed_tracks: usize,
pub total_size_bytes: u64,
pub limit_bytes: Option<u64>,
pub cache_path: String,
}
/// Progress update for caching a track
#[derive(Debug, Clone, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct CacheProgress {
pub track_id: u64,
pub progress_percent: u8,
pub bytes_downloaded: u64,
pub total_bytes: Option<u64>,
pub status: OfflineCacheStatus,
}
/// Track metadata for initiating offline caching
#[derive(Debug, Clone)]
pub struct TrackCacheInfo {
pub track_id: u64,
pub title: String,
pub artist: String,
pub album: Option<String>,
pub album_id: Option<String>,
pub duration_secs: u64,
pub quality: String,
pub bit_depth: Option<u32>,
pub sample_rate: Option<f64>,
}
/// Offline cache state manager
pub struct OfflineCacheState {
pub db: Arc<Mutex<OfflineCacheDb>>,
pub fetcher: Arc<StreamFetcher>,
pub cache_dir: PathBuf,
/// Cache limit in bytes (None = unlimited)
pub limit_bytes: Arc<Mutex<Option<u64>>>,
pub cache_semaphore: Arc<Semaphore>,
}
impl OfflineCacheState {
/// Initialize the offline cache
pub fn new() -> Result<Self, String> {
let cache_dir = dirs::cache_dir()
.ok_or("Could not determine cache directory")?
.join("qbz")
.join("audio");
// Create directories
std::fs::create_dir_all(&cache_dir)
.map_err(|e| format!("Failed to create cache directory: {}", e))?;
std::fs::create_dir_all(cache_dir.join("tracks"))
.map_err(|e| format!("Failed to create tracks directory: {}", e))?;
std::fs::create_dir_all(cache_dir.join("artwork"))
.map_err(|e| format!("Failed to create artwork directory: {}", e))?;
let db_path = cache_dir.join("index.db");
let db = OfflineCacheDb::new(&db_path)?;
// Default limit: 2GB
let default_limit = Some(2 * 1024 * 1024 * 1024u64);
let state = Self {
db: Arc::new(Mutex::new(db)),
fetcher: Arc::new(StreamFetcher::new()),
cache_dir: cache_dir.clone(),
limit_bytes: Arc::new(Mutex::new(default_limit)),
cache_semaphore: Arc::new(Semaphore::new(3)),
};
log::info!("Offline cache initialized at: {:?}", cache_dir);
Ok(state)
}
/// Get the path for a track's audio file
pub fn track_file_path(&self, track_id: u64, format: &str) -> PathBuf {
self.cache_dir.join("tracks").join(format!("{}.{}", track_id, format))
}
/// Get the path for an album's artwork
pub fn artwork_path(&self, album_id: &str) -> PathBuf {
self.cache_dir.join("artwork").join(format!("{}.jpg", album_id))
}
/// Get the cache directory path
pub fn get_cache_path(&self) -> String {
self.cache_dir.to_string_lossy().to_string()
}
}
@@ -0,0 +1,238 @@
//! Offline cache path validation and management
//!
//! Handles path validation, permission checking, and mount status verification.
use std::fs;
use std::path::{Path, PathBuf};
use serde::{Deserialize, Serialize};
#[derive(Debug, Clone, Serialize, Deserialize)]
pub enum PathStatus {
Valid,
DoesNotExist,
NotADirectory,
NoWritePermission,
NotMounted,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct PathValidationResult {
pub status: PathStatus,
pub message: String,
}
/// Validate an offline cache path
pub fn validate_path(path: &str) -> Result<PathValidationResult, String> {
let path_obj = Path::new(path);
if !path_obj.exists() {
return Ok(PathValidationResult {
status: PathStatus::DoesNotExist,
message: format!("Path does not exist: {}", path),
});
}
if !path_obj.is_dir() {
return Ok(PathValidationResult {
status: PathStatus::NotADirectory,
message: format!("Path is not a directory: {}", path),
});
}
if !check_mount_status(path)? {
return Ok(PathValidationResult {
status: PathStatus::NotMounted,
message: "Storage device is not mounted".to_string(),
});
}
if !check_permissions(path)? {
return Ok(PathValidationResult {
status: PathStatus::NoWritePermission,
message: "No write permission for this directory".to_string(),
});
}
Ok(PathValidationResult {
status: PathStatus::Valid,
message: "Path is valid and writable".to_string(),
})
}
/// Check if we have write permissions on a path
pub fn check_permissions(path: &str) -> Result<bool, String> {
let path_obj = Path::new(path);
let test_file = path_obj.join(".qbz_write_test");
match fs::write(&test_file, b"test") {
Ok(_) => {
let _ = fs::remove_file(&test_file);
Ok(true)
}
Err(e) => {
if e.kind() == std::io::ErrorKind::PermissionDenied {
Ok(false)
} else {
Err(format!("Failed to check permissions: {}", e))
}
}
}
}
/// Check if the path is on a mounted filesystem
pub fn check_mount_status(path: &str) -> Result<bool, String> {
let path_obj = Path::new(path);
// Try to canonicalize the path
match path_obj.canonicalize() {
Ok(canonical) => {
// If we can read the metadata, the mount is accessible
match canonical.metadata() {
Ok(_) => Ok(true),
Err(e) => {
if e.kind() == std::io::ErrorKind::NotFound {
Ok(false)
} else {
Err(format!("Failed to check mount status: {}", e))
}
}
}
}
Err(e) => {
if e.kind() == std::io::ErrorKind::NotFound {
Ok(false)
} else {
Err(format!("Failed to canonicalize path: {}", e))
}
}
}
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct MoveReport {
pub total_files: usize,
pub moved_count: usize,
pub failed_files: Vec<String>,
}
/// Move cached files from old path to new path
pub fn move_cached_files_to_new_path(
old_root: &str,
new_root: &str,
) -> Result<MoveReport, String> {
let old_path = Path::new(old_root);
let new_path = Path::new(new_root);
// Validate new path
let validation = validate_path(new_root)?;
if !matches!(validation.status, PathStatus::Valid) {
return Err(format!("New path is not valid: {}", validation.message));
}
// Create new root if it doesn't exist
fs::create_dir_all(new_path)
.map_err(|e| format!("Failed to create new directory: {}", e))?;
let mut report = MoveReport {
total_files: 0,
moved_count: 0,
failed_files: Vec::new(),
};
// Collect all FLAC files recursively
let files = collect_flac_files(old_path)?;
report.total_files = files.len();
for old_file in files {
// Get relative path from old root
let relative_path = old_file
.strip_prefix(old_path)
.map_err(|e| format!("Failed to get relative path: {}", e))?;
let new_file = new_path.join(relative_path);
// Create parent directories in new location
if let Some(parent) = new_file.parent() {
fs::create_dir_all(parent)
.map_err(|e| format!("Failed to create directory: {}", e))?;
}
// Move file
match fs::rename(&old_file, &new_file) {
Ok(_) => {
report.moved_count += 1;
}
Err(e) => {
log::warn!("Failed to move file {:?}: {}", old_file, e);
report.failed_files.push(old_file.to_string_lossy().to_string());
}
}
}
Ok(report)
}
/// Recursively collect all FLAC files in a directory
fn collect_flac_files(dir: &Path) -> Result<Vec<PathBuf>, String> {
let mut files = Vec::new();
if !dir.is_dir() {
return Ok(files);
}
let entries = fs::read_dir(dir)
.map_err(|e| format!("Failed to read directory: {}", e))?;
for entry in entries {
let entry = entry.map_err(|e| format!("Failed to read entry: {}", e))?;
let path = entry.path();
if path.is_dir() {
// Recurse into subdirectories
files.extend(collect_flac_files(&path)?);
} else if path.extension().and_then(|s| s.to_str()) == Some("flac") {
files.push(path);
}
}
Ok(files)
}
// Mount status cache
use std::sync::Mutex;
use std::time::{Duration, SystemTime};
struct MountStatusCache {
path: String,
is_mounted: bool,
last_check: SystemTime,
}
static MOUNT_CACHE: Mutex<Option<MountStatusCache>> = Mutex::new(None);
const CACHE_DURATION: Duration = Duration::from_secs(30);
/// Check mount status with caching (30s cache)
pub fn is_offline_root_available(path: &str) -> Result<bool, String> {
let mut cache = MOUNT_CACHE.lock().map_err(|e| format!("Cache lock error: {}", e))?;
if let Some(cached) = cache.as_ref() {
if cached.path == path {
if let Ok(elapsed) = SystemTime::now().duration_since(cached.last_check) {
if elapsed < CACHE_DURATION {
return Ok(cached.is_mounted);
}
}
}
}
// Cache miss or expired, check mount status
let is_mounted = check_mount_status(path)?;
*cache = Some(MountStatusCache {
path: path.to_string(),
is_mounted,
last_check: SystemTime::now(),
});
Ok(is_mounted)
}