feat: Qobuz™ compliance, subscription gating, and settings cleanup
cx
This commit is contained in:
1 parent
ee515573a2
commit
2a8b7c6d55
29 files changed
+918
-306
No files matched your search
@@ -1,5 +1,6 @@
|
||||
//! Authentication and request signing
|
||||
|
||||
use chrono::{TimeZone, Utc};
|
||||
use md5::{Digest, Md5};
|
||||
use std::time::{SystemTime, UNIX_EPOCH};
|
||||
|
||||
@@ -77,6 +78,41 @@ pub fn parse_login_response(response: &serde_json::Value) -> Result<UserSession>
|
||||
.unwrap_or("Unknown")
|
||||
.to_string();
|
||||
|
||||
fn parse_subscription_valid_until(parameters: &serde_json::Value) -> Option<String> {
|
||||
// Try common string fields first.
|
||||
let string_keys = [
|
||||
"end_date",
|
||||
"expiration_date",
|
||||
"valid_until",
|
||||
"expires_at",
|
||||
"expiry_date",
|
||||
];
|
||||
for key in string_keys {
|
||||
if let Some(s) = parameters.get(key).and_then(|v| v.as_str()) {
|
||||
let trimmed = s.trim();
|
||||
if !trimmed.is_empty() {
|
||||
return Some(trimmed.to_string());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Try common timestamp fields (seconds).
|
||||
let ts_keys = ["end_date_ts", "expires_at_ts", "expiration_ts", "valid_until_ts"];
|
||||
for key in ts_keys {
|
||||
if let Some(ts) = parameters.get(key).and_then(|v| v.as_i64()) {
|
||||
if ts > 0 {
|
||||
return Some(Utc.timestamp_opt(ts, 0).single()?.date_naive().to_string());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
None
|
||||
}
|
||||
|
||||
let subscription_valid_until = credential
|
||||
.and_then(|c| c.get("parameters"))
|
||||
.and_then(parse_subscription_valid_until);
|
||||
|
||||
// Check if user has valid subscription
|
||||
let has_subscription = credential
|
||||
.and_then(|c| c.get("parameters"))
|
||||
@@ -93,6 +129,7 @@ pub fn parse_login_response(response: &serde_json::Value) -> Result<UserSession>
|
||||
email,
|
||||
display_name,
|
||||
subscription_label,
|
||||
subscription_valid_until,
|
||||
})
|
||||
}
|
||||
|
||||
|
||||
@@ -166,10 +166,14 @@ impl QobuzClient {
|
||||
*self.session.write().await = None;
|
||||
}
|
||||
|
||||
/// Get current user info (display name and subscription)
|
||||
pub async fn get_user_info(&self) -> Option<(String, String)> {
|
||||
/// Get current user info (display name, subscription, and expiry if available)
|
||||
pub async fn get_user_info(&self) -> Option<(String, String, Option<String>)> {
|
||||
self.session.read().await.as_ref().map(|s| {
|
||||
(s.display_name.clone(), s.subscription_label.clone())
|
||||
(
|
||||
s.display_name.clone(),
|
||||
s.subscription_label.clone(),
|
||||
s.subscription_valid_until.clone(),
|
||||
)
|
||||
})
|
||||
}
|
||||
|
||||
|
||||
@@ -50,6 +50,8 @@ pub struct UserSession {
|
||||
pub email: String,
|
||||
pub display_name: String,
|
||||
pub subscription_label: String,
|
||||
#[serde(default)]
|
||||
pub subscription_valid_until: Option<String>,
|
||||
}
|
||||
|
||||
/// Stream URL response
|
||||
|
||||
+141
-14
@@ -1,16 +1,69 @@
|
||||
//! Authentication commands
|
||||
|
||||
use tauri::State;
|
||||
use std::time::{SystemTime, UNIX_EPOCH};
|
||||
|
||||
use crate::credentials;
|
||||
use crate::AppState;
|
||||
use crate::api::error::ApiError;
|
||||
use crate::config::SubscriptionStateState;
|
||||
use crate::download_cache::DownloadCacheState;
|
||||
|
||||
#[derive(serde::Serialize)]
|
||||
pub struct LoginResponse {
|
||||
pub success: bool,
|
||||
pub user_name: Option<String>,
|
||||
pub subscription: Option<String>,
|
||||
pub subscription_valid_until: Option<String>,
|
||||
pub error: Option<String>,
|
||||
pub error_code: Option<String>,
|
||||
}
|
||||
|
||||
fn now_unix_secs() -> i64 {
|
||||
SystemTime::now()
|
||||
.duration_since(UNIX_EPOCH)
|
||||
.unwrap_or_default()
|
||||
.as_secs() as i64
|
||||
}
|
||||
|
||||
async fn maybe_purge_downloads_for_invalid_subscription(
|
||||
now: i64,
|
||||
subscription_state: &SubscriptionStateState,
|
||||
cache_state: &DownloadCacheState,
|
||||
library_state: &crate::library::commands::LibraryState,
|
||||
) {
|
||||
let should_purge = {
|
||||
let store = match subscription_state.lock() {
|
||||
Ok(s) => s,
|
||||
Err(e) => {
|
||||
log::warn!("Subscription state lock error: {}", e);
|
||||
return;
|
||||
}
|
||||
};
|
||||
match store.should_purge_downloads(now) {
|
||||
Ok(v) => v,
|
||||
Err(e) => {
|
||||
log::warn!("Failed to evaluate purge condition: {}", e);
|
||||
false
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
if !should_purge {
|
||||
return;
|
||||
}
|
||||
|
||||
log::warn!("Subscription invalid for >3 days. Purging offline downloads.");
|
||||
if let Err(e) = crate::download_cache::commands::purge_all_downloads(cache_state, library_state).await {
|
||||
log::error!("Failed to purge downloads: {}", e);
|
||||
return;
|
||||
}
|
||||
|
||||
if let Ok(store) = subscription_state.lock() {
|
||||
if let Err(e) = store.mark_downloads_purged(now) {
|
||||
log::warn!("Failed to persist purge timestamp: {}", e);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[tauri::command]
|
||||
@@ -18,21 +71,54 @@ pub async fn login(
|
||||
email: String,
|
||||
password: String,
|
||||
state: State<'_, AppState>,
|
||||
subscription_state: State<'_, SubscriptionStateState>,
|
||||
cache_state: State<'_, DownloadCacheState>,
|
||||
library_state: State<'_, crate::library::commands::LibraryState>,
|
||||
) -> Result<LoginResponse, String> {
|
||||
let client = state.client.lock().await;
|
||||
let now = now_unix_secs();
|
||||
|
||||
match client.login(&email, &password).await {
|
||||
Ok(session) => Ok(LoginResponse {
|
||||
success: true,
|
||||
user_name: Some(session.display_name),
|
||||
subscription: Some(session.subscription_label),
|
||||
error: None,
|
||||
}),
|
||||
Ok(session) => {
|
||||
if let Ok(store) = subscription_state.lock() {
|
||||
let _ = store.mark_valid(now);
|
||||
}
|
||||
Ok(LoginResponse {
|
||||
success: true,
|
||||
user_name: Some(session.display_name),
|
||||
subscription: Some(session.subscription_label),
|
||||
subscription_valid_until: session.subscription_valid_until,
|
||||
error: None,
|
||||
error_code: None,
|
||||
})
|
||||
}
|
||||
Err(ApiError::IneligibleUser) => {
|
||||
if let Ok(store) = subscription_state.lock() {
|
||||
let _ = store.mark_invalid(now);
|
||||
}
|
||||
maybe_purge_downloads_for_invalid_subscription(
|
||||
now,
|
||||
subscription_state.inner(),
|
||||
cache_state.inner(),
|
||||
library_state.inner(),
|
||||
)
|
||||
.await;
|
||||
Ok(LoginResponse {
|
||||
success: false,
|
||||
user_name: None,
|
||||
subscription: None,
|
||||
subscription_valid_until: None,
|
||||
error: Some("No active subscription".to_string()),
|
||||
error_code: Some("ineligible_user".to_string()),
|
||||
})
|
||||
}
|
||||
Err(e) => Ok(LoginResponse {
|
||||
success: false,
|
||||
user_name: None,
|
||||
subscription: None,
|
||||
subscription_valid_until: None,
|
||||
error: Some(e.to_string()),
|
||||
error_code: None,
|
||||
}),
|
||||
}
|
||||
}
|
||||
@@ -63,14 +149,16 @@ pub async fn logout(state: State<'_, AppState>) -> Result<(), String> {
|
||||
pub struct UserInfo {
|
||||
pub user_name: String,
|
||||
pub subscription: String,
|
||||
pub subscription_valid_until: Option<String>,
|
||||
}
|
||||
|
||||
#[tauri::command]
|
||||
pub async fn get_user_info(state: State<'_, AppState>) -> Result<Option<UserInfo>, String> {
|
||||
let client = state.client.lock().await;
|
||||
Ok(client.get_user_info().await.map(|(name, sub)| UserInfo {
|
||||
Ok(client.get_user_info().await.map(|(name, sub, until)| UserInfo {
|
||||
user_name: name,
|
||||
subscription: sub,
|
||||
subscription_valid_until: until,
|
||||
}))
|
||||
}
|
||||
|
||||
@@ -97,7 +185,12 @@ pub fn clear_saved_credentials() -> Result<(), String> {
|
||||
/// Auto-login using saved credentials
|
||||
/// Returns LoginResponse with success status
|
||||
#[tauri::command]
|
||||
pub async fn auto_login(state: State<'_, AppState>) -> Result<LoginResponse, String> {
|
||||
pub async fn auto_login(
|
||||
state: State<'_, AppState>,
|
||||
subscription_state: State<'_, SubscriptionStateState>,
|
||||
cache_state: State<'_, DownloadCacheState>,
|
||||
library_state: State<'_, crate::library::commands::LibraryState>,
|
||||
) -> Result<LoginResponse, String> {
|
||||
// Check for saved credentials
|
||||
let creds = match credentials::load_qobuz_credentials() {
|
||||
Ok(Some(c)) => c,
|
||||
@@ -106,7 +199,9 @@ pub async fn auto_login(state: State<'_, AppState>) -> Result<LoginResponse, Str
|
||||
success: false,
|
||||
user_name: None,
|
||||
subscription: None,
|
||||
subscription_valid_until: None,
|
||||
error: Some("No saved credentials".to_string()),
|
||||
error_code: None,
|
||||
});
|
||||
}
|
||||
Err(e) => {
|
||||
@@ -114,20 +209,50 @@ pub async fn auto_login(state: State<'_, AppState>) -> Result<LoginResponse, Str
|
||||
success: false,
|
||||
user_name: None,
|
||||
subscription: None,
|
||||
subscription_valid_until: None,
|
||||
error: Some(e),
|
||||
error_code: None,
|
||||
});
|
||||
}
|
||||
};
|
||||
|
||||
// Try to login with saved credentials
|
||||
let client = state.client.lock().await;
|
||||
let now = now_unix_secs();
|
||||
match client.login(&creds.email, &creds.password).await {
|
||||
Ok(session) => Ok(LoginResponse {
|
||||
success: true,
|
||||
user_name: Some(session.display_name),
|
||||
subscription: Some(session.subscription_label),
|
||||
error: None,
|
||||
}),
|
||||
Ok(session) => {
|
||||
if let Ok(store) = subscription_state.lock() {
|
||||
let _ = store.mark_valid(now);
|
||||
}
|
||||
Ok(LoginResponse {
|
||||
success: true,
|
||||
user_name: Some(session.display_name),
|
||||
subscription: Some(session.subscription_label),
|
||||
subscription_valid_until: session.subscription_valid_until,
|
||||
error: None,
|
||||
error_code: None,
|
||||
})
|
||||
}
|
||||
Err(ApiError::IneligibleUser) => {
|
||||
if let Ok(store) = subscription_state.lock() {
|
||||
let _ = store.mark_invalid(now);
|
||||
}
|
||||
maybe_purge_downloads_for_invalid_subscription(
|
||||
now,
|
||||
subscription_state.inner(),
|
||||
cache_state.inner(),
|
||||
library_state.inner(),
|
||||
)
|
||||
.await;
|
||||
Ok(LoginResponse {
|
||||
success: false,
|
||||
user_name: None,
|
||||
subscription: None,
|
||||
subscription_valid_until: None,
|
||||
error: Some("No active subscription".to_string()),
|
||||
error_code: Some("ineligible_user".to_string()),
|
||||
})
|
||||
}
|
||||
Err(e) => {
|
||||
// Credentials might be invalid, but don't clear them automatically
|
||||
// Let the user decide
|
||||
@@ -136,7 +261,9 @@ pub async fn auto_login(state: State<'_, AppState>) -> Result<LoginResponse, Str
|
||||
success: false,
|
||||
user_name: None,
|
||||
subscription: None,
|
||||
subscription_valid_until: None,
|
||||
error: Some(e.to_string()),
|
||||
error_code: None,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
@@ -13,6 +13,7 @@ pub mod audio_settings;
|
||||
pub mod download_settings;
|
||||
pub mod playback_preferences;
|
||||
pub mod favorites_preferences;
|
||||
pub mod subscription_state;
|
||||
|
||||
pub use audio_settings::{
|
||||
AudioSettings,
|
||||
@@ -47,3 +48,10 @@ pub use favorites_preferences::{
|
||||
get_favorites_preferences,
|
||||
save_favorites_preferences,
|
||||
};
|
||||
|
||||
pub use subscription_state::{
|
||||
SubscriptionState,
|
||||
SubscriptionStateState,
|
||||
SubscriptionStateStore,
|
||||
create_subscription_state,
|
||||
};
|
||||
@@ -0,0 +1,147 @@
|
||||
//! Subscription validity tracking (for offline download compliance)
|
||||
//!
|
||||
//! Tracks when a user was first observed without a valid subscription. If the
|
||||
//! invalid state persists for more than a grace period, offline downloads are
|
||||
//! purged.
|
||||
|
||||
use rusqlite::{Connection, params};
|
||||
use serde::{Deserialize, Serialize};
|
||||
use std::sync::{Arc, Mutex};
|
||||
|
||||
const GRACE_PERIOD_SECS: i64 = 3 * 24 * 60 * 60; // 3 days
|
||||
|
||||
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct SubscriptionState {
|
||||
pub invalid_since: Option<i64>,
|
||||
pub last_invalid_at: Option<i64>,
|
||||
pub last_valid_at: Option<i64>,
|
||||
pub last_checked_at: Option<i64>,
|
||||
pub downloads_purged_at: Option<i64>,
|
||||
}
|
||||
|
||||
impl Default for SubscriptionState {
|
||||
fn default() -> Self {
|
||||
Self {
|
||||
invalid_since: None,
|
||||
last_invalid_at: None,
|
||||
last_valid_at: None,
|
||||
last_checked_at: None,
|
||||
downloads_purged_at: None,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub struct SubscriptionStateStore {
|
||||
conn: Connection,
|
||||
}
|
||||
|
||||
impl SubscriptionStateStore {
|
||||
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("subscription_state.db");
|
||||
let conn = Connection::open(&db_path)
|
||||
.map_err(|e| format!("Failed to open subscription state database: {}", e))?;
|
||||
|
||||
conn.execute_batch(
|
||||
"CREATE TABLE IF NOT EXISTS subscription_state (
|
||||
id INTEGER PRIMARY KEY CHECK (id = 1),
|
||||
invalid_since INTEGER,
|
||||
last_invalid_at INTEGER,
|
||||
last_valid_at INTEGER,
|
||||
last_checked_at INTEGER,
|
||||
downloads_purged_at INTEGER
|
||||
);
|
||||
INSERT OR IGNORE INTO subscription_state (id) VALUES (1);"
|
||||
).map_err(|e| format!("Failed to create subscription state table: {}", e))?;
|
||||
|
||||
Ok(Self { conn })
|
||||
}
|
||||
|
||||
pub fn get_state(&self) -> Result<SubscriptionState, String> {
|
||||
self.conn
|
||||
.query_row(
|
||||
"SELECT invalid_since, last_invalid_at, last_valid_at, last_checked_at, downloads_purged_at
|
||||
FROM subscription_state WHERE id = 1",
|
||||
[],
|
||||
|row| {
|
||||
Ok(SubscriptionState {
|
||||
invalid_since: row.get(0)?,
|
||||
last_invalid_at: row.get(1)?,
|
||||
last_valid_at: row.get(2)?,
|
||||
last_checked_at: row.get(3)?,
|
||||
downloads_purged_at: row.get(4)?,
|
||||
})
|
||||
},
|
||||
)
|
||||
.map_err(|e| format!("Failed to read subscription state: {}", e))
|
||||
}
|
||||
|
||||
pub fn mark_valid(&self, now: i64) -> Result<(), String> {
|
||||
self.conn
|
||||
.execute(
|
||||
"UPDATE subscription_state
|
||||
SET invalid_since = NULL,
|
||||
last_valid_at = ?1,
|
||||
last_checked_at = ?1
|
||||
WHERE id = 1",
|
||||
params![now],
|
||||
)
|
||||
.map_err(|e| format!("Failed to update subscription state: {}", e))?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub fn mark_invalid(&self, now: i64) -> Result<(), String> {
|
||||
// Only set invalid_since if it's not already set (first observation).
|
||||
self.conn
|
||||
.execute(
|
||||
"UPDATE subscription_state
|
||||
SET invalid_since = COALESCE(invalid_since, ?1),
|
||||
last_invalid_at = ?1,
|
||||
last_checked_at = ?1
|
||||
WHERE id = 1",
|
||||
params![now],
|
||||
)
|
||||
.map_err(|e| format!("Failed to update subscription state: {}", e))?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub fn mark_downloads_purged(&self, now: i64) -> Result<(), String> {
|
||||
self.conn
|
||||
.execute(
|
||||
"UPDATE subscription_state SET downloads_purged_at = ?1 WHERE id = 1",
|
||||
params![now],
|
||||
)
|
||||
.map_err(|e| format!("Failed to update purge timestamp: {}", e))?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub fn should_purge_downloads(&self, now: i64) -> Result<bool, String> {
|
||||
let state = self.get_state()?;
|
||||
let Some(invalid_since) = state.invalid_since else { return Ok(false); };
|
||||
if now - invalid_since < GRACE_PERIOD_SECS {
|
||||
return Ok(false);
|
||||
}
|
||||
// Purge at most once per invalid period.
|
||||
if let Some(purged_at) = state.downloads_purged_at {
|
||||
if purged_at >= invalid_since {
|
||||
return Ok(false);
|
||||
}
|
||||
}
|
||||
Ok(true)
|
||||
}
|
||||
}
|
||||
|
||||
pub type SubscriptionStateState = Arc<Mutex<SubscriptionStateStore>>;
|
||||
|
||||
pub fn create_subscription_state() -> Result<SubscriptionStateState, String> {
|
||||
let store = SubscriptionStateStore::new()?;
|
||||
Ok(Arc::new(Mutex::new(store)))
|
||||
}
|
||||
|
||||
@@ -364,7 +364,14 @@ pub async fn clear_download_cache(
|
||||
library_state: State<'_, crate::library::commands::LibraryState>,
|
||||
) -> Result<(), String> {
|
||||
log::info!("Command: clear_download_cache");
|
||||
purge_all_downloads(cache_state.inner(), library_state.inner()).await
|
||||
}
|
||||
|
||||
/// Clear entire download cache (internal helper)
|
||||
pub async fn purge_all_downloads(
|
||||
cache_state: &DownloadCacheState,
|
||||
library_state: &crate::library::commands::LibraryState,
|
||||
) -> Result<(), String> {
|
||||
let db = cache_state.db.lock().await;
|
||||
|
||||
// Get all file paths and clear DB
|
||||
@@ -391,7 +398,8 @@ pub async fn clear_download_cache(
|
||||
|
||||
// Remove all Qobuz downloads from library
|
||||
let library_db = library_state.db.lock().await;
|
||||
let removed_count = library_db.remove_all_qobuz_downloads()
|
||||
let removed_count = library_db
|
||||
.remove_all_qobuz_downloads()
|
||||
.map_err(|e| format!("Failed to remove downloads from library: {}", e))?;
|
||||
log::info!("Removed {} Qobuz downloads from library", removed_count);
|
||||
|
||||
|
||||
+61
-3
@@ -1,7 +1,6 @@
|
||||
//! QBZ-NIX: Native Qobuz client for Linux
|
||||
//! QBZ-NIX: Native high-fidelity streaming client for Linux
|
||||
//!
|
||||
//! A high-fidelity music streaming client for Qobuz, designed for audiophiles
|
||||
//! who need bit-perfect playback without browser sample rate limitations.
|
||||
//! This application uses the Qobuz API but is not certified by Qobuz.
|
||||
|
||||
pub mod api;
|
||||
pub mod api_cache;
|
||||
@@ -187,6 +186,9 @@ pub fn run() {
|
||||
// Initialize favorites preferences state
|
||||
let favorites_prefs_state = config::favorites_preferences::FavoritesPreferencesState::new()
|
||||
.expect("Failed to initialize favorites preferences");
|
||||
// Initialize subscription validity tracking (for offline download compliance)
|
||||
let subscription_state = config::create_subscription_state()
|
||||
.expect("Failed to initialize subscription state");
|
||||
|
||||
// Read saved audio device and settings for player initialization
|
||||
let (saved_device, audio_settings) = audio_settings_state
|
||||
@@ -229,6 +231,60 @@ pub fn run() {
|
||||
.media_controls
|
||||
.init(app.handle().clone());
|
||||
|
||||
// Purge offline downloads if the subscription has been invalid for > 3 days
|
||||
// (compliance requirement for cached content).
|
||||
let app_handle = app.handle().clone();
|
||||
tauri::async_runtime::spawn(async move {
|
||||
let now = std::time::SystemTime::now()
|
||||
.duration_since(std::time::UNIX_EPOCH)
|
||||
.unwrap_or_default()
|
||||
.as_secs() as i64;
|
||||
|
||||
let subscription_state = app_handle
|
||||
.state::<config::SubscriptionStateState>()
|
||||
.inner()
|
||||
.clone();
|
||||
let should_purge = {
|
||||
let store = match subscription_state.lock() {
|
||||
Ok(s) => s,
|
||||
Err(e) => {
|
||||
log::warn!("Subscription state lock error: {}", e);
|
||||
return;
|
||||
}
|
||||
};
|
||||
match store.should_purge_downloads(now) {
|
||||
Ok(v) => v,
|
||||
Err(e) => {
|
||||
log::warn!("Failed to evaluate purge condition: {}", e);
|
||||
false
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
if !should_purge {
|
||||
return;
|
||||
}
|
||||
|
||||
log::warn!("Subscription invalid for >3 days. Purging offline downloads.");
|
||||
let cache_state = app_handle.state::<download_cache::DownloadCacheState>();
|
||||
let library_state = app_handle.state::<crate::library::commands::LibraryState>();
|
||||
if let Err(e) = download_cache::commands::purge_all_downloads(cache_state.inner(), library_state.inner()).await {
|
||||
log::error!("Failed to purge downloads: {}", e);
|
||||
return;
|
||||
}
|
||||
|
||||
let store = match subscription_state.lock() {
|
||||
Ok(s) => s,
|
||||
Err(e) => {
|
||||
log::warn!("Subscription state lock error: {}", e);
|
||||
return;
|
||||
}
|
||||
};
|
||||
if let Err(e) = store.mark_downloads_purged(now) {
|
||||
log::warn!("Failed to persist purge timestamp: {}", e);
|
||||
}
|
||||
});
|
||||
|
||||
// Start background task to emit playback events
|
||||
let app_handle = app.handle().clone();
|
||||
let player_state = app.state::<AppState>().player.state.clone();
|
||||
@@ -310,6 +366,7 @@ pub fn run() {
|
||||
.manage(session_store_state)
|
||||
.manage(audio_settings_state)
|
||||
.manage(download_settings_state)
|
||||
.manage(subscription_state)
|
||||
.manage(offline_state)
|
||||
.manage(playback_prefs_state)
|
||||
.manage(favorites_prefs_state)
|
||||
@@ -556,6 +613,7 @@ pub fn run() {
|
||||
download_cache::commands::sync_downloads_to_library,
|
||||
// Lyrics commands
|
||||
lyrics::commands::lyrics_get,
|
||||
lyrics::commands::lyrics_get_cache_stats,
|
||||
lyrics::commands::lyrics_clear_cache,
|
||||
// Recommendation store commands
|
||||
reco_store::commands::reco_log_event,
|
||||
|
||||
@@ -131,4 +131,12 @@ impl LyricsCacheDb {
|
||||
.map_err(|e| format!("Failed to clear lyrics cache: {}", e))?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub fn count_entries(&self) -> Result<u64, String> {
|
||||
let count: i64 = self
|
||||
.conn
|
||||
.query_row("SELECT COUNT(*) FROM lyrics_cache", [], |row| row.get(0))
|
||||
.map_err(|e| format!("Failed to count lyrics cache entries: {}", e))?;
|
||||
Ok(count.max(0) as u64)
|
||||
}
|
||||
}
|
||||
@@ -1,6 +1,7 @@
|
||||
//! Tauri commands for lyrics
|
||||
|
||||
use tauri::State;
|
||||
use serde::Serialize;
|
||||
|
||||
use super::{build_cache_key, LyricsPayload, LyricsState};
|
||||
use super::providers::{fetch_lrclib, fetch_lyrics_ovh};
|
||||
@@ -82,3 +83,30 @@ pub async fn lyrics_clear_cache(state: State<'_, LyricsState>) -> Result<(), Str
|
||||
let db = state.db.lock().await;
|
||||
db.clear()
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Serialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct LyricsCacheStats {
|
||||
pub entries: u64,
|
||||
pub size_bytes: u64,
|
||||
}
|
||||
|
||||
#[tauri::command]
|
||||
pub async fn lyrics_get_cache_stats(state: State<'_, LyricsState>) -> Result<LyricsCacheStats, String> {
|
||||
let entries = {
|
||||
let db = state.db.lock().await;
|
||||
db.count_entries()?
|
||||
};
|
||||
|
||||
// Approximate on-disk usage as the SQLite DB file size.
|
||||
let db_path = dirs::cache_dir()
|
||||
.ok_or("Could not determine cache directory")?
|
||||
.join("qbz")
|
||||
.join("lyrics")
|
||||
.join("lyrics.db");
|
||||
let size_bytes = std::fs::metadata(&db_path)
|
||||
.map(|m| m.len())
|
||||
.unwrap_or(0);
|
||||
|
||||
Ok(LyricsCacheStats { entries, size_bytes })
|
||||
}
|
||||
Reference in new issue
Block a user