Compare commits
3 Commits
8ddad497bf
...
642ec17069
| Author | SHA1 | Date | |
|---|---|---|---|
| 642ec17069 | |||
| e560258a4b | |||
| d1e5ba4c5d |
@ -10,6 +10,13 @@ use crate::download::{DownloadInfo, DownloadManager};
|
|||||||
use crate::storage::db_service::{DatabaseService, Query, QueryParam};
|
use crate::storage::db_service::{DatabaseService, Query, QueryParam};
|
||||||
use super::{DatabaseWrapper, SmartCacheWrapper};
|
use super::{DatabaseWrapper, SmartCacheWrapper};
|
||||||
|
|
||||||
|
// Cohesive command clusters in their own submodules, re-exported so the command
|
||||||
|
// names remain at `commands::download::*` (invoke_handler unchanged).
|
||||||
|
mod pinning;
|
||||||
|
mod smart_cache;
|
||||||
|
pub use pinning::*;
|
||||||
|
pub use smart_cache::*;
|
||||||
|
|
||||||
/// Wrapper for DownloadManager to be used as Tauri state
|
/// Wrapper for DownloadManager to be used as Tauri state
|
||||||
pub struct DownloadManagerWrapper(pub Mutex<DownloadManager>);
|
pub struct DownloadManagerWrapper(pub Mutex<DownloadManager>);
|
||||||
|
|
||||||
@ -522,61 +529,6 @@ pub async fn download_season(
|
|||||||
Ok(download_ids)
|
Ok(download_ids)
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Pin an item's metadata (protects from cache clear)
|
|
||||||
#[tauri::command]
|
|
||||||
pub async fn pin_item(db: State<'_, DatabaseWrapper>, item_id: String) -> Result<(), String> {
|
|
||||||
let db_service = {
|
|
||||||
let database = db.0.lock().map_err(|e| e.to_string())?;
|
|
||||||
Arc::new(database.service())
|
|
||||||
};
|
|
||||||
|
|
||||||
let query = Query::with_params(
|
|
||||||
"UPDATE items SET is_pinned = 1 WHERE id = ?",
|
|
||||||
vec![QueryParam::String(item_id)],
|
|
||||||
);
|
|
||||||
|
|
||||||
db_service.execute(query).await.map_err(|e| e.to_string())?;
|
|
||||||
Ok(())
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Unpin an item's metadata
|
|
||||||
#[tauri::command]
|
|
||||||
pub async fn unpin_item(db: State<'_, DatabaseWrapper>, item_id: String) -> Result<(), String> {
|
|
||||||
let db_service = {
|
|
||||||
let database = db.0.lock().map_err(|e| e.to_string())?;
|
|
||||||
Arc::new(database.service())
|
|
||||||
};
|
|
||||||
|
|
||||||
let query = Query::with_params(
|
|
||||||
"UPDATE items SET is_pinned = 0 WHERE id = ?",
|
|
||||||
vec![QueryParam::String(item_id)],
|
|
||||||
);
|
|
||||||
|
|
||||||
db_service.execute(query).await.map_err(|e| e.to_string())?;
|
|
||||||
Ok(())
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Check if an item is pinned
|
|
||||||
#[tauri::command]
|
|
||||||
pub async fn is_item_pinned(db: State<'_, DatabaseWrapper>, item_id: String) -> Result<bool, String> {
|
|
||||||
let db_service = {
|
|
||||||
let database = db.0.lock().map_err(|e| e.to_string())?;
|
|
||||||
Arc::new(database.service())
|
|
||||||
};
|
|
||||||
|
|
||||||
let query = Query::with_params(
|
|
||||||
"SELECT COALESCE(is_pinned, 0) FROM items WHERE id = ?",
|
|
||||||
vec![QueryParam::String(item_id)],
|
|
||||||
);
|
|
||||||
|
|
||||||
let is_pinned: i32 = db_service
|
|
||||||
.query_optional(query, |row| row.get(0))
|
|
||||||
.await
|
|
||||||
.map_err(|e| e.to_string())?
|
|
||||||
.unwrap_or(0);
|
|
||||||
|
|
||||||
Ok(is_pinned == 1)
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Helper to compute download statistics from a list of downloads
|
/// Helper to compute download statistics from a list of downloads
|
||||||
#[allow(dead_code)]
|
#[allow(dead_code)]
|
||||||
@ -1336,220 +1288,6 @@ pub async fn set_max_concurrent_downloads(
|
|||||||
Ok(())
|
Ok(())
|
||||||
}
|
}
|
||||||
|
|
||||||
/// SmartCache statistics
|
|
||||||
#[derive(Debug, Clone, serde::Serialize)]
|
|
||||||
pub struct SmartCacheStats {
|
|
||||||
pub total_size: u64,
|
|
||||||
pub storage_limit: u64,
|
|
||||||
pub available_space: u64,
|
|
||||||
pub items_count: i64,
|
|
||||||
pub config: crate::download::cache::CacheConfig,
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Get SmartCache statistics
|
|
||||||
#[tauri::command]
|
|
||||||
pub async fn get_smart_cache_stats(
|
|
||||||
db: State<'_, DatabaseWrapper>,
|
|
||||||
smart_cache: State<'_, SmartCacheWrapper>,
|
|
||||||
user_id: String,
|
|
||||||
) -> Result<SmartCacheStats, String> {
|
|
||||||
let db_service = {
|
|
||||||
let database = db.0.lock().map_err(|e| e.to_string())?;
|
|
||||||
Arc::new(database.service())
|
|
||||||
};
|
|
||||||
|
|
||||||
// Clone cache to avoid holding lock across async operations
|
|
||||||
let cache = {
|
|
||||||
let guard = smart_cache.0.lock().map_err(|e| e.to_string())?;
|
|
||||||
guard.clone()
|
|
||||||
};
|
|
||||||
|
|
||||||
let total_size = cache
|
|
||||||
.get_total_download_size_async(&db_service, &user_id)
|
|
||||||
.await?;
|
|
||||||
|
|
||||||
let config = cache
|
|
||||||
.get_config()
|
|
||||||
.ok_or_else(|| "Failed to get cache config".to_string())?;
|
|
||||||
|
|
||||||
let storage_limit = config.storage_limit;
|
|
||||||
let available_space = storage_limit.saturating_sub(total_size);
|
|
||||||
|
|
||||||
// Get item count
|
|
||||||
let count_query = Query::with_params(
|
|
||||||
"SELECT COUNT(*) FROM downloads WHERE user_id = ? AND status = 'completed'",
|
|
||||||
vec![QueryParam::String(user_id)],
|
|
||||||
);
|
|
||||||
let items_count: i64 = db_service
|
|
||||||
.query_one(count_query, |row| row.get(0))
|
|
||||||
.await
|
|
||||||
.unwrap_or(0);
|
|
||||||
|
|
||||||
Ok(SmartCacheStats {
|
|
||||||
total_size,
|
|
||||||
storage_limit,
|
|
||||||
available_space,
|
|
||||||
items_count,
|
|
||||||
config,
|
|
||||||
})
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Update SmartCache configuration
|
|
||||||
#[tauri::command]
|
|
||||||
pub async fn update_smart_cache_config(
|
|
||||||
smart_cache: State<'_, SmartCacheWrapper>,
|
|
||||||
config: crate::download::cache::CacheConfig,
|
|
||||||
) -> Result<(), String> {
|
|
||||||
let cache = smart_cache.0.lock().map_err(|e| e.to_string())?;
|
|
||||||
cache.update_config(config);
|
|
||||||
info!("Updated SmartCache configuration");
|
|
||||||
Ok(())
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Get SmartCache configuration
|
|
||||||
#[tauri::command]
|
|
||||||
pub async fn get_smart_cache_config(
|
|
||||||
smart_cache: State<'_, SmartCacheWrapper>,
|
|
||||||
) -> Result<crate::download::cache::CacheConfig, String> {
|
|
||||||
let cache = smart_cache.0.lock().map_err(|e| e.to_string())?;
|
|
||||||
cache
|
|
||||||
.get_config()
|
|
||||||
.ok_or_else(|| "Failed to get cache config".to_string())
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Album recommendation info
|
|
||||||
#[derive(Debug, Clone, serde::Serialize)]
|
|
||||||
pub struct AlbumRecommendation {
|
|
||||||
pub album_id: String,
|
|
||||||
pub album_name: String,
|
|
||||||
pub tracks_played: usize,
|
|
||||||
pub total_tracks: usize,
|
|
||||||
pub should_download: bool,
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Album affinity status info
|
|
||||||
#[derive(Debug, Clone, serde::Serialize)]
|
|
||||||
#[serde(rename_all = "camelCase")]
|
|
||||||
pub struct AlbumAffinityStatus {
|
|
||||||
pub album_id: String,
|
|
||||||
pub unique_tracks_played: usize,
|
|
||||||
pub threshold: usize,
|
|
||||||
pub threshold_reached: bool,
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Get album recommendations based on play history
|
|
||||||
#[tauri::command]
|
|
||||||
pub async fn get_album_recommendations(
|
|
||||||
db: State<'_, DatabaseWrapper>,
|
|
||||||
smart_cache: State<'_, SmartCacheWrapper>,
|
|
||||||
user_id: String,
|
|
||||||
) -> Result<Vec<AlbumRecommendation>, String> {
|
|
||||||
let db_service = {
|
|
||||||
let database = db.0.lock().map_err(|e| e.to_string())?;
|
|
||||||
Arc::new(database.service())
|
|
||||||
};
|
|
||||||
|
|
||||||
// Clone cache to avoid holding lock across async operations
|
|
||||||
let cache = {
|
|
||||||
let guard = smart_cache.0.lock().map_err(|e| e.to_string())?;
|
|
||||||
guard.clone()
|
|
||||||
};
|
|
||||||
|
|
||||||
// Get all albums that user has played tracks from
|
|
||||||
let query = Query::with_params(
|
|
||||||
"SELECT DISTINCT i.album_id, a.name
|
|
||||||
FROM user_data ud
|
|
||||||
JOIN items i ON ud.item_id = i.id
|
|
||||||
JOIN items a ON i.album_id = a.id
|
|
||||||
WHERE ud.user_id = ?
|
|
||||||
AND ud.play_count > 0
|
|
||||||
AND i.item_type = 'Audio'
|
|
||||||
AND i.album_id IS NOT NULL",
|
|
||||||
vec![QueryParam::String(user_id.clone())],
|
|
||||||
);
|
|
||||||
|
|
||||||
let albums: Vec<(String, String)> = db_service
|
|
||||||
.query_many(query, |row| Ok((row.get(0)?, row.get(1)?)))
|
|
||||||
.await
|
|
||||||
.unwrap_or_default();
|
|
||||||
|
|
||||||
let mut recommendations = Vec::new();
|
|
||||||
|
|
||||||
for (album_id, album_name) in albums {
|
|
||||||
// Check if should cache
|
|
||||||
let should_download = cache.should_cache_album(&album_id).unwrap_or(false);
|
|
||||||
|
|
||||||
// Get track counts
|
|
||||||
let tracks_query = Query::with_params(
|
|
||||||
"SELECT
|
|
||||||
COUNT(*) as total,
|
|
||||||
COUNT(ud.id) as played
|
|
||||||
FROM items i
|
|
||||||
LEFT JOIN user_data ud ON i.id = ud.item_id AND ud.user_id = ?
|
|
||||||
WHERE i.album_id = ? AND i.item_type = 'Audio'",
|
|
||||||
vec![
|
|
||||||
QueryParam::String(user_id.clone()),
|
|
||||||
QueryParam::String(album_id.clone()),
|
|
||||||
],
|
|
||||||
);
|
|
||||||
|
|
||||||
let (total_tracks, tracks_played): (i64, i64) = db_service
|
|
||||||
.query_one(tracks_query, |row| Ok((row.get(0)?, row.get(1)?)))
|
|
||||||
.await
|
|
||||||
.unwrap_or((0, 0));
|
|
||||||
|
|
||||||
if tracks_played > 0 {
|
|
||||||
recommendations.push(AlbumRecommendation {
|
|
||||||
album_id,
|
|
||||||
album_name,
|
|
||||||
tracks_played: tracks_played as usize,
|
|
||||||
total_tracks: total_tracks as usize,
|
|
||||||
should_download,
|
|
||||||
});
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// Sort by tracks played (descending)
|
|
||||||
recommendations.sort_by(|a, b| b.tracks_played.cmp(&a.tracks_played));
|
|
||||||
|
|
||||||
Ok(recommendations)
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Get album affinity status for all tracked albums
|
|
||||||
/// This shows the SmartCache's internal play history and threshold status
|
|
||||||
#[tauri::command]
|
|
||||||
pub fn get_album_affinity_status(
|
|
||||||
smart_cache: State<'_, SmartCacheWrapper>,
|
|
||||||
) -> Result<Vec<AlbumAffinityStatus>, String> {
|
|
||||||
let cache = smart_cache.0.lock().map_err(|e| e.to_string())?;
|
|
||||||
|
|
||||||
// Get the threshold from config
|
|
||||||
let threshold = cache
|
|
||||||
.get_config()
|
|
||||||
.map(|c| c.album_affinity_threshold)
|
|
||||||
.unwrap_or(3);
|
|
||||||
|
|
||||||
// Get all tracked albums with their play counts
|
|
||||||
let play_history = cache.get_album_play_history();
|
|
||||||
|
|
||||||
let mut statuses: Vec<AlbumAffinityStatus> = play_history
|
|
||||||
.into_iter()
|
|
||||||
.map(|(album_id, unique_tracks_played)| {
|
|
||||||
let threshold_reached = unique_tracks_played >= threshold;
|
|
||||||
AlbumAffinityStatus {
|
|
||||||
album_id,
|
|
||||||
unique_tracks_played,
|
|
||||||
threshold,
|
|
||||||
threshold_reached,
|
|
||||||
}
|
|
||||||
})
|
|
||||||
.collect();
|
|
||||||
|
|
||||||
// Sort by play count (descending)
|
|
||||||
statuses.sort_by(|a, b| b.unique_tracks_played.cmp(&a.unique_tracks_played));
|
|
||||||
|
|
||||||
Ok(statuses)
|
|
||||||
}
|
|
||||||
|
|
||||||
// TRACES: UR-011, UR-018 | DR-015, DR-018 | UT-042, UT-043
|
// TRACES: UR-011, UR-018 | DR-015, DR-018 | UT-042, UT-043
|
||||||
#[cfg(test)]
|
#[cfg(test)]
|
||||||
63
src-tauri/src/commands/download/pinning.rs
Normal file
63
src-tauri/src/commands/download/pinning.rs
Normal file
@ -0,0 +1,63 @@
|
|||||||
|
//! Pinning commands - protect an item's cached metadata from cache clearing.
|
||||||
|
|
||||||
|
use std::sync::Arc;
|
||||||
|
use tauri::State;
|
||||||
|
|
||||||
|
use crate::commands::DatabaseWrapper;
|
||||||
|
use crate::storage::db_service::{DatabaseService, Query, QueryParam};
|
||||||
|
|
||||||
|
/// Pin an item's metadata (protects from cache clear)
|
||||||
|
#[tauri::command]
|
||||||
|
pub async fn pin_item(db: State<'_, DatabaseWrapper>, item_id: String) -> Result<(), String> {
|
||||||
|
let db_service = {
|
||||||
|
let database = db.0.lock().map_err(|e| e.to_string())?;
|
||||||
|
Arc::new(database.service())
|
||||||
|
};
|
||||||
|
|
||||||
|
let query = Query::with_params(
|
||||||
|
"UPDATE items SET is_pinned = 1 WHERE id = ?",
|
||||||
|
vec![QueryParam::String(item_id)],
|
||||||
|
);
|
||||||
|
|
||||||
|
db_service.execute(query).await.map_err(|e| e.to_string())?;
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Unpin an item's metadata
|
||||||
|
#[tauri::command]
|
||||||
|
pub async fn unpin_item(db: State<'_, DatabaseWrapper>, item_id: String) -> Result<(), String> {
|
||||||
|
let db_service = {
|
||||||
|
let database = db.0.lock().map_err(|e| e.to_string())?;
|
||||||
|
Arc::new(database.service())
|
||||||
|
};
|
||||||
|
|
||||||
|
let query = Query::with_params(
|
||||||
|
"UPDATE items SET is_pinned = 0 WHERE id = ?",
|
||||||
|
vec![QueryParam::String(item_id)],
|
||||||
|
);
|
||||||
|
|
||||||
|
db_service.execute(query).await.map_err(|e| e.to_string())?;
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Check if an item is pinned
|
||||||
|
#[tauri::command]
|
||||||
|
pub async fn is_item_pinned(db: State<'_, DatabaseWrapper>, item_id: String) -> Result<bool, String> {
|
||||||
|
let db_service = {
|
||||||
|
let database = db.0.lock().map_err(|e| e.to_string())?;
|
||||||
|
Arc::new(database.service())
|
||||||
|
};
|
||||||
|
|
||||||
|
let query = Query::with_params(
|
||||||
|
"SELECT COALESCE(is_pinned, 0) FROM items WHERE id = ?",
|
||||||
|
vec![QueryParam::String(item_id)],
|
||||||
|
);
|
||||||
|
|
||||||
|
let is_pinned: i32 = db_service
|
||||||
|
.query_optional(query, |row| row.get(0))
|
||||||
|
.await
|
||||||
|
.map_err(|e| e.to_string())?
|
||||||
|
.unwrap_or(0);
|
||||||
|
|
||||||
|
Ok(is_pinned == 1)
|
||||||
|
}
|
||||||
223
src-tauri/src/commands/download/smart_cache.rs
Normal file
223
src-tauri/src/commands/download/smart_cache.rs
Normal file
@ -0,0 +1,223 @@
|
|||||||
|
//! Smart-cache statistics/config and album recommendation commands.
|
||||||
|
|
||||||
|
use std::sync::Arc;
|
||||||
|
use log::info;
|
||||||
|
use tauri::State;
|
||||||
|
|
||||||
|
use crate::commands::{DatabaseWrapper, SmartCacheWrapper};
|
||||||
|
use crate::storage::db_service::{DatabaseService, Query, QueryParam};
|
||||||
|
|
||||||
|
/// SmartCache statistics
|
||||||
|
#[derive(Debug, Clone, serde::Serialize)]
|
||||||
|
pub struct SmartCacheStats {
|
||||||
|
pub total_size: u64,
|
||||||
|
pub storage_limit: u64,
|
||||||
|
pub available_space: u64,
|
||||||
|
pub items_count: i64,
|
||||||
|
pub config: crate::download::cache::CacheConfig,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Get SmartCache statistics
|
||||||
|
#[tauri::command]
|
||||||
|
pub async fn get_smart_cache_stats(
|
||||||
|
db: State<'_, DatabaseWrapper>,
|
||||||
|
smart_cache: State<'_, SmartCacheWrapper>,
|
||||||
|
user_id: String,
|
||||||
|
) -> Result<SmartCacheStats, String> {
|
||||||
|
let db_service = {
|
||||||
|
let database = db.0.lock().map_err(|e| e.to_string())?;
|
||||||
|
Arc::new(database.service())
|
||||||
|
};
|
||||||
|
|
||||||
|
// Clone cache to avoid holding lock across async operations
|
||||||
|
let cache = {
|
||||||
|
let guard = smart_cache.0.lock().map_err(|e| e.to_string())?;
|
||||||
|
guard.clone()
|
||||||
|
};
|
||||||
|
|
||||||
|
let total_size = cache
|
||||||
|
.get_total_download_size_async(&db_service, &user_id)
|
||||||
|
.await?;
|
||||||
|
|
||||||
|
let config = cache
|
||||||
|
.get_config()
|
||||||
|
.ok_or_else(|| "Failed to get cache config".to_string())?;
|
||||||
|
|
||||||
|
let storage_limit = config.storage_limit;
|
||||||
|
let available_space = storage_limit.saturating_sub(total_size);
|
||||||
|
|
||||||
|
// Get item count
|
||||||
|
let count_query = Query::with_params(
|
||||||
|
"SELECT COUNT(*) FROM downloads WHERE user_id = ? AND status = 'completed'",
|
||||||
|
vec![QueryParam::String(user_id)],
|
||||||
|
);
|
||||||
|
let items_count: i64 = db_service
|
||||||
|
.query_one(count_query, |row| row.get(0))
|
||||||
|
.await
|
||||||
|
.unwrap_or(0);
|
||||||
|
|
||||||
|
Ok(SmartCacheStats {
|
||||||
|
total_size,
|
||||||
|
storage_limit,
|
||||||
|
available_space,
|
||||||
|
items_count,
|
||||||
|
config,
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Update SmartCache configuration
|
||||||
|
#[tauri::command]
|
||||||
|
pub async fn update_smart_cache_config(
|
||||||
|
smart_cache: State<'_, SmartCacheWrapper>,
|
||||||
|
config: crate::download::cache::CacheConfig,
|
||||||
|
) -> Result<(), String> {
|
||||||
|
let cache = smart_cache.0.lock().map_err(|e| e.to_string())?;
|
||||||
|
cache.update_config(config);
|
||||||
|
info!("Updated SmartCache configuration");
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Get SmartCache configuration
|
||||||
|
#[tauri::command]
|
||||||
|
pub async fn get_smart_cache_config(
|
||||||
|
smart_cache: State<'_, SmartCacheWrapper>,
|
||||||
|
) -> Result<crate::download::cache::CacheConfig, String> {
|
||||||
|
let cache = smart_cache.0.lock().map_err(|e| e.to_string())?;
|
||||||
|
cache
|
||||||
|
.get_config()
|
||||||
|
.ok_or_else(|| "Failed to get cache config".to_string())
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Album recommendation info
|
||||||
|
#[derive(Debug, Clone, serde::Serialize)]
|
||||||
|
pub struct AlbumRecommendation {
|
||||||
|
pub album_id: String,
|
||||||
|
pub album_name: String,
|
||||||
|
pub tracks_played: usize,
|
||||||
|
pub total_tracks: usize,
|
||||||
|
pub should_download: bool,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Album affinity status info
|
||||||
|
#[derive(Debug, Clone, serde::Serialize)]
|
||||||
|
#[serde(rename_all = "camelCase")]
|
||||||
|
pub struct AlbumAffinityStatus {
|
||||||
|
pub album_id: String,
|
||||||
|
pub unique_tracks_played: usize,
|
||||||
|
pub threshold: usize,
|
||||||
|
pub threshold_reached: bool,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Get album recommendations based on play history
|
||||||
|
#[tauri::command]
|
||||||
|
pub async fn get_album_recommendations(
|
||||||
|
db: State<'_, DatabaseWrapper>,
|
||||||
|
smart_cache: State<'_, SmartCacheWrapper>,
|
||||||
|
user_id: String,
|
||||||
|
) -> Result<Vec<AlbumRecommendation>, String> {
|
||||||
|
let db_service = {
|
||||||
|
let database = db.0.lock().map_err(|e| e.to_string())?;
|
||||||
|
Arc::new(database.service())
|
||||||
|
};
|
||||||
|
|
||||||
|
// Clone cache to avoid holding lock across async operations
|
||||||
|
let cache = {
|
||||||
|
let guard = smart_cache.0.lock().map_err(|e| e.to_string())?;
|
||||||
|
guard.clone()
|
||||||
|
};
|
||||||
|
|
||||||
|
// Get all albums that user has played tracks from
|
||||||
|
let query = Query::with_params(
|
||||||
|
"SELECT DISTINCT i.album_id, a.name
|
||||||
|
FROM user_data ud
|
||||||
|
JOIN items i ON ud.item_id = i.id
|
||||||
|
JOIN items a ON i.album_id = a.id
|
||||||
|
WHERE ud.user_id = ?
|
||||||
|
AND ud.play_count > 0
|
||||||
|
AND i.item_type = 'Audio'
|
||||||
|
AND i.album_id IS NOT NULL",
|
||||||
|
vec![QueryParam::String(user_id.clone())],
|
||||||
|
);
|
||||||
|
|
||||||
|
let albums: Vec<(String, String)> = db_service
|
||||||
|
.query_many(query, |row| Ok((row.get(0)?, row.get(1)?)))
|
||||||
|
.await
|
||||||
|
.unwrap_or_default();
|
||||||
|
|
||||||
|
let mut recommendations = Vec::new();
|
||||||
|
|
||||||
|
for (album_id, album_name) in albums {
|
||||||
|
// Check if should cache
|
||||||
|
let should_download = cache.should_cache_album(&album_id).unwrap_or(false);
|
||||||
|
|
||||||
|
// Get track counts
|
||||||
|
let tracks_query = Query::with_params(
|
||||||
|
"SELECT
|
||||||
|
COUNT(*) as total,
|
||||||
|
COUNT(ud.id) as played
|
||||||
|
FROM items i
|
||||||
|
LEFT JOIN user_data ud ON i.id = ud.item_id AND ud.user_id = ?
|
||||||
|
WHERE i.album_id = ? AND i.item_type = 'Audio'",
|
||||||
|
vec![
|
||||||
|
QueryParam::String(user_id.clone()),
|
||||||
|
QueryParam::String(album_id.clone()),
|
||||||
|
],
|
||||||
|
);
|
||||||
|
|
||||||
|
let (total_tracks, tracks_played): (i64, i64) = db_service
|
||||||
|
.query_one(tracks_query, |row| Ok((row.get(0)?, row.get(1)?)))
|
||||||
|
.await
|
||||||
|
.unwrap_or((0, 0));
|
||||||
|
|
||||||
|
if tracks_played > 0 {
|
||||||
|
recommendations.push(AlbumRecommendation {
|
||||||
|
album_id,
|
||||||
|
album_name,
|
||||||
|
tracks_played: tracks_played as usize,
|
||||||
|
total_tracks: total_tracks as usize,
|
||||||
|
should_download,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Sort by tracks played (descending)
|
||||||
|
recommendations.sort_by(|a, b| b.tracks_played.cmp(&a.tracks_played));
|
||||||
|
|
||||||
|
Ok(recommendations)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Get album affinity status for all tracked albums
|
||||||
|
/// This shows the SmartCache's internal play history and threshold status
|
||||||
|
#[tauri::command]
|
||||||
|
pub fn get_album_affinity_status(
|
||||||
|
smart_cache: State<'_, SmartCacheWrapper>,
|
||||||
|
) -> Result<Vec<AlbumAffinityStatus>, String> {
|
||||||
|
let cache = smart_cache.0.lock().map_err(|e| e.to_string())?;
|
||||||
|
|
||||||
|
// Get the threshold from config
|
||||||
|
let threshold = cache
|
||||||
|
.get_config()
|
||||||
|
.map(|c| c.album_affinity_threshold)
|
||||||
|
.unwrap_or(3);
|
||||||
|
|
||||||
|
// Get all tracked albums with their play counts
|
||||||
|
let play_history = cache.get_album_play_history();
|
||||||
|
|
||||||
|
let mut statuses: Vec<AlbumAffinityStatus> = play_history
|
||||||
|
.into_iter()
|
||||||
|
.map(|(album_id, unique_tracks_played)| {
|
||||||
|
let threshold_reached = unique_tracks_played >= threshold;
|
||||||
|
AlbumAffinityStatus {
|
||||||
|
album_id,
|
||||||
|
unique_tracks_played,
|
||||||
|
threshold,
|
||||||
|
threshold_reached,
|
||||||
|
}
|
||||||
|
})
|
||||||
|
.collect();
|
||||||
|
|
||||||
|
// Sort by play count (descending)
|
||||||
|
statuses.sort_by(|a, b| b.unique_tracks_played.cmp(&a.unique_tracks_played));
|
||||||
|
|
||||||
|
Ok(statuses)
|
||||||
|
}
|
||||||
@ -1,9 +1,17 @@
|
|||||||
//! TRACES: UR-003, UR-004, UR-005, UR-010, UR-020, UR-021 | JA-022, JA-023, JA-024, JA-025, JA-026 | DR-001
|
//! TRACES: UR-003, UR-004, UR-005, UR-010, UR-020, UR-021 | JA-022, JA-023, JA-024, JA-025, JA-026 | DR-001
|
||||||
|
|
||||||
// Remote Jellyfin session control commands (casting) live in their own submodule
|
// Cohesive command clusters live in their own submodules and are re-exported so
|
||||||
// and are re-exported so the command names remain at `commands::player::*`.
|
// the command names remain at `commands::player::*` (invoke_handler unchanged).
|
||||||
|
mod queue;
|
||||||
mod remote;
|
mod remote;
|
||||||
|
mod session;
|
||||||
|
mod settings;
|
||||||
|
mod timers;
|
||||||
|
pub use queue::*;
|
||||||
pub use remote::*;
|
pub use remote::*;
|
||||||
|
pub use session::*;
|
||||||
|
pub use settings::*;
|
||||||
|
pub use timers::*;
|
||||||
|
|
||||||
use crate::utils::lock::MutexSafe;
|
use crate::utils::lock::MutexSafe;
|
||||||
use log::{debug, error, info, warn};
|
use log::{debug, error, info, warn};
|
||||||
@ -17,12 +25,12 @@ use super::DatabaseWrapper;
|
|||||||
use crate::download::cache::{CacheConfig, SmartCache};
|
use crate::download::cache::{CacheConfig, SmartCache};
|
||||||
use crate::jellyfin::{JellyfinClient, JellyfinConfig};
|
use crate::jellyfin::{JellyfinClient, JellyfinConfig};
|
||||||
use crate::player::{
|
use crate::player::{
|
||||||
determine_video_seek_strategy, AutoplaySettings, MediaItem, MediaSource, MediaType,
|
determine_video_seek_strategy, MediaItem, MediaSource, MediaType,
|
||||||
MediaSessionManager, PlayerController, PlayerState, PlayerStatusEvent, QueueContext, RepeatMode,
|
MediaSessionManager, PlayerController, PlayerState, PlayerStatusEvent, QueueContext, RepeatMode,
|
||||||
SleepTimerMode, SleepTimerState, VideoSeekStrategy,
|
VideoSeekStrategy,
|
||||||
};
|
};
|
||||||
use crate::repository::{MediaRepository, types::{GetItemsOptions, ImageOptions, ImageType}};
|
use crate::repository::{MediaRepository, types::{GetItemsOptions, ImageOptions, ImageType}};
|
||||||
use crate::settings::{AudioSettings, VideoSettings};
|
use crate::settings::VideoSettings;
|
||||||
use crate::storage::db_service::{DatabaseService, Query, QueryParam};
|
use crate::storage::db_service::{DatabaseService, Query, QueryParam};
|
||||||
|
|
||||||
/// SmartCache wrapper for Tauri state management
|
/// SmartCache wrapper for Tauri state management
|
||||||
@ -280,7 +288,7 @@ pub enum AudioTrackSwitchResponse {
|
|||||||
///
|
///
|
||||||
/// PlayItemRequest is now video-only, so we create a video MediaItem.
|
/// PlayItemRequest is now video-only, so we create a video MediaItem.
|
||||||
/// Audio playback uses player_play_tracks which fetches full metadata from backend.
|
/// Audio playback uses player_play_tracks which fetches full metadata from backend.
|
||||||
async fn create_media_item(
|
pub(super) async fn create_media_item(
|
||||||
req: PlayItemRequest,
|
req: PlayItemRequest,
|
||||||
db: Option<&DatabaseWrapper>,
|
db: Option<&DatabaseWrapper>,
|
||||||
) -> Result<MediaItem, String> {
|
) -> Result<MediaItem, String> {
|
||||||
@ -334,7 +342,7 @@ async fn create_media_item(
|
|||||||
}
|
}
|
||||||
|
|
||||||
/// Check if an item has a completed download
|
/// Check if an item has a completed download
|
||||||
async fn check_for_local_download(
|
pub(super) async fn check_for_local_download(
|
||||||
db: &DatabaseWrapper,
|
db: &DatabaseWrapper,
|
||||||
item_id: &str,
|
item_id: &str,
|
||||||
) -> Result<Option<String>, String> {
|
) -> Result<Option<String>, String> {
|
||||||
@ -1162,58 +1170,8 @@ pub async fn player_get_queue(player: State<'_, PlayerStateWrapper>) -> Result<Q
|
|||||||
Ok(get_queue_status(&controller))
|
Ok(get_queue_status(&controller))
|
||||||
}
|
}
|
||||||
|
|
||||||
#[tauri::command]
|
|
||||||
pub async fn player_set_audio_settings(
|
|
||||||
player: State<'_, PlayerStateWrapper>,
|
|
||||||
settings: AudioSettings,
|
|
||||||
) -> Result<AudioSettings, String> {
|
|
||||||
let mut controller = player.0.lock().await;
|
|
||||||
controller
|
|
||||||
.set_audio_settings(&settings)
|
|
||||||
.map_err(|e| e.to_string())?;
|
|
||||||
Ok(controller.audio_settings())
|
|
||||||
}
|
|
||||||
|
|
||||||
#[tauri::command]
|
pub(super) fn get_player_status(controller: &PlayerController) -> PlayerStatus {
|
||||||
pub async fn player_get_audio_settings(
|
|
||||||
player: State<'_, PlayerStateWrapper>,
|
|
||||||
) -> Result<AudioSettings, String> {
|
|
||||||
let controller = player.0.lock().await;
|
|
||||||
Ok(controller.audio_settings())
|
|
||||||
}
|
|
||||||
|
|
||||||
#[tauri::command]
|
|
||||||
pub async fn player_set_video_settings(
|
|
||||||
video_settings: State<'_, VideoSettingsWrapper>,
|
|
||||||
player: State<'_, PlayerStateWrapper>,
|
|
||||||
settings: VideoSettings,
|
|
||||||
) -> Result<VideoSettings, String> {
|
|
||||||
let validated = settings.with_countdown_clamped();
|
|
||||||
{
|
|
||||||
let mut current = video_settings.0.lock().map_err(|e| e.to_string())?;
|
|
||||||
*current = validated.clone();
|
|
||||||
} // Drop MutexGuard before await
|
|
||||||
|
|
||||||
// Sync to PlayerController's autoplay settings so on_playback_ended() uses current values
|
|
||||||
let controller = player.0.lock().await;
|
|
||||||
controller.set_autoplay_settings(AutoplaySettings {
|
|
||||||
enabled: validated.auto_play_next_episode,
|
|
||||||
countdown_seconds: validated.auto_play_countdown_seconds,
|
|
||||||
max_episodes: validated.auto_play_max_episodes,
|
|
||||||
});
|
|
||||||
|
|
||||||
Ok(validated)
|
|
||||||
}
|
|
||||||
|
|
||||||
#[tauri::command]
|
|
||||||
pub async fn player_get_video_settings(
|
|
||||||
video_settings: State<'_, VideoSettingsWrapper>,
|
|
||||||
) -> Result<VideoSettings, String> {
|
|
||||||
let current = video_settings.0.lock().map_err(|e| e.to_string())?;
|
|
||||||
Ok(current.clone())
|
|
||||||
}
|
|
||||||
|
|
||||||
fn get_player_status(controller: &PlayerController) -> PlayerStatus {
|
|
||||||
// Determine backend at compile time based on platform
|
// Determine backend at compile time based on platform
|
||||||
let (backend, use_html5_element) = if cfg!(target_os = "android") {
|
let (backend, use_html5_element) = if cfg!(target_os = "android") {
|
||||||
// Android uses ExoPlayer native backend
|
// Android uses ExoPlayer native backend
|
||||||
@ -1241,7 +1199,7 @@ fn get_player_status(controller: &PlayerController) -> PlayerStatus {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
fn get_queue_status(controller: &PlayerController) -> QueueStatus {
|
pub(super) fn get_queue_status(controller: &PlayerController) -> QueueStatus {
|
||||||
let queue = controller.queue();
|
let queue = controller.queue();
|
||||||
let queue_lock = queue.lock_safe();
|
let queue_lock = queue.lock_safe();
|
||||||
|
|
||||||
@ -1255,351 +1213,6 @@ fn get_queue_status(controller: &PlayerController) -> QueueStatus {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Request to add items to queue
|
|
||||||
#[derive(Debug, Deserialize)]
|
|
||||||
#[serde(rename_all = "camelCase")]
|
|
||||||
pub struct AddToQueueRequest {
|
|
||||||
pub items: Vec<PlayItemRequest>,
|
|
||||||
pub position: String, // "next" or "end"
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Request to add a track by ID - backend fetches metadata
|
|
||||||
#[derive(Debug, Deserialize)]
|
|
||||||
#[serde(rename_all = "camelCase")]
|
|
||||||
pub struct AddTrackByIdRequest {
|
|
||||||
pub track_id: String,
|
|
||||||
pub position: String, // "next" or "end"
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Request to add multiple tracks by IDs - backend fetches metadata
|
|
||||||
#[derive(Debug, Deserialize)]
|
|
||||||
#[serde(rename_all = "camelCase")]
|
|
||||||
pub struct AddTracksByIdsRequest {
|
|
||||||
pub track_ids: Vec<String>,
|
|
||||||
pub position: String, // "next" or "end"
|
|
||||||
}
|
|
||||||
|
|
||||||
#[tauri::command]
|
|
||||||
pub async fn player_add_to_queue(
|
|
||||||
player: State<'_, PlayerStateWrapper>,
|
|
||||||
db: State<'_, DatabaseWrapper>,
|
|
||||||
request: AddToQueueRequest,
|
|
||||||
) -> Result<QueueStatus, String> {
|
|
||||||
use crate::player::queue::AddPosition;
|
|
||||||
|
|
||||||
let position = match request.position.as_str() {
|
|
||||||
"next" => AddPosition::Next,
|
|
||||||
_ => AddPosition::End,
|
|
||||||
};
|
|
||||||
|
|
||||||
// Create media items first (without holding any locks during await)
|
|
||||||
let mut items: Vec<MediaItem> = Vec::new();
|
|
||||||
for req in request.items {
|
|
||||||
items.push(create_media_item(req, Some(&db)).await?);
|
|
||||||
}
|
|
||||||
|
|
||||||
// Now add to queue
|
|
||||||
let controller = player.0.lock().await;
|
|
||||||
let queue = controller.queue();
|
|
||||||
let mut queue_lock = queue.lock().map_err(|e| e.to_string())?;
|
|
||||||
|
|
||||||
queue_lock.add(items, position);
|
|
||||||
|
|
||||||
let result = QueueStatus {
|
|
||||||
items: queue_lock.items().to_vec(),
|
|
||||||
current_index: queue_lock.current_index(),
|
|
||||||
shuffle: queue_lock.is_shuffle(),
|
|
||||||
repeat: queue_lock.repeat_mode(),
|
|
||||||
has_next: queue_lock.has_next(),
|
|
||||||
has_previous: queue_lock.has_previous(),
|
|
||||||
};
|
|
||||||
|
|
||||||
drop(queue_lock);
|
|
||||||
controller.emit_queue_changed();
|
|
||||||
|
|
||||||
Ok(result)
|
|
||||||
}
|
|
||||||
|
|
||||||
#[tauri::command]
|
|
||||||
pub async fn player_remove_from_queue(
|
|
||||||
player: State<'_, PlayerStateWrapper>,
|
|
||||||
index: usize,
|
|
||||||
) -> Result<QueueStatus, String> {
|
|
||||||
let controller = player.0.lock().await;
|
|
||||||
let queue = controller.queue();
|
|
||||||
let mut queue_lock = queue.lock().map_err(|e| e.to_string())?;
|
|
||||||
|
|
||||||
queue_lock.remove(index);
|
|
||||||
|
|
||||||
let result = QueueStatus {
|
|
||||||
items: queue_lock.items().to_vec(),
|
|
||||||
current_index: queue_lock.current_index(),
|
|
||||||
shuffle: queue_lock.is_shuffle(),
|
|
||||||
repeat: queue_lock.repeat_mode(),
|
|
||||||
has_next: queue_lock.has_next(),
|
|
||||||
has_previous: queue_lock.has_previous(),
|
|
||||||
};
|
|
||||||
|
|
||||||
drop(queue_lock);
|
|
||||||
controller.emit_queue_changed();
|
|
||||||
|
|
||||||
Ok(result)
|
|
||||||
}
|
|
||||||
|
|
||||||
#[tauri::command]
|
|
||||||
pub async fn player_move_in_queue(
|
|
||||||
player: State<'_, PlayerStateWrapper>,
|
|
||||||
from_index: usize,
|
|
||||||
to_index: usize,
|
|
||||||
) -> Result<QueueStatus, String> {
|
|
||||||
let controller = player.0.lock().await;
|
|
||||||
let queue = controller.queue();
|
|
||||||
let mut queue_lock = queue.lock().map_err(|e| e.to_string())?;
|
|
||||||
|
|
||||||
if !queue_lock.move_item(from_index, to_index) {
|
|
||||||
return Err("Invalid indices for move operation".to_string());
|
|
||||||
}
|
|
||||||
|
|
||||||
let result = QueueStatus {
|
|
||||||
items: queue_lock.items().to_vec(),
|
|
||||||
current_index: queue_lock.current_index(),
|
|
||||||
shuffle: queue_lock.is_shuffle(),
|
|
||||||
repeat: queue_lock.repeat_mode(),
|
|
||||||
has_next: queue_lock.has_next(),
|
|
||||||
has_previous: queue_lock.has_previous(),
|
|
||||||
};
|
|
||||||
|
|
||||||
drop(queue_lock);
|
|
||||||
controller.emit_queue_changed();
|
|
||||||
|
|
||||||
Ok(result)
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Add a track to queue by ID - backend fetches metadata and constructs URLs
|
|
||||||
#[tauri::command]
|
|
||||||
pub async fn player_add_track_by_id(
|
|
||||||
player: State<'_, PlayerStateWrapper>,
|
|
||||||
db: State<'_, DatabaseWrapper>,
|
|
||||||
repository_manager: State<'_, super::repository::RepositoryManagerWrapper>,
|
|
||||||
repository_handle: String,
|
|
||||||
request: AddTrackByIdRequest,
|
|
||||||
) -> Result<QueueStatus, String> {
|
|
||||||
use crate::player::queue::AddPosition;
|
|
||||||
|
|
||||||
info!("player_add_track_by_id called: track_id={}, position={}",
|
|
||||||
request.track_id, request.position);
|
|
||||||
|
|
||||||
// Get repository (hybrid - supports offline/online)
|
|
||||||
let repository = repository_manager.0.get(&repository_handle)
|
|
||||||
.ok_or("Repository not found - user may need to log in")?;
|
|
||||||
|
|
||||||
// Fetch track metadata via repository
|
|
||||||
info!("Fetching metadata for track {} via repository", request.track_id);
|
|
||||||
let track = repository.get_item(&request.track_id).await
|
|
||||||
.map_err(|e| format!("Failed to fetch track metadata: {}", e))?;
|
|
||||||
|
|
||||||
// Check for local download first
|
|
||||||
let local_path = check_for_local_download(&db, &request.track_id).await?;
|
|
||||||
|
|
||||||
let source = if let Some(path) = local_path {
|
|
||||||
info!("Using local download for track {}", request.track_id);
|
|
||||||
MediaSource::Local {
|
|
||||||
file_path: PathBuf::from(path),
|
|
||||||
jellyfin_item_id: Some(track.id.clone()),
|
|
||||||
}
|
|
||||||
} else {
|
|
||||||
// Get stream URL from repository (works online/offline)
|
|
||||||
let stream_url = repository.get_audio_stream_url(&track.id).await
|
|
||||||
.map_err(|e| format!("Failed to get stream URL for {}: {}", track.name, e))?;
|
|
||||||
|
|
||||||
MediaSource::Remote {
|
|
||||||
stream_url,
|
|
||||||
jellyfin_item_id: track.id.clone(),
|
|
||||||
}
|
|
||||||
};
|
|
||||||
|
|
||||||
// Build MediaItem with artwork URL from repository and frontend-compatible fields
|
|
||||||
let primary_image_tag_for_url = track.primary_image_tag.clone();
|
|
||||||
let media_item = MediaItem {
|
|
||||||
id: track.id.clone(),
|
|
||||||
title: track.name.clone(),
|
|
||||||
name: Some(track.name.clone()), // Frontend compatibility
|
|
||||||
artist: track.album_artist.clone().or_else(|| track.artists.as_ref().and_then(|a| a.first().cloned())),
|
|
||||||
album: track.album_name.clone(),
|
|
||||||
album_name: track.album_name.clone(), // Frontend compatibility
|
|
||||||
album_id: track.album_id.clone(),
|
|
||||||
artist_items: track.artist_items.clone(), // For clickable artist links
|
|
||||||
artists: track.artists.clone(), // Fallback artist info
|
|
||||||
primary_image_tag: track.primary_image_tag.clone(), // For frontend image display
|
|
||||||
item_type: Some(track.item_type.clone()), // Frontend compatibility
|
|
||||||
playlist_id: None,
|
|
||||||
duration: track.runtime_ticks.map(|t| t as f64 / 10_000_000.0),
|
|
||||||
artwork_url: primary_image_tag_for_url.and_then(|tag| {
|
|
||||||
track.album_id.as_ref().map(|album_id| {
|
|
||||||
repository.get_image_url(album_id, ImageType::Primary, Some(ImageOptions {
|
|
||||||
max_width: Some(300),
|
|
||||||
tag: Some(tag),
|
|
||||||
..Default::default()
|
|
||||||
}))
|
|
||||||
})
|
|
||||||
}),
|
|
||||||
media_type: MediaType::Audio,
|
|
||||||
source,
|
|
||||||
video_codec: None,
|
|
||||||
needs_transcoding: false,
|
|
||||||
video_width: None,
|
|
||||||
video_height: None,
|
|
||||||
subtitles: vec![],
|
|
||||||
series_id: None,
|
|
||||||
server_id: None,
|
|
||||||
};
|
|
||||||
|
|
||||||
// Add to queue at specified position
|
|
||||||
let position = match request.position.as_str() {
|
|
||||||
"next" => AddPosition::Next,
|
|
||||||
_ => AddPosition::End,
|
|
||||||
};
|
|
||||||
|
|
||||||
let controller = player.0.lock().await;
|
|
||||||
let queue = controller.queue();
|
|
||||||
let mut queue_lock = queue.lock().map_err(|e| e.to_string())?;
|
|
||||||
|
|
||||||
queue_lock.add(vec![media_item], position);
|
|
||||||
|
|
||||||
let result = get_queue_status(&controller);
|
|
||||||
drop(queue_lock);
|
|
||||||
controller.emit_queue_changed();
|
|
||||||
|
|
||||||
info!("Successfully added track {} to queue", request.track_id);
|
|
||||||
Ok(result)
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Add multiple tracks to queue by IDs - backend fetches metadata and constructs URLs
|
|
||||||
#[tauri::command]
|
|
||||||
pub async fn player_add_tracks_by_ids(
|
|
||||||
player: State<'_, PlayerStateWrapper>,
|
|
||||||
db: State<'_, DatabaseWrapper>,
|
|
||||||
repository_manager: State<'_, super::repository::RepositoryManagerWrapper>,
|
|
||||||
repository_handle: String,
|
|
||||||
request: AddTracksByIdsRequest,
|
|
||||||
) -> Result<QueueStatus, String> {
|
|
||||||
use crate::player::queue::AddPosition;
|
|
||||||
|
|
||||||
info!("player_add_tracks_by_ids called: {} tracks, position={}",
|
|
||||||
request.track_ids.len(), request.position);
|
|
||||||
|
|
||||||
// Get repository (hybrid - supports offline/online)
|
|
||||||
let repository = repository_manager.0.get(&repository_handle)
|
|
||||||
.ok_or("Repository not found - user may need to log in")?;
|
|
||||||
|
|
||||||
// Fetch metadata and build MediaItems for all tracks
|
|
||||||
let mut media_items = Vec::new();
|
|
||||||
for track_id in &request.track_ids {
|
|
||||||
info!("Fetching metadata for track {} via repository", track_id);
|
|
||||||
let track = repository.get_item(track_id).await
|
|
||||||
.map_err(|e| format!("Failed to fetch track metadata for {}: {}", track_id, e))?;
|
|
||||||
|
|
||||||
// Check for local download first
|
|
||||||
let local_path = check_for_local_download(&db, track_id).await?;
|
|
||||||
|
|
||||||
let source = if let Some(path) = local_path {
|
|
||||||
info!("Using local download for track {}", track_id);
|
|
||||||
MediaSource::Local {
|
|
||||||
file_path: PathBuf::from(path),
|
|
||||||
jellyfin_item_id: Some(track.id.clone()),
|
|
||||||
}
|
|
||||||
} else {
|
|
||||||
// Get stream URL from repository (works online/offline)
|
|
||||||
let stream_url = repository.get_audio_stream_url(&track.id).await
|
|
||||||
.map_err(|e| format!("Failed to get stream URL for {}: {}", track.name, e))?;
|
|
||||||
|
|
||||||
MediaSource::Remote {
|
|
||||||
stream_url,
|
|
||||||
jellyfin_item_id: track.id.clone(),
|
|
||||||
}
|
|
||||||
};
|
|
||||||
|
|
||||||
// Build MediaItem with artwork URL from repository and frontend-compatible fields
|
|
||||||
let primary_image_tag_for_url = track.primary_image_tag.clone();
|
|
||||||
let media_item = MediaItem {
|
|
||||||
id: track.id.clone(),
|
|
||||||
title: track.name.clone(),
|
|
||||||
name: Some(track.name.clone()), // Frontend compatibility
|
|
||||||
artist: track.album_artist.clone().or_else(|| track.artists.as_ref().and_then(|a| a.first().cloned())),
|
|
||||||
album: track.album_name.clone(),
|
|
||||||
album_name: track.album_name.clone(), // Frontend compatibility
|
|
||||||
album_id: track.album_id.clone(),
|
|
||||||
artist_items: track.artist_items.clone(), // For clickable artist links
|
|
||||||
artists: track.artists.clone(), // Fallback artist info
|
|
||||||
primary_image_tag: track.primary_image_tag.clone(), // For frontend image display
|
|
||||||
item_type: Some(track.item_type.clone()), // Frontend compatibility
|
|
||||||
playlist_id: None,
|
|
||||||
duration: track.runtime_ticks.map(|t| t as f64 / 10_000_000.0),
|
|
||||||
artwork_url: primary_image_tag_for_url.and_then(|tag| {
|
|
||||||
track.album_id.as_ref().map(|album_id| {
|
|
||||||
repository.get_image_url(album_id, ImageType::Primary, Some(ImageOptions {
|
|
||||||
max_width: Some(300),
|
|
||||||
tag: Some(tag),
|
|
||||||
..Default::default()
|
|
||||||
}))
|
|
||||||
})
|
|
||||||
}),
|
|
||||||
media_type: MediaType::Audio,
|
|
||||||
source,
|
|
||||||
video_codec: None,
|
|
||||||
needs_transcoding: false,
|
|
||||||
video_width: None,
|
|
||||||
video_height: None,
|
|
||||||
subtitles: vec![],
|
|
||||||
series_id: None,
|
|
||||||
server_id: None,
|
|
||||||
};
|
|
||||||
|
|
||||||
media_items.push(media_item);
|
|
||||||
}
|
|
||||||
|
|
||||||
// Add to queue at specified position
|
|
||||||
let position = match request.position.as_str() {
|
|
||||||
"next" => AddPosition::Next,
|
|
||||||
_ => AddPosition::End,
|
|
||||||
};
|
|
||||||
|
|
||||||
let controller = player.0.lock().await;
|
|
||||||
let queue = controller.queue();
|
|
||||||
let mut queue_lock = queue.lock().map_err(|e| e.to_string())?;
|
|
||||||
|
|
||||||
queue_lock.add(media_items, position);
|
|
||||||
|
|
||||||
let result = get_queue_status(&controller);
|
|
||||||
drop(queue_lock);
|
|
||||||
controller.emit_queue_changed();
|
|
||||||
|
|
||||||
info!("Successfully added {} tracks to queue", request.track_ids.len());
|
|
||||||
Ok(result)
|
|
||||||
}
|
|
||||||
|
|
||||||
#[tauri::command]
|
|
||||||
pub async fn player_skip_to(
|
|
||||||
player: State<'_, PlayerStateWrapper>,
|
|
||||||
index: usize,
|
|
||||||
) -> Result<PlayerStatus, String> {
|
|
||||||
let controller = player.0.lock().await;
|
|
||||||
|
|
||||||
// Skip to the index and get the item to play
|
|
||||||
let item = {
|
|
||||||
let queue = controller.queue();
|
|
||||||
let mut queue_lock = queue.lock().map_err(|e| e.to_string())?;
|
|
||||||
queue_lock.skip_to(index).cloned().ok_or("Invalid index")?
|
|
||||||
};
|
|
||||||
|
|
||||||
// Play the item without modifying the queue
|
|
||||||
controller.load_and_play(&item).map_err(|e| e.to_string())?;
|
|
||||||
|
|
||||||
// Emit queue changed event
|
|
||||||
controller.emit_queue_changed();
|
|
||||||
|
|
||||||
Ok(get_player_status(&controller))
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Play a track from an album - backend fetches all album tracks and builds queue
|
/// Play a track from an album - backend fetches all album tracks and builds queue
|
||||||
#[tauri::command]
|
#[tauri::command]
|
||||||
@ -2116,255 +1729,6 @@ pub async fn player_disable_jellyfin(
|
|||||||
Ok(())
|
Ok(())
|
||||||
}
|
}
|
||||||
|
|
||||||
// ===== Sleep Timer Commands =====
|
|
||||||
|
|
||||||
/// Set sleep timer mode
|
|
||||||
#[tauri::command]
|
|
||||||
pub async fn player_set_sleep_timer(
|
|
||||||
player: State<'_, PlayerStateWrapper>,
|
|
||||||
mode: SleepTimerMode,
|
|
||||||
) -> Result<SleepTimerState, String> {
|
|
||||||
let controller = player.0.lock().await;
|
|
||||||
controller.set_sleep_timer(mode);
|
|
||||||
Ok(controller.sleep_timer_state())
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Cancel sleep timer
|
|
||||||
#[tauri::command]
|
|
||||||
pub async fn player_cancel_sleep_timer(
|
|
||||||
player: State<'_, PlayerStateWrapper>,
|
|
||||||
) -> Result<SleepTimerState, String> {
|
|
||||||
let controller = player.0.lock().await;
|
|
||||||
controller.cancel_sleep_timer();
|
|
||||||
Ok(controller.sleep_timer_state())
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Get current sleep timer state
|
|
||||||
#[tauri::command]
|
|
||||||
pub async fn player_get_sleep_timer(
|
|
||||||
player: State<'_, PlayerStateWrapper>,
|
|
||||||
) -> Result<SleepTimerState, String> {
|
|
||||||
let controller = player.0.lock().await;
|
|
||||||
Ok(controller.sleep_timer_state())
|
|
||||||
}
|
|
||||||
|
|
||||||
// ===== Autoplay Commands =====
|
|
||||||
|
|
||||||
/// Get autoplay settings
|
|
||||||
#[tauri::command]
|
|
||||||
pub async fn player_get_autoplay_settings(
|
|
||||||
player: State<'_, PlayerStateWrapper>,
|
|
||||||
) -> Result<AutoplaySettings, String> {
|
|
||||||
let controller = player.0.lock().await;
|
|
||||||
Ok(controller.autoplay_settings())
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Set autoplay settings and persist to database
|
|
||||||
#[tauri::command]
|
|
||||||
pub async fn player_set_autoplay_settings(
|
|
||||||
player: State<'_, PlayerStateWrapper>,
|
|
||||||
db: State<'_, DatabaseWrapper>,
|
|
||||||
user_id: String,
|
|
||||||
settings: AutoplaySettings,
|
|
||||||
) -> Result<AutoplaySettings, String> {
|
|
||||||
let validated = settings.with_validated_countdown();
|
|
||||||
|
|
||||||
// Set in controller
|
|
||||||
{
|
|
||||||
let controller = player.0.lock().await;
|
|
||||||
controller.set_autoplay_settings(validated.clone());
|
|
||||||
}
|
|
||||||
|
|
||||||
// Persist to database
|
|
||||||
let db_service = {
|
|
||||||
let database = db.0.lock().map_err(|e| e.to_string())?;
|
|
||||||
Arc::new(database.service())
|
|
||||||
};
|
|
||||||
|
|
||||||
let query = Query::with_params(
|
|
||||||
"INSERT INTO user_player_settings (user_id, autoplay_next_episode, autoplay_countdown_seconds, autoplay_max_episodes, updated_at)
|
|
||||||
VALUES (?, ?, ?, ?, CURRENT_TIMESTAMP)
|
|
||||||
ON CONFLICT(user_id) DO UPDATE SET
|
|
||||||
autoplay_next_episode = excluded.autoplay_next_episode,
|
|
||||||
autoplay_countdown_seconds = excluded.autoplay_countdown_seconds,
|
|
||||||
autoplay_max_episodes = excluded.autoplay_max_episodes,
|
|
||||||
updated_at = CURRENT_TIMESTAMP",
|
|
||||||
vec![
|
|
||||||
QueryParam::String(user_id),
|
|
||||||
QueryParam::Int(if validated.enabled { 1 } else { 0 }),
|
|
||||||
QueryParam::Int(validated.countdown_seconds as i32),
|
|
||||||
QueryParam::Int(validated.max_episodes as i32),
|
|
||||||
],
|
|
||||||
);
|
|
||||||
|
|
||||||
db_service.execute(query).await.map_err(|e| e.to_string())?;
|
|
||||||
|
|
||||||
Ok(validated)
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Cancel active autoplay countdown
|
|
||||||
#[tauri::command]
|
|
||||||
pub async fn player_cancel_autoplay_countdown(
|
|
||||||
player: State<'_, PlayerStateWrapper>,
|
|
||||||
) -> Result<(), String> {
|
|
||||||
let controller = player.0.lock().await;
|
|
||||||
controller.cancel_autoplay_countdown();
|
|
||||||
Ok(())
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Play next episode (user confirmed from popup)
|
|
||||||
#[tauri::command]
|
|
||||||
pub async fn player_play_next_episode(
|
|
||||||
player: State<'_, PlayerStateWrapper>,
|
|
||||||
db: State<'_, DatabaseWrapper>,
|
|
||||||
item: PlayItemRequest,
|
|
||||||
) -> Result<PlayerStatus, String> {
|
|
||||||
// Convert request to MediaItem
|
|
||||||
let media_item = create_media_item(item, Some(&db)).await?;
|
|
||||||
|
|
||||||
let controller = player.0.lock().await;
|
|
||||||
controller.play_item(media_item).map_err(|e| e.to_string())?;
|
|
||||||
|
|
||||||
Ok(get_player_status(&controller))
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Handle playback ended event - triggers autoplay decision logic
|
|
||||||
/// This is called from:
|
|
||||||
/// - Frontend when HTML5 video ends (Linux/desktop) - passes itemId + repositoryHandle for the video
|
|
||||||
/// - Frontend when audio track ends via backend event - no itemId/repositoryHandle needed
|
|
||||||
/// - Android JNI callback also triggers this logic directly
|
|
||||||
#[tauri::command]
|
|
||||||
pub async fn player_on_playback_ended(
|
|
||||||
player: State<'_, PlayerStateWrapper>,
|
|
||||||
repository_manager: State<'_, super::repository::RepositoryManagerWrapper>,
|
|
||||||
item_id: Option<String>,
|
|
||||||
repository_handle: Option<String>,
|
|
||||||
) -> Result<(), String> {
|
|
||||||
use crate::player::autoplay::AutoplayDecision;
|
|
||||||
use crate::player::PlayerStatusEvent;
|
|
||||||
|
|
||||||
let controller_arc = player.0.clone();
|
|
||||||
|
|
||||||
// Run autoplay decision logic
|
|
||||||
// If item_id is provided (HTML5 video case), use the video-specific path
|
|
||||||
// that bypasses the backend queue and stale end_reason
|
|
||||||
let decision = {
|
|
||||||
let controller = controller_arc.lock().await;
|
|
||||||
if let Some(ref id) = item_id {
|
|
||||||
// Video path: need repository to look up episode info
|
|
||||||
let repo = repository_handle
|
|
||||||
.as_ref()
|
|
||||||
.and_then(|handle| repository_manager.0.get(handle));
|
|
||||||
if let Some(repo) = repo {
|
|
||||||
controller.on_video_playback_ended(id, repo).await?
|
|
||||||
} else {
|
|
||||||
log::warn!("[Autoplay] No repository available for video autoplay (itemId: {})", id);
|
|
||||||
AutoplayDecision::Stop
|
|
||||||
}
|
|
||||||
} else {
|
|
||||||
controller.on_playback_ended().await?
|
|
||||||
}
|
|
||||||
};
|
|
||||||
|
|
||||||
// Handle the decision
|
|
||||||
match decision {
|
|
||||||
AutoplayDecision::Stop => {
|
|
||||||
log::debug!("[Autoplay] Decision: Stop playback");
|
|
||||||
let controller = controller_arc.lock().await;
|
|
||||||
if let Some(emitter) = controller.event_emitter() {
|
|
||||||
// Emit StateChanged to idle to clear the current media from mini player
|
|
||||||
// Note: Do NOT emit PlaybackEnded here - it would cause an infinite loop
|
|
||||||
// (frontend receives PlaybackEnded → calls player_on_playback_ended → Stop → PlaybackEnded → ...)
|
|
||||||
emitter.emit(PlayerStatusEvent::StateChanged {
|
|
||||||
state: "idle".to_string(),
|
|
||||||
media_id: None,
|
|
||||||
});
|
|
||||||
}
|
|
||||||
}
|
|
||||||
AutoplayDecision::AdvanceToNext => {
|
|
||||||
log::debug!("[Autoplay] Decision: Advance to next track");
|
|
||||||
// Advance to next track in queue
|
|
||||||
let controller = controller_arc.lock().await;
|
|
||||||
if let Err(e) = controller.next() {
|
|
||||||
log::error!("[Autoplay] Failed to advance to next track: {}", e);
|
|
||||||
// Emit PlaybackEnded event on error
|
|
||||||
if let Some(emitter) = controller.event_emitter() {
|
|
||||||
emitter.emit(PlayerStatusEvent::PlaybackEnded);
|
|
||||||
}
|
|
||||||
} else {
|
|
||||||
// Emit queue changed event so frontend updates UI with new current track
|
|
||||||
controller.emit_queue_changed();
|
|
||||||
}
|
|
||||||
}
|
|
||||||
AutoplayDecision::ShowNextEpisodePopup {
|
|
||||||
current_episode,
|
|
||||||
next_episode,
|
|
||||||
countdown_seconds,
|
|
||||||
auto_advance,
|
|
||||||
} => {
|
|
||||||
log::info!(
|
|
||||||
"[Autoplay] Decision: Show next episode popup (countdown: {}s, auto: {})",
|
|
||||||
countdown_seconds,
|
|
||||||
auto_advance
|
|
||||||
);
|
|
||||||
|
|
||||||
// Emit popup event to frontend
|
|
||||||
if let Some(emitter) = controller_arc.lock().await.event_emitter() {
|
|
||||||
emitter.emit(PlayerStatusEvent::ShowNextEpisodePopup {
|
|
||||||
current_episode: current_episode.clone(),
|
|
||||||
next_episode: next_episode.clone(),
|
|
||||||
countdown_seconds,
|
|
||||||
auto_advance,
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
// Start countdown if auto_advance enabled
|
|
||||||
if auto_advance {
|
|
||||||
controller_arc
|
|
||||||
.lock()
|
|
||||||
.await
|
|
||||||
.start_autoplay_countdown(next_episode, countdown_seconds);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
Ok(())
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Get the current media session state
|
|
||||||
#[tauri::command]
|
|
||||||
pub async fn player_get_session(
|
|
||||||
session: State<'_, MediaSessionManagerWrapper>,
|
|
||||||
) -> Result<crate::player::session::MediaSessionType, String> {
|
|
||||||
let manager = session.0.lock().map_err(|e| e.to_string())?;
|
|
||||||
Ok(manager.current().clone())
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Dismiss the current media session (returns to Idle)
|
|
||||||
#[tauri::command]
|
|
||||||
pub async fn player_dismiss_session(
|
|
||||||
session: State<'_, MediaSessionManagerWrapper>,
|
|
||||||
player: State<'_, PlayerStateWrapper>,
|
|
||||||
) -> Result<(), String> {
|
|
||||||
log::info!("[Session] Dismissing current media session");
|
|
||||||
|
|
||||||
// Dismiss the session
|
|
||||||
{
|
|
||||||
let mut manager = session.0.lock().map_err(|e| e.to_string())?;
|
|
||||||
manager.dismiss();
|
|
||||||
}
|
|
||||||
|
|
||||||
// Emit session changed event
|
|
||||||
if let Some(emitter) = player.0.lock().await.event_emitter() {
|
|
||||||
let manager = session.0.lock().map_err(|e| e.to_string())?;
|
|
||||||
emitter.emit(PlayerStatusEvent::SessionChanged {
|
|
||||||
session: manager.current().clone(),
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
Ok(())
|
|
||||||
}
|
|
||||||
|
|
||||||
#[cfg(test)]
|
#[cfg(test)]
|
||||||
mod tests {
|
mod tests {
|
||||||
/// Test track index finding in album
|
/// Test track index finding in album
|
||||||
|
|||||||
362
src-tauri/src/commands/player/queue.rs
Normal file
362
src-tauri/src/commands/player/queue.rs
Normal file
@ -0,0 +1,362 @@
|
|||||||
|
//! Queue manipulation commands (add / remove / move / skip).
|
||||||
|
|
||||||
|
use std::path::PathBuf;
|
||||||
|
|
||||||
|
use log::info;
|
||||||
|
use serde::Deserialize;
|
||||||
|
use tauri::State;
|
||||||
|
|
||||||
|
use super::{
|
||||||
|
check_for_local_download, create_media_item, get_player_status, get_queue_status,
|
||||||
|
DatabaseWrapper, PlayItemRequest, PlayerStateWrapper, PlayerStatus, QueueStatus,
|
||||||
|
};
|
||||||
|
use crate::commands::repository::RepositoryManagerWrapper;
|
||||||
|
use crate::player::{MediaItem, MediaSource, MediaType};
|
||||||
|
use crate::repository::types::{ImageOptions, ImageType};
|
||||||
|
use crate::repository::MediaRepository;
|
||||||
|
|
||||||
|
/// Request to add items to queue
|
||||||
|
#[derive(Debug, Deserialize)]
|
||||||
|
#[serde(rename_all = "camelCase")]
|
||||||
|
pub struct AddToQueueRequest {
|
||||||
|
pub items: Vec<PlayItemRequest>,
|
||||||
|
pub position: String, // "next" or "end"
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Request to add a track by ID - backend fetches metadata
|
||||||
|
#[derive(Debug, Deserialize)]
|
||||||
|
#[serde(rename_all = "camelCase")]
|
||||||
|
pub struct AddTrackByIdRequest {
|
||||||
|
pub track_id: String,
|
||||||
|
pub position: String, // "next" or "end"
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Request to add multiple tracks by IDs - backend fetches metadata
|
||||||
|
#[derive(Debug, Deserialize)]
|
||||||
|
#[serde(rename_all = "camelCase")]
|
||||||
|
pub struct AddTracksByIdsRequest {
|
||||||
|
pub track_ids: Vec<String>,
|
||||||
|
pub position: String, // "next" or "end"
|
||||||
|
}
|
||||||
|
|
||||||
|
#[tauri::command]
|
||||||
|
pub async fn player_add_to_queue(
|
||||||
|
player: State<'_, PlayerStateWrapper>,
|
||||||
|
db: State<'_, DatabaseWrapper>,
|
||||||
|
request: AddToQueueRequest,
|
||||||
|
) -> Result<QueueStatus, String> {
|
||||||
|
use crate::player::queue::AddPosition;
|
||||||
|
|
||||||
|
let position = match request.position.as_str() {
|
||||||
|
"next" => AddPosition::Next,
|
||||||
|
_ => AddPosition::End,
|
||||||
|
};
|
||||||
|
|
||||||
|
// Create media items first (without holding any locks during await)
|
||||||
|
let mut items: Vec<MediaItem> = Vec::new();
|
||||||
|
for req in request.items {
|
||||||
|
items.push(create_media_item(req, Some(&db)).await?);
|
||||||
|
}
|
||||||
|
|
||||||
|
// Now add to queue
|
||||||
|
let controller = player.0.lock().await;
|
||||||
|
let queue = controller.queue();
|
||||||
|
let mut queue_lock = queue.lock().map_err(|e| e.to_string())?;
|
||||||
|
|
||||||
|
queue_lock.add(items, position);
|
||||||
|
|
||||||
|
let result = QueueStatus {
|
||||||
|
items: queue_lock.items().to_vec(),
|
||||||
|
current_index: queue_lock.current_index(),
|
||||||
|
shuffle: queue_lock.is_shuffle(),
|
||||||
|
repeat: queue_lock.repeat_mode(),
|
||||||
|
has_next: queue_lock.has_next(),
|
||||||
|
has_previous: queue_lock.has_previous(),
|
||||||
|
};
|
||||||
|
|
||||||
|
drop(queue_lock);
|
||||||
|
controller.emit_queue_changed();
|
||||||
|
|
||||||
|
Ok(result)
|
||||||
|
}
|
||||||
|
|
||||||
|
#[tauri::command]
|
||||||
|
pub async fn player_remove_from_queue(
|
||||||
|
player: State<'_, PlayerStateWrapper>,
|
||||||
|
index: usize,
|
||||||
|
) -> Result<QueueStatus, String> {
|
||||||
|
let controller = player.0.lock().await;
|
||||||
|
let queue = controller.queue();
|
||||||
|
let mut queue_lock = queue.lock().map_err(|e| e.to_string())?;
|
||||||
|
|
||||||
|
queue_lock.remove(index);
|
||||||
|
|
||||||
|
let result = QueueStatus {
|
||||||
|
items: queue_lock.items().to_vec(),
|
||||||
|
current_index: queue_lock.current_index(),
|
||||||
|
shuffle: queue_lock.is_shuffle(),
|
||||||
|
repeat: queue_lock.repeat_mode(),
|
||||||
|
has_next: queue_lock.has_next(),
|
||||||
|
has_previous: queue_lock.has_previous(),
|
||||||
|
};
|
||||||
|
|
||||||
|
drop(queue_lock);
|
||||||
|
controller.emit_queue_changed();
|
||||||
|
|
||||||
|
Ok(result)
|
||||||
|
}
|
||||||
|
|
||||||
|
#[tauri::command]
|
||||||
|
pub async fn player_move_in_queue(
|
||||||
|
player: State<'_, PlayerStateWrapper>,
|
||||||
|
from_index: usize,
|
||||||
|
to_index: usize,
|
||||||
|
) -> Result<QueueStatus, String> {
|
||||||
|
let controller = player.0.lock().await;
|
||||||
|
let queue = controller.queue();
|
||||||
|
let mut queue_lock = queue.lock().map_err(|e| e.to_string())?;
|
||||||
|
|
||||||
|
if !queue_lock.move_item(from_index, to_index) {
|
||||||
|
return Err("Invalid indices for move operation".to_string());
|
||||||
|
}
|
||||||
|
|
||||||
|
let result = QueueStatus {
|
||||||
|
items: queue_lock.items().to_vec(),
|
||||||
|
current_index: queue_lock.current_index(),
|
||||||
|
shuffle: queue_lock.is_shuffle(),
|
||||||
|
repeat: queue_lock.repeat_mode(),
|
||||||
|
has_next: queue_lock.has_next(),
|
||||||
|
has_previous: queue_lock.has_previous(),
|
||||||
|
};
|
||||||
|
|
||||||
|
drop(queue_lock);
|
||||||
|
controller.emit_queue_changed();
|
||||||
|
|
||||||
|
Ok(result)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Add a track to queue by ID - backend fetches metadata and constructs URLs
|
||||||
|
#[tauri::command]
|
||||||
|
pub async fn player_add_track_by_id(
|
||||||
|
player: State<'_, PlayerStateWrapper>,
|
||||||
|
db: State<'_, DatabaseWrapper>,
|
||||||
|
repository_manager: State<'_, RepositoryManagerWrapper>,
|
||||||
|
repository_handle: String,
|
||||||
|
request: AddTrackByIdRequest,
|
||||||
|
) -> Result<QueueStatus, String> {
|
||||||
|
use crate::player::queue::AddPosition;
|
||||||
|
|
||||||
|
info!("player_add_track_by_id called: track_id={}, position={}",
|
||||||
|
request.track_id, request.position);
|
||||||
|
|
||||||
|
// Get repository (hybrid - supports offline/online)
|
||||||
|
let repository = repository_manager.0.get(&repository_handle)
|
||||||
|
.ok_or("Repository not found - user may need to log in")?;
|
||||||
|
|
||||||
|
// Fetch track metadata via repository
|
||||||
|
info!("Fetching metadata for track {} via repository", request.track_id);
|
||||||
|
let track = repository.get_item(&request.track_id).await
|
||||||
|
.map_err(|e| format!("Failed to fetch track metadata: {}", e))?;
|
||||||
|
|
||||||
|
// Check for local download first
|
||||||
|
let local_path = check_for_local_download(&db, &request.track_id).await?;
|
||||||
|
|
||||||
|
let source = if let Some(path) = local_path {
|
||||||
|
info!("Using local download for track {}", request.track_id);
|
||||||
|
MediaSource::Local {
|
||||||
|
file_path: PathBuf::from(path),
|
||||||
|
jellyfin_item_id: Some(track.id.clone()),
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
// Get stream URL from repository (works online/offline)
|
||||||
|
let stream_url = repository.get_audio_stream_url(&track.id).await
|
||||||
|
.map_err(|e| format!("Failed to get stream URL for {}: {}", track.name, e))?;
|
||||||
|
|
||||||
|
MediaSource::Remote {
|
||||||
|
stream_url,
|
||||||
|
jellyfin_item_id: track.id.clone(),
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
// Build MediaItem with artwork URL from repository and frontend-compatible fields
|
||||||
|
let primary_image_tag_for_url = track.primary_image_tag.clone();
|
||||||
|
let media_item = MediaItem {
|
||||||
|
id: track.id.clone(),
|
||||||
|
title: track.name.clone(),
|
||||||
|
name: Some(track.name.clone()), // Frontend compatibility
|
||||||
|
artist: track.album_artist.clone().or_else(|| track.artists.as_ref().and_then(|a| a.first().cloned())),
|
||||||
|
album: track.album_name.clone(),
|
||||||
|
album_name: track.album_name.clone(), // Frontend compatibility
|
||||||
|
album_id: track.album_id.clone(),
|
||||||
|
artist_items: track.artist_items.clone(), // For clickable artist links
|
||||||
|
artists: track.artists.clone(), // Fallback artist info
|
||||||
|
primary_image_tag: track.primary_image_tag.clone(), // For frontend image display
|
||||||
|
item_type: Some(track.item_type.clone()), // Frontend compatibility
|
||||||
|
playlist_id: None,
|
||||||
|
duration: track.runtime_ticks.map(|t| t as f64 / 10_000_000.0),
|
||||||
|
artwork_url: primary_image_tag_for_url.and_then(|tag| {
|
||||||
|
track.album_id.as_ref().map(|album_id| {
|
||||||
|
repository.get_image_url(album_id, ImageType::Primary, Some(ImageOptions {
|
||||||
|
max_width: Some(300),
|
||||||
|
tag: Some(tag),
|
||||||
|
..Default::default()
|
||||||
|
}))
|
||||||
|
})
|
||||||
|
}),
|
||||||
|
media_type: MediaType::Audio,
|
||||||
|
source,
|
||||||
|
video_codec: None,
|
||||||
|
needs_transcoding: false,
|
||||||
|
video_width: None,
|
||||||
|
video_height: None,
|
||||||
|
subtitles: vec![],
|
||||||
|
series_id: None,
|
||||||
|
server_id: None,
|
||||||
|
};
|
||||||
|
|
||||||
|
// Add to queue at specified position
|
||||||
|
let position = match request.position.as_str() {
|
||||||
|
"next" => AddPosition::Next,
|
||||||
|
_ => AddPosition::End,
|
||||||
|
};
|
||||||
|
|
||||||
|
let controller = player.0.lock().await;
|
||||||
|
let queue = controller.queue();
|
||||||
|
let mut queue_lock = queue.lock().map_err(|e| e.to_string())?;
|
||||||
|
|
||||||
|
queue_lock.add(vec![media_item], position);
|
||||||
|
|
||||||
|
let result = get_queue_status(&controller);
|
||||||
|
drop(queue_lock);
|
||||||
|
controller.emit_queue_changed();
|
||||||
|
|
||||||
|
info!("Successfully added track {} to queue", request.track_id);
|
||||||
|
Ok(result)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Add multiple tracks to queue by IDs - backend fetches metadata and constructs URLs
|
||||||
|
#[tauri::command]
|
||||||
|
pub async fn player_add_tracks_by_ids(
|
||||||
|
player: State<'_, PlayerStateWrapper>,
|
||||||
|
db: State<'_, DatabaseWrapper>,
|
||||||
|
repository_manager: State<'_, RepositoryManagerWrapper>,
|
||||||
|
repository_handle: String,
|
||||||
|
request: AddTracksByIdsRequest,
|
||||||
|
) -> Result<QueueStatus, String> {
|
||||||
|
use crate::player::queue::AddPosition;
|
||||||
|
|
||||||
|
info!("player_add_tracks_by_ids called: {} tracks, position={}",
|
||||||
|
request.track_ids.len(), request.position);
|
||||||
|
|
||||||
|
// Get repository (hybrid - supports offline/online)
|
||||||
|
let repository = repository_manager.0.get(&repository_handle)
|
||||||
|
.ok_or("Repository not found - user may need to log in")?;
|
||||||
|
|
||||||
|
// Fetch metadata and build MediaItems for all tracks
|
||||||
|
let mut media_items = Vec::new();
|
||||||
|
for track_id in &request.track_ids {
|
||||||
|
info!("Fetching metadata for track {} via repository", track_id);
|
||||||
|
let track = repository.get_item(track_id).await
|
||||||
|
.map_err(|e| format!("Failed to fetch track metadata for {}: {}", track_id, e))?;
|
||||||
|
|
||||||
|
// Check for local download first
|
||||||
|
let local_path = check_for_local_download(&db, track_id).await?;
|
||||||
|
|
||||||
|
let source = if let Some(path) = local_path {
|
||||||
|
info!("Using local download for track {}", track_id);
|
||||||
|
MediaSource::Local {
|
||||||
|
file_path: PathBuf::from(path),
|
||||||
|
jellyfin_item_id: Some(track.id.clone()),
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
// Get stream URL from repository (works online/offline)
|
||||||
|
let stream_url = repository.get_audio_stream_url(&track.id).await
|
||||||
|
.map_err(|e| format!("Failed to get stream URL for {}: {}", track.name, e))?;
|
||||||
|
|
||||||
|
MediaSource::Remote {
|
||||||
|
stream_url,
|
||||||
|
jellyfin_item_id: track.id.clone(),
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
// Build MediaItem with artwork URL from repository and frontend-compatible fields
|
||||||
|
let primary_image_tag_for_url = track.primary_image_tag.clone();
|
||||||
|
let media_item = MediaItem {
|
||||||
|
id: track.id.clone(),
|
||||||
|
title: track.name.clone(),
|
||||||
|
name: Some(track.name.clone()), // Frontend compatibility
|
||||||
|
artist: track.album_artist.clone().or_else(|| track.artists.as_ref().and_then(|a| a.first().cloned())),
|
||||||
|
album: track.album_name.clone(),
|
||||||
|
album_name: track.album_name.clone(), // Frontend compatibility
|
||||||
|
album_id: track.album_id.clone(),
|
||||||
|
artist_items: track.artist_items.clone(), // For clickable artist links
|
||||||
|
artists: track.artists.clone(), // Fallback artist info
|
||||||
|
primary_image_tag: track.primary_image_tag.clone(), // For frontend image display
|
||||||
|
item_type: Some(track.item_type.clone()), // Frontend compatibility
|
||||||
|
playlist_id: None,
|
||||||
|
duration: track.runtime_ticks.map(|t| t as f64 / 10_000_000.0),
|
||||||
|
artwork_url: primary_image_tag_for_url.and_then(|tag| {
|
||||||
|
track.album_id.as_ref().map(|album_id| {
|
||||||
|
repository.get_image_url(album_id, ImageType::Primary, Some(ImageOptions {
|
||||||
|
max_width: Some(300),
|
||||||
|
tag: Some(tag),
|
||||||
|
..Default::default()
|
||||||
|
}))
|
||||||
|
})
|
||||||
|
}),
|
||||||
|
media_type: MediaType::Audio,
|
||||||
|
source,
|
||||||
|
video_codec: None,
|
||||||
|
needs_transcoding: false,
|
||||||
|
video_width: None,
|
||||||
|
video_height: None,
|
||||||
|
subtitles: vec![],
|
||||||
|
series_id: None,
|
||||||
|
server_id: None,
|
||||||
|
};
|
||||||
|
|
||||||
|
media_items.push(media_item);
|
||||||
|
}
|
||||||
|
|
||||||
|
// Add to queue at specified position
|
||||||
|
let position = match request.position.as_str() {
|
||||||
|
"next" => AddPosition::Next,
|
||||||
|
_ => AddPosition::End,
|
||||||
|
};
|
||||||
|
|
||||||
|
let controller = player.0.lock().await;
|
||||||
|
let queue = controller.queue();
|
||||||
|
let mut queue_lock = queue.lock().map_err(|e| e.to_string())?;
|
||||||
|
|
||||||
|
queue_lock.add(media_items, position);
|
||||||
|
|
||||||
|
let result = get_queue_status(&controller);
|
||||||
|
drop(queue_lock);
|
||||||
|
controller.emit_queue_changed();
|
||||||
|
|
||||||
|
info!("Successfully added {} tracks to queue", request.track_ids.len());
|
||||||
|
Ok(result)
|
||||||
|
}
|
||||||
|
|
||||||
|
#[tauri::command]
|
||||||
|
pub async fn player_skip_to(
|
||||||
|
player: State<'_, PlayerStateWrapper>,
|
||||||
|
index: usize,
|
||||||
|
) -> Result<PlayerStatus, String> {
|
||||||
|
let controller = player.0.lock().await;
|
||||||
|
|
||||||
|
// Skip to the index and get the item to play
|
||||||
|
let item = {
|
||||||
|
let queue = controller.queue();
|
||||||
|
let mut queue_lock = queue.lock().map_err(|e| e.to_string())?;
|
||||||
|
queue_lock.skip_to(index).cloned().ok_or("Invalid index")?
|
||||||
|
};
|
||||||
|
|
||||||
|
// Play the item without modifying the queue
|
||||||
|
controller.load_and_play(&item).map_err(|e| e.to_string())?;
|
||||||
|
|
||||||
|
// Emit queue changed event
|
||||||
|
controller.emit_queue_changed();
|
||||||
|
|
||||||
|
Ok(get_player_status(&controller))
|
||||||
|
}
|
||||||
43
src-tauri/src/commands/player/session.rs
Normal file
43
src-tauri/src/commands/player/session.rs
Normal file
@ -0,0 +1,43 @@
|
|||||||
|
//! Media session state commands.
|
||||||
|
//!
|
||||||
|
//! Read and dismiss the current media session (the Now Playing surface backing
|
||||||
|
//! lockscreen/notification controls).
|
||||||
|
|
||||||
|
use tauri::State;
|
||||||
|
|
||||||
|
use super::{MediaSessionManagerWrapper, PlayerStateWrapper};
|
||||||
|
use crate::player::PlayerStatusEvent;
|
||||||
|
|
||||||
|
/// Get the current media session state
|
||||||
|
#[tauri::command]
|
||||||
|
pub async fn player_get_session(
|
||||||
|
session: State<'_, MediaSessionManagerWrapper>,
|
||||||
|
) -> Result<crate::player::session::MediaSessionType, String> {
|
||||||
|
let manager = session.0.lock().map_err(|e| e.to_string())?;
|
||||||
|
Ok(manager.current().clone())
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Dismiss the current media session (returns to Idle)
|
||||||
|
#[tauri::command]
|
||||||
|
pub async fn player_dismiss_session(
|
||||||
|
session: State<'_, MediaSessionManagerWrapper>,
|
||||||
|
player: State<'_, PlayerStateWrapper>,
|
||||||
|
) -> Result<(), String> {
|
||||||
|
log::info!("[Session] Dismissing current media session");
|
||||||
|
|
||||||
|
// Dismiss the session
|
||||||
|
{
|
||||||
|
let mut manager = session.0.lock().map_err(|e| e.to_string())?;
|
||||||
|
manager.dismiss();
|
||||||
|
}
|
||||||
|
|
||||||
|
// Emit session changed event
|
||||||
|
if let Some(emitter) = player.0.lock().await.event_emitter() {
|
||||||
|
let manager = session.0.lock().map_err(|e| e.to_string())?;
|
||||||
|
emitter.emit(PlayerStatusEvent::SessionChanged {
|
||||||
|
session: manager.current().clone(),
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
58
src-tauri/src/commands/player/settings.rs
Normal file
58
src-tauri/src/commands/player/settings.rs
Normal file
@ -0,0 +1,58 @@
|
|||||||
|
//! Audio and video playback settings commands.
|
||||||
|
|
||||||
|
use tauri::State;
|
||||||
|
|
||||||
|
use super::{PlayerStateWrapper, VideoSettingsWrapper};
|
||||||
|
use crate::player::AutoplaySettings;
|
||||||
|
use crate::settings::{AudioSettings, VideoSettings};
|
||||||
|
|
||||||
|
#[tauri::command]
|
||||||
|
pub async fn player_set_audio_settings(
|
||||||
|
player: State<'_, PlayerStateWrapper>,
|
||||||
|
settings: AudioSettings,
|
||||||
|
) -> Result<AudioSettings, String> {
|
||||||
|
let mut controller = player.0.lock().await;
|
||||||
|
controller
|
||||||
|
.set_audio_settings(&settings)
|
||||||
|
.map_err(|e| e.to_string())?;
|
||||||
|
Ok(controller.audio_settings())
|
||||||
|
}
|
||||||
|
|
||||||
|
#[tauri::command]
|
||||||
|
pub async fn player_get_audio_settings(
|
||||||
|
player: State<'_, PlayerStateWrapper>,
|
||||||
|
) -> Result<AudioSettings, String> {
|
||||||
|
let controller = player.0.lock().await;
|
||||||
|
Ok(controller.audio_settings())
|
||||||
|
}
|
||||||
|
|
||||||
|
#[tauri::command]
|
||||||
|
pub async fn player_set_video_settings(
|
||||||
|
video_settings: State<'_, VideoSettingsWrapper>,
|
||||||
|
player: State<'_, PlayerStateWrapper>,
|
||||||
|
settings: VideoSettings,
|
||||||
|
) -> Result<VideoSettings, String> {
|
||||||
|
let validated = settings.with_countdown_clamped();
|
||||||
|
{
|
||||||
|
let mut current = video_settings.0.lock().map_err(|e| e.to_string())?;
|
||||||
|
*current = validated.clone();
|
||||||
|
} // Drop MutexGuard before await
|
||||||
|
|
||||||
|
// Sync to PlayerController's autoplay settings so on_playback_ended() uses current values
|
||||||
|
let controller = player.0.lock().await;
|
||||||
|
controller.set_autoplay_settings(AutoplaySettings {
|
||||||
|
enabled: validated.auto_play_next_episode,
|
||||||
|
countdown_seconds: validated.auto_play_countdown_seconds,
|
||||||
|
max_episodes: validated.auto_play_max_episodes,
|
||||||
|
});
|
||||||
|
|
||||||
|
Ok(validated)
|
||||||
|
}
|
||||||
|
|
||||||
|
#[tauri::command]
|
||||||
|
pub async fn player_get_video_settings(
|
||||||
|
video_settings: State<'_, VideoSettingsWrapper>,
|
||||||
|
) -> Result<VideoSettings, String> {
|
||||||
|
let current = video_settings.0.lock().map_err(|e| e.to_string())?;
|
||||||
|
Ok(current.clone())
|
||||||
|
}
|
||||||
229
src-tauri/src/commands/player/timers.rs
Normal file
229
src-tauri/src/commands/player/timers.rs
Normal file
@ -0,0 +1,229 @@
|
|||||||
|
//! Sleep-timer and autoplay commands.
|
||||||
|
//!
|
||||||
|
//! Thin command adapters over `PlayerController`'s sleep-timer and autoplay
|
||||||
|
//! logic, plus persistence of autoplay settings to the database.
|
||||||
|
|
||||||
|
use std::sync::Arc;
|
||||||
|
use tauri::State;
|
||||||
|
|
||||||
|
use super::{
|
||||||
|
create_media_item, get_player_status, DatabaseWrapper, PlayItemRequest, PlayerStatus,
|
||||||
|
PlayerStateWrapper,
|
||||||
|
};
|
||||||
|
use crate::player::{AutoplaySettings, SleepTimerMode, SleepTimerState};
|
||||||
|
use crate::storage::db_service::{DatabaseService, Query, QueryParam};
|
||||||
|
|
||||||
|
// ===== Sleep Timer Commands =====
|
||||||
|
|
||||||
|
/// Set sleep timer mode
|
||||||
|
#[tauri::command]
|
||||||
|
pub async fn player_set_sleep_timer(
|
||||||
|
player: State<'_, PlayerStateWrapper>,
|
||||||
|
mode: SleepTimerMode,
|
||||||
|
) -> Result<SleepTimerState, String> {
|
||||||
|
let controller = player.0.lock().await;
|
||||||
|
controller.set_sleep_timer(mode);
|
||||||
|
Ok(controller.sleep_timer_state())
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Cancel sleep timer
|
||||||
|
#[tauri::command]
|
||||||
|
pub async fn player_cancel_sleep_timer(
|
||||||
|
player: State<'_, PlayerStateWrapper>,
|
||||||
|
) -> Result<SleepTimerState, String> {
|
||||||
|
let controller = player.0.lock().await;
|
||||||
|
controller.cancel_sleep_timer();
|
||||||
|
Ok(controller.sleep_timer_state())
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Get current sleep timer state
|
||||||
|
#[tauri::command]
|
||||||
|
pub async fn player_get_sleep_timer(
|
||||||
|
player: State<'_, PlayerStateWrapper>,
|
||||||
|
) -> Result<SleepTimerState, String> {
|
||||||
|
let controller = player.0.lock().await;
|
||||||
|
Ok(controller.sleep_timer_state())
|
||||||
|
}
|
||||||
|
|
||||||
|
// ===== Autoplay Commands =====
|
||||||
|
|
||||||
|
/// Get autoplay settings
|
||||||
|
#[tauri::command]
|
||||||
|
pub async fn player_get_autoplay_settings(
|
||||||
|
player: State<'_, PlayerStateWrapper>,
|
||||||
|
) -> Result<AutoplaySettings, String> {
|
||||||
|
let controller = player.0.lock().await;
|
||||||
|
Ok(controller.autoplay_settings())
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Set autoplay settings and persist to database
|
||||||
|
#[tauri::command]
|
||||||
|
pub async fn player_set_autoplay_settings(
|
||||||
|
player: State<'_, PlayerStateWrapper>,
|
||||||
|
db: State<'_, DatabaseWrapper>,
|
||||||
|
user_id: String,
|
||||||
|
settings: AutoplaySettings,
|
||||||
|
) -> Result<AutoplaySettings, String> {
|
||||||
|
let validated = settings.with_validated_countdown();
|
||||||
|
|
||||||
|
// Set in controller
|
||||||
|
{
|
||||||
|
let controller = player.0.lock().await;
|
||||||
|
controller.set_autoplay_settings(validated.clone());
|
||||||
|
}
|
||||||
|
|
||||||
|
// Persist to database
|
||||||
|
let db_service = {
|
||||||
|
let database = db.0.lock().map_err(|e| e.to_string())?;
|
||||||
|
Arc::new(database.service())
|
||||||
|
};
|
||||||
|
|
||||||
|
let query = Query::with_params(
|
||||||
|
"INSERT INTO user_player_settings (user_id, autoplay_next_episode, autoplay_countdown_seconds, autoplay_max_episodes, updated_at)
|
||||||
|
VALUES (?, ?, ?, ?, CURRENT_TIMESTAMP)
|
||||||
|
ON CONFLICT(user_id) DO UPDATE SET
|
||||||
|
autoplay_next_episode = excluded.autoplay_next_episode,
|
||||||
|
autoplay_countdown_seconds = excluded.autoplay_countdown_seconds,
|
||||||
|
autoplay_max_episodes = excluded.autoplay_max_episodes,
|
||||||
|
updated_at = CURRENT_TIMESTAMP",
|
||||||
|
vec![
|
||||||
|
QueryParam::String(user_id),
|
||||||
|
QueryParam::Int(if validated.enabled { 1 } else { 0 }),
|
||||||
|
QueryParam::Int(validated.countdown_seconds as i32),
|
||||||
|
QueryParam::Int(validated.max_episodes as i32),
|
||||||
|
],
|
||||||
|
);
|
||||||
|
|
||||||
|
db_service.execute(query).await.map_err(|e| e.to_string())?;
|
||||||
|
|
||||||
|
Ok(validated)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Cancel active autoplay countdown
|
||||||
|
#[tauri::command]
|
||||||
|
pub async fn player_cancel_autoplay_countdown(
|
||||||
|
player: State<'_, PlayerStateWrapper>,
|
||||||
|
) -> Result<(), String> {
|
||||||
|
let controller = player.0.lock().await;
|
||||||
|
controller.cancel_autoplay_countdown();
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Play next episode (user confirmed from popup)
|
||||||
|
#[tauri::command]
|
||||||
|
pub async fn player_play_next_episode(
|
||||||
|
player: State<'_, PlayerStateWrapper>,
|
||||||
|
db: State<'_, DatabaseWrapper>,
|
||||||
|
item: PlayItemRequest,
|
||||||
|
) -> Result<PlayerStatus, String> {
|
||||||
|
// Convert request to MediaItem
|
||||||
|
let media_item = create_media_item(item, Some(&db)).await?;
|
||||||
|
|
||||||
|
let controller = player.0.lock().await;
|
||||||
|
controller.play_item(media_item).map_err(|e| e.to_string())?;
|
||||||
|
|
||||||
|
Ok(get_player_status(&controller))
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Handle playback ended event - triggers autoplay decision logic
|
||||||
|
/// This is called from:
|
||||||
|
/// - Frontend when HTML5 video ends (Linux/desktop) - passes itemId + repositoryHandle for the video
|
||||||
|
/// - Frontend when audio track ends via backend event - no itemId/repositoryHandle needed
|
||||||
|
/// - Android JNI callback also triggers this logic directly
|
||||||
|
#[tauri::command]
|
||||||
|
pub async fn player_on_playback_ended(
|
||||||
|
player: State<'_, PlayerStateWrapper>,
|
||||||
|
repository_manager: State<'_, crate::commands::repository::RepositoryManagerWrapper>,
|
||||||
|
item_id: Option<String>,
|
||||||
|
repository_handle: Option<String>,
|
||||||
|
) -> Result<(), String> {
|
||||||
|
use crate::player::autoplay::AutoplayDecision;
|
||||||
|
use crate::player::PlayerStatusEvent;
|
||||||
|
|
||||||
|
let controller_arc = player.0.clone();
|
||||||
|
|
||||||
|
// Run autoplay decision logic
|
||||||
|
// If item_id is provided (HTML5 video case), use the video-specific path
|
||||||
|
// that bypasses the backend queue and stale end_reason
|
||||||
|
let decision = {
|
||||||
|
let controller = controller_arc.lock().await;
|
||||||
|
if let Some(ref id) = item_id {
|
||||||
|
// Video path: need repository to look up episode info
|
||||||
|
let repo = repository_handle
|
||||||
|
.as_ref()
|
||||||
|
.and_then(|handle| repository_manager.0.get(handle));
|
||||||
|
if let Some(repo) = repo {
|
||||||
|
controller.on_video_playback_ended(id, repo).await?
|
||||||
|
} else {
|
||||||
|
log::warn!("[Autoplay] No repository available for video autoplay (itemId: {})", id);
|
||||||
|
AutoplayDecision::Stop
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
controller.on_playback_ended().await?
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
// Handle the decision
|
||||||
|
match decision {
|
||||||
|
AutoplayDecision::Stop => {
|
||||||
|
log::debug!("[Autoplay] Decision: Stop playback");
|
||||||
|
let controller = controller_arc.lock().await;
|
||||||
|
if let Some(emitter) = controller.event_emitter() {
|
||||||
|
// Emit StateChanged to idle to clear the current media from mini player
|
||||||
|
// Note: Do NOT emit PlaybackEnded here - it would cause an infinite loop
|
||||||
|
// (frontend receives PlaybackEnded → calls player_on_playback_ended → Stop → PlaybackEnded → ...)
|
||||||
|
emitter.emit(PlayerStatusEvent::StateChanged {
|
||||||
|
state: "idle".to_string(),
|
||||||
|
media_id: None,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
||||||
|
AutoplayDecision::AdvanceToNext => {
|
||||||
|
log::debug!("[Autoplay] Decision: Advance to next track");
|
||||||
|
// Advance to next track in queue
|
||||||
|
let controller = controller_arc.lock().await;
|
||||||
|
if let Err(e) = controller.next() {
|
||||||
|
log::error!("[Autoplay] Failed to advance to next track: {}", e);
|
||||||
|
// Emit PlaybackEnded event on error
|
||||||
|
if let Some(emitter) = controller.event_emitter() {
|
||||||
|
emitter.emit(PlayerStatusEvent::PlaybackEnded);
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
// Emit queue changed event so frontend updates UI with new current track
|
||||||
|
controller.emit_queue_changed();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
AutoplayDecision::ShowNextEpisodePopup {
|
||||||
|
current_episode,
|
||||||
|
next_episode,
|
||||||
|
countdown_seconds,
|
||||||
|
auto_advance,
|
||||||
|
} => {
|
||||||
|
log::info!(
|
||||||
|
"[Autoplay] Decision: Show next episode popup (countdown: {}s, auto: {})",
|
||||||
|
countdown_seconds,
|
||||||
|
auto_advance
|
||||||
|
);
|
||||||
|
|
||||||
|
// Emit popup event to frontend
|
||||||
|
if let Some(emitter) = controller_arc.lock().await.event_emitter() {
|
||||||
|
emitter.emit(PlayerStatusEvent::ShowNextEpisodePopup {
|
||||||
|
current_episode: current_episode.clone(),
|
||||||
|
next_episode: next_episode.clone(),
|
||||||
|
countdown_seconds,
|
||||||
|
auto_advance,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
// Start countdown if auto_advance enabled
|
||||||
|
if auto_advance {
|
||||||
|
controller_arc
|
||||||
|
.lock()
|
||||||
|
.await
|
||||||
|
.start_autoplay_countdown(next_episode, countdown_seconds);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
@ -12,7 +12,7 @@ mod session_poller;
|
|||||||
pub mod settings;
|
pub mod settings;
|
||||||
mod storage;
|
mod storage;
|
||||||
mod thumbnail;
|
mod thumbnail;
|
||||||
mod utils;
|
pub mod utils;
|
||||||
|
|
||||||
use std::sync::{Arc, Mutex};
|
use std::sync::{Arc, Mutex};
|
||||||
use tokio::sync::Mutex as TokioMutex;
|
use tokio::sync::Mutex as TokioMutex;
|
||||||
|
|||||||
@ -24,6 +24,7 @@ pub const TICKS_PER_SECOND: i64 = 10_000_000;
|
|||||||
///
|
///
|
||||||
/// # Example
|
/// # Example
|
||||||
/// ```
|
/// ```
|
||||||
|
/// # use jellytau_lib::utils::conversions::*;
|
||||||
/// let ticks = seconds_to_ticks(1.5); // 15,000,000 ticks
|
/// let ticks = seconds_to_ticks(1.5); // 15,000,000 ticks
|
||||||
/// ```
|
/// ```
|
||||||
#[inline]
|
#[inline]
|
||||||
@ -41,6 +42,7 @@ pub fn seconds_to_ticks(seconds: f64) -> i64 {
|
|||||||
///
|
///
|
||||||
/// # Example
|
/// # Example
|
||||||
/// ```
|
/// ```
|
||||||
|
/// # use jellytau_lib::utils::conversions::*;
|
||||||
/// let seconds = ticks_to_seconds(15_000_000); // 1.5 seconds
|
/// let seconds = ticks_to_seconds(15_000_000); // 1.5 seconds
|
||||||
/// ```
|
/// ```
|
||||||
#[inline]
|
#[inline]
|
||||||
@ -61,6 +63,7 @@ pub fn ticks_to_seconds(ticks: i64) -> f64 {
|
|||||||
///
|
///
|
||||||
/// # Example
|
/// # Example
|
||||||
/// ```
|
/// ```
|
||||||
|
/// # use jellytau_lib::utils::conversions::*;
|
||||||
/// let normalized = percent_to_volume(75.0); // 0.75
|
/// let normalized = percent_to_volume(75.0); // 0.75
|
||||||
/// ```
|
/// ```
|
||||||
#[inline]
|
#[inline]
|
||||||
@ -81,6 +84,7 @@ pub fn percent_to_volume(percent: f64) -> f64 {
|
|||||||
///
|
///
|
||||||
/// # Example
|
/// # Example
|
||||||
/// ```
|
/// ```
|
||||||
|
/// # use jellytau_lib::utils::conversions::*;
|
||||||
/// let percent = volume_to_percent(0.75); // 75.0
|
/// let percent = volume_to_percent(0.75); // 75.0
|
||||||
/// ```
|
/// ```
|
||||||
#[inline]
|
#[inline]
|
||||||
@ -99,6 +103,7 @@ pub fn volume_to_percent(volume: f64) -> f64 {
|
|||||||
///
|
///
|
||||||
/// # Example
|
/// # Example
|
||||||
/// ```
|
/// ```
|
||||||
|
/// # use jellytau_lib::utils::conversions::*;
|
||||||
/// let formatted = format_time(225.0); // "3:45"
|
/// let formatted = format_time(225.0); // "3:45"
|
||||||
/// ```
|
/// ```
|
||||||
pub fn format_time(seconds: f64) -> String {
|
pub fn format_time(seconds: f64) -> String {
|
||||||
@ -121,6 +126,7 @@ pub fn format_time(seconds: f64) -> String {
|
|||||||
///
|
///
|
||||||
/// # Example
|
/// # Example
|
||||||
/// ```
|
/// ```
|
||||||
|
/// # use jellytau_lib::utils::conversions::*;
|
||||||
/// let short = format_time_long(225.0); // "3:45"
|
/// let short = format_time_long(225.0); // "3:45"
|
||||||
/// let long = format_time_long(5025.0); // "1:23:45"
|
/// let long = format_time_long(5025.0); // "1:23:45"
|
||||||
/// ```
|
/// ```
|
||||||
@ -147,6 +153,7 @@ pub fn format_time_long(seconds: f64) -> String {
|
|||||||
///
|
///
|
||||||
/// # Example
|
/// # Example
|
||||||
/// ```
|
/// ```
|
||||||
|
/// # use jellytau_lib::utils::conversions::*;
|
||||||
/// let progress = calculate_progress(45.0, 180.0); // 25.0
|
/// let progress = calculate_progress(45.0, 180.0); // 25.0
|
||||||
/// ```
|
/// ```
|
||||||
pub fn calculate_progress(position: f64, duration: f64) -> f64 {
|
pub fn calculate_progress(position: f64, duration: f64) -> f64 {
|
||||||
|
|||||||
Loading…
x
Reference in New Issue
Block a user