feat(favorites): implement local SQLite persistence for favorites
This ensures favorites sync properly across all views (album detail, continue listening, etc.) by using local persistence as the source of truth for UI, with API calls for actual operations. Backend (Rust): - Add favorites_cache.rs module with SQLite tables: - favorite_tracks (track_id INTEGER PRIMARY KEY) - favorite_albums (album_id TEXT PRIMARY KEY) - favorite_artists (artist_id INTEGER PRIMARY KEY) - Add Tauri commands for cache operations: - get_cached_favorite_* - read from local cache - cache_favorite_* / uncache_favorite_* - add/remove single items - sync_cached_favorite_* - bulk sync from API data - clear_favorites_cache - for logout Frontend: - Rewrite favoritesStore.ts to use persistence: - loadFavorites(): Load from cache first, then sync from API - toggleFavorite(): API call first → update cache on success - No optimistic updates - UI shows loading state until confirmed - Rewrite albumFavoritesStore.ts with same pattern - Create artistFavoritesStore.ts for artist favorites - Update +page.svelte to load all favorites on login - Update FavoritesView to sync cache when loading from API Sync strategy: - On login: Fetch from Qobuz API → sync to local cache - On toggle: API call → on success → update local cache → notify UI - FavoritesView reads from API and syncs local cache - All other views read from local cache (instant UI)
This commit is contained in:
1 parent
defd2f0fe1
commit
4c606e029e
8 files changed
+929
-72
No files matched your search
@@ -0,0 +1,478 @@
|
|||||||
|
//! Local cache for favorite tracks, albums, and artists
|
||||||
|
//!
|
||||||
|
//! This module provides local persistence for favorites to:
|
||||||
|
//! - Enable instant UI updates without API calls
|
||||||
|
//! - Reduce load on Qobuz API
|
||||||
|
//! - Provide offline favorite status display
|
||||||
|
//!
|
||||||
|
//! Sync strategy:
|
||||||
|
//! - On login: Fetch all favorites from API and populate local cache
|
||||||
|
//! - On toggle: API call first, then update local cache on success
|
||||||
|
//! - FavoritesView reads from API and syncs local cache
|
||||||
|
|
||||||
|
use rusqlite::{params, Connection};
|
||||||
|
use serde::{Deserialize, Serialize};
|
||||||
|
use std::sync::{Arc, Mutex};
|
||||||
|
|
||||||
|
/// Represents a cached favorite track
|
||||||
|
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||||
|
pub struct CachedFavoriteTrack {
|
||||||
|
pub track_id: i64,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Represents a cached favorite album
|
||||||
|
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||||
|
pub struct CachedFavoriteAlbum {
|
||||||
|
pub album_id: String,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Represents a cached favorite artist
|
||||||
|
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||||
|
pub struct CachedFavoriteArtist {
|
||||||
|
pub artist_id: i64,
|
||||||
|
}
|
||||||
|
|
||||||
|
pub struct FavoritesCacheStore {
|
||||||
|
conn: Connection,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl FavoritesCacheStore {
|
||||||
|
pub fn new() -> Result<Self, String> {
|
||||||
|
let data_dir = dirs::data_dir()
|
||||||
|
.ok_or("Could not determine data directory")?
|
||||||
|
.join("qbz");
|
||||||
|
|
||||||
|
std::fs::create_dir_all(&data_dir)
|
||||||
|
.map_err(|e| format!("Failed to create data directory: {}", e))?;
|
||||||
|
|
||||||
|
let db_path = data_dir.join("favorites_cache.db");
|
||||||
|
let conn = Connection::open(&db_path)
|
||||||
|
.map_err(|e| format!("Failed to open favorites cache database: {}", e))?;
|
||||||
|
|
||||||
|
// Create tables
|
||||||
|
conn.execute(
|
||||||
|
"CREATE TABLE IF NOT EXISTS favorite_tracks (
|
||||||
|
track_id INTEGER PRIMARY KEY,
|
||||||
|
created_at TEXT DEFAULT CURRENT_TIMESTAMP
|
||||||
|
)",
|
||||||
|
[],
|
||||||
|
)
|
||||||
|
.map_err(|e| format!("Failed to create favorite_tracks table: {}", e))?;
|
||||||
|
|
||||||
|
conn.execute(
|
||||||
|
"CREATE TABLE IF NOT EXISTS favorite_albums (
|
||||||
|
album_id TEXT PRIMARY KEY,
|
||||||
|
created_at TEXT DEFAULT CURRENT_TIMESTAMP
|
||||||
|
)",
|
||||||
|
[],
|
||||||
|
)
|
||||||
|
.map_err(|e| format!("Failed to create favorite_albums table: {}", e))?;
|
||||||
|
|
||||||
|
conn.execute(
|
||||||
|
"CREATE TABLE IF NOT EXISTS favorite_artists (
|
||||||
|
artist_id INTEGER PRIMARY KEY,
|
||||||
|
created_at TEXT DEFAULT CURRENT_TIMESTAMP
|
||||||
|
)",
|
||||||
|
[],
|
||||||
|
)
|
||||||
|
.map_err(|e| format!("Failed to create favorite_artists table: {}", e))?;
|
||||||
|
|
||||||
|
Ok(Self { conn })
|
||||||
|
}
|
||||||
|
|
||||||
|
// ============ Track favorites ============
|
||||||
|
|
||||||
|
pub fn get_favorite_track_ids(&self) -> Result<Vec<i64>, String> {
|
||||||
|
let mut stmt = self.conn
|
||||||
|
.prepare("SELECT track_id FROM favorite_tracks")
|
||||||
|
.map_err(|e| format!("Failed to prepare query: {}", e))?;
|
||||||
|
|
||||||
|
let rows = stmt
|
||||||
|
.query_map([], |row| row.get(0))
|
||||||
|
.map_err(|e| format!("Failed to query favorite tracks: {}", e))?;
|
||||||
|
|
||||||
|
let mut ids = Vec::new();
|
||||||
|
for row in rows {
|
||||||
|
ids.push(row.map_err(|e| format!("Failed to read row: {}", e))?);
|
||||||
|
}
|
||||||
|
Ok(ids)
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn is_track_favorite(&self, track_id: i64) -> Result<bool, String> {
|
||||||
|
let mut stmt = self.conn
|
||||||
|
.prepare("SELECT 1 FROM favorite_tracks WHERE track_id = ?1")
|
||||||
|
.map_err(|e| format!("Failed to prepare query: {}", e))?;
|
||||||
|
|
||||||
|
let exists = stmt
|
||||||
|
.exists(params![track_id])
|
||||||
|
.map_err(|e| format!("Failed to check favorite: {}", e))?;
|
||||||
|
|
||||||
|
Ok(exists)
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn add_favorite_track(&self, track_id: i64) -> Result<(), String> {
|
||||||
|
self.conn
|
||||||
|
.execute(
|
||||||
|
"INSERT OR IGNORE INTO favorite_tracks (track_id) VALUES (?1)",
|
||||||
|
params![track_id],
|
||||||
|
)
|
||||||
|
.map_err(|e| format!("Failed to add favorite track: {}", e))?;
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn remove_favorite_track(&self, track_id: i64) -> Result<(), String> {
|
||||||
|
self.conn
|
||||||
|
.execute(
|
||||||
|
"DELETE FROM favorite_tracks WHERE track_id = ?1",
|
||||||
|
params![track_id],
|
||||||
|
)
|
||||||
|
.map_err(|e| format!("Failed to remove favorite track: {}", e))?;
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn sync_favorite_tracks(&self, track_ids: &[i64]) -> Result<(), String> {
|
||||||
|
// Clear existing and insert new
|
||||||
|
self.conn
|
||||||
|
.execute("DELETE FROM favorite_tracks", [])
|
||||||
|
.map_err(|e| format!("Failed to clear favorite tracks: {}", e))?;
|
||||||
|
|
||||||
|
for &track_id in track_ids {
|
||||||
|
self.conn
|
||||||
|
.execute(
|
||||||
|
"INSERT INTO favorite_tracks (track_id) VALUES (?1)",
|
||||||
|
params![track_id],
|
||||||
|
)
|
||||||
|
.map_err(|e| format!("Failed to insert favorite track: {}", e))?;
|
||||||
|
}
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
// ============ Album favorites ============
|
||||||
|
|
||||||
|
pub fn get_favorite_album_ids(&self) -> Result<Vec<String>, String> {
|
||||||
|
let mut stmt = self.conn
|
||||||
|
.prepare("SELECT album_id FROM favorite_albums")
|
||||||
|
.map_err(|e| format!("Failed to prepare query: {}", e))?;
|
||||||
|
|
||||||
|
let rows = stmt
|
||||||
|
.query_map([], |row| row.get(0))
|
||||||
|
.map_err(|e| format!("Failed to query favorite albums: {}", e))?;
|
||||||
|
|
||||||
|
let mut ids = Vec::new();
|
||||||
|
for row in rows {
|
||||||
|
ids.push(row.map_err(|e| format!("Failed to read row: {}", e))?);
|
||||||
|
}
|
||||||
|
Ok(ids)
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn is_album_favorite(&self, album_id: &str) -> Result<bool, String> {
|
||||||
|
let mut stmt = self.conn
|
||||||
|
.prepare("SELECT 1 FROM favorite_albums WHERE album_id = ?1")
|
||||||
|
.map_err(|e| format!("Failed to prepare query: {}", e))?;
|
||||||
|
|
||||||
|
let exists = stmt
|
||||||
|
.exists(params![album_id])
|
||||||
|
.map_err(|e| format!("Failed to check favorite: {}", e))?;
|
||||||
|
|
||||||
|
Ok(exists)
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn add_favorite_album(&self, album_id: &str) -> Result<(), String> {
|
||||||
|
self.conn
|
||||||
|
.execute(
|
||||||
|
"INSERT OR IGNORE INTO favorite_albums (album_id) VALUES (?1)",
|
||||||
|
params![album_id],
|
||||||
|
)
|
||||||
|
.map_err(|e| format!("Failed to add favorite album: {}", e))?;
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn remove_favorite_album(&self, album_id: &str) -> Result<(), String> {
|
||||||
|
self.conn
|
||||||
|
.execute(
|
||||||
|
"DELETE FROM favorite_albums WHERE album_id = ?1",
|
||||||
|
params![album_id],
|
||||||
|
)
|
||||||
|
.map_err(|e| format!("Failed to remove favorite album: {}", e))?;
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn sync_favorite_albums(&self, album_ids: &[String]) -> Result<(), String> {
|
||||||
|
self.conn
|
||||||
|
.execute("DELETE FROM favorite_albums", [])
|
||||||
|
.map_err(|e| format!("Failed to clear favorite albums: {}", e))?;
|
||||||
|
|
||||||
|
for album_id in album_ids {
|
||||||
|
self.conn
|
||||||
|
.execute(
|
||||||
|
"INSERT INTO favorite_albums (album_id) VALUES (?1)",
|
||||||
|
params![album_id],
|
||||||
|
)
|
||||||
|
.map_err(|e| format!("Failed to insert favorite album: {}", e))?;
|
||||||
|
}
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
// ============ Artist favorites ============
|
||||||
|
|
||||||
|
pub fn get_favorite_artist_ids(&self) -> Result<Vec<i64>, String> {
|
||||||
|
let mut stmt = self.conn
|
||||||
|
.prepare("SELECT artist_id FROM favorite_artists")
|
||||||
|
.map_err(|e| format!("Failed to prepare query: {}", e))?;
|
||||||
|
|
||||||
|
let rows = stmt
|
||||||
|
.query_map([], |row| row.get(0))
|
||||||
|
.map_err(|e| format!("Failed to query favorite artists: {}", e))?;
|
||||||
|
|
||||||
|
let mut ids = Vec::new();
|
||||||
|
for row in rows {
|
||||||
|
ids.push(row.map_err(|e| format!("Failed to read row: {}", e))?);
|
||||||
|
}
|
||||||
|
Ok(ids)
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn is_artist_favorite(&self, artist_id: i64) -> Result<bool, String> {
|
||||||
|
let mut stmt = self.conn
|
||||||
|
.prepare("SELECT 1 FROM favorite_artists WHERE artist_id = ?1")
|
||||||
|
.map_err(|e| format!("Failed to prepare query: {}", e))?;
|
||||||
|
|
||||||
|
let exists = stmt
|
||||||
|
.exists(params![artist_id])
|
||||||
|
.map_err(|e| format!("Failed to check favorite: {}", e))?;
|
||||||
|
|
||||||
|
Ok(exists)
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn add_favorite_artist(&self, artist_id: i64) -> Result<(), String> {
|
||||||
|
self.conn
|
||||||
|
.execute(
|
||||||
|
"INSERT OR IGNORE INTO favorite_artists (artist_id) VALUES (?1)",
|
||||||
|
params![artist_id],
|
||||||
|
)
|
||||||
|
.map_err(|e| format!("Failed to add favorite artist: {}", e))?;
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn remove_favorite_artist(&self, artist_id: i64) -> Result<(), String> {
|
||||||
|
self.conn
|
||||||
|
.execute(
|
||||||
|
"DELETE FROM favorite_artists WHERE artist_id = ?1",
|
||||||
|
params![artist_id],
|
||||||
|
)
|
||||||
|
.map_err(|e| format!("Failed to remove favorite artist: {}", e))?;
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn sync_favorite_artists(&self, artist_ids: &[i64]) -> Result<(), String> {
|
||||||
|
self.conn
|
||||||
|
.execute("DELETE FROM favorite_artists", [])
|
||||||
|
.map_err(|e| format!("Failed to clear favorite artists: {}", e))?;
|
||||||
|
|
||||||
|
for &artist_id in artist_ids {
|
||||||
|
self.conn
|
||||||
|
.execute(
|
||||||
|
"INSERT INTO favorite_artists (artist_id) VALUES (?1)",
|
||||||
|
params![artist_id],
|
||||||
|
)
|
||||||
|
.map_err(|e| format!("Failed to insert favorite artist: {}", e))?;
|
||||||
|
}
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
// ============ Clear all (for logout) ============
|
||||||
|
|
||||||
|
pub fn clear_all(&self) -> Result<(), String> {
|
||||||
|
self.conn
|
||||||
|
.execute("DELETE FROM favorite_tracks", [])
|
||||||
|
.map_err(|e| format!("Failed to clear favorite tracks: {}", e))?;
|
||||||
|
self.conn
|
||||||
|
.execute("DELETE FROM favorite_albums", [])
|
||||||
|
.map_err(|e| format!("Failed to clear favorite albums: {}", e))?;
|
||||||
|
self.conn
|
||||||
|
.execute("DELETE FROM favorite_artists", [])
|
||||||
|
.map_err(|e| format!("Failed to clear favorite artists: {}", e))?;
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// ============ Tauri State ============
|
||||||
|
|
||||||
|
pub struct FavoritesCacheState {
|
||||||
|
pub store: Arc<Mutex<FavoritesCacheStore>>,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl FavoritesCacheState {
|
||||||
|
pub fn new() -> Result<Self, String> {
|
||||||
|
let store = FavoritesCacheStore::new()?;
|
||||||
|
Ok(Self {
|
||||||
|
store: Arc::new(Mutex::new(store)),
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// ============ Tauri Commands ============
|
||||||
|
|
||||||
|
/// Get all cached favorite track IDs
|
||||||
|
#[tauri::command]
|
||||||
|
pub fn get_cached_favorite_tracks(
|
||||||
|
state: tauri::State<FavoritesCacheState>,
|
||||||
|
) -> Result<Vec<i64>, String> {
|
||||||
|
let store = state
|
||||||
|
.store
|
||||||
|
.lock()
|
||||||
|
.map_err(|_| "Failed to lock favorites cache store".to_string())?;
|
||||||
|
store.get_favorite_track_ids()
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Get all cached favorite album IDs
|
||||||
|
#[tauri::command]
|
||||||
|
pub fn get_cached_favorite_albums(
|
||||||
|
state: tauri::State<FavoritesCacheState>,
|
||||||
|
) -> Result<Vec<String>, String> {
|
||||||
|
let store = state
|
||||||
|
.store
|
||||||
|
.lock()
|
||||||
|
.map_err(|_| "Failed to lock favorites cache store".to_string())?;
|
||||||
|
store.get_favorite_album_ids()
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Get all cached favorite artist IDs
|
||||||
|
#[tauri::command]
|
||||||
|
pub fn get_cached_favorite_artists(
|
||||||
|
state: tauri::State<FavoritesCacheState>,
|
||||||
|
) -> Result<Vec<i64>, String> {
|
||||||
|
let store = state
|
||||||
|
.store
|
||||||
|
.lock()
|
||||||
|
.map_err(|_| "Failed to lock favorites cache store".to_string())?;
|
||||||
|
store.get_favorite_artist_ids()
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Add a track to local favorites cache (call after API success)
|
||||||
|
#[tauri::command]
|
||||||
|
pub fn cache_favorite_track(
|
||||||
|
track_id: i64,
|
||||||
|
state: tauri::State<FavoritesCacheState>,
|
||||||
|
) -> Result<(), String> {
|
||||||
|
let store = state
|
||||||
|
.store
|
||||||
|
.lock()
|
||||||
|
.map_err(|_| "Failed to lock favorites cache store".to_string())?;
|
||||||
|
store.add_favorite_track(track_id)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Remove a track from local favorites cache (call after API success)
|
||||||
|
#[tauri::command]
|
||||||
|
pub fn uncache_favorite_track(
|
||||||
|
track_id: i64,
|
||||||
|
state: tauri::State<FavoritesCacheState>,
|
||||||
|
) -> Result<(), String> {
|
||||||
|
let store = state
|
||||||
|
.store
|
||||||
|
.lock()
|
||||||
|
.map_err(|_| "Failed to lock favorites cache store".to_string())?;
|
||||||
|
store.remove_favorite_track(track_id)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Add an album to local favorites cache (call after API success)
|
||||||
|
#[tauri::command]
|
||||||
|
pub fn cache_favorite_album(
|
||||||
|
album_id: String,
|
||||||
|
state: tauri::State<FavoritesCacheState>,
|
||||||
|
) -> Result<(), String> {
|
||||||
|
let store = state
|
||||||
|
.store
|
||||||
|
.lock()
|
||||||
|
.map_err(|_| "Failed to lock favorites cache store".to_string())?;
|
||||||
|
store.add_favorite_album(&album_id)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Remove an album from local favorites cache (call after API success)
|
||||||
|
#[tauri::command]
|
||||||
|
pub fn uncache_favorite_album(
|
||||||
|
album_id: String,
|
||||||
|
state: tauri::State<FavoritesCacheState>,
|
||||||
|
) -> Result<(), String> {
|
||||||
|
let store = state
|
||||||
|
.store
|
||||||
|
.lock()
|
||||||
|
.map_err(|_| "Failed to lock favorites cache store".to_string())?;
|
||||||
|
store.remove_favorite_album(&album_id)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Add an artist to local favorites cache (call after API success)
|
||||||
|
#[tauri::command]
|
||||||
|
pub fn cache_favorite_artist(
|
||||||
|
artist_id: i64,
|
||||||
|
state: tauri::State<FavoritesCacheState>,
|
||||||
|
) -> Result<(), String> {
|
||||||
|
let store = state
|
||||||
|
.store
|
||||||
|
.lock()
|
||||||
|
.map_err(|_| "Failed to lock favorites cache store".to_string())?;
|
||||||
|
store.add_favorite_artist(artist_id)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Remove an artist from local favorites cache (call after API success)
|
||||||
|
#[tauri::command]
|
||||||
|
pub fn uncache_favorite_artist(
|
||||||
|
artist_id: i64,
|
||||||
|
state: tauri::State<FavoritesCacheState>,
|
||||||
|
) -> Result<(), String> {
|
||||||
|
let store = state
|
||||||
|
.store
|
||||||
|
.lock()
|
||||||
|
.map_err(|_| "Failed to lock favorites cache store".to_string())?;
|
||||||
|
store.remove_favorite_artist(artist_id)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Sync track favorites from a list of IDs (call after fetching from API)
|
||||||
|
#[tauri::command]
|
||||||
|
pub fn sync_cached_favorite_tracks(
|
||||||
|
track_ids: Vec<i64>,
|
||||||
|
state: tauri::State<FavoritesCacheState>,
|
||||||
|
) -> Result<(), String> {
|
||||||
|
let store = state
|
||||||
|
.store
|
||||||
|
.lock()
|
||||||
|
.map_err(|_| "Failed to lock favorites cache store".to_string())?;
|
||||||
|
store.sync_favorite_tracks(&track_ids)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Sync album favorites from a list of IDs (call after fetching from API)
|
||||||
|
#[tauri::command]
|
||||||
|
pub fn sync_cached_favorite_albums(
|
||||||
|
album_ids: Vec<String>,
|
||||||
|
state: tauri::State<FavoritesCacheState>,
|
||||||
|
) -> Result<(), String> {
|
||||||
|
let store = state
|
||||||
|
.store
|
||||||
|
.lock()
|
||||||
|
.map_err(|_| "Failed to lock favorites cache store".to_string())?;
|
||||||
|
store.sync_favorite_albums(&album_ids)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Sync artist favorites from a list of IDs (call after fetching from API)
|
||||||
|
#[tauri::command]
|
||||||
|
pub fn sync_cached_favorite_artists(
|
||||||
|
artist_ids: Vec<i64>,
|
||||||
|
state: tauri::State<FavoritesCacheState>,
|
||||||
|
) -> Result<(), String> {
|
||||||
|
let store = state
|
||||||
|
.store
|
||||||
|
.lock()
|
||||||
|
.map_err(|_| "Failed to lock favorites cache store".to_string())?;
|
||||||
|
store.sync_favorite_artists(&artist_ids)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Clear all cached favorites (call on logout)
|
||||||
|
#[tauri::command]
|
||||||
|
pub fn clear_favorites_cache(
|
||||||
|
state: tauri::State<FavoritesCacheState>,
|
||||||
|
) -> Result<(), String> {
|
||||||
|
let store = state
|
||||||
|
.store
|
||||||
|
.lock()
|
||||||
|
.map_err(|_| "Failed to lock favorites cache store".to_string())?;
|
||||||
|
store.clear_all()
|
||||||
|
}
|
||||||
@@ -13,6 +13,7 @@ pub mod audio_settings;
|
|||||||
pub mod download_settings;
|
pub mod download_settings;
|
||||||
pub mod playback_preferences;
|
pub mod playback_preferences;
|
||||||
pub mod favorites_preferences;
|
pub mod favorites_preferences;
|
||||||
|
pub mod favorites_cache;
|
||||||
pub mod subscription_state;
|
pub mod subscription_state;
|
||||||
pub mod tray_settings;
|
pub mod tray_settings;
|
||||||
|
|
||||||
@@ -65,3 +66,20 @@ pub use tray_settings::{
|
|||||||
set_minimize_to_tray,
|
set_minimize_to_tray,
|
||||||
set_close_to_tray,
|
set_close_to_tray,
|
||||||
};
|
};
|
||||||
|
|
||||||
|
pub use favorites_cache::{
|
||||||
|
FavoritesCacheState,
|
||||||
|
get_cached_favorite_tracks,
|
||||||
|
get_cached_favorite_albums,
|
||||||
|
get_cached_favorite_artists,
|
||||||
|
cache_favorite_track,
|
||||||
|
uncache_favorite_track,
|
||||||
|
cache_favorite_album,
|
||||||
|
uncache_favorite_album,
|
||||||
|
cache_favorite_artist,
|
||||||
|
uncache_favorite_artist,
|
||||||
|
sync_cached_favorite_tracks,
|
||||||
|
sync_cached_favorite_albums,
|
||||||
|
sync_cached_favorite_artists,
|
||||||
|
clear_favorites_cache,
|
||||||
|
};
|
||||||
@@ -190,6 +190,9 @@ pub fn run() {
|
|||||||
// Initialize favorites preferences state
|
// Initialize favorites preferences state
|
||||||
let favorites_prefs_state = config::favorites_preferences::FavoritesPreferencesState::new()
|
let favorites_prefs_state = config::favorites_preferences::FavoritesPreferencesState::new()
|
||||||
.expect("Failed to initialize favorites preferences");
|
.expect("Failed to initialize favorites preferences");
|
||||||
|
// Initialize favorites cache state (local persistence for favorite IDs)
|
||||||
|
let favorites_cache_state = config::favorites_cache::FavoritesCacheState::new()
|
||||||
|
.expect("Failed to initialize favorites cache");
|
||||||
// Initialize tray settings state
|
// Initialize tray settings state
|
||||||
let tray_settings_state = config::tray_settings::TraySettingsState::new()
|
let tray_settings_state = config::tray_settings::TraySettingsState::new()
|
||||||
.expect("Failed to initialize tray settings");
|
.expect("Failed to initialize tray settings");
|
||||||
@@ -437,6 +440,7 @@ pub fn run() {
|
|||||||
.manage(offline_state)
|
.manage(offline_state)
|
||||||
.manage(playback_prefs_state)
|
.manage(playback_prefs_state)
|
||||||
.manage(favorites_prefs_state)
|
.manage(favorites_prefs_state)
|
||||||
|
.manage(favorites_cache_state)
|
||||||
.manage(tray_settings_state)
|
.manage(tray_settings_state)
|
||||||
.manage(updates_state)
|
.manage(updates_state)
|
||||||
.manage(musicbrainz_state)
|
.manage(musicbrainz_state)
|
||||||
@@ -775,6 +779,20 @@ pub fn run() {
|
|||||||
config::playback_preferences::set_show_context_icon,
|
config::playback_preferences::set_show_context_icon,
|
||||||
config::favorites_preferences::get_favorites_preferences,
|
config::favorites_preferences::get_favorites_preferences,
|
||||||
config::favorites_preferences::save_favorites_preferences,
|
config::favorites_preferences::save_favorites_preferences,
|
||||||
|
// Favorites cache commands (local persistence)
|
||||||
|
config::favorites_cache::get_cached_favorite_tracks,
|
||||||
|
config::favorites_cache::get_cached_favorite_albums,
|
||||||
|
config::favorites_cache::get_cached_favorite_artists,
|
||||||
|
config::favorites_cache::cache_favorite_track,
|
||||||
|
config::favorites_cache::uncache_favorite_track,
|
||||||
|
config::favorites_cache::cache_favorite_album,
|
||||||
|
config::favorites_cache::uncache_favorite_album,
|
||||||
|
config::favorites_cache::cache_favorite_artist,
|
||||||
|
config::favorites_cache::uncache_favorite_artist,
|
||||||
|
config::favorites_cache::sync_cached_favorite_tracks,
|
||||||
|
config::favorites_cache::sync_cached_favorite_albums,
|
||||||
|
config::favorites_cache::sync_cached_favorite_artists,
|
||||||
|
config::favorites_cache::clear_favorites_cache,
|
||||||
// Updates commands
|
// Updates commands
|
||||||
updates::get_update_preferences,
|
updates::get_update_preferences,
|
||||||
updates::set_update_check_on_launch,
|
updates::set_update_check_on_launch,
|
||||||
|
|||||||
@@ -11,6 +11,9 @@
|
|||||||
import { type OfflineCacheStatus } from '$lib/stores/offlineCacheState';
|
import { type OfflineCacheStatus } from '$lib/stores/offlineCacheState';
|
||||||
import { consumeContextTrackFocus, setPlaybackContext } from '$lib/stores/playbackContextStore';
|
import { consumeContextTrackFocus, setPlaybackContext } from '$lib/stores/playbackContextStore';
|
||||||
import { normalizeFavoritesTabOrder } from '$lib/utils/favorites';
|
import { normalizeFavoritesTabOrder } from '$lib/utils/favorites';
|
||||||
|
import { syncCache as syncTrackCache } from '$lib/stores/favoritesStore';
|
||||||
|
import { syncCache as syncAlbumCache } from '$lib/stores/albumFavoritesStore';
|
||||||
|
import { syncCache as syncArtistCache } from '$lib/stores/artistFavoritesStore';
|
||||||
import type { FavoritesPreferences } from '$lib/types';
|
import type { FavoritesPreferences } from '$lib/types';
|
||||||
|
|
||||||
interface FavoriteAlbum {
|
interface FavoriteAlbum {
|
||||||
@@ -490,11 +493,20 @@
|
|||||||
|
|
||||||
if (type === 'tracks') {
|
if (type === 'tracks') {
|
||||||
favoriteTracks = items as FavoriteTrack[];
|
favoriteTracks = items as FavoriteTrack[];
|
||||||
|
// Sync to local cache for other views
|
||||||
|
const trackIds = favoriteTracks.map(t => t.id);
|
||||||
|
void syncTrackCache(trackIds);
|
||||||
} else if (type === 'albums') {
|
} else if (type === 'albums') {
|
||||||
favoriteAlbums = items as FavoriteAlbum[];
|
favoriteAlbums = items as FavoriteAlbum[];
|
||||||
await loadAllAlbumOfflineCacheStatuses(favoriteAlbums);
|
await loadAllAlbumOfflineCacheStatuses(favoriteAlbums);
|
||||||
|
// Sync to local cache for other views
|
||||||
|
const albumIds = favoriteAlbums.map(a => a.id);
|
||||||
|
void syncAlbumCache(albumIds);
|
||||||
} else if (type === 'artists') {
|
} else if (type === 'artists') {
|
||||||
favoriteArtists = items as FavoriteArtist[];
|
favoriteArtists = items as FavoriteArtist[];
|
||||||
|
// Sync to local cache for other views
|
||||||
|
const artistIds = favoriteArtists.map(a => a.id);
|
||||||
|
void syncArtistCache(artistIds);
|
||||||
}
|
}
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
console.error(`Failed to load ${type} favorites:`, err);
|
console.error(`Failed to load ${type} favorites:`, err);
|
||||||
|
|||||||
@@ -2,13 +2,19 @@
|
|||||||
* Album Favorites Store
|
* Album Favorites Store
|
||||||
*
|
*
|
||||||
* Centralized store for tracking favorite albums.
|
* Centralized store for tracking favorite albums.
|
||||||
|
* Uses local SQLite persistence for instant UI updates.
|
||||||
|
*
|
||||||
|
* Sync strategy:
|
||||||
|
* - On login: Fetch from Qobuz API → sync to local cache → populate store
|
||||||
|
* - On toggle: API call first → on success → update local cache → notify UI
|
||||||
|
* - UI reads from in-memory store (backed by local cache)
|
||||||
*/
|
*/
|
||||||
|
|
||||||
import { invoke } from '@tauri-apps/api/core';
|
import { invoke } from '@tauri-apps/api/core';
|
||||||
import { logRecoEvent } from '$lib/services/recoService';
|
import { logRecoEvent } from '$lib/services/recoService';
|
||||||
|
|
||||||
let favoriteAlbumIds = new Set<string>();
|
let favoriteAlbumIds = new Set<string>();
|
||||||
let togglingAlbumIds = new Set<string>(); // Album IDs currently being toggled (API in progress)
|
let togglingAlbumIds = new Set<string>(); // Album IDs currently being toggled
|
||||||
let isLoaded = false;
|
let isLoaded = false;
|
||||||
let isLoading = false;
|
let isLoading = false;
|
||||||
const listeners = new Set<() => void>();
|
const listeners = new Set<() => void>();
|
||||||
@@ -40,14 +46,50 @@ export function isFavoritesLoaded(): boolean {
|
|||||||
return isLoaded;
|
return isLoaded;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Load album favorites from local cache first, then sync from API
|
||||||
|
*/
|
||||||
export async function loadAlbumFavorites(): Promise<void> {
|
export async function loadAlbumFavorites(): Promise<void> {
|
||||||
if (isLoading || isLoaded) return;
|
if (isLoading) return;
|
||||||
isLoading = true;
|
|
||||||
|
|
||||||
|
isLoading = true;
|
||||||
try {
|
try {
|
||||||
|
// Step 1: Load from local cache for instant UI
|
||||||
|
try {
|
||||||
|
const cachedIds = await invoke<string[]>('get_cached_favorite_albums');
|
||||||
|
if (cachedIds.length > 0) {
|
||||||
|
favoriteAlbumIds = new Set(cachedIds);
|
||||||
|
isLoaded = true;
|
||||||
|
notifyListeners();
|
||||||
|
console.log(`[AlbumFavorites] Loaded ${cachedIds.length} albums from local cache`);
|
||||||
|
}
|
||||||
|
} catch (cacheErr) {
|
||||||
|
console.debug('[AlbumFavorites] No local cache available:', cacheErr);
|
||||||
|
}
|
||||||
|
|
||||||
|
// Step 2: Fetch from API and sync to local cache
|
||||||
|
await syncFromApi();
|
||||||
|
|
||||||
|
} catch (err) {
|
||||||
|
console.error('[AlbumFavorites] Failed to load favorites:', err);
|
||||||
|
if (!isLoaded) {
|
||||||
|
favoriteAlbumIds = new Set();
|
||||||
|
isLoaded = true;
|
||||||
|
notifyListeners();
|
||||||
|
}
|
||||||
|
} finally {
|
||||||
|
isLoading = false;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Sync album favorites from Qobuz API to local cache
|
||||||
|
*/
|
||||||
|
export async function syncFromApi(): Promise<void> {
|
||||||
|
try {
|
||||||
|
const allAlbumIds: string[] = [];
|
||||||
let offset = 0;
|
let offset = 0;
|
||||||
const limit = 500;
|
const limit = 500;
|
||||||
const collected: string[] = [];
|
|
||||||
|
|
||||||
while (true) {
|
while (true) {
|
||||||
const result = await invoke<{ albums?: { items: Array<{ id: string }>; total?: number } }>('get_favorites', {
|
const result = await invoke<{ albums?: { items: Array<{ id: string }>; total?: number } }>('get_favorites', {
|
||||||
@@ -59,25 +101,33 @@ export async function loadAlbumFavorites(): Promise<void> {
|
|||||||
const items = result.albums?.items ?? [];
|
const items = result.albums?.items ?? [];
|
||||||
if (!items.length) break;
|
if (!items.length) break;
|
||||||
|
|
||||||
collected.push(...items.map(item => item.id));
|
allAlbumIds.push(...items.map(item => item.id));
|
||||||
offset += items.length;
|
offset += items.length;
|
||||||
|
|
||||||
if (items.length < limit) break;
|
if (items.length < limit) break;
|
||||||
if (result.albums?.total && offset >= result.albums.total) break;
|
if (result.albums?.total && offset >= result.albums.total) break;
|
||||||
}
|
}
|
||||||
|
|
||||||
favoriteAlbumIds = new Set(collected);
|
// Sync to local cache
|
||||||
|
await invoke('sync_cached_favorite_albums', { albumIds: allAlbumIds });
|
||||||
|
|
||||||
|
// Update in-memory store
|
||||||
|
favoriteAlbumIds = new Set(allAlbumIds);
|
||||||
isLoaded = true;
|
isLoaded = true;
|
||||||
notifyListeners();
|
notifyListeners();
|
||||||
|
|
||||||
|
console.log(`[AlbumFavorites] Synced ${allAlbumIds.length} albums from API`);
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
console.error('Failed to load album favorites:', err);
|
console.error('[AlbumFavorites] Failed to sync from API:', err);
|
||||||
} finally {
|
throw err;
|
||||||
isLoading = false;
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Toggle album favorite status
|
||||||
|
* API call first → on success → update local cache → notify UI
|
||||||
|
*/
|
||||||
export async function toggleAlbumFavorite(albumId: string): Promise<boolean> {
|
export async function toggleAlbumFavorite(albumId: string): Promise<boolean> {
|
||||||
// Prevent double-toggling while API call is in progress
|
|
||||||
if (togglingAlbumIds.has(albumId)) {
|
if (togglingAlbumIds.has(albumId)) {
|
||||||
return favoriteAlbumIds.has(albumId);
|
return favoriteAlbumIds.has(albumId);
|
||||||
}
|
}
|
||||||
@@ -85,18 +135,15 @@ export async function toggleAlbumFavorite(albumId: string): Promise<boolean> {
|
|||||||
const wasFavorite = favoriteAlbumIds.has(albumId);
|
const wasFavorite = favoriteAlbumIds.has(albumId);
|
||||||
const newState = !wasFavorite;
|
const newState = !wasFavorite;
|
||||||
|
|
||||||
// Optimistic update + mark as toggling
|
// Mark as toggling
|
||||||
if (newState) {
|
|
||||||
favoriteAlbumIds.add(albumId);
|
|
||||||
} else {
|
|
||||||
favoriteAlbumIds.delete(albumId);
|
|
||||||
}
|
|
||||||
togglingAlbumIds.add(albumId);
|
togglingAlbumIds.add(albumId);
|
||||||
notifyListeners();
|
notifyListeners();
|
||||||
|
|
||||||
try {
|
try {
|
||||||
if (newState) {
|
if (newState) {
|
||||||
await invoke('add_favorite', { favType: 'album', itemId: albumId });
|
await invoke('add_favorite', { favType: 'album', itemId: albumId });
|
||||||
|
await invoke('cache_favorite_album', { albumId });
|
||||||
|
favoriteAlbumIds.add(albumId);
|
||||||
void logRecoEvent({
|
void logRecoEvent({
|
||||||
eventType: 'favorite',
|
eventType: 'favorite',
|
||||||
itemType: 'album',
|
itemType: 'album',
|
||||||
@@ -104,26 +151,37 @@ export async function toggleAlbumFavorite(albumId: string): Promise<boolean> {
|
|||||||
});
|
});
|
||||||
} else {
|
} else {
|
||||||
await invoke('remove_favorite', { favType: 'album', itemId: albumId });
|
await invoke('remove_favorite', { favType: 'album', itemId: albumId });
|
||||||
|
await invoke('uncache_favorite_album', { albumId });
|
||||||
|
favoriteAlbumIds.delete(albumId);
|
||||||
}
|
}
|
||||||
return newState;
|
return newState;
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
if (newState) {
|
console.error('[AlbumFavorites] Failed to toggle favorite:', err);
|
||||||
favoriteAlbumIds.delete(albumId);
|
|
||||||
} else {
|
|
||||||
favoriteAlbumIds.add(albumId);
|
|
||||||
}
|
|
||||||
console.error('Failed to toggle album favorite:', err);
|
|
||||||
return wasFavorite;
|
return wasFavorite;
|
||||||
} finally {
|
} finally {
|
||||||
// Always clear toggling state
|
|
||||||
togglingAlbumIds.delete(albumId);
|
togglingAlbumIds.delete(albumId);
|
||||||
notifyListeners();
|
notifyListeners();
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Sync local cache from an array of album IDs
|
||||||
|
* Used by FavoritesView after fetching from API
|
||||||
|
*/
|
||||||
|
export async function syncCache(albumIds: string[]): Promise<void> {
|
||||||
|
try {
|
||||||
|
await invoke('sync_cached_favorite_albums', { albumIds });
|
||||||
|
favoriteAlbumIds = new Set(albumIds);
|
||||||
|
notifyListeners();
|
||||||
|
} catch (err) {
|
||||||
|
console.error('[AlbumFavorites] Failed to sync cache:', err);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
export function markAsFavorite(albumId: string): void {
|
export function markAsFavorite(albumId: string): void {
|
||||||
if (!favoriteAlbumIds.has(albumId)) {
|
if (!favoriteAlbumIds.has(albumId)) {
|
||||||
favoriteAlbumIds.add(albumId);
|
favoriteAlbumIds.add(albumId);
|
||||||
|
invoke('cache_favorite_album', { albumId }).catch(() => {});
|
||||||
notifyListeners();
|
notifyListeners();
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -131,6 +189,7 @@ export function markAsFavorite(albumId: string): void {
|
|||||||
export function unmarkAsFavorite(albumId: string): void {
|
export function unmarkAsFavorite(albumId: string): void {
|
||||||
if (favoriteAlbumIds.has(albumId)) {
|
if (favoriteAlbumIds.has(albumId)) {
|
||||||
favoriteAlbumIds.delete(albumId);
|
favoriteAlbumIds.delete(albumId);
|
||||||
|
invoke('uncache_favorite_album', { albumId }).catch(() => {});
|
||||||
notifyListeners();
|
notifyListeners();
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -0,0 +1,195 @@
|
|||||||
|
/**
|
||||||
|
* Artist Favorites Store
|
||||||
|
*
|
||||||
|
* Centralized store for tracking favorite artists.
|
||||||
|
* Uses local SQLite persistence for instant UI updates.
|
||||||
|
*
|
||||||
|
* Sync strategy:
|
||||||
|
* - On login: Fetch from Qobuz API → sync to local cache → populate store
|
||||||
|
* - On toggle: API call first → on success → update local cache → notify UI
|
||||||
|
* - UI reads from in-memory store (backed by local cache)
|
||||||
|
*/
|
||||||
|
|
||||||
|
import { invoke } from '@tauri-apps/api/core';
|
||||||
|
import { logRecoEvent } from '$lib/services/recoService';
|
||||||
|
|
||||||
|
let favoriteArtistIds = new Set<number>();
|
||||||
|
let togglingArtistIds = new Set<number>(); // Artist IDs currently being toggled
|
||||||
|
let isLoaded = false;
|
||||||
|
let isLoading = false;
|
||||||
|
const listeners = new Set<() => void>();
|
||||||
|
|
||||||
|
function notifyListeners(): void {
|
||||||
|
for (const listener of listeners) {
|
||||||
|
listener();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
export function subscribe(listener: () => void): () => void {
|
||||||
|
listeners.add(listener);
|
||||||
|
return () => listeners.delete(listener);
|
||||||
|
}
|
||||||
|
|
||||||
|
export function isArtistFavorite(artistId: number): boolean {
|
||||||
|
return favoriteArtistIds.has(artistId);
|
||||||
|
}
|
||||||
|
|
||||||
|
export function isArtistToggling(artistId: number): boolean {
|
||||||
|
return togglingArtistIds.has(artistId);
|
||||||
|
}
|
||||||
|
|
||||||
|
export function getFavoriteArtistIds(): number[] {
|
||||||
|
return Array.from(favoriteArtistIds);
|
||||||
|
}
|
||||||
|
|
||||||
|
export function isFavoritesLoaded(): boolean {
|
||||||
|
return isLoaded;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Load artist favorites from local cache first, then sync from API
|
||||||
|
*/
|
||||||
|
export async function loadArtistFavorites(): Promise<void> {
|
||||||
|
if (isLoading) return;
|
||||||
|
|
||||||
|
isLoading = true;
|
||||||
|
try {
|
||||||
|
// Step 1: Load from local cache for instant UI
|
||||||
|
try {
|
||||||
|
const cachedIds = await invoke<number[]>('get_cached_favorite_artists');
|
||||||
|
if (cachedIds.length > 0) {
|
||||||
|
favoriteArtistIds = new Set(cachedIds);
|
||||||
|
isLoaded = true;
|
||||||
|
notifyListeners();
|
||||||
|
console.log(`[ArtistFavorites] Loaded ${cachedIds.length} artists from local cache`);
|
||||||
|
}
|
||||||
|
} catch (cacheErr) {
|
||||||
|
console.debug('[ArtistFavorites] No local cache available:', cacheErr);
|
||||||
|
}
|
||||||
|
|
||||||
|
// Step 2: Fetch from API and sync to local cache
|
||||||
|
await syncFromApi();
|
||||||
|
|
||||||
|
} catch (err) {
|
||||||
|
console.error('[ArtistFavorites] Failed to load favorites:', err);
|
||||||
|
if (!isLoaded) {
|
||||||
|
favoriteArtistIds = new Set();
|
||||||
|
isLoaded = true;
|
||||||
|
notifyListeners();
|
||||||
|
}
|
||||||
|
} finally {
|
||||||
|
isLoading = false;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Sync artist favorites from Qobuz API to local cache
|
||||||
|
*/
|
||||||
|
export async function syncFromApi(): Promise<void> {
|
||||||
|
try {
|
||||||
|
const allArtistIds: number[] = [];
|
||||||
|
let offset = 0;
|
||||||
|
const limit = 500;
|
||||||
|
|
||||||
|
while (true) {
|
||||||
|
const result = await invoke<{ artists?: { items: Array<{ id: number }>; total?: number } }>('get_favorites', {
|
||||||
|
favType: 'artists',
|
||||||
|
limit,
|
||||||
|
offset
|
||||||
|
});
|
||||||
|
|
||||||
|
const items = result.artists?.items ?? [];
|
||||||
|
if (!items.length) break;
|
||||||
|
|
||||||
|
allArtistIds.push(...items.map(item => item.id));
|
||||||
|
offset += items.length;
|
||||||
|
|
||||||
|
if (items.length < limit) break;
|
||||||
|
if (result.artists?.total && offset >= result.artists.total) break;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Sync to local cache
|
||||||
|
await invoke('sync_cached_favorite_artists', { artistIds: allArtistIds });
|
||||||
|
|
||||||
|
// Update in-memory store
|
||||||
|
favoriteArtistIds = new Set(allArtistIds);
|
||||||
|
isLoaded = true;
|
||||||
|
notifyListeners();
|
||||||
|
|
||||||
|
console.log(`[ArtistFavorites] Synced ${allArtistIds.length} artists from API`);
|
||||||
|
} catch (err) {
|
||||||
|
console.error('[ArtistFavorites] Failed to sync from API:', err);
|
||||||
|
throw err;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Toggle artist favorite status
|
||||||
|
* API call first → on success → update local cache → notify UI
|
||||||
|
*/
|
||||||
|
export async function toggleArtistFavorite(artistId: number): Promise<boolean> {
|
||||||
|
if (togglingArtistIds.has(artistId)) {
|
||||||
|
return favoriteArtistIds.has(artistId);
|
||||||
|
}
|
||||||
|
|
||||||
|
const wasFavorite = favoriteArtistIds.has(artistId);
|
||||||
|
const newState = !wasFavorite;
|
||||||
|
|
||||||
|
// Mark as toggling
|
||||||
|
togglingArtistIds.add(artistId);
|
||||||
|
notifyListeners();
|
||||||
|
|
||||||
|
try {
|
||||||
|
if (newState) {
|
||||||
|
await invoke('add_favorite', { favType: 'artist', itemId: String(artistId) });
|
||||||
|
await invoke('cache_favorite_artist', { artistId });
|
||||||
|
favoriteArtistIds.add(artistId);
|
||||||
|
void logRecoEvent({
|
||||||
|
eventType: 'favorite',
|
||||||
|
itemType: 'artist',
|
||||||
|
artistId
|
||||||
|
});
|
||||||
|
} else {
|
||||||
|
await invoke('remove_favorite', { favType: 'artist', itemId: String(artistId) });
|
||||||
|
await invoke('uncache_favorite_artist', { artistId });
|
||||||
|
favoriteArtistIds.delete(artistId);
|
||||||
|
}
|
||||||
|
return newState;
|
||||||
|
} catch (err) {
|
||||||
|
console.error('[ArtistFavorites] Failed to toggle favorite:', err);
|
||||||
|
return wasFavorite;
|
||||||
|
} finally {
|
||||||
|
togglingArtistIds.delete(artistId);
|
||||||
|
notifyListeners();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Sync local cache from an array of artist IDs
|
||||||
|
* Used by FavoritesView after fetching from API
|
||||||
|
*/
|
||||||
|
export async function syncCache(artistIds: number[]): Promise<void> {
|
||||||
|
try {
|
||||||
|
await invoke('sync_cached_favorite_artists', { artistIds });
|
||||||
|
favoriteArtistIds = new Set(artistIds);
|
||||||
|
notifyListeners();
|
||||||
|
} catch (err) {
|
||||||
|
console.error('[ArtistFavorites] Failed to sync cache:', err);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
export function markAsFavorite(artistId: number): void {
|
||||||
|
if (!favoriteArtistIds.has(artistId)) {
|
||||||
|
favoriteArtistIds.add(artistId);
|
||||||
|
invoke('cache_favorite_artist', { artistId }).catch(() => {});
|
||||||
|
notifyListeners();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
export function unmarkAsFavorite(artistId: number): void {
|
||||||
|
if (favoriteArtistIds.has(artistId)) {
|
||||||
|
favoriteArtistIds.delete(artistId);
|
||||||
|
invoke('uncache_favorite_artist', { artistId }).catch(() => {});
|
||||||
|
notifyListeners();
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -2,7 +2,12 @@
|
|||||||
* Favorites Store
|
* Favorites Store
|
||||||
*
|
*
|
||||||
* Centralized store for tracking favorite tracks.
|
* Centralized store for tracking favorite tracks.
|
||||||
* Components can check if a track is favorite and toggle status without prop drilling.
|
* Uses local SQLite persistence for instant UI updates.
|
||||||
|
*
|
||||||
|
* Sync strategy:
|
||||||
|
* - On login: Fetch from Qobuz API → sync to local cache → populate store
|
||||||
|
* - On toggle: API call first → on success → update local cache → notify UI
|
||||||
|
* - UI reads from in-memory store (backed by local cache)
|
||||||
*/
|
*/
|
||||||
|
|
||||||
import { invoke } from '@tauri-apps/api/core';
|
import { invoke } from '@tauri-apps/api/core';
|
||||||
@@ -60,39 +65,90 @@ export function isFavoritesLoaded(): boolean {
|
|||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Load favorites from backend (call once on app init)
|
* Load favorites from local cache first, then sync from API
|
||||||
|
* Call once on app init/login
|
||||||
*/
|
*/
|
||||||
export async function loadFavorites(): Promise<void> {
|
export async function loadFavorites(): Promise<void> {
|
||||||
if (isLoading || isLoaded) return;
|
if (isLoading) return;
|
||||||
|
|
||||||
isLoading = true;
|
isLoading = true;
|
||||||
try {
|
try {
|
||||||
const response = await invoke<{ tracks?: { items?: Array<{ id: number }> } }>('get_favorites', {
|
// Step 1: Load from local cache for instant UI (if available)
|
||||||
favType: 'track',
|
try {
|
||||||
limit: 500
|
const cachedIds = await invoke<number[]>('get_cached_favorite_tracks');
|
||||||
});
|
if (cachedIds.length > 0) {
|
||||||
|
favoriteTrackIds = new Set(cachedIds);
|
||||||
// Defensive: handle missing tracks or items
|
isLoaded = true;
|
||||||
if (response?.tracks?.items) {
|
notifyListeners();
|
||||||
favoriteTrackIds = new Set(response.tracks.items.map(t => t.id));
|
console.log(`[Favorites] Loaded ${cachedIds.length} tracks from local cache`);
|
||||||
} else {
|
}
|
||||||
// No favorites or unexpected response structure
|
} catch (cacheErr) {
|
||||||
favoriteTrackIds = new Set();
|
console.debug('[Favorites] No local cache available:', cacheErr);
|
||||||
}
|
}
|
||||||
|
|
||||||
isLoaded = true;
|
// Step 2: Fetch from API and sync to local cache
|
||||||
notifyListeners();
|
await syncFromApi();
|
||||||
|
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
console.error('Failed to load favorites:', err);
|
console.error('[Favorites] Failed to load favorites:', err);
|
||||||
// On error, initialize as empty set
|
// If no cache was loaded, initialize as empty
|
||||||
favoriteTrackIds = new Set();
|
if (!isLoaded) {
|
||||||
|
favoriteTrackIds = new Set();
|
||||||
|
isLoaded = true;
|
||||||
|
notifyListeners();
|
||||||
|
}
|
||||||
} finally {
|
} finally {
|
||||||
isLoading = false;
|
isLoading = false;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Sync favorites from Qobuz API to local cache
|
||||||
|
* Called on login and when FavoritesView loads
|
||||||
|
*/
|
||||||
|
export async function syncFromApi(): Promise<void> {
|
||||||
|
try {
|
||||||
|
// Fetch all favorites from API (paginated)
|
||||||
|
const allTrackIds: number[] = [];
|
||||||
|
let offset = 0;
|
||||||
|
const limit = 500;
|
||||||
|
|
||||||
|
while (true) {
|
||||||
|
const response = await invoke<{ tracks?: { items?: Array<{ id: number }>; total?: number } }>('get_favorites', {
|
||||||
|
favType: 'tracks',
|
||||||
|
limit,
|
||||||
|
offset
|
||||||
|
});
|
||||||
|
|
||||||
|
const items = response?.tracks?.items ?? [];
|
||||||
|
if (items.length === 0) break;
|
||||||
|
|
||||||
|
allTrackIds.push(...items.map(t => t.id));
|
||||||
|
offset += items.length;
|
||||||
|
|
||||||
|
// Check if we've fetched all
|
||||||
|
if (items.length < limit) break;
|
||||||
|
if (response.tracks?.total && offset >= response.tracks.total) break;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Sync to local cache
|
||||||
|
await invoke('sync_cached_favorite_tracks', { trackIds: allTrackIds });
|
||||||
|
|
||||||
|
// Update in-memory store
|
||||||
|
favoriteTrackIds = new Set(allTrackIds);
|
||||||
|
isLoaded = true;
|
||||||
|
notifyListeners();
|
||||||
|
|
||||||
|
console.log(`[Favorites] Synced ${allTrackIds.length} tracks from API`);
|
||||||
|
} catch (err) {
|
||||||
|
console.error('[Favorites] Failed to sync from API:', err);
|
||||||
|
throw err;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Toggle favorite status for a track
|
* Toggle favorite status for a track
|
||||||
|
* API call first → on success → update local cache → notify UI
|
||||||
* Returns the new favorite state
|
* Returns the new favorite state
|
||||||
*/
|
*/
|
||||||
export async function toggleTrackFavorite(trackId: number): Promise<boolean> {
|
export async function toggleTrackFavorite(trackId: number): Promise<boolean> {
|
||||||
@@ -104,18 +160,19 @@ export async function toggleTrackFavorite(trackId: number): Promise<boolean> {
|
|||||||
const wasFavorite = favoriteTrackIds.has(trackId);
|
const wasFavorite = favoriteTrackIds.has(trackId);
|
||||||
const newState = !wasFavorite;
|
const newState = !wasFavorite;
|
||||||
|
|
||||||
// Optimistic update + mark as toggling
|
// Mark as toggling (UI shows loading state)
|
||||||
if (newState) {
|
|
||||||
favoriteTrackIds.add(trackId);
|
|
||||||
} else {
|
|
||||||
favoriteTrackIds.delete(trackId);
|
|
||||||
}
|
|
||||||
togglingTrackIds.add(trackId);
|
togglingTrackIds.add(trackId);
|
||||||
notifyListeners();
|
notifyListeners();
|
||||||
|
|
||||||
try {
|
try {
|
||||||
|
// Call API first - no optimistic update
|
||||||
if (newState) {
|
if (newState) {
|
||||||
await invoke('add_favorite', { favType: 'track', itemId: String(trackId) });
|
await invoke('add_favorite', { favType: 'track', itemId: String(trackId) });
|
||||||
|
// API succeeded - update local cache
|
||||||
|
await invoke('cache_favorite_track', { trackId });
|
||||||
|
// Update in-memory store
|
||||||
|
favoriteTrackIds.add(trackId);
|
||||||
|
// Log for recommendations
|
||||||
void logRecoEvent({
|
void logRecoEvent({
|
||||||
eventType: 'favorite',
|
eventType: 'favorite',
|
||||||
itemType: 'track',
|
itemType: 'track',
|
||||||
@@ -123,16 +180,16 @@ export async function toggleTrackFavorite(trackId: number): Promise<boolean> {
|
|||||||
});
|
});
|
||||||
} else {
|
} else {
|
||||||
await invoke('remove_favorite', { favType: 'track', itemId: String(trackId) });
|
await invoke('remove_favorite', { favType: 'track', itemId: String(trackId) });
|
||||||
|
// API succeeded - update local cache
|
||||||
|
await invoke('uncache_favorite_track', { trackId });
|
||||||
|
// Update in-memory store
|
||||||
|
favoriteTrackIds.delete(trackId);
|
||||||
}
|
}
|
||||||
|
|
||||||
return newState;
|
return newState;
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
// Rollback on error
|
// API failed - no state change, just log error
|
||||||
if (newState) {
|
console.error('[Favorites] Failed to toggle favorite:', err);
|
||||||
favoriteTrackIds.delete(trackId);
|
|
||||||
} else {
|
|
||||||
favoriteTrackIds.add(trackId);
|
|
||||||
}
|
|
||||||
console.error('Failed to toggle favorite:', err);
|
|
||||||
return wasFavorite;
|
return wasFavorite;
|
||||||
} finally {
|
} finally {
|
||||||
// Always clear toggling state
|
// Always clear toggling state
|
||||||
@@ -159,32 +216,50 @@ export async function removeTrackFavorite(trackId: number): Promise<boolean> {
|
|||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Manually add a track ID to the local set (for when we add favorites elsewhere)
|
* Sync local cache from an array of track IDs
|
||||||
|
* Used by FavoritesView after fetching from API
|
||||||
*/
|
*/
|
||||||
export function markAsFavorite(trackId: number): void {
|
export async function syncCache(trackIds: number[]): Promise<void> {
|
||||||
if (!favoriteTrackIds.has(trackId)) {
|
try {
|
||||||
favoriteTrackIds.add(trackId);
|
await invoke('sync_cached_favorite_tracks', { trackIds });
|
||||||
|
favoriteTrackIds = new Set(trackIds);
|
||||||
notifyListeners();
|
notifyListeners();
|
||||||
|
} catch (err) {
|
||||||
|
console.error('[Favorites] Failed to sync cache:', err);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Manually remove a track ID from the local set
|
* Reset store (for logout)
|
||||||
*/
|
*/
|
||||||
export function unmarkAsFavorite(trackId: number): void {
|
export async function reset(): Promise<void> {
|
||||||
if (favoriteTrackIds.has(trackId)) {
|
try {
|
||||||
favoriteTrackIds.delete(trackId);
|
await invoke('clear_favorites_cache');
|
||||||
notifyListeners();
|
} catch (err) {
|
||||||
|
console.debug('[Favorites] Failed to clear cache:', err);
|
||||||
}
|
}
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Reset store (for testing or logout)
|
|
||||||
*/
|
|
||||||
export function reset(): void {
|
|
||||||
favoriteTrackIds = new Set();
|
favoriteTrackIds = new Set();
|
||||||
togglingTrackIds = new Set();
|
togglingTrackIds = new Set();
|
||||||
isLoaded = false;
|
isLoaded = false;
|
||||||
isLoading = false;
|
isLoading = false;
|
||||||
notifyListeners();
|
notifyListeners();
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Legacy functions for backwards compatibility
|
||||||
|
export function markAsFavorite(trackId: number): void {
|
||||||
|
if (!favoriteTrackIds.has(trackId)) {
|
||||||
|
favoriteTrackIds.add(trackId);
|
||||||
|
// Also update cache
|
||||||
|
invoke('cache_favorite_track', { trackId }).catch(() => {});
|
||||||
|
notifyListeners();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
export function unmarkAsFavorite(trackId: number): void {
|
||||||
|
if (favoriteTrackIds.has(trackId)) {
|
||||||
|
favoriteTrackIds.delete(trackId);
|
||||||
|
// Also update cache
|
||||||
|
invoke('uncache_favorite_track', { trackId }).catch(() => {});
|
||||||
|
notifyListeners();
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -93,6 +93,7 @@
|
|||||||
// Favorites state management
|
// Favorites state management
|
||||||
import { loadFavorites } from '$lib/stores/favoritesStore';
|
import { loadFavorites } from '$lib/stores/favoritesStore';
|
||||||
import { loadAlbumFavorites } from '$lib/stores/albumFavoritesStore';
|
import { loadAlbumFavorites } from '$lib/stores/albumFavoritesStore';
|
||||||
|
import { loadArtistFavorites } from '$lib/stores/artistFavoritesStore';
|
||||||
import { getDefaultFavoritesTab } from '$lib/utils/favorites';
|
import { getDefaultFavoritesTab } from '$lib/utils/favorites';
|
||||||
import type { FavoritesPreferences, ResolvedMusician } from '$lib/types';
|
import type { FavoritesPreferences, ResolvedMusician } from '$lib/types';
|
||||||
|
|
||||||
@@ -1937,8 +1938,9 @@
|
|||||||
showToast(`Welcome, ${info.userName}!`, 'success');
|
showToast(`Welcome, ${info.userName}!`, 'success');
|
||||||
|
|
||||||
// Load favorites now that login is confirmed (sync with Qobuz)
|
// Load favorites now that login is confirmed (sync with Qobuz)
|
||||||
loadFavorites(); // Track favorites
|
loadFavorites(); // Track favorites
|
||||||
loadAlbumFavorites(); // Album favorites
|
loadAlbumFavorites(); // Album favorites
|
||||||
|
loadArtistFavorites(); // Artist favorites
|
||||||
|
|
||||||
// Refresh offline status now that we're logged in
|
// Refresh offline status now that we're logged in
|
||||||
await refreshOfflineStatus();
|
await refreshOfflineStatus();
|
||||||
|
|||||||
Reference in new issue
Block a user