refactor(v2): hard-delete unused legacy command files

cx
This commit is contained in:
vicrodh committed 2026-02-16 17:11:24 -06:00
1 parent ffd5c992b0
commit 1037b59cfa
23 files changed
-5884

No files matched your search

@@ -1,67 +0,0 @@
//! Tauri commands for artist blacklist management
use tauri::State;
use crate::artist_blacklist::{BlacklistSettings, BlacklistState, BlacklistedArtist};
/// Get all blacklisted artists
#[tauri::command]
pub fn get_artist_blacklist(state: State<BlacklistState>) -> Result<Vec<BlacklistedArtist>, String> {
state.get_all()
}
/// Add an artist to the blacklist
#[tauri::command]
pub fn add_to_artist_blacklist(
artist_id: u64,
artist_name: String,
notes: Option<String>,
state: State<BlacklistState>,
) -> Result<(), String> {
state.add(artist_id, &artist_name, notes.as_deref())
}
/// Remove an artist from the blacklist
#[tauri::command]
pub fn remove_from_artist_blacklist(
artist_id: u64,
state: State<BlacklistState>,
) -> Result<(), String> {
state.remove(artist_id)
}
/// Check if an artist is blacklisted
#[tauri::command]
pub fn is_artist_blacklisted(artist_id: u64, state: State<BlacklistState>) -> Result<bool, String> {
Ok(state.is_blacklisted(artist_id))
}
/// Set the blacklist enabled state
#[tauri::command]
pub fn set_blacklist_enabled(enabled: bool, state: State<BlacklistState>) -> Result<(), String> {
state.set_enabled(enabled)
}
/// Check if the blacklist feature is enabled
#[tauri::command]
pub fn is_blacklist_enabled(state: State<BlacklistState>) -> Result<bool, String> {
Ok(state.is_enabled())
}
/// Get blacklist settings
#[tauri::command]
pub fn get_blacklist_settings(state: State<BlacklistState>) -> Result<BlacklistSettings, String> {
state.get_settings()
}
/// Get the count of blacklisted artists
#[tauri::command]
pub fn get_blacklist_count(state: State<BlacklistState>) -> Result<usize, String> {
Ok(state.count())
}
/// Clear all blacklisted artists
#[tauri::command]
pub fn clear_artist_blacklist(state: State<BlacklistState>) -> Result<(), String> {
state.clear_all()
}
-656
View File
@@ -1,656 +0,0 @@
//! Tauri commands for audio backend management
use crate::audio::{AlsaPlugin, AudioBackendType, AudioDevice, BackendManager};
use serde::{Deserialize, Serialize};
/// Backend information for UI display
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct BackendInfo {
pub backend_type: AudioBackendType,
pub name: String,
pub description: String,
pub is_available: bool,
}
/// ALSA plugin information for UI display
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct AlsaPluginInfo {
pub plugin: AlsaPlugin,
pub name: String,
pub description: String,
}
/// Get list of available audio backends
#[tauri::command]
pub fn get_available_backends() -> Result<Vec<BackendInfo>, String> {
log::info!("Command: get_available_backends");
let backends = BackendManager::available_backends();
let backend_infos: Vec<BackendInfo> = backends
.into_iter()
.map(|backend_type| {
// Create backend instance to check availability and get description
let backend = BackendManager::create_backend(backend_type);
let (is_available, description) = match backend {
Ok(b) => (b.is_available(), b.description().to_string()),
Err(_) => (false, "Not available".to_string()),
};
let name = match backend_type {
AudioBackendType::PipeWire => "PipeWire",
AudioBackendType::Alsa => "ALSA Direct",
AudioBackendType::Pulse => "PulseAudio",
};
BackendInfo {
backend_type,
name: name.to_string(),
description,
is_available,
}
})
.collect();
log::info!("Found {} backends", backend_infos.len());
for info in &backend_infos {
log::info!(" - {} (available: {})", info.name, info.is_available);
}
Ok(backend_infos)
}
/// Get list of devices for a specific backend
#[tauri::command]
pub fn get_devices_for_backend(backend_type: AudioBackendType) -> Result<Vec<AudioDevice>, String> {
log::info!("Command: get_devices_for_backend({:?})", backend_type);
let backend = BackendManager::create_backend(backend_type)?;
let devices = backend.enumerate_devices()?;
log::info!("Found {} devices for {:?} backend", devices.len(), backend_type);
for (idx, device) in devices.iter().enumerate() {
log::info!(" [{}] {} (id: {})", idx, device.name, device.id);
}
Ok(devices)
}
/// Get list of available ALSA plugins
#[tauri::command]
pub fn get_alsa_plugins() -> Result<Vec<AlsaPluginInfo>, String> {
log::info!("Command: get_alsa_plugins");
let plugins = vec![
AlsaPluginInfo {
plugin: AlsaPlugin::Hw,
name: "hw (Direct Hardware)".to_string(),
description: "Bit-perfect, exclusive access, blocks device for other apps".to_string(),
},
AlsaPluginInfo {
plugin: AlsaPlugin::PlugHw,
name: "plughw (Plugin Hardware)".to_string(),
description: "Automatic format conversion, still relatively direct".to_string(),
},
AlsaPluginInfo {
plugin: AlsaPlugin::Pcm,
name: "pcm (Default)".to_string(),
description: "Generic ALSA device, most compatible".to_string(),
},
];
Ok(plugins)
}
/// Check if ALSA device enumeration is available
/// Note: As of v1.1.14, we read directly from /proc/asound instead of using aplay,
/// so alsa-utils package is no longer required. This always returns true for compatibility.
#[tauri::command]
pub fn check_alsa_utils_installed() -> bool {
// We no longer depend on alsa-utils - device info comes from /proc/asound
true
}
/// Get the name/description of the current default audio device for a backend
#[tauri::command]
pub fn get_default_device_name(backend_type: AudioBackendType) -> Option<String> {
use std::process::Command;
match backend_type {
AudioBackendType::PipeWire | AudioBackendType::Pulse => {
// Use pactl to get default sink description
let output = Command::new("pactl")
.args(["get-default-sink"])
.output()
.ok()?;
if !output.status.success() {
return None;
}
let sink_name = String::from_utf8_lossy(&output.stdout).trim().to_string();
if sink_name.is_empty() {
return None;
}
// Now get the description for this sink
let list_output = Command::new("pactl")
.args(["list", "sinks", "short"])
.output()
.ok()?;
// If we can't get description, return the sink name itself
if !list_output.status.success() {
return Some(sink_name);
}
// Try to get a nicer description from pactl list sinks
let full_list = Command::new("pactl")
.args(["list", "sinks"])
.output()
.ok()?;
if full_list.status.success() {
let stdout = String::from_utf8_lossy(&full_list.stdout);
let mut in_target = false;
for line in stdout.lines() {
if line.contains("Name:") && line.contains(&sink_name) {
in_target = true;
}
if in_target && line.trim().starts_with("Description:") {
return line.trim()
.strip_prefix("Description:")
.map(|s| s.trim().to_string());
}
if in_target && line.starts_with("Sink #") {
break; // Moved to next sink
}
}
}
Some(sink_name)
}
AudioBackendType::Alsa => {
// For ALSA, read from /proc/asound to find which card is default
// The "default" ALSA device typically follows PipeWire/Pulse default
// So we can reuse the PipeWire logic, or read ALSA config
// Simple approach: use CPAL to get default device name
use rodio::cpal::traits::HostTrait;
let available_hosts = rodio::cpal::available_hosts();
let alsa_host_id = available_hosts.into_iter().find(|h| h.name() == "ALSA")?;
let host = rodio::cpal::host_from_id(alsa_host_id).ok()?;
let default_device = host.default_output_device()?;
use rodio::cpal::traits::DeviceTrait;
let device_name = default_device.name().ok()?;
// If it's just "default", try to resolve what it actually points to
if device_name == "default" {
// Fall back to PipeWire/Pulse default since ALSA often uses that
return get_default_device_name(AudioBackendType::PipeWire);
}
Some(device_name)
}
}
}
/// Linux distribution info for install commands
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct LinuxDistroInfo {
pub distro_id: String,
pub distro_name: String,
pub install_command: String,
}
/// Detect Linux distribution and return appropriate install command for alsa-utils
#[tauri::command]
pub fn get_linux_distro() -> LinuxDistroInfo {
use std::fs;
// Try to read /etc/os-release
let os_release = fs::read_to_string("/etc/os-release").unwrap_or_default();
let mut distro_id = String::new();
let mut distro_name = String::new();
for line in os_release.lines() {
if let Some(id) = line.strip_prefix("ID=") {
distro_id = id.trim_matches('"').to_lowercase();
}
if let Some(name) = line.strip_prefix("NAME=") {
distro_name = name.trim_matches('"').to_string();
}
}
// Determine install command based on distro
let install_command = match distro_id.as_str() {
"arch" | "manjaro" | "endeavouros" | "garuda" | "artix" =>
"sudo pacman -S alsa-utils".to_string(),
"debian" | "ubuntu" | "linuxmint" | "pop" | "elementary" | "zorin" | "kali" =>
"sudo apt install alsa-utils".to_string(),
"fedora" | "rhel" | "centos" | "rocky" | "alma" =>
"sudo dnf install alsa-utils".to_string(),
"opensuse" | "opensuse-leap" | "opensuse-tumbleweed" =>
"sudo zypper install alsa-utils".to_string(),
"void" =>
"sudo xbps-install alsa-utils".to_string(),
"gentoo" =>
"sudo emerge media-sound/alsa-utils".to_string(),
"nixos" =>
"nix-env -iA nixpkgs.alsa-utils".to_string(),
_ => "# Install alsa-utils using your package manager".to_string(),
};
LinuxDistroInfo {
distro_id,
distro_name,
install_command,
}
}
/// DAC capabilities information
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct DacCapabilities {
pub node_name: String,
pub sample_rates: Vec<u32>,
pub formats: Vec<String>,
pub channels: Option<u32>,
pub description: Option<String>,
pub error: Option<String>,
}
/// Query DAC capabilities from PipeWire
#[tauri::command]
pub fn query_dac_capabilities(node_name: String) -> DacCapabilities {
use std::process::Command;
log::info!("Command: query_dac_capabilities({})", node_name);
let mut caps = DacCapabilities {
node_name: node_name.clone(),
sample_rates: Vec::new(),
formats: Vec::new(),
channels: None,
description: None,
error: None,
};
// First, try to get the node ID from the node name using pw-cli
let pw_dump = Command::new("pw-cli")
.args(["list-objects", "Node"])
.output();
let node_id = match pw_dump {
Ok(output) if output.status.success() => {
let stdout = String::from_utf8_lossy(&output.stdout);
// Find the node ID for this node name
// Format: id X, type PipeWire:Interface:Node/3
// ... node.name = "alsa_output.usb-..."
let mut found_id: Option<String> = None;
let mut current_id: Option<String> = None;
for line in stdout.lines() {
if line.contains("id ") && line.contains("type PipeWire:Interface:Node") {
// Extract ID from line like "id 46, type PipeWire:Interface:Node/3"
if let Some(id_part) = line.split("id ").nth(1) {
if let Some(id) = id_part.split(',').next() {
current_id = Some(id.trim().to_string());
}
}
}
if line.contains("node.name") && line.contains(&node_name) {
found_id = current_id.clone();
break;
}
}
found_id
}
_ => None,
};
// If we found the node ID, query its properties
if let Some(id) = node_id {
log::info!("Found node ID: {} for {}", id, node_name);
// Query node properties using pw-cli
let inspect = Command::new("pw-cli")
.args(["info", &id])
.output();
if let Ok(output) = inspect {
if output.status.success() {
let stdout = String::from_utf8_lossy(&output.stdout);
parse_pw_info(&stdout, &mut caps);
}
}
// Also try pactl for additional info
let pactl = Command::new("pactl")
.args(["list", "sinks"])
.output();
if let Ok(output) = pactl {
if output.status.success() {
let stdout = String::from_utf8_lossy(&output.stdout);
parse_pactl_sinks(&stdout, &node_name, &mut caps);
}
}
} else {
// Try pactl directly if pw-cli didn't find it
let pactl = Command::new("pactl")
.args(["list", "sinks"])
.output();
match pactl {
Ok(output) if output.status.success() => {
let stdout = String::from_utf8_lossy(&output.stdout);
if !parse_pactl_sinks(&stdout, &node_name, &mut caps) {
caps.error = Some("Device not found. Make sure the node name is correct.".to_string());
}
}
Ok(_) => {
caps.error = Some("pactl command failed".to_string());
}
Err(e) => {
caps.error = Some(format!("Failed to run pactl: {}", e));
}
}
}
// Query ALSA hardware capabilities for actual supported rates
// This is more reliable than PipeWire/PulseAudio which only show current config
query_alsa_hw_capabilities(&node_name, &mut caps);
// Sort sample rates
caps.sample_rates.sort();
caps.sample_rates.dedup();
// If we still don't have sample rates, add common defaults with a note
if caps.sample_rates.is_empty() && caps.error.is_none() {
caps.error = Some("Could not detect sample rates. Check device manually.".to_string());
}
log::info!("DAC capabilities: {:?}", caps);
caps
}
/// Query ALSA hardware capabilities from /proc/asound
fn query_alsa_hw_capabilities(node_name: &str, caps: &mut DacCapabilities) {
use std::fs;
// Try to extract card info from node name
// Format: alsa_output.usb-Manufacturer_Product-00.analog-stereo
// or: alsa_output.pci-0000_00_1f.3.analog-stereo
// First, try to find the card by listing /proc/asound/cards
let cards_output = fs::read_to_string("/proc/asound/cards").unwrap_or_default();
// Try to match card by description from pactl or by USB identifier in node name
let mut card_num: Option<u32> = None;
// Extract USB identifier from node name if present
let usb_id = if node_name.contains("usb-") {
node_name
.split("usb-")
.nth(1)
.and_then(|s| s.split('-').next())
.map(|s| s.to_lowercase())
} else {
None
};
// Search for matching card
for line in cards_output.lines() {
// Format: " 0 [Generic ]: USB-Audio - USB Audio"
if let Some(num_str) = line.trim().split_whitespace().next() {
if let Ok(num) = num_str.parse::<u32>() {
let line_lower = line.to_lowercase();
// Match by USB identifier or description
if let Some(ref usb) = usb_id {
if line_lower.contains(usb) || line_lower.contains("usb") {
card_num = Some(num);
break;
}
}
// Match by description if we have one
if let Some(ref desc) = caps.description {
if line_lower.contains(&desc.to_lowercase()) {
card_num = Some(num);
break;
}
}
}
}
}
// If we found a card, try to read its stream info
if let Some(card) = card_num {
log::info!("Found ALSA card {} for {}", card, node_name);
// Try /proc/asound/cardX/stream0 for USB devices
let stream_path = format!("/proc/asound/card{}/stream0", card);
if let Ok(stream_info) = fs::read_to_string(&stream_path) {
parse_alsa_stream_info(&stream_info, caps);
}
// Try /proc/asound/cardX/pcmXp/sub0/hw_params for additional info (if stream is active)
// This provides current hardware params but may not be available if device isn't in use
for subdev in 0..2 {
let hw_params_path = format!("/proc/asound/card{}/pcm{}p/sub0/hw_params", card, subdev);
if let Ok(hw_params) = fs::read_to_string(&hw_params_path) {
if hw_params.contains("rate:") {
parse_proc_hw_params(&hw_params, caps);
break;
}
}
}
}
}
/// Parse /proc/asound/cardX/stream0 output
fn parse_alsa_stream_info(output: &str, caps: &mut DacCapabilities) {
let mut in_playback = false;
for line in output.lines() {
let line = line.trim();
// Look for Playback section
if line.starts_with("Playback:") {
in_playback = true;
continue;
}
if line.starts_with("Capture:") {
in_playback = false;
continue;
}
if in_playback {
// Format line contains info like: "Format: S32_LE"
if line.starts_with("Format:") {
if let Some(format) = line.strip_prefix("Format:") {
let format = format.trim().to_string();
if !format.is_empty() && !caps.formats.contains(&format) {
caps.formats.push(format);
}
}
}
// Rates line: "Rates: 44100, 48000, 88200, 96000, 176400, 192000"
if line.starts_with("Rates:") {
if let Some(rates_str) = line.strip_prefix("Rates:") {
for rate_str in rates_str.split(',') {
if let Ok(rate) = rate_str.trim().parse::<u32>() {
if !caps.sample_rates.contains(&rate) {
caps.sample_rates.push(rate);
}
}
}
}
}
}
}
}
/// Parse /proc/asound/cardX/pcmXp/sub0/hw_params output (when device is active)
fn parse_proc_hw_params(output: &str, caps: &mut DacCapabilities) {
for line in output.lines() {
let line = line.trim();
// Format: "rate: 192000 (192000/1)"
if line.starts_with("rate:") {
if let Some(rate_part) = line.strip_prefix("rate:") {
// Take first number before any parenthesis or space
let rate_str = rate_part.trim().split_whitespace().next().unwrap_or("");
if let Ok(rate) = rate_str.parse::<u32>() {
if !caps.sample_rates.contains(&rate) {
caps.sample_rates.push(rate);
}
}
}
}
// Format: "format: S32_LE"
if line.starts_with("format:") {
if let Some(format_str) = line.strip_prefix("format:") {
let format = format_str.trim().to_string();
if !format.is_empty() && !caps.formats.contains(&format) {
caps.formats.push(format);
}
}
}
}
}
fn parse_pw_info(output: &str, caps: &mut DacCapabilities) {
for line in output.lines() {
let line = line.trim();
// Look for audio.rate or similar
if line.contains("audio.rate") || line.contains("default.clock.rate") {
if let Some(rate_str) = line.split('=').last() {
if let Ok(rate) = rate_str.trim().trim_matches('"').parse::<u32>() {
if !caps.sample_rates.contains(&rate) {
caps.sample_rates.push(rate);
}
}
}
}
// Look for allowed rates
if line.contains("clock.allowed-rates") || line.contains("audio.allowed-rates") {
// Format: [ 44100 48000 88200 96000 176400 192000 ]
if let Some(rates_part) = line.split('[').last() {
if let Some(rates_str) = rates_part.split(']').next() {
for rate_str in rates_str.split_whitespace() {
if let Ok(rate) = rate_str.parse::<u32>() {
if !caps.sample_rates.contains(&rate) {
caps.sample_rates.push(rate);
}
}
}
}
}
}
// Look for audio format
if line.contains("audio.format") || line.contains("format.dsp") {
if let Some(format) = line.split('=').last() {
let format = format.trim().trim_matches('"').to_string();
if !format.is_empty() && !caps.formats.contains(&format) {
caps.formats.push(format);
}
}
}
// Look for channels
if line.contains("audio.channels") {
if let Some(ch_str) = line.split('=').last() {
if let Ok(ch) = ch_str.trim().trim_matches('"').parse::<u32>() {
caps.channels = Some(ch);
}
}
}
// Look for description
if line.contains("node.description") {
if let Some(desc) = line.split('=').last() {
caps.description = Some(desc.trim().trim_matches('"').to_string());
}
}
}
}
fn parse_pactl_sinks(output: &str, node_name: &str, caps: &mut DacCapabilities) -> bool {
let mut in_target_sink = false;
let mut found = false;
for line in output.lines() {
let line_trimmed = line.trim();
// Check if we're entering a new sink block
if line.starts_with("Sink #") {
in_target_sink = false;
}
// Check if this is our target sink
if line_trimmed.contains("Name:") && line_trimmed.contains(node_name) {
in_target_sink = true;
found = true;
}
if in_target_sink {
// Get description
if line_trimmed.starts_with("Description:") {
if let Some(desc) = line_trimmed.strip_prefix("Description:") {
caps.description = Some(desc.trim().to_string());
}
}
// Get sample spec (contains rate and format)
if line_trimmed.starts_with("Sample Specification:") {
// Format: "s32le 2ch 192000Hz"
if let Some(spec) = line_trimmed.strip_prefix("Sample Specification:") {
let parts: Vec<&str> = spec.trim().split_whitespace().collect();
for part in parts {
// Format like s16le, s24le, s32le, float32le
if part.starts_with('s') || part.starts_with("float") {
let format = part.to_uppercase();
if !caps.formats.contains(&format) {
caps.formats.push(format);
}
}
// Channels like 2ch
if part.ends_with("ch") {
if let Ok(ch) = part.trim_end_matches("ch").parse::<u32>() {
caps.channels = Some(ch);
}
}
// Rate like 192000Hz
if part.ends_with("Hz") {
if let Ok(rate) = part.trim_end_matches("Hz").parse::<u32>() {
if !caps.sample_rates.contains(&rate) {
caps.sample_rates.push(rate);
}
}
}
}
}
}
// Look for alternate sample rates in properties
if line_trimmed.contains("device.buffering.buffer_size") {
// End of useful properties for this sink
}
}
}
// Sort sample rates
caps.sample_rates.sort();
found
}
-109
View File
@@ -1,109 +0,0 @@
//! Audio diagnostics commands for detecting actual hardware sample rate
//! and verifying effective bit depth of the audio pipeline.
use std::fs;
use tauri::Manager;
use crate::AppState;
use crate::audio::BitDepthResult;
/// Hardware audio status
#[derive(Debug, Clone, serde::Serialize)]
pub struct HardwareAudioStatus {
/// Actual sample rate being used by hardware (Hz)
pub hardware_sample_rate: Option<u32>,
/// Audio format (e.g., "S32_LE")
pub hardware_format: Option<String>,
/// Whether hardware is currently active
pub is_active: bool,
}
/// Get actual hardware audio status by reading /proc/asound
#[tauri::command]
pub fn get_hardware_audio_status() -> Result<HardwareAudioStatus, String> {
// Read all hw_params files from /proc/asound
let proc_pattern = "/proc/asound/card*/pcm*/sub*/hw_params";
// Use glob to find all matching files
let paths = glob::glob(proc_pattern)
.map_err(|e| format!("Failed to glob hw_params: {}", e))?;
for path in paths.flatten() {
if let Ok(contents) = fs::read_to_string(&path) {
// Parse the hw_params file
let mut sample_rate: Option<u32> = None;
let mut format: Option<String> = None;
for line in contents.lines() {
let line = line.trim();
// Parse rate line: "rate: 192000 (192000/1)"
if line.starts_with("rate:") {
if let Some(rate_str) = line.split_whitespace().nth(1) {
sample_rate = rate_str.parse().ok();
}
}
// Parse format line: "format: S32_LE"
if line.starts_with("format:") {
if let Some(fmt) = line.split_whitespace().nth(1) {
format = Some(fmt.to_string());
}
}
}
// If we found both, return it
if sample_rate.is_some() {
log::debug!(
"Hardware audio status: {}Hz, format: {:?}",
sample_rate.unwrap_or(0),
format
);
return Ok(HardwareAudioStatus {
hardware_sample_rate: sample_rate,
hardware_format: format,
is_active: true,
});
}
}
}
// No active hardware found
Ok(HardwareAudioStatus {
hardware_sample_rate: None,
hardware_format: None,
is_active: false,
})
}
/// Start bit-depth diagnostic capture on the currently playing audio.
/// Samples are analyzed on-the-fly with zero allocation (OR-mask of i32 values).
/// Call `stop_bitdepth_capture` after a few seconds to get the result.
#[tauri::command]
pub fn start_bitdepth_capture(
app: tauri::AppHandle,
) -> Result<String, String> {
let state = app.state::<AppState>();
let sample_rate = state.player.state.get_sample_rate();
if sample_rate == 0 {
return Err("No audio playing — cannot start capture".to_string());
}
// Default to 2 channels (stereo) — SharedState doesn't track channels
state.player.diagnostic.start_capture(sample_rate, 2);
Ok(format!("Capture started at {}Hz", sample_rate))
}
/// Stop bit-depth capture and return analysis.
///
/// The `effective_bits` field is the key result:
/// - 24 → source data has 24-bit precision (f32 pipeline working)
/// - 16 → source data truncated to 16-bit (bug)
/// - Other values → intermediate precision or pipeline issue
#[tauri::command]
pub fn stop_bitdepth_capture(
app: tauri::AppHandle,
) -> Result<BitDepthResult, String> {
let state = app.state::<AppState>();
Ok(state.player.diagnostic.stop_and_analyze())
}
-385
View File
@@ -1,385 +0,0 @@
//! 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::core_bridge::CoreBridgeState;
use crate::offline_cache::OfflineCacheState;
use crate::runtime::RuntimeManagerState;
#[derive(serde::Serialize)]
pub struct LoginResponse {
pub success: bool,
pub user_name: Option<String>,
pub user_id: Option<u64>,
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_offline_cache_for_invalid_subscription(
now: i64,
subscription_state: &SubscriptionStateState,
cache_state: &OfflineCacheState,
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.as_ref().and_then(|s| s.should_purge_offline_cache(now).ok()) {
Some(v) => v,
None => {
log::warn!("Failed to evaluate purge condition");
false
}
}
};
if !should_purge {
return;
}
log::warn!("Subscription invalid for >3 days. Purging offline cache.");
if let Err(e) = crate::offline_cache::commands::purge_all_cached_files(cache_state, library_state).await {
log::error!("Failed to purge offline cache: {}", e);
return;
}
if let Ok(guard) = subscription_state.lock() {
if let Some(store) = guard.as_ref() {
if let Err(e) = store.mark_offline_cache_purged(now) {
log::warn!("Failed to persist purge timestamp: {}", e);
}
}
}
}
#[tauri::command]
pub async fn login(
email: String,
password: String,
state: State<'_, AppState>,
subscription_state: State<'_, SubscriptionStateState>,
cache_state: State<'_, OfflineCacheState>,
library_state: State<'_, crate::library::commands::LibraryState>,
core_bridge: State<'_, CoreBridgeState>,
runtime_manager: State<'_, RuntimeManagerState>,
) -> Result<LoginResponse, String> {
let client = state.client.read().await;
let now = now_unix_secs();
match client.login(&email, &password).await {
Ok(session) => {
if let Ok(guard) = subscription_state.lock() {
if let Some(store) = guard.as_ref() {
let _ = store.mark_valid(now);
}
}
// Update runtime state - legacy auth succeeded
let user_id = session.user_id;
runtime_manager.manager().set_legacy_auth(true, Some(user_id)).await;
// V2 CoreBridge authentication - REQUIRED per ADR Runtime Session Contract
// If V2 auth fails, return typed failure and do not report full success
if let Some(bridge) = core_bridge.try_get().await {
if let Err(e) = bridge.login(&email, &password).await {
log::error!("[Auth] V2 CoreBridge login failed: {}", e);
// V2 auth failed - report failure per ADR
return Ok(LoginResponse {
success: false,
user_name: Some(session.display_name),
user_id: Some(user_id),
subscription: Some(session.subscription_label),
subscription_valid_until: session.subscription_valid_until,
error: Some(format!("V2 authentication failed: {}", e)),
error_code: Some("v2_auth_failed".to_string()),
});
}
log::info!("[Auth] V2 CoreBridge authenticated successfully");
runtime_manager.manager().set_corebridge_auth(true).await;
} else {
log::error!("[Auth] V2 CoreBridge not initialized - cannot complete auth");
return Ok(LoginResponse {
success: false,
user_name: Some(session.display_name),
user_id: Some(user_id),
subscription: Some(session.subscription_label),
subscription_valid_until: session.subscription_valid_until,
error: Some("V2 client not initialized".to_string()),
error_code: Some("v2_not_initialized".to_string()),
});
}
Ok(LoginResponse {
success: true,
user_name: Some(session.display_name),
user_id: Some(user_id),
subscription: Some(session.subscription_label),
subscription_valid_until: session.subscription_valid_until,
error: None,
error_code: None,
})
}
Err(ApiError::IneligibleUser) => {
if let Ok(guard) = subscription_state.lock() {
if let Some(store) = guard.as_ref() {
let _ = store.mark_invalid(now);
}
}
maybe_purge_offline_cache_for_invalid_subscription(
now,
subscription_state.inner(),
cache_state.inner(),
library_state.inner(),
)
.await;
Ok(LoginResponse {
success: false,
user_name: None,
user_id: 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,
user_id: None,
subscription: None,
subscription_valid_until: None,
error: Some(e.to_string()),
error_code: None,
}),
}
}
#[tauri::command]
pub async fn is_logged_in(state: State<'_, AppState>) -> Result<bool, String> {
let client = state.client.read().await;
Ok(client.is_logged_in().await)
}
#[tauri::command]
pub async fn init_client(state: State<'_, AppState>) -> Result<bool, String> {
let client = state.client.read().await;
match client.init().await {
Ok(_) => Ok(true),
Err(e) => Err(e.to_string()),
}
}
#[tauri::command]
pub async fn logout(
state: State<'_, AppState>,
core_bridge: State<'_, CoreBridgeState>,
runtime_manager: State<'_, RuntimeManagerState>,
) -> Result<(), String> {
// Logout from legacy client
let client = state.client.read().await;
client.logout().await;
// Also logout from V2 CoreBridge (if initialized)
if let Some(bridge) = core_bridge.try_get().await {
if let Err(e) = bridge.logout().await {
log::warn!("[Auth] V2 CoreBridge logout failed: {}", e);
}
}
// Update runtime state - auth cleared
runtime_manager.manager().set_legacy_auth(false, None).await;
Ok(())
}
#[derive(serde::Serialize)]
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.read().await;
Ok(client.get_user_info().await.map(|(name, sub, until)| UserInfo {
user_name: name,
subscription: sub,
subscription_valid_until: until,
}))
}
// === Credential persistence commands ===
/// Check if saved credentials exist in system keyring
#[tauri::command]
pub fn has_saved_credentials() -> bool {
credentials::has_saved_credentials()
}
/// Save credentials to system keyring
#[tauri::command]
pub fn save_credentials(email: String, password: String) -> Result<(), String> {
credentials::save_qobuz_credentials(&email, &password)
}
/// Clear saved credentials from system keyring
#[tauri::command]
pub fn clear_saved_credentials() -> Result<(), String> {
credentials::clear_qobuz_credentials()
}
/// Auto-login using saved credentials
/// Returns LoginResponse with success status
#[tauri::command]
pub async fn auto_login(
state: State<'_, AppState>,
subscription_state: State<'_, SubscriptionStateState>,
cache_state: State<'_, OfflineCacheState>,
library_state: State<'_, crate::library::commands::LibraryState>,
core_bridge: State<'_, CoreBridgeState>,
) -> Result<LoginResponse, String> {
// Check for saved credentials
let creds = match credentials::load_qobuz_credentials() {
Ok(Some(c)) => c,
Ok(None) => {
return Ok(LoginResponse {
success: false,
user_name: None,
user_id: None,
subscription: None,
subscription_valid_until: None,
error: Some("No saved credentials".to_string()),
error_code: None,
});
}
Err(e) => {
return Ok(LoginResponse {
success: false,
user_name: None,
user_id: None,
subscription: None,
subscription_valid_until: None,
error: Some(e),
error_code: None,
});
}
};
// Try to login with saved credentials
let client = state.client.read().await;
let now = now_unix_secs();
match client.login(&creds.email, &creds.password).await {
Ok(session) => {
if let Ok(guard) = subscription_state.lock() {
if let Some(store) = guard.as_ref() {
let _ = store.mark_valid(now);
}
}
// V2 CoreBridge authentication - REQUIRED per ADR Runtime Session Contract
// If V2 auth fails, return typed failure and do not report full success
if let Some(bridge) = core_bridge.try_get().await {
if let Err(e) = bridge.login(&creds.email, &creds.password).await {
log::error!("[Auth/Auto] V2 CoreBridge login failed: {}", e);
// V2 auth failed - report failure per ADR
return Ok(LoginResponse {
success: false,
user_name: Some(session.display_name.clone()),
user_id: Some(session.user_id),
subscription: Some(session.subscription_label.clone()),
subscription_valid_until: session.subscription_valid_until.clone(),
error: Some(format!("V2 authentication failed: {}", e)),
error_code: Some("v2_auth_failed".to_string()),
});
}
log::info!("[Auth/Auto] V2 CoreBridge authenticated successfully");
} else {
log::error!("[Auth/Auto] V2 CoreBridge not initialized - cannot complete auth");
return Ok(LoginResponse {
success: false,
user_name: Some(session.display_name.clone()),
user_id: Some(session.user_id),
subscription: Some(session.subscription_label.clone()),
subscription_valid_until: session.subscription_valid_until.clone(),
error: Some("V2 CoreBridge not initialized".to_string()),
error_code: Some("v2_not_initialized".to_string()),
});
}
Ok(LoginResponse {
success: true,
user_name: Some(session.display_name),
user_id: Some(session.user_id),
subscription: Some(session.subscription_label),
subscription_valid_until: session.subscription_valid_until,
error: None,
error_code: None,
})
}
Err(ApiError::IneligibleUser) => {
if let Ok(guard) = subscription_state.lock() {
if let Some(store) = guard.as_ref() {
let _ = store.mark_invalid(now);
}
}
maybe_purge_offline_cache_for_invalid_subscription(
now,
subscription_state.inner(),
cache_state.inner(),
library_state.inner(),
)
.await;
Ok(LoginResponse {
success: false,
user_name: None,
user_id: 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
log::warn!("Auto-login failed: {}", e);
Ok(LoginResponse {
success: false,
user_name: None,
user_id: None,
subscription: None,
subscription_valid_until: None,
error: Some(e.to_string()),
error_code: None,
})
}
}
}
#[tauri::command]
pub async fn set_api_locale(locale: String, state: State<'_, AppState>) -> Result<(), String> {
log::info!("Command: set_api_locale {}", locale);
let client = state.client.read().await;
client.set_locale(locale).await;
Ok(())
}
-31
View File
@@ -1,31 +0,0 @@
//! Cache management commands
use tauri::State;
use crate::api_cache::ApiCacheState;
use crate::cache::CacheStats;
use crate::AppState;
/// Get cache statistics
#[tauri::command]
pub fn get_cache_stats(state: State<'_, AppState>) -> CacheStats {
log::info!("Command: get_cache_stats");
state.audio_cache.stats()
}
/// Clear the audio cache
#[tauri::command]
pub fn clear_cache(state: State<'_, AppState>) -> Result<(), String> {
log::info!("Command: clear_cache");
state.audio_cache.clear();
Ok(())
}
/// Clear all cached artists (useful when changing language settings)
#[tauri::command]
pub async fn clear_artist_cache(cache_state: State<'_, ApiCacheState>) -> Result<usize, String> {
log::info!("Command: clear_artist_cache");
let guard = cache_state.cache.lock().await;
let cache = guard.as_ref().ok_or("No active session - please log in")?;
cache.clear_all_artists()
}
-175
View File
@@ -1,175 +0,0 @@
//! Track credits and album credits Tauri commands
use serde::Serialize;
use tauri::State;
use crate::api::models::Album;
use crate::api::performers::{parse_performers, Performer};
use crate::AppState;
/// Track credits with parsed performers
#[derive(Debug, Clone, Serialize)]
pub struct TrackCredits {
pub id: u64,
pub number: u32,
pub title: String,
pub artist: String,
pub duration: String,
pub duration_seconds: u32,
pub performers: Vec<Performer>,
pub copyright: Option<String>,
pub album_id: Option<String>,
pub artist_id: Option<u64>,
}
/// Album credits response with all tracks
#[derive(Debug, Clone, Serialize)]
pub struct AlbumCredits {
pub album: AlbumInfo,
pub tracks: Vec<TrackCredits>,
}
/// Album metadata for credits modal
#[derive(Debug, Clone, Serialize)]
pub struct AlbumInfo {
pub id: String,
pub artwork: String,
pub title: String,
pub artist: String,
pub artist_id: Option<u64>,
pub year: String,
pub release_date: Option<String>,
pub label: String,
pub label_id: Option<u64>,
pub genre: String,
pub quality: String,
pub track_count: u32,
pub duration: String,
pub bit_depth: Option<u32>,
pub sampling_rate: Option<f64>,
/// Editorial description/review of the album
pub description: Option<String>,
}
/// Format duration in seconds to "Xm Ys" or "Xh Ym" format
fn format_duration(seconds: u32) -> String {
let hours = seconds / 3600;
let minutes = (seconds % 3600) / 60;
let secs = seconds % 60;
if hours > 0 {
format!("{}h {}m", hours, minutes)
} else {
format!("{}m {}s", minutes, secs)
}
}
/// Format track duration to "M:SS" format
fn format_track_duration(seconds: u32) -> String {
let minutes = seconds / 60;
let secs = seconds % 60;
format!("{}:{:02}", minutes, secs)
}
/// Build quality string from bit depth and sample rate
fn format_quality(bit_depth: Option<u32>, sampling_rate: Option<f64>) -> String {
match (bit_depth, sampling_rate) {
(Some(bd), Some(sr)) => format!("{}-bit / {}kHz", bd, sr),
(Some(bd), None) => format!("{}-bit", bd),
(None, Some(sr)) => format!("{}kHz", sr),
(None, None) => "Lossless".to_string(),
}
}
/// Convert API Album to AlbumInfo
fn album_to_info(album: &Album) -> AlbumInfo {
let year = album
.release_date_original
.as_ref()
.and_then(|d| d.split('-').next())
.unwrap_or("")
.to_string();
let total_duration = album.duration.unwrap_or(0);
AlbumInfo {
id: album.id.clone(),
artwork: album.image.large.clone().unwrap_or_default(),
title: album.title.clone(),
artist: album.artist.name.clone(),
artist_id: if album.artist.id > 0 { Some(album.artist.id) } else { None },
year,
release_date: album.release_date_original.clone(),
label: album.label.as_ref().map(|l| l.name.clone()).unwrap_or_default(),
label_id: album.label.as_ref().map(|l| l.id),
genre: album.genre.as_ref().map(|g| g.name.clone()).unwrap_or_default(),
quality: format_quality(album.maximum_bit_depth, album.maximum_sampling_rate),
track_count: album.tracks_count.unwrap_or(0),
duration: format_duration(total_duration),
bit_depth: album.maximum_bit_depth,
sampling_rate: album.maximum_sampling_rate,
description: album.description.clone(),
}
}
/// Get album credits with all tracks and parsed performers
#[tauri::command]
pub async fn get_album_credits(
album_id: String,
state: State<'_, AppState>,
) -> Result<AlbumCredits, String> {
log::info!("Command: get_album_credits {}", album_id);
let client = state.client.read().await;
// Fetch the album with tracks
let album = client
.get_album(&album_id)
.await
.map_err(|e| format!("Failed to get album: {}", e))?;
// Convert album to info
let album_info = album_to_info(&album);
// Process tracks with performers
let tracks: Vec<TrackCredits> = album
.tracks
.as_ref()
.map(|tc| {
tc.items
.iter()
.map(|track| {
let performers = track
.performers
.as_ref()
.map(|p| parse_performers(p))
.unwrap_or_default();
TrackCredits {
id: track.id,
number: track.track_number,
title: track.title.clone(),
artist: track
.performer
.as_ref()
.map(|p| p.name.clone())
.unwrap_or_else(|| album.artist.name.clone()),
duration: format_track_duration(track.duration),
duration_seconds: track.duration,
performers,
copyright: track.copyright.clone(),
album_id: Some(album.id.clone()),
artist_id: track.performer.as_ref().and_then(|p| {
if p.id > 0 { Some(p.id) } else { None }
}),
}
})
.collect()
})
.unwrap_or_default();
Ok(AlbumCredits {
album: album_info,
tracks,
})
}
-144
View File
@@ -1,144 +0,0 @@
//! Factory reset command
//!
//! Deletes all application data, cache, and config directories.
//! This is the nuclear option for unrecoverable states.
use tauri::State;
use crate::api_cache::ApiCacheState;
use crate::artist_blacklist::BlacklistState;
use crate::artist_vectors::ArtistVectorStoreState;
use crate::config::{
audio_settings::AudioSettingsState,
download_settings::DownloadSettingsState,
favorites_cache::FavoritesCacheState,
favorites_preferences::FavoritesPreferencesState,
legal_settings::LegalSettingsState,
playback_preferences::PlaybackPreferencesState,
remote_control_settings::{AllowedOriginsState, RemoteControlSettingsState},
subscription_state::SubscriptionStateState,
tray_settings::TraySettingsState,
};
use crate::library::commands::LibraryState;
use crate::listenbrainz::ListenBrainzSharedState;
use crate::lyrics::LyricsState;
use crate::musicbrainz::MusicBrainzSharedState;
use crate::offline::OfflineState;
use crate::offline_cache::OfflineCacheState;
use crate::reco_store::RecoState;
use crate::session_store::SessionStoreState;
use crate::updates::UpdatesState;
use crate::user_data::UserDataPaths;
use crate::AppState;
use super::user_session::teardown_type_alias_state;
/// Delete all application data, cache, and config.
///
/// Steps:
/// 1. Stop playback
/// 2. Tear down all per-user stores (close DB connections)
/// 3. Clear credentials from keyring
/// 4. Remove ~/.local/share/qbz/
/// 5. Remove ~/.cache/qbz/
/// 6. Remove ~/.config/qbz/
#[tauri::command]
pub async fn factory_reset(
app_state: State<'_, AppState>,
user_paths: State<'_, UserDataPaths>,
session_store: State<'_, SessionStoreState>,
favorites_cache: State<'_, FavoritesCacheState>,
subscription_state: State<'_, SubscriptionStateState>,
playback_prefs: State<'_, PlaybackPreferencesState>,
favorites_prefs: State<'_, FavoritesPreferencesState>,
download_settings: State<'_, DownloadSettingsState>,
audio_settings: State<'_, AudioSettingsState>,
tray_settings: State<'_, TraySettingsState>,
remote_control_settings: State<'_, RemoteControlSettingsState>,
allowed_origins: State<'_, AllowedOriginsState>,
legal_settings: State<'_, LegalSettingsState>,
updates: State<'_, UpdatesState>,
library: State<'_, LibraryState>,
reco: State<'_, RecoState>,
api_cache: State<'_, ApiCacheState>,
artist_vectors: State<'_, ArtistVectorStoreState>,
blacklist: State<'_, BlacklistState>,
offline: State<'_, OfflineState>,
offline_cache: State<'_, OfflineCacheState>,
lyrics: State<'_, LyricsState>,
musicbrainz: State<'_, MusicBrainzSharedState>,
listenbrainz: State<'_, ListenBrainzSharedState>,
) -> Result<(), String> {
log::warn!("FACTORY RESET: Starting — all application data will be deleted");
// 1. Stop playback
let _ = app_state.player.stop();
app_state.media_controls.set_stopped();
// 2. Tear down all per-user stores (close DB connections before deleting files)
session_store.teardown();
let _ = favorites_cache.teardown();
let _ = playback_prefs.teardown();
let _ = favorites_prefs.teardown();
let _ = audio_settings.teardown();
let _ = tray_settings.teardown();
let _ = remote_control_settings.teardown();
let _ = allowed_origins.teardown();
updates.teardown();
library.teardown().await;
reco.teardown().await;
api_cache.teardown().await;
artist_vectors.teardown().await;
blacklist.teardown();
offline.teardown();
offline_cache.teardown().await;
lyrics.teardown().await;
musicbrainz.teardown().await;
listenbrainz.teardown().await;
teardown_type_alias_state(&*subscription_state);
teardown_type_alias_state(&*download_settings);
teardown_type_alias_state(&*legal_settings);
// Clear the active user
user_paths.clear_user();
UserDataPaths::clear_last_user_id();
// 3. Clear credentials from keyring
if let Err(e) = crate::credentials::clear_qobuz_credentials() {
log::error!("FACTORY RESET: Failed to clear credentials: {}", e);
// Continue anyway — deleting the dirs is more important
}
// 4. Remove data directory (~/.local/share/qbz/)
if let Ok(data_dir) = UserDataPaths::global_data_dir() {
if data_dir.exists() {
log::info!("FACTORY RESET: Removing {}", data_dir.display());
if let Err(e) = std::fs::remove_dir_all(&data_dir) {
log::error!("FACTORY RESET: Failed to remove data dir: {}", e);
}
}
}
// 5. Remove cache directory (~/.cache/qbz/)
if let Ok(cache_dir) = UserDataPaths::global_cache_dir() {
if cache_dir.exists() {
log::info!("FACTORY RESET: Removing {}", cache_dir.display());
if let Err(e) = std::fs::remove_dir_all(&cache_dir) {
log::error!("FACTORY RESET: Failed to remove cache dir: {}", e);
}
}
}
// 6. Remove config directory (~/.config/qbz/)
if let Some(config_dir) = dirs::config_dir().map(|d| d.join("qbz")) {
if config_dir.exists() {
log::info!("FACTORY RESET: Removing {}", config_dir.display());
if let Err(e) = std::fs::remove_dir_all(&config_dir) {
log::error!("FACTORY RESET: Failed to remove config dir: {}", e);
}
}
}
log::warn!("FACTORY RESET: Complete — all application data deleted");
Ok(())
}
-107
View File
@@ -1,107 +0,0 @@
//! Favorites-related Tauri commands
use serde_json::Value;
use tauri::State;
use crate::api_cache::ApiCacheState;
use crate::AppState;
/// Get user's favorites
/// fav_type can be: "albums", "tracks", or "artists"
#[tauri::command]
pub async fn get_favorites(
fav_type: String,
limit: Option<u32>,
offset: Option<u32>,
state: State<'_, AppState>,
) -> Result<Value, String> {
log::debug!("Command: get_favorites type={} limit={:?} offset={:?}", fav_type, limit, offset);
let client = state.client.read().await;
client
.get_favorites(&fav_type, limit.unwrap_or(50), offset.unwrap_or(0))
.await
.map_err(|e| format!("Failed to get favorites: {}", e))
}
/// Add item to favorites
/// fav_type can be: "album", "track", or "artist"
#[tauri::command]
pub async fn add_favorite(
fav_type: String,
item_id: String,
state: State<'_, AppState>,
cache_state: State<'_, ApiCacheState>,
) -> Result<(), String> {
log::info!("Command: add_favorite type={} id={}", fav_type, item_id);
let client = state.client.read().await;
client
.add_favorite(&fav_type, &item_id)
.await
.map_err(|e| format!("Failed to add favorite: {}", e))?;
// Invalidate stale cache entry so next fetch gets fresh data
{
let guard = cache_state.cache.lock().await;
if let Some(cache) = guard.as_ref() {
match fav_type.as_str() {
"album" => { let _ = cache.invalidate_album(&item_id); }
"track" => {
if let Ok(id) = item_id.parse::<u64>() {
let _ = cache.invalidate_track(id);
}
}
"artist" => {
if let Ok(id) = item_id.parse::<u64>() {
let _ = cache.invalidate_artist(id);
}
}
_ => {}
}
}
}
Ok(())
}
/// Remove item from favorites
/// fav_type can be: "album", "track", or "artist"
#[tauri::command]
pub async fn remove_favorite(
fav_type: String,
item_id: String,
state: State<'_, AppState>,
cache_state: State<'_, ApiCacheState>,
) -> Result<(), String> {
log::info!("Command: remove_favorite type={} id={}", fav_type, item_id);
let client = state.client.read().await;
client
.remove_favorite(&fav_type, &item_id)
.await
.map_err(|e| format!("Failed to remove favorite: {}", e))?;
// Invalidate stale cache entry so next fetch gets fresh data
{
let guard = cache_state.cache.lock().await;
if let Some(cache) = guard.as_ref() {
match fav_type.as_str() {
"album" => { let _ = cache.invalidate_album(&item_id); }
"track" => {
if let Ok(id) = item_id.parse::<u64>() {
let _ = cache.invalidate_track(id);
}
}
"artist" => {
if let Ok(id) = item_id.parse::<u64>() {
let _ = cache.invalidate_artist(id);
}
}
_ => {}
}
}
}
Ok(())
}
-131
View File
@@ -1,131 +0,0 @@
//! Last.fm integration commands
//!
//! **DEPRECATED**: Use V2 commands in `commands_v2.rs` instead.
//! These legacy commands will be removed in a future version.
#![allow(deprecated)]
use tauri::State;
use crate::lastfm::{LastFmClient, LastFmSession};
use crate::AppState;
/// Check if Last.fm has embedded (build-time) credentials
#[tauri::command]
pub fn lastfm_has_embedded_credentials() -> bool {
LastFmClient::has_embedded_credentials()
}
/// Check if Last.fm has API credentials configured (embedded or user-provided)
#[tauri::command]
pub async fn lastfm_has_credentials(state: State<'_, AppState>) -> Result<bool, String> {
let client = state.lastfm.lock().await;
Ok(client.has_credentials())
}
/// Open a URL in the default browser
#[tauri::command]
pub async fn lastfm_open_auth_url(url: String) -> Result<(), String> {
open::that(&url).map_err(|e| format!("Failed to open browser: {}", e))
}
/// Set Last.fm API credentials
#[tauri::command]
pub async fn lastfm_set_credentials(
api_key: String,
api_secret: String,
state: State<'_, AppState>,
) -> Result<(), String> {
log::info!("Command: lastfm_set_credentials");
let mut client = state.lastfm.lock().await;
client.set_credentials(api_key, api_secret);
Ok(())
}
/// Check if Last.fm is authenticated
#[deprecated(since = "1.2.0", note = "Use v2_lastfm_is_authenticated instead")]
#[tauri::command]
pub async fn lastfm_is_authenticated(state: State<'_, AppState>) -> Result<bool, String> {
let client = state.lastfm.lock().await;
Ok(client.is_authenticated())
}
/// Get Last.fm authentication token and URL
#[deprecated(since = "1.2.0", note = "Use v2_lastfm_get_auth_url instead")]
#[tauri::command]
pub async fn lastfm_get_auth_url(state: State<'_, AppState>) -> Result<(String, String), String> {
log::info!("Command: lastfm_get_auth_url");
let client = state.lastfm.lock().await;
// Proxy handles credentials, always available
client.get_token().await
}
/// Complete Last.fm authentication with token
#[deprecated(since = "1.2.0", note = "Use v2_lastfm_complete_auth instead")]
#[tauri::command]
pub async fn lastfm_authenticate(
token: String,
state: State<'_, AppState>,
) -> Result<LastFmSession, String> {
log::info!("Command: lastfm_authenticate");
let mut client = state.lastfm.lock().await;
client.get_session(&token).await
}
/// Set Last.fm session key (for restoring saved session)
#[deprecated(since = "1.2.0", note = "Use v2_lastfm_set_session instead")]
#[tauri::command]
pub async fn lastfm_set_session(
session_key: String,
state: State<'_, AppState>,
) -> Result<(), String> {
log::info!("Command: lastfm_set_session");
let mut client = state.lastfm.lock().await;
client.set_session_key(session_key);
Ok(())
}
/// Disconnect from Last.fm
#[deprecated(since = "1.2.0", note = "Use v2_lastfm_disconnect instead")]
#[tauri::command]
pub async fn lastfm_disconnect(state: State<'_, AppState>) -> Result<(), String> {
log::info!("Command: lastfm_disconnect");
let mut client = state.lastfm.lock().await;
// Reset to default (clears session key)
*client = crate::lastfm::LastFmClient::default();
Ok(())
}
/// Scrobble a track to Last.fm
#[deprecated(since = "1.2.0", note = "Use v2_lastfm_scrobble instead")]
#[tauri::command]
pub async fn lastfm_scrobble(
artist: String,
track: String,
album: Option<String>,
timestamp: u64,
state: State<'_, AppState>,
) -> Result<(), String> {
log::info!("Command: lastfm_scrobble - {} - {}", artist, track);
let client = state.lastfm.lock().await;
client
.scrobble(&artist, &track, album.as_deref(), timestamp)
.await
}
/// Update "now playing" on Last.fm
#[deprecated(since = "1.2.0", note = "Use v2_lastfm_now_playing instead")]
#[tauri::command]
pub async fn lastfm_now_playing(
artist: String,
track: String,
album: Option<String>,
state: State<'_, AppState>,
) -> Result<(), String> {
log::info!("Command: lastfm_now_playing - {} - {}", artist, track);
let client = state.lastfm.lock().await;
client
.update_now_playing(&artist, &track, album.as_deref())
.await
}
-325
View File
@@ -1,325 +0,0 @@
//! ListenBrainz Tauri commands
//!
//! Exposes ListenBrainz scrobbling to the frontend
//!
//! **DEPRECATED**: Use V2 commands in `commands_v2.rs` instead.
//! These legacy commands will be removed in a future version.
#![allow(deprecated)]
use tauri::State;
use crate::listenbrainz::{
AdditionalInfo, ListenBrainzSharedState, ListenBrainzStatus, QueuedListen, UserInfo,
};
/// Get ListenBrainz connection status
#[deprecated(since = "1.2.0", note = "Use v2_listenbrainz_get_status instead")]
#[tauri::command]
pub async fn listenbrainz_get_status(
state: State<'_, ListenBrainzSharedState>,
) -> Result<ListenBrainzStatus, String> {
let client = state.client.lock().await;
Ok(client.get_status().await)
}
/// Check if ListenBrainz is enabled
#[deprecated(since = "1.2.0", note = "Use v2_listenbrainz_is_enabled instead")]
#[tauri::command]
pub async fn listenbrainz_is_enabled(
state: State<'_, ListenBrainzSharedState>,
) -> Result<bool, String> {
let client = state.client.lock().await;
Ok(client.is_enabled().await)
}
/// Enable or disable ListenBrainz integration
#[deprecated(since = "1.2.0", note = "Use v2_listenbrainz_set_enabled instead")]
#[tauri::command]
pub async fn listenbrainz_set_enabled(
enabled: bool,
state: State<'_, ListenBrainzSharedState>,
) -> Result<(), String> {
// Update client
{
let client = state.client.lock().await;
client.set_enabled(enabled).await;
}
// Persist setting
{
let cache_opt__ = state.cache.lock().await;
let cache = cache_opt__.as_ref().ok_or("No active session - please log in")?;
cache.set_enabled(enabled)?;
}
log::info!(
"ListenBrainz integration {}",
if enabled { "enabled" } else { "disabled" }
);
Ok(())
}
/// Connect to ListenBrainz with a user token
#[deprecated(since = "1.2.0", note = "Use v2_listenbrainz_connect instead")]
#[tauri::command]
pub async fn listenbrainz_connect(
token: String,
state: State<'_, ListenBrainzSharedState>,
) -> Result<UserInfo, String> {
log::info!("Command: listenbrainz_connect");
// Validate token and get user info
let user_info = {
let client = state.client.lock().await;
client.set_token(&token).await?
};
// Persist credentials
{
let cache_opt__ = state.cache.lock().await;
let cache = cache_opt__.as_ref().ok_or("No active session - please log in")?;
cache.set_credentials(Some(&token), Some(&user_info.user_name))?;
}
Ok(user_info)
}
/// Disconnect from ListenBrainz
#[deprecated(since = "1.2.0", note = "Use v2_listenbrainz_disconnect instead")]
#[tauri::command]
pub async fn listenbrainz_disconnect(
state: State<'_, ListenBrainzSharedState>,
) -> Result<(), String> {
log::info!("Command: listenbrainz_disconnect");
// Clear client state
{
let client = state.client.lock().await;
client.disconnect().await;
}
// Clear persisted credentials
{
let cache_opt__ = state.cache.lock().await;
let cache = cache_opt__.as_ref().ok_or("No active session - please log in")?;
cache.clear_credentials()?;
}
Ok(())
}
/// Submit "now playing" to ListenBrainz
#[deprecated(since = "1.2.0", note = "Use v2_listenbrainz_now_playing instead")]
#[tauri::command]
pub async fn listenbrainz_now_playing(
artist: String,
track: String,
album: Option<String>,
recording_mbid: Option<String>,
release_mbid: Option<String>,
artist_mbids: Option<Vec<String>>,
isrc: Option<String>,
duration_ms: Option<u64>,
state: State<'_, ListenBrainzSharedState>,
) -> Result<(), String> {
log::debug!("Command: listenbrainz_now_playing - {} - {}", artist, track);
let client = state.client.lock().await;
// Build additional info with MusicBrainz data
let mut info = AdditionalInfo::new();
info.recording_mbid = recording_mbid;
info.release_mbid = release_mbid;
info.artist_mbids = artist_mbids;
info.isrc = isrc;
info.duration_ms = duration_ms;
client
.submit_playing_now(&artist, &track, album.as_deref(), Some(info))
.await
}
/// Submit a scrobble to ListenBrainz
#[deprecated(since = "1.2.0", note = "Use v2_listenbrainz_scrobble instead")]
#[tauri::command]
pub async fn listenbrainz_scrobble(
artist: String,
track: String,
album: Option<String>,
timestamp: i64,
recording_mbid: Option<String>,
release_mbid: Option<String>,
artist_mbids: Option<Vec<String>>,
isrc: Option<String>,
duration_ms: Option<u64>,
state: State<'_, ListenBrainzSharedState>,
) -> Result<(), String> {
log::info!("Command: listenbrainz_scrobble - {} - {}", artist, track);
let client = state.client.lock().await;
// Build additional info with MusicBrainz data
let mut info = AdditionalInfo::new();
info.recording_mbid = recording_mbid;
info.release_mbid = release_mbid;
info.artist_mbids = artist_mbids;
info.isrc = isrc;
info.duration_ms = duration_ms;
client
.submit_listen(&artist, &track, album.as_deref(), timestamp, Some(info))
.await
}
/// Queue a listen for offline submission
#[deprecated(since = "1.2.0", note = "Use v2_listenbrainz_queue_listen instead")]
#[tauri::command]
pub async fn listenbrainz_queue_listen(
artist: String,
track: String,
album: Option<String>,
timestamp: i64,
recording_mbid: Option<String>,
release_mbid: Option<String>,
artist_mbids: Option<Vec<String>>,
isrc: Option<String>,
duration_ms: Option<u64>,
state: State<'_, ListenBrainzSharedState>,
) -> Result<i64, String> {
log::info!("Command: listenbrainz_queue_listen - {} - {}", artist, track);
let cache_opt__ = state.cache.lock().await;
let cache = cache_opt__.as_ref().ok_or("No active session - please log in")?;
cache.queue_listen(
timestamp,
&artist,
&track,
album.as_deref(),
recording_mbid.as_deref(),
release_mbid.as_deref(),
artist_mbids.as_deref(),
isrc.as_deref(),
duration_ms,
)
}
/// Get queued listens (for sync)
#[tauri::command]
pub async fn listenbrainz_get_queue(
limit: Option<u32>,
state: State<'_, ListenBrainzSharedState>,
) -> Result<Vec<QueuedListen>, String> {
let cache_opt__ = state.cache.lock().await;
let cache = cache_opt__.as_ref().ok_or("No active session - please log in")?;
cache.get_queued_listens(limit.unwrap_or(50))
}
/// Get queue count
#[tauri::command]
pub async fn listenbrainz_get_queue_count(
state: State<'_, ListenBrainzSharedState>,
) -> Result<u32, String> {
let cache_opt__ = state.cache.lock().await;
let cache = cache_opt__.as_ref().ok_or("No active session - please log in")?;
cache.get_queue_count()
}
/// Mark queued listens as sent
#[tauri::command]
pub async fn listenbrainz_mark_sent(
ids: Vec<i64>,
state: State<'_, ListenBrainzSharedState>,
) -> Result<(), String> {
let cache_opt__ = state.cache.lock().await;
let cache = cache_opt__.as_ref().ok_or("No active session - please log in")?;
cache.mark_listens_sent(&ids)
}
/// Flush queue (submit all pending listens)
#[tauri::command]
pub async fn listenbrainz_flush_queue(
state: State<'_, ListenBrainzSharedState>,
) -> Result<u32, String> {
log::info!("Command: listenbrainz_flush_queue");
// Get pending listens
let pending = {
let cache_opt__ = state.cache.lock().await;
let cache = cache_opt__.as_ref().ok_or("No active session - please log in")?;
cache.get_queued_listens(50)?
};
if pending.is_empty() {
return Ok(0);
}
let client = state.client.lock().await;
let mut sent_ids = Vec::new();
for listen in &pending {
// Build additional info
let mut info = AdditionalInfo::new();
info.recording_mbid = listen.recording_mbid.clone();
info.release_mbid = listen.release_mbid.clone();
info.artist_mbids = listen.artist_mbids.clone();
info.isrc = listen.isrc.clone();
info.duration_ms = listen.duration_ms;
match client
.submit_listen(
&listen.artist_name,
&listen.track_name,
listen.release_name.as_deref(),
listen.listened_at,
Some(info),
)
.await
{
Ok(()) => {
sent_ids.push(listen.id);
}
Err(e) => {
log::warn!("Failed to submit queued listen {}: {}", listen.id, e);
// Increment attempt count
let cache_opt__ = state.cache.lock().await;
let cache = cache_opt__.as_ref().ok_or("No active session - please log in")?;
let _ = cache.increment_attempts(listen.id);
}
}
}
// Mark successful ones as sent
if !sent_ids.is_empty() {
let cache_opt__ = state.cache.lock().await;
let cache = cache_opt__.as_ref().ok_or("No active session - please log in")?;
cache.mark_listens_sent(&sent_ids)?;
}
let sent_count = sent_ids.len() as u32;
log::info!("ListenBrainz queue flush: sent {}/{} listens", sent_count, pending.len());
Ok(sent_count)
}
/// Clear the offline queue
#[tauri::command]
pub async fn listenbrainz_clear_queue(
state: State<'_, ListenBrainzSharedState>,
) -> Result<(), String> {
log::info!("Command: listenbrainz_clear_queue");
let cache_opt__ = state.cache.lock().await;
let cache = cache_opt__.as_ref().ok_or("No active session - please log in")?;
cache.clear_queue()
}
/// Cleanup old sent listens
#[tauri::command]
pub async fn listenbrainz_cleanup_queue(
older_than_days: Option<u32>,
state: State<'_, ListenBrainzSharedState>,
) -> Result<u32, String> {
let cache_opt__ = state.cache.lock().await;
let cache = cache_opt__.as_ref().ok_or("No active session - please log in")?;
cache.cleanup_sent_listens(older_than_days.unwrap_or(7))
}
-457
View File
@@ -1,457 +0,0 @@
//! MusicBrainz Tauri commands
//!
//! Exposes MusicBrainz entity resolution to the frontend
//!
//! **DEPRECATED**: Use V2 commands in `commands_v2.rs` instead.
//! These legacy commands will be removed in a future version.
#![allow(deprecated)]
use tauri::State;
use crate::musicbrainz::{
ArtistRelationships, CacheStats, MatchConfidence, MusicBrainzSharedState, ResolvedArtist,
ResolvedRelease, ResolvedTrack,
};
/// Resolve a track to MusicBrainz by ISRC
#[tauri::command]
pub async fn musicbrainz_resolve_track(
isrc: Option<String>,
title: String,
artist: String,
state: State<'_, MusicBrainzSharedState>,
) -> Result<ResolvedTrack, String> {
if !state.client.is_enabled().await {
return Ok(ResolvedTrack::empty());
}
// Check cache first (short lock)
if let Some(ref isrc_val) = isrc {
let cached = {
let cache_opt__ = state.cache.lock().await;
let cache = cache_opt__.as_ref().ok_or("No active session - please log in")?;
cache.get_recording(isrc_val).ok().flatten()
};
if let Some(cached) = cached {
log::debug!("MusicBrainz cache hit for ISRC: {}", isrc_val);
return Ok(cached);
}
}
// Try ISRC lookup
if let Some(ref isrc_val) = isrc {
match state.client.search_recording_by_isrc(isrc_val).await {
Ok(response) => {
if let Some(recording) = response.recordings.first() {
let resolved = recording_to_resolved(recording);
// Cache the result (short lock)
{
let cache_opt__ = state.cache.lock().await;
let cache = cache_opt__.as_ref().ok_or("No active session - please log in")?;
let _ = cache.set_recording(isrc_val, &resolved);
}
return Ok(resolved);
}
}
Err(e) => {
log::warn!("MusicBrainz ISRC lookup failed: {}", e);
}
}
}
// Fallback to title+artist search
match state.client.search_recording(&title, &artist).await {
Ok(response) => {
if let Some(recording) = response
.recordings
.iter()
.find(|r| r.score.unwrap_or(0) >= 80)
{
let resolved = recording_to_resolved(recording);
// Cache by ISRC if available
if let Some(ref isrc_val) = isrc {
let cache_opt__ = state.cache.lock().await;
let cache = cache_opt__.as_ref().ok_or("No active session - please log in")?;
let _ = cache.set_recording(isrc_val, &resolved);
}
return Ok(resolved);
}
}
Err(e) => {
log::warn!("MusicBrainz recording search failed: {}", e);
}
}
// Cache negative result
if let Some(ref isrc_val) = isrc {
let empty = ResolvedTrack::empty();
let cache_opt__ = state.cache.lock().await;
let cache = cache_opt__.as_ref().ok_or("No active session - please log in")?;
let _ = cache.set_recording(isrc_val, &empty);
}
Ok(ResolvedTrack::empty())
}
/// Resolve an artist to MusicBrainz by name
#[tauri::command]
pub async fn musicbrainz_resolve_artist(
name: String,
state: State<'_, MusicBrainzSharedState>,
) -> Result<ResolvedArtist, String> {
if !state.client.is_enabled().await {
return Ok(ResolvedArtist::empty());
}
// Check cache first
let cached = {
let cache_opt__ = state.cache.lock().await;
let cache = cache_opt__.as_ref().ok_or("No active session - please log in")?;
cache.get_artist(&name).ok().flatten()
};
if let Some(cached) = cached {
log::debug!("MusicBrainz cache hit for artist: {}", name);
return Ok(cached);
}
match state.client.search_artist(&name).await {
Ok(response) => {
if let Some(artist) = response
.artists
.iter()
.find(|a| a.score.unwrap_or(0) >= 90)
{
let resolved = artist_to_resolved(artist);
// Cache the result
{
let cache_opt__ = state.cache.lock().await;
let cache = cache_opt__.as_ref().ok_or("No active session - please log in")?;
let _ = cache.set_artist(&name, &resolved);
}
return Ok(resolved);
}
}
Err(e) => {
log::warn!("MusicBrainz artist search failed: {}", e);
}
}
// Cache negative result
let empty = ResolvedArtist::empty();
{
let cache_opt__ = state.cache.lock().await;
let cache = cache_opt__.as_ref().ok_or("No active session - please log in")?;
let _ = cache.set_artist(&name, &empty);
}
Ok(empty)
}
/// Resolve a release to MusicBrainz by UPC/barcode
#[tauri::command]
pub async fn musicbrainz_resolve_release(
upc: Option<String>,
title: String,
artist: String,
state: State<'_, MusicBrainzSharedState>,
) -> Result<ResolvedRelease, String> {
if !state.client.is_enabled().await {
return Ok(ResolvedRelease::empty());
}
// Check cache first
if let Some(ref upc_val) = upc {
let cached = {
let cache_opt__ = state.cache.lock().await;
let cache = cache_opt__.as_ref().ok_or("No active session - please log in")?;
cache.get_release(upc_val).ok().flatten()
};
if let Some(cached) = cached {
log::debug!("MusicBrainz cache hit for UPC: {}", upc_val);
return Ok(cached);
}
}
// Try barcode lookup
if let Some(ref upc_val) = upc {
match state.client.search_release_by_barcode(upc_val).await {
Ok(response) => {
if let Some(release) = response.releases.first() {
let resolved = release_to_resolved(release);
// Cache the result
{
let cache_opt__ = state.cache.lock().await;
let cache = cache_opt__.as_ref().ok_or("No active session - please log in")?;
let _ = cache.set_release(upc_val, &resolved);
}
return Ok(resolved);
}
}
Err(e) => {
log::warn!("MusicBrainz barcode lookup failed: {}", e);
}
}
}
// Fallback to title+artist search
match state.client.search_release(&title, &artist).await {
Ok(response) => {
if let Some(release) = response
.releases
.iter()
.find(|r| r.score.unwrap_or(0) >= 80)
{
let resolved = release_to_resolved(release);
// Cache by UPC if available
if let Some(ref upc_val) = upc {
let cache_opt__ = state.cache.lock().await;
let cache = cache_opt__.as_ref().ok_or("No active session - please log in")?;
let _ = cache.set_release(upc_val, &resolved);
}
return Ok(resolved);
}
}
Err(e) => {
log::warn!("MusicBrainz release search failed: {}", e);
}
}
// Cache negative result
if let Some(ref upc_val) = upc {
let empty = ResolvedRelease::empty();
let cache_opt__ = state.cache.lock().await;
let cache = cache_opt__.as_ref().ok_or("No active session - please log in")?;
let _ = cache.set_release(upc_val, &empty);
}
Ok(ResolvedRelease::empty())
}
/// Get artist relationships by MBID (for Stage 3)
#[tauri::command]
pub async fn musicbrainz_get_artist_relationships(
mbid: String,
state: State<'_, MusicBrainzSharedState>,
) -> Result<ArtistRelationships, String> {
if !state.client.is_enabled().await {
return Ok(ArtistRelationships::empty());
}
// Check cache first
let cached = {
let cache_opt__ = state.cache.lock().await;
let cache = cache_opt__.as_ref().ok_or("No active session - please log in")?;
cache.get_artist_relations(&mbid).ok().flatten()
};
if let Some(cached) = cached {
log::debug!("MusicBrainz cache hit for artist relations: {}", mbid);
return Ok(cached);
}
match state.client.get_artist_with_relations(&mbid).await {
Ok(response) => {
let relations = extract_relationships(&response);
// Cache the result
{
let cache_opt__ = state.cache.lock().await;
let cache = cache_opt__.as_ref().ok_or("No active session - please log in")?;
let _ = cache.set_artist_relations(&mbid, &relations);
}
Ok(relations)
}
Err(e) => {
log::warn!("MusicBrainz artist relations lookup failed: {}", e);
// Cache negative result
let empty = ArtistRelationships::empty();
{
let cache_opt__ = state.cache.lock().await;
let cache = cache_opt__.as_ref().ok_or("No active session - please log in")?;
let _ = cache.set_artist_relations(&mbid, &empty);
}
Ok(empty)
}
}
}
/// Check if MusicBrainz integration is enabled
#[deprecated(since = "1.2.0", note = "Use v2_musicbrainz_is_enabled instead")]
#[tauri::command]
pub async fn musicbrainz_is_enabled(
state: State<'_, MusicBrainzSharedState>,
) -> Result<bool, String> {
Ok(state.client.is_enabled().await)
}
/// Enable or disable MusicBrainz integration
#[deprecated(since = "1.2.0", note = "Use v2_musicbrainz_set_enabled instead")]
#[tauri::command]
pub async fn musicbrainz_set_enabled(
enabled: bool,
state: State<'_, MusicBrainzSharedState>,
) -> Result<(), String> {
state.client.set_enabled(enabled).await;
log::info!(
"MusicBrainz integration {}",
if enabled { "enabled" } else { "disabled" }
);
Ok(())
}
/// Get MusicBrainz cache statistics
#[tauri::command]
pub async fn musicbrainz_get_cache_stats(
state: State<'_, MusicBrainzSharedState>,
) -> Result<CacheStats, String> {
let cache_opt__ = state.cache.lock().await;
let cache = cache_opt__.as_ref().ok_or("No active session - please log in")?;
cache.get_stats()
}
/// Clear MusicBrainz cache
#[tauri::command]
pub async fn musicbrainz_clear_cache(
state: State<'_, MusicBrainzSharedState>,
) -> Result<(), String> {
let cache_opt__ = state.cache.lock().await;
let cache = cache_opt__.as_ref().ok_or("No active session - please log in")?;
cache.clear_all()
}
/// Cleanup expired cache entries
#[tauri::command]
pub async fn musicbrainz_cleanup_cache(
state: State<'_, MusicBrainzSharedState>,
) -> Result<usize, String> {
let cache_opt__ = state.cache.lock().await;
let cache = cache_opt__.as_ref().ok_or("No active session - please log in")?;
cache.cleanup_expired()
}
// ============ Helper functions ============
use crate::musicbrainz::models::{
ArtistFullResponse, ArtistResult, RecordingResult, RelatedArtist, ReleaseResult, Period,
};
fn recording_to_resolved(recording: &RecordingResult) -> ResolvedTrack {
let artist_credit = recording.artist_credit.as_ref().map(|credits| {
credits
.iter()
.map(|c| {
format!(
"{}{}",
c.name.as_deref().unwrap_or(&c.artist.name),
c.joinphrase.as_deref().unwrap_or("")
)
})
.collect::<Vec<_>>()
.join("")
});
let artist_mbids = recording
.artist_credit
.as_ref()
.map(|credits| credits.iter().map(|c| c.artist.id.clone()).collect());
let (release_mbid, release_title) = recording
.releases
.as_ref()
.and_then(|releases| releases.first())
.map(|r| (Some(r.id.clone()), r.title.clone()))
.unwrap_or((None, None));
ResolvedTrack {
mbid: Some(recording.id.clone()),
title: recording.title.clone(),
artist_credit,
artist_mbids,
release_mbid,
release_title,
confidence: MatchConfidence::from_score(recording.score),
}
}
fn artist_to_resolved(artist: &ArtistResult) -> ResolvedArtist {
use crate::musicbrainz::ArtistType;
ResolvedArtist {
mbid: Some(artist.id.clone()),
name: Some(artist.name.clone()),
sort_name: artist.sort_name.clone(),
artist_type: Some(ArtistType::from(artist.artist_type.as_deref())),
country: artist.country.clone(),
disambiguation: artist.disambiguation.clone(),
confidence: MatchConfidence::from_score(artist.score),
}
}
fn release_to_resolved(release: &ReleaseResult) -> ResolvedRelease {
let (label, catalog_number) = release
.label_info
.as_ref()
.and_then(|info| info.first())
.map(|li| (li.label.as_ref().map(|l| l.name.clone()), li.catalog_number.clone()))
.unwrap_or((None, None));
ResolvedRelease {
mbid: Some(release.id.clone()),
title: Some(release.title.clone()),
release_group_mbid: release.release_group.as_ref().map(|rg| rg.id.clone()),
label,
catalog_number,
country: release.country.clone(),
date: release.date.clone(),
confidence: MatchConfidence::from_score(release.score),
}
}
fn extract_relationships(artist: &ArtistFullResponse) -> ArtistRelationships {
let mut members = Vec::new();
let past_members = Vec::new();
let mut groups = Vec::new();
let mut collaborators = Vec::new();
if let Some(relations) = &artist.relations {
for relation in relations {
let Some(related_artist) = &relation.artist else {
continue;
};
let related = RelatedArtist {
mbid: related_artist.id.clone(),
name: related_artist.name.clone(),
role: relation.attributes.as_ref().and_then(|a| a.first().cloned()),
period: Some(Period {
begin: relation.begin.clone(),
end: relation.end.clone(),
}),
ended: relation.ended.unwrap_or(false),
};
match relation.relation_type.as_str() {
"member of band" => {
if relation.direction.as_deref() == Some("backward") {
// We're viewing a BAND, the related artist is a MEMBER
// All members go to the same list - don't separate by ended status
members.push(related);
} else {
// We're viewing a PERSON, the related artist is a BAND/GROUP
groups.push(related);
}
}
"collaboration" => {
collaborators.push(related);
}
_ => {}
}
}
}
ArtistRelationships {
members,
past_members,
groups,
collaborators,
}
}
-615
View File
@@ -1,615 +0,0 @@
//! Musician resolution commands
//!
//! Handles musician discovery and confidence assessment for the
//! Musician Page and Informational Modal features.
use std::collections::HashSet;
use tauri::State;
// Note: We use Qobuz search APIs which return these types internally
use crate::musicbrainz::{
AlbumAppearance, MusicBrainzSharedState, MusicianAppearances, MusicianConfidence,
ResolvedMusician,
};
use crate::AppState;
/// Resolve a musician from credits to determine navigation destination
///
/// Returns a ResolvedMusician with:
/// - Confidence level (determines UI: Artist Page, Musician Page, or Modal)
/// - Qobuz artist ID if found (for navigation to Artist Page)
/// - MusicBrainz data if available (bands, MBID)
/// - Appears-on count from Qobuz
#[tauri::command]
pub async fn resolve_musician(
name: String,
role: String,
state: State<'_, AppState>,
mb_state: State<'_, MusicBrainzSharedState>,
) -> Result<ResolvedMusician, String> {
log::info!("Resolving musician: {} (role: {})", name, role);
let mut musician = ResolvedMusician::empty(name.clone(), role.clone());
// Step 1: Search Qobuz for artist, handling "The" prefix variations
// MusicBrainz often has "Beatles" but Qobuz has "The Beatles"
let qobuz_artist = {
let client = state.client.read().await;
let name_lower = name.to_lowercase();
// Search with original name
let mut best_match: Option<crate::api::Artist> = None;
if let Ok(results) = client.search_artists(&name, 10, 0, None).await {
// Look for exact match first
for artist in &results.items {
let artist_lower = artist.name.to_lowercase();
if artist_lower == name_lower {
best_match = Some(artist.clone());
break;
}
}
// If no exact match, check for "The X" variant
if best_match.is_none() {
let the_name = format!("the {}", name_lower);
for artist in &results.items {
let artist_lower = artist.name.to_lowercase();
if artist_lower == the_name {
log::info!("Found 'The' variant: {} -> {}", name, artist.name);
best_match = Some(artist.clone());
break;
}
}
}
// Always check if "The X" variant has more STUDIO albums
// Total album count is misleading (tributes, compilations inflate it)
if let Some(ref current) = best_match {
// Count studio albums for current match
let current_studio = count_studio_albums(&client, current.id).await;
log::info!(
"Match '{}' has {} studio albums (total: {})",
current.name, current_studio, current.albums_count.unwrap_or(0)
);
// If few studio albums, check "The X" variant
if current_studio < 10 {
let the_name = format!("The {}", name);
if let Ok(the_results) = client.search_artists(&the_name, 5, 0, None).await {
for artist in the_results.items {
let artist_lower = artist.name.to_lowercase();
let the_name_lower = the_name.to_lowercase();
if artist_lower == the_name_lower {
let the_studio = count_studio_albums(&client, artist.id).await;
log::info!(
"Comparing studio albums: '{}' has {} studio, 'The {}' has {} studio",
current.name, current_studio, name, the_studio
);
if the_studio > current_studio {
log::info!(
"Preferring 'The {}' ({} studio albums) over '{}' ({} studio albums)",
name, the_studio, current.name, current_studio
);
best_match = Some(artist);
}
break;
}
}
}
}
}
}
best_match
};
// Step 2: If found, check if they have a real catalog
if let Some(artist) = qobuz_artist {
let has_catalog = artist.albums_count.unwrap_or(0) > 0;
if has_catalog {
// Confidence = 3: Has a dedicated Qobuz artist page
musician.qobuz_artist_id = Some(artist.id as i64);
musician.confidence = MusicianConfidence::Confirmed;
log::info!(
"Musician {} resolved as Confirmed (Qobuz artist ID: {}, name: {})",
name,
artist.id,
artist.name
);
}
}
// Step 3: If no artist page, search for appearances in track credits
if musician.confidence == MusicianConfidence::None {
let appearances_count = count_track_appearances(&state, &name).await;
musician.appears_on_count = appearances_count;
if appearances_count >= 3 {
// Confidence = 2: Appears in multiple album credits
musician.confidence = MusicianConfidence::Contextual;
log::info!(
"Musician {} resolved as Contextual ({} appearances)",
name,
appearances_count
);
} else if appearances_count > 0 {
// Confidence = 1: Sparse results
musician.confidence = MusicianConfidence::Weak;
log::info!(
"Musician {} resolved as Weak ({} appearances)",
name,
appearances_count
);
}
}
// Step 4: Try MusicBrainz enrichment (if enabled)
if mb_state.client.is_enabled().await {
match enrich_from_musicbrainz(&mb_state, &name).await {
Ok((mbid, bands)) => {
musician.mbid = mbid;
musician.bands = bands;
}
Err(e) => {
log::warn!("MusicBrainz enrichment failed for {}: {}", name, e);
// Continue without MB data - don't block
}
}
}
log::info!(
"Musician {} final confidence: {:?}",
name,
musician.confidence
);
Ok(musician)
}
/// Get albums a musician appears on (Qobuz only)
///
/// Returns deduplicated album appearances sorted by year.
/// This is the data source for the "Appears On" section of the Musician Page.
#[tauri::command]
pub async fn get_musician_appearances(
name: String,
_role: Option<String>,
limit: u32,
offset: u32,
state: State<'_, AppState>,
) -> Result<MusicianAppearances, String> {
log::info!(
"Getting musician appearances: {} (limit: {}, offset: {})",
name,
limit,
offset
);
// Search for tracks by performer name
let tracks = {
let client = state.client.read().await;
client
.search_tracks(&name, 100, 0, None)
.await
.map_err(|e| e.to_string())?
};
// Deduplicate by album, keeping track of roles
let mut seen_albums = HashSet::new();
let mut albums: Vec<AlbumAppearance> = Vec::new();
for track in tracks.items {
// Check if performer matches
let performer_name = track
.performer
.as_ref()
.map(|p| p.name.as_str())
.unwrap_or("");
// Also check the performers string for session musicians
let performers_str = track.performers.as_deref().unwrap_or("");
let name_lower = name.to_lowercase();
let matches = performer_name.to_lowercase() == name_lower
|| performers_str.to_lowercase().contains(&name_lower);
if !matches {
continue;
}
if let Some(album) = &track.album {
if seen_albums.contains(&album.id) {
continue;
}
seen_albums.insert(album.id.clone());
// Extract role from performers string if possible
let role = extract_role_from_performers(performers_str, &name);
albums.push(AlbumAppearance {
album_id: album.id.clone(),
album_title: album.title.clone(),
album_artwork: album
.image
.large
.clone()
.or_else(|| album.image.thumbnail.clone())
.unwrap_or_default(),
// AlbumSummary doesn't have artist field, use track's performer
artist_name: track
.performer
.as_ref()
.map(|p| p.name.clone())
.unwrap_or_else(|| performer_name.to_string()),
// AlbumSummary doesn't have release_date_original
year: None,
role_on_album: role,
});
}
}
// Sort by year descending
albums.sort_by(|a, b| {
let year_a = a.year.as_deref().unwrap_or("0");
let year_b = b.year.as_deref().unwrap_or("0");
year_b.cmp(year_a)
});
let total = albums.len();
// Apply pagination
let start = offset as usize;
let end = (start + limit as usize).min(albums.len());
let paginated = if start < albums.len() {
albums[start..end].to_vec()
} else {
Vec::new()
};
Ok(MusicianAppearances {
albums: paginated,
total,
})
}
// ============ Helper Functions ============
/// Count how many unique albums a musician appears on
async fn count_track_appearances(state: &State<'_, AppState>, name: &str) -> usize {
let client = state.client.read().await;
match client.search_tracks(name, 50, 0, None).await {
Ok(results) => {
let mut seen_albums = HashSet::new();
let name_lower = name.to_lowercase();
for track in results.items {
// Check performer name
let performer_name = track
.performer
.as_ref()
.map(|p| p.name.to_lowercase())
.unwrap_or_default();
// Check performers string
let performers_str = track
.performers
.as_ref()
.map(|s| s.to_lowercase())
.unwrap_or_default();
let matches =
performer_name == name_lower || performers_str.contains(&name_lower);
if matches {
if let Some(album) = &track.album {
seen_albums.insert(album.id.clone());
}
}
}
seen_albums.len()
}
Err(e) => {
log::warn!("Failed to count appearances for {}: {}", name, e);
0
}
}
}
/// Enrich musician data from MusicBrainz
async fn enrich_from_musicbrainz(
mb_state: &State<'_, MusicBrainzSharedState>,
name: &str,
) -> Result<(Option<String>, Vec<String>), String> {
// Resolve artist to get MBID
let resolved = {
let cache_opt__ = mb_state.cache.lock().await;
let cache = cache_opt__.as_ref().ok_or("No active session - please log in")?;
cache.get_artist(name).ok().flatten()
};
let mbid = if let Some(cached) = resolved {
cached.mbid
} else {
// Search MusicBrainz for the artist
match mb_state.client.search_artist(name).await {
Ok(response) => {
// Find best match (score >= 90)
response
.artists
.into_iter()
.find(|a| a.score.unwrap_or(0) >= 90)
.map(|a| a.id)
}
Err(e) => {
log::warn!("MusicBrainz artist search failed: {}", e);
None
}
}
};
let mut bands = Vec::new();
// If we have an MBID, get relationships to find bands
if let Some(ref mbid) = mbid {
match mb_state.client.get_artist_with_relations(mbid).await {
Ok(response) => {
if let Some(relations) = response.relations {
for relation in relations {
// "member of band" relation with forward direction means this person is in a band
if relation.relation_type == "member of band"
&& relation.direction.as_deref() != Some("backward")
{
if let Some(artist) = relation.artist {
bands.push(artist.name);
}
}
}
}
}
Err(e) => {
log::warn!("MusicBrainz relations fetch failed: {}", e);
}
}
}
Ok((mbid, bands))
}
/// Extract role from performers string
/// e.g., "John Smith, Piano - Jane Doe, Vocals" -> "Piano" for "John Smith"
fn extract_role_from_performers(performers: &str, name: &str) -> String {
let name_lower = name.to_lowercase();
// Split by common delimiters
for segment in performers.split(&['-', '–', '|', ';'][..]) {
let segment = segment.trim();
// Check if this segment contains the name
if segment.to_lowercase().contains(&name_lower) {
// Try to extract role after comma
if let Some(comma_pos) = segment.find(',') {
let after_comma = segment[comma_pos + 1..].trim();
// Clean up - take first word or phrase before next punctuation
let role = after_comma
.split(&[',', '(', ')'][..])
.next()
.unwrap_or(after_comma)
.trim();
if !role.is_empty() {
return role.to_string();
}
}
}
}
// Fallback
"Performer".to_string()
}
// ============ Album Categorization (mirrors qobuzAdapters.ts logic) ============
use lazy_static::lazy_static;
use regex::Regex;
lazy_static! {
// Unofficial releases patterns
static ref BROADCAST_PATTERNS: Regex = Regex::new(r"(?i)\b(fm broadcasts?|radio broadcasts?|broadcasts?|bootleg|unofficial|pirate)\b").unwrap();
static ref NON_MUSIC_PATTERNS: Regex = Regex::new(r"(?i)\b(interviews?|speaks|talking|in their own words|the interviews?|memories:?\s*the)\b").unwrap();
static ref BOOTLEG_LABELS: Regex = Regex::new(r"(?i)\b(leftfield media|purple pyramid|cleopatra|laser media|radio lu|broadcast archives)\b").unwrap();
// Compilation patterns
static ref COMPILATION_PATTERNS: Regex = Regex::new(r"(?i)\b(greatest hits|best of|anthology|the very best|essentials?|definitive collection|gold|platinum|hits collection|complete collection|hit collection|b-sides|rarities)\b").unwrap();
static ref VARIOUS_PATTERNS: Regex = Regex::new(r"(?i)\b(various artists|v\.?a\.?|original soundtrack|ost)\b").unwrap();
// Live album patterns
static ref LIVE_PATTERNS: Regex = Regex::new(r"(?i)\blive\b|\blive at\b|\blive in\b|\bin concert\b|\bunplugged\b|\bmtv unplugged\b|\bacoustic live\b|\balive\b|\bon stage\b").unwrap();
static ref LIVE_MULTILANG: Regex = Regex::new(r"(?i)\b(en vivo|en directo|ao vivo|dal vivo|en direct|konzert|liveopname)\b|ライブ|라이브|콘서트").unwrap();
static ref FM_BROADCAST: Regex = Regex::new(r"(?i)\b(fm broadcasts?|radio broadcasts?|broadcasts?)\b").unwrap();
// Studio album variant patterns
static ref STUDIO_VARIANT: Regex = Regex::new(r"(?i)\b(deluxe|remaster|anniversary|expanded|special edition|collector|box set)\b").unwrap();
// EP/Single patterns
static ref EP_PATTERNS: Regex = Regex::new(r"(?i)\b(- ep|\.ep|\(ep\))\b").unwrap();
static ref EP_SUFFIX: Regex = Regex::new(r"(?i)\bep\s*$").unwrap();
static ref SINGLE_PATTERNS: Regex = Regex::new(r"(?i)\b(- single|\(single\))\b").unwrap();
}
/// Album category for filtering
#[derive(Debug, Clone, Copy, PartialEq)]
enum AlbumCategory {
Albums, // Studio albums (main discography)
Tributes, // Albums by other artists
Others, // Compilations, bootlegs, unofficial
Live, // Live recordings
Eps, // EPs and singles
}
/// Check if album is by a different artist
fn is_different_artist(album: &crate::api::Album, main_artist_id: u64) -> bool {
album.artist.id != main_artist_id
}
/// Check if this is an unofficial/bootleg release
fn is_unofficial_release(title: &str, label: &str, track_count: u32, duration: u32) -> bool {
// FM Broadcasts, bootlegs
if BROADCAST_PATTERNS.is_match(title) {
return true;
}
// Interviews, spoken word
if NON_MUSIC_PATTERNS.is_match(title) {
return true;
}
// Known bootleg labels
if BOOTLEG_LABELS.is_match(label) {
return true;
}
// Podcast-like: single long track
if track_count == 1 && duration >= 1200 {
return true;
}
false
}
/// Check if this is a compilation/greatest hits
fn is_compilation_album(title: &str) -> bool {
COMPILATION_PATTERNS.is_match(title) || VARIOUS_PATTERNS.is_match(title)
}
/// Check if this is a live album
fn is_live_album(title: &str) -> bool {
// Don't classify FM broadcasts as live
if FM_BROADCAST.is_match(title) {
return false;
}
if LIVE_PATTERNS.is_match(title) || LIVE_MULTILANG.is_match(title) {
return true;
}
false
}
/// Check if this is a studio album (main discography material)
fn is_studio_album(title: &str, track_count: u32, duration: u32) -> bool {
// Single-track releases over 20 min are likely podcasts
if track_count == 1 && duration >= 1200 {
return false;
}
// Deluxe/remastered editions are studio albums
if STUDIO_VARIANT.is_match(title) && (track_count >= 7 || duration >= 2100) {
return true;
}
// Standard album: 7+ tracks or 25+ minutes
if track_count >= 7 {
return true;
}
if duration >= 1500 {
return true;
}
false
}
/// Check if this is an EP or Single
fn is_ep_or_single(title: &str, track_count: u32, duration: u32) -> bool {
// Explicitly marked as EP or Single
if EP_PATTERNS.is_match(title) || EP_SUFFIX.is_match(title) || SINGLE_PATTERNS.is_match(title) {
return true;
}
// Very short releases: 1-4 tracks
if track_count > 0 && track_count <= 4 {
return true;
}
// Under 15 minutes
if duration > 0 && duration <= 900 {
return true;
}
// 5-6 tracks AND under 20 minutes
if track_count >= 5 && track_count <= 6 && duration > 0 && duration <= 1200 {
return true;
}
false
}
/// Categorize an album (mirrors TypeScript categorizeAlbum)
fn categorize_album(album: &crate::api::Album, main_artist_id: u64) -> AlbumCategory {
let title = album.title.to_lowercase();
let label = album.label.as_ref().map(|l| l.name.as_str()).unwrap_or("");
let track_count = album.tracks_count.unwrap_or(0);
let duration = album.duration.unwrap_or(0);
// 1. Albums by different artists -> Tributes
if is_different_artist(album, main_artist_id) {
return AlbumCategory::Tributes;
}
// 2. Unofficial releases -> Others
if is_unofficial_release(&title, label, track_count, duration) {
return AlbumCategory::Others;
}
// 3. Compilations -> Others
if is_compilation_album(&title) {
return AlbumCategory::Others;
}
// 4. Live albums -> Live
if is_live_album(&title) {
return AlbumCategory::Live;
}
// 5. Check if it's a studio album first
if is_studio_album(&title, track_count, duration) {
return AlbumCategory::Albums;
}
// 6. EPs and Singles
if is_ep_or_single(&title, track_count, duration) {
return AlbumCategory::Eps;
}
// 7. Default: treat as studio album
AlbumCategory::Albums
}
/// Count studio albums for an artist (fetches albums and filters)
async fn count_studio_albums(
client: &crate::api::QobuzClient,
artist_id: u64,
) -> usize {
// Fetch artist with albums (limit to 50 for performance)
match client.get_artist_with_pagination(artist_id, true, Some(50), None).await {
Ok(artist) => {
if let Some(albums) = artist.albums {
albums
.items
.iter()
.filter(|album| categorize_album(album, artist_id) == AlbumCategory::Albums)
.count()
} else {
0
}
}
Err(e) => {
log::warn!("Failed to fetch albums for artist {}: {}", artist_id, e);
0
}
}
}
-192
View File
@@ -1,192 +0,0 @@
//! System notification commands
use notify_rust::Notification;
use md5::{Digest, Md5};
use std::path::PathBuf;
use std::fs;
use std::io::Write;
/// Cache directory for notification artwork
fn get_artwork_cache_dir() -> Result<PathBuf, String> {
let cache_dir = dirs::cache_dir()
.ok_or_else(|| "Could not find cache directory".to_string())?
.join("qbz")
.join("artwork");
fs::create_dir_all(&cache_dir)
.map_err(|e| format!("Failed to create artwork cache dir: {}", e))?;
Ok(cache_dir)
}
/// Download artwork to cache and return the path
fn cache_artwork(url: &str) -> Result<PathBuf, String> {
if let Some(local_path) = resolve_local_artwork(url) {
if local_path.exists() {
return Ok(local_path);
}
}
// Create a hash of the URL for the filename
let mut hasher = Md5::new();
hasher.update(url.as_bytes());
let hash = format!("{:x}", hasher.finalize());
let cache_dir = get_artwork_cache_dir()?;
let cache_path = cache_dir.join(format!("{}.jpg", hash));
// Return cached file if exists
if cache_path.exists() {
return Ok(cache_path);
}
// Download the image
let response = reqwest::blocking::Client::new()
.get(url)
.timeout(std::time::Duration::from_secs(5))
.send()
.map_err(|e| format!("Failed to download artwork: {}", e))?;
if !response.status().is_success() {
return Err(format!("Failed to download artwork: HTTP {}", response.status()));
}
let bytes = response.bytes()
.map_err(|e| format!("Failed to read artwork bytes: {}", e))?;
// Write to cache
let mut file = fs::File::create(&cache_path)
.map_err(|e| format!("Failed to create artwork cache file: {}", e))?;
file.write_all(&bytes)
.map_err(|e| format!("Failed to write artwork cache: {}", e))?;
Ok(cache_path)
}
fn resolve_local_artwork(url: &str) -> Option<PathBuf> {
if let Some(path) = url.strip_prefix("file://") {
return Some(PathBuf::from(path));
}
if let Some(path) = url.strip_prefix("asset://localhost/") {
let decoded = urlencoding::decode(path).ok()?;
return Some(PathBuf::from(decoded.into_owned()));
}
None
}
/// Format quality info for notification
fn format_quality(bit_depth: Option<u32>, sample_rate: Option<f64>) -> String {
match (bit_depth, sample_rate) {
(Some(bits), Some(rate)) if bits >= 24 || rate > 48.0 => {
// Format sample rate: 44.1 → 44.1, 48.0 → 48, 192.0 → 192
let rate_str = if rate.fract() == 0.0 {
format!("{}", rate as u32)
} else {
format!("{}", rate)
};
format!("Hi-Res • {}-bit/{}kHz", bits, rate_str)
}
(Some(bits), Some(rate)) => {
let rate_str = if rate.fract() == 0.0 {
format!("{}", rate as u32)
} else {
format!("{}", rate)
};
format!("CD Quality • {}-bit/{}kHz", bits, rate_str)
}
_ => String::new()
}
}
/// Show a track change notification with artwork
#[tauri::command]
pub fn show_track_notification(
title: String,
artist: String,
album: String,
artwork_url: Option<String>,
bit_depth: Option<u32>,
sample_rate: Option<f64>, // Changed from u32 to f64 to support 44.1, 88.2, 176.4, etc.
) -> Result<(), String> {
log::info!("Command: show_track_notification - {} by {}", title, artist);
// Build body with 2-3 lines:
// Line 1: Artist • Album
// Line 2: Quality (if available)
let mut lines = Vec::new();
// Line 1: Artist and Album
let mut line1_parts = Vec::new();
if !artist.is_empty() {
line1_parts.push(artist.clone());
}
if !album.is_empty() {
line1_parts.push(album.clone());
}
if !line1_parts.is_empty() {
lines.push(line1_parts.join(" • "));
}
// Line 2: Quality info
let quality = format_quality(bit_depth, sample_rate);
if !quality.is_empty() {
lines.push(quality);
}
let body = lines.join("\n");
let mut notification = Notification::new();
notification
.summary(&title)
.body(&body)
.appname("QBZ")
.timeout(4000); // 4 seconds
// Try to add artwork
if let Some(url) = artwork_url {
match cache_artwork(&url) {
Ok(path) => {
if let Some(path_str) = path.to_str() {
notification.image_path(path_str);
log::debug!("Notification artwork set: {}", path_str);
}
}
Err(e) => {
log::warn!("Could not cache artwork for notification: {}", e);
}
}
}
// Show notification, but don't fail if notification system is unavailable
// This handles systems without a notification daemon (issue #32)
if let Err(e) = notification.show() {
log::warn!("Could not show notification (notification system may be unavailable): {}", e);
}
Ok(())
}
/// Show a generic notification
#[tauri::command]
pub fn show_notification(
title: String,
body: Option<String>,
) -> Result<(), String> {
log::info!("Command: show_notification - {}", title);
let mut notification = Notification::new();
notification.summary(&title).appname("QBZ").timeout(3000);
if let Some(body_text) = body {
notification.body(&body_text);
}
// Show notification, but don't fail if notification system is unavailable
// This handles systems without a notification daemon (issue #32)
if let Err(e) = notification.show() {
log::warn!("Could not show notification (notification system may be unavailable): {}", e);
}
Ok(())
}
@@ -1,67 +0,0 @@
//! Playback context commands
use tauri::State;
use crate::playback_context::{PlaybackContext, ContextType, ContentSource};
use crate::AppState;
/// Get the current playback context
#[tauri::command]
pub fn get_playback_context(state: State<'_, AppState>) -> Option<PlaybackContext> {
state.context.get_context()
}
/// Set a new playback context
#[tauri::command]
pub fn set_playback_context(
context_type: String,
id: String,
label: String,
source: String,
track_ids: Vec<u64>,
start_position: usize,
state: State<'_, AppState>,
) -> Result<(), String> {
// Parse context type
let ctx_type = match context_type.as_str() {
"album" => ContextType::Album,
"playlist" => ContextType::Playlist,
"artist_top" => ContextType::ArtistTop,
"home_list" => ContextType::HomeList,
"favorites" => ContextType::Favorites,
"local_library" => ContextType::LocalLibrary,
"radio" => ContextType::Radio,
_ => return Err(format!("Invalid context type: {}", context_type)),
};
// Parse source
let content_source = match source.as_str() {
"qobuz" => ContentSource::Qobuz,
"local" => ContentSource::Local,
"plex" => ContentSource::Plex,
_ => return Err(format!("Invalid source: {}", source)),
};
let context = PlaybackContext::new(
ctx_type,
id,
label,
content_source,
track_ids,
start_position,
);
state.context.set_context(context);
Ok(())
}
/// Clear the current playback context
#[tauri::command]
pub fn clear_playback_context(state: State<'_, AppState>) {
state.context.clear_context();
}
/// Check if a playback context is active
#[tauri::command]
pub fn has_playback_context(state: State<'_, AppState>) -> bool {
state.context.has_context()
}
-412
View File
@@ -1,412 +0,0 @@
//! Playlist-related Tauri commands
use serde::Serialize;
use tauri::State;
use crate::api::models::{Playlist, PlaylistDuplicateResult, PlaylistWithTrackIds, SearchResultsPage, Track};
use crate::api::performers::{parse_performers, Performer};
use crate::library::commands::LibraryState;
use crate::AppState;
/// Track info with parsed performers for display
#[derive(Debug, Clone, Serialize)]
pub struct TrackInfo {
pub track: Track,
pub performers: Vec<Performer>,
}
/// Get user's playlists
#[tauri::command]
pub async fn get_user_playlists(
state: State<'_, AppState>,
) -> Result<Vec<Playlist>, String> {
log::debug!("Command: get_user_playlists");
let client = state.client.read().await;
client
.get_user_playlists()
.await
.map_err(|e| format!("Failed to get user playlists: {}", e))
}
/// Get a specific playlist by ID
#[tauri::command]
pub async fn get_playlist(
playlist_id: u64,
state: State<'_, AppState>,
) -> Result<Playlist, String> {
let cmd_start = std::time::Instant::now();
log::debug!("Command: get_playlist {}", playlist_id);
let client = state.client.read().await;
let lock_elapsed = cmd_start.elapsed();
let result = client
.get_playlist(playlist_id)
.await
.map_err(|e| format!("Failed to get playlist: {}", e));
let total_elapsed = cmd_start.elapsed();
log::info!(
"Command: get_playlist {} — lock: {:.1}ms, total: {:.1}ms, tracks: {}",
playlist_id,
lock_elapsed.as_secs_f64() * 1000.0,
total_elapsed.as_secs_f64() * 1000.0,
result.as_ref().map(|p| p.tracks.as_ref().map(|t| t.items.len()).unwrap_or(0)).unwrap_or(0)
);
result
}
/// Get playlist metadata + ordered track IDs (lightweight, no full track data)
#[tauri::command]
pub async fn get_playlist_track_ids(
playlist_id: u64,
state: State<'_, AppState>,
) -> Result<PlaylistWithTrackIds, String> {
let cmd_start = std::time::Instant::now();
log::debug!("Command: get_playlist_track_ids {}", playlist_id);
let client = state.client.read().await;
let result = client
.get_playlist_track_ids(playlist_id)
.await
.map_err(|e| format!("Failed to get playlist track IDs: {}", e));
let elapsed = cmd_start.elapsed();
log::info!(
"Command: get_playlist_track_ids {} — {:.1}ms, {} IDs",
playlist_id,
elapsed.as_secs_f64() * 1000.0,
result.as_ref().map(|p| p.track_ids.len()).unwrap_or(0)
);
result
}
/// Fetch full track details for a batch of track IDs (max 50)
#[tauri::command]
pub async fn get_tracks_batch(
track_ids: Vec<u64>,
state: State<'_, AppState>,
) -> Result<Vec<Track>, String> {
log::debug!("Command: get_tracks_batch ({} IDs)", track_ids.len());
let client = state.client.read().await;
client
.get_tracks_batch(&track_ids)
.await
.map_err(|e| format!("Failed to get tracks batch: {}", e))
}
/// Check for duplicate tracks in a playlist
#[tauri::command]
pub async fn check_playlist_duplicates(
playlist_id: u64,
track_ids: Vec<u64>,
state: State<'_, AppState>,
) -> Result<PlaylistDuplicateResult, String> {
log::debug!(
"Command: check_playlist_duplicates {} ({} tracks)",
playlist_id,
track_ids.len()
);
let client = state.client.read().await;
let playlist = client
.get_playlist(playlist_id)
.await
.map_err(|e| format!("Failed to get playlist: {}", e))?;
let incoming_track_ids: std::collections::HashSet<u64> = track_ids.iter().copied().collect();
let duplicate_track_ids: std::collections::HashSet<u64> = playlist
.tracks
.map(|tracks| {
tracks
.items
.into_iter()
.filter(|track| incoming_track_ids.contains(&track.id))
.map(|track| track.id)
.collect()
})
.unwrap_or_default();
let duplicate_count = duplicate_track_ids.len();
let total_tracks = track_ids.len();
Ok(PlaylistDuplicateResult {
total_tracks,
duplicate_count,
duplicate_track_ids,
})
}
/// Search playlists
#[tauri::command]
pub async fn search_playlists(
query: String,
limit: Option<u32>,
offset: Option<u32>,
state: State<'_, AppState>,
) -> Result<SearchResultsPage<Playlist>, String> {
log::debug!("Command: search_playlists \"{}\" limit={:?} offset={:?}", query, limit, offset);
let client = state.client.read().await;
client
.search_playlists(&query, limit.unwrap_or(20), offset.unwrap_or(0))
.await
.map_err(|e| format!("Failed to search playlists: {}", e))
}
/// Create a new playlist
#[tauri::command]
pub async fn create_playlist(
name: String,
description: Option<String>,
is_public: Option<bool>,
state: State<'_, AppState>,
) -> Result<Playlist, String> {
log::info!("Command: create_playlist \"{}\"", name);
let client = state.client.read().await;
client
.create_playlist(&name, description.as_deref(), is_public.unwrap_or(false))
.await
.map_err(|e| format!("Failed to create playlist: {}", e))
}
/// Delete a playlist
#[tauri::command]
pub async fn delete_playlist(
playlist_id: u64,
state: State<'_, AppState>,
) -> Result<(), String> {
log::info!("Command: delete_playlist {}", playlist_id);
let client = state.client.read().await;
client
.delete_playlist(playlist_id)
.await
.map_err(|e| format!("Failed to delete playlist: {}", e))
}
/// Add tracks to a playlist
#[tauri::command]
pub async fn add_tracks_to_playlist(
playlist_id: u64,
track_ids: Vec<u64>,
state: State<'_, AppState>,
) -> Result<(), String> {
log::info!("Command: add_tracks_to_playlist {} ({} tracks)", playlist_id, track_ids.len());
let client = state.client.read().await;
client
.add_tracks_to_playlist(playlist_id, &track_ids)
.await
.map_err(|e| format!("Failed to add tracks to playlist: {}", e))
}
/// Remove tracks from a playlist.
/// Accepts either playlist_track_ids (direct Qobuz IDs) or regular track_ids.
/// When track_ids are provided (and playlist_track_ids is empty), resolves them
/// by fetching the full playlist to find the corresponding playlist_track_ids.
#[tauri::command]
pub async fn remove_tracks_from_playlist(
playlist_id: u64,
#[allow(unused_variables)]
playlist_track_ids: Option<Vec<u64>>,
track_ids: Option<Vec<u64>>,
state: State<'_, AppState>,
) -> Result<(), String> {
let ptids = playlist_track_ids.unwrap_or_default();
let tids = track_ids.unwrap_or_default();
log::info!(
"Command: remove_tracks_from_playlist {} (playlist_track_ids={}, track_ids={})",
playlist_id, ptids.len(), tids.len()
);
let client = state.client.read().await;
// If we have direct playlist_track_ids, use them
if !ptids.is_empty() {
return client
.remove_tracks_from_playlist(playlist_id, &ptids)
.await
.map_err(|e| format!("Failed to remove tracks from playlist: {}", e));
}
// Otherwise resolve track_ids → playlist_track_ids via full playlist fetch
if !tids.is_empty() {
let playlist = client
.get_playlist(playlist_id)
.await
.map_err(|e| format!("Failed to fetch playlist for track ID resolution: {}", e))?;
let track_id_set: std::collections::HashSet<u64> = tids.into_iter().collect();
let resolved_ptids: Vec<u64> = playlist
.tracks
.map(|tc| {
tc.items
.into_iter()
.filter(|track| track_id_set.contains(&track.id))
.filter_map(|track| track.playlist_track_id)
.collect()
})
.unwrap_or_default();
if resolved_ptids.is_empty() {
return Err("Could not resolve any track IDs to playlist track IDs".to_string());
}
return client
.remove_tracks_from_playlist(playlist_id, &resolved_ptids)
.await
.map_err(|e| format!("Failed to remove tracks from playlist: {}", e));
}
Err("Either playlist_track_ids or track_ids must be provided".to_string())
}
/// Update playlist metadata
#[tauri::command]
pub async fn update_playlist(
playlist_id: u64,
name: Option<String>,
description: Option<String>,
is_public: Option<bool>,
state: State<'_, AppState>,
) -> Result<Playlist, String> {
log::info!("Command: update_playlist {}", playlist_id);
let client = state.client.read().await;
client
.update_playlist(playlist_id, name.as_deref(), description.as_deref(), is_public)
.await
.map_err(|e| format!("Failed to update playlist: {}", e))
}
/// Get multiple tracks by their IDs
#[tauri::command]
pub async fn get_tracks_by_ids(
track_ids: Vec<u64>,
state: State<'_, AppState>,
) -> Result<Vec<crate::api::models::Track>, String> {
log::debug!("Command: get_tracks_by_ids ({} tracks)", track_ids.len());
let client = state.client.read().await;
let mut tracks = Vec::new();
for track_id in track_ids {
match client.get_track(track_id).await {
Ok(track) => tracks.push(track),
Err(e) => {
log::warn!("Failed to get track {}: {}", track_id, e);
// Continue with other tracks even if one fails
}
}
}
Ok(tracks)
}
/// Get the current user's Qobuz ID
#[tauri::command]
pub async fn get_current_user_id(state: State<'_, AppState>) -> Result<Option<u64>, String> {
log::debug!("Command: get_current_user_id");
let client = state.client.read().await;
Ok(client.get_user_id().await)
}
/// Subscribe to (copy) a playlist to the user's library
/// This creates a new playlist with all the tracks from the source playlist
#[tauri::command]
pub async fn subscribe_playlist(
playlist_id: u64,
state: State<'_, AppState>,
library_state: State<'_, LibraryState>,
) -> Result<Playlist, String> {
log::info!("Command: subscribe_playlist {}", playlist_id);
let client = state.client.read().await;
// 1. Get the source playlist with all its tracks
let source = client
.get_playlist(playlist_id)
.await
.map_err(|e| format!("Failed to get source playlist: {}", e))?;
// 2. Extract track IDs from the source playlist
let track_ids: Vec<u64> = source
.tracks
.as_ref()
.map(|t| t.items.iter().map(|track| track.id).collect())
.unwrap_or_default();
if track_ids.is_empty() {
return Err("Source playlist has no tracks to copy".to_string());
}
// 3. Build description with attribution
let attribution = format!("\n\n---\nOriginally curated by {} on Qobuz", source.owner.name);
let new_description = match source.description {
Some(ref desc) if !desc.is_empty() => Some(format!("{}{}", desc, attribution)),
_ => Some(attribution.trim_start().to_string()),
};
// 4. Create a new playlist with the same name and attributed description
let new_playlist = client
.create_playlist(&source.name, new_description.as_deref(), false)
.await
.map_err(|e| format!("Failed to create new playlist: {}", e))?;
// 5. Add all tracks to the new playlist
client
.add_tracks_to_playlist(new_playlist.id, &track_ids)
.await
.map_err(|e| format!("Failed to add tracks to new playlist: {}", e))?;
// 6. Save the original playlist's image as custom artwork for the new playlist
if let Some(ref images) = source.images {
if let Some(image_url) = images.first() {
let db_guard = library_state.db.lock().await;
if let Some(ref db) = *db_guard {
if let Err(e) = db.update_playlist_artwork(new_playlist.id, Some(image_url)) {
log::warn!("Failed to save original playlist artwork: {}", e);
}
}
}
}
// 7. Return the new playlist with updated track count
Ok(Playlist {
tracks_count: track_ids.len() as u32,
..new_playlist
})
}
/// Get track info with parsed performers/credits
#[tauri::command]
pub async fn get_track_info(
track_id: u64,
state: State<'_, AppState>,
) -> Result<TrackInfo, String> {
log::debug!("Command: get_track_info {}", track_id);
let client = state.client.read().await;
let track = client
.get_track(track_id)
.await
.map_err(|e| format!("Failed to get track: {}", e))?;
// Parse the performers string if available
let performers = track
.performers
.as_ref()
.map(|p| parse_performers(p))
.unwrap_or_default();
Ok(TrackInfo { track, performers })
}
-41
View File
@@ -1,41 +0,0 @@
//! Playlist import commands
use tauri::State;
use crate::playlist_import::{
import_public_playlist, preview_public_playlist, ImportPlaylist, ImportSummary,
};
use crate::AppState;
#[tauri::command]
pub async fn playlist_import_preview(
url: String,
) -> Result<ImportPlaylist, String> {
log::info!("Command: playlist_import_preview {}", url);
preview_public_playlist(&url)
.await
.map_err(|e| e.to_string())
}
#[tauri::command]
pub async fn playlist_import_execute(
app: tauri::AppHandle,
url: String,
name_override: Option<String>,
is_public: Option<bool>,
state: State<'_, AppState>,
) -> Result<ImportSummary, String> {
log::info!("Command: playlist_import_execute {}", url);
let client = state.client.read().await;
import_public_playlist(
&url,
&client,
name_override.as_deref(),
is_public.unwrap_or(false),
&app,
)
.await
.map_err(|e| e.to_string())
}
@@ -1,309 +0,0 @@
//! Tauri commands for vector-based playlist suggestions
//!
//! These commands expose the playlist suggestions engine to the frontend.
use std::collections::HashSet;
use std::sync::Arc;
use tauri::State;
use crate::artist_blacklist::BlacklistState;
use crate::artist_vectors::{
ArtistVectorBuilder, ArtistVectorStoreState, RelationshipWeights, StoreStats,
SuggestionConfig, SuggestionResult, SuggestionsEngine,
};
use crate::musicbrainz::{MatchConfidence, MusicBrainzSharedState, ResolvedArtist};
use crate::AppState;
/// Artist info from the frontend
#[derive(Debug, Clone, serde::Deserialize)]
pub struct PlaylistArtist {
/// Artist name (required)
pub name: String,
/// Qobuz artist ID (optional, for better matching)
#[serde(default)]
pub qobuz_id: Option<u64>,
}
/// Genres that are typically incompatible with rock/metal playlists
/// Used to filter out false positives from name-only matching
const INCOMPATIBLE_GENRE_KEYWORDS: &[&str] = &[
"merengue", "reggaeton", "salsa", "bachata", "cumbia", "vallenato",
"k-pop", "kpop", "j-pop", "jpop", "mandopop", "cantopop",
"schlager", "volksmusi", "chanson",
"country singer", "country music",
"gospel singer", "christian music",
"children", "nursery",
];
/// Check if an artist's disambiguation suggests an incompatible genre
fn has_incompatible_disambiguation(disambiguation: Option<&str>) -> bool {
match disambiguation {
Some(d) => {
let lower = d.to_lowercase();
INCOMPATIBLE_GENRE_KEYWORDS.iter().any(|kw| lower.contains(kw))
}
None => false,
}
}
/// Input for generating suggestions
#[derive(Debug, Clone, serde::Deserialize)]
pub struct SuggestionsInput {
/// Artists from the playlist (names + optional Qobuz IDs)
pub artists: Vec<PlaylistArtist>,
/// Track IDs already in the playlist (to exclude)
pub exclude_track_ids: Vec<u64>,
/// Whether to include reason strings (dev mode)
#[serde(default)]
pub include_reasons: bool,
/// Optional custom configuration
pub config: Option<SuggestionConfig>,
}
/// Get suggestions for a playlist based on artist similarity vectors
#[tauri::command]
pub async fn get_playlist_suggestions_v2(
input: SuggestionsInput,
store_state: State<'_, ArtistVectorStoreState>,
mb_state: State<'_, MusicBrainzSharedState>,
app_state: State<'_, AppState>,
blacklist_state: State<'_, BlacklistState>,
) -> Result<SuggestionResult, String> {
use std::time::Instant;
let total_start = Instant::now();
log::info!(
"[Suggestions] Starting for {} artists, exclude {} tracks",
input.artists.len(),
input.exclude_track_ids.len()
);
// Get config early to check skip_vector_build
let config = input.config.unwrap_or_default();
let skip_network = config.skip_vector_build;
// Resolve artist names to MBIDs (with caching)
// Store (mbid, name) tuples so we can search for tracks by name
let resolve_start = Instant::now();
let mut artist_info: Vec<(String, String)> = Vec::new(); // (mbid, name)
let mut cached_count = 0;
let mut resolved_count = 0;
let mut skipped_count = 0;
for artist in &input.artists {
// Check cache first
let cached = {
let cache_opt__ = mb_state.cache.lock().await;
let cache = cache_opt__.as_ref().ok_or("No active session - please log in")?;
cache.get_artist(&artist.name).ok().flatten()
};
if let Some(resolved) = cached {
if let Some(mbid) = resolved.mbid {
if resolved.confidence != MatchConfidence::None
&& resolved.confidence != MatchConfidence::Low
{
artist_info.push((mbid, artist.name.clone()));
cached_count += 1;
continue;
}
}
// Cached as "no match" - skip
skipped_count += 1;
continue;
}
// If skip_network is true, don't make network calls for uncached artists
if skip_network {
skipped_count += 1;
continue;
}
// Try to resolve via MusicBrainz search
if mb_state.client.is_enabled().await {
match mb_state.client.search_artist(&artist.name).await {
Ok(response) => {
// Find best match: high score AND compatible genre
// This prevents "Martín Méndez" (Opeth bassist) matching "Martin Mendez" (merengue singer)
if let Some(mb_artist) = response
.artists
.iter()
.filter(|a| a.score.unwrap_or(0) >= 90)
.find(|a| !has_incompatible_disambiguation(a.disambiguation.as_deref()))
{
let mbid = mb_artist.id.clone();
log::debug!(
"[Suggestions] Resolved '{}' -> {} (score={}, disambiguation={:?})",
artist.name,
mb_artist.name,
mb_artist.score.unwrap_or(0),
mb_artist.disambiguation
);
// Cache the resolved artist
let resolved = ResolvedArtist {
mbid: Some(mbid.clone()),
name: Some(mb_artist.name.clone()),
sort_name: mb_artist.sort_name.clone(),
artist_type: None,
country: mb_artist.country.clone(),
disambiguation: mb_artist.disambiguation.clone(),
confidence: MatchConfidence::High,
};
{
let cache_opt__ = mb_state.cache.lock().await;
let cache = cache_opt__.as_ref().ok_or("No active session - please log in")?;
let _ = cache.set_artist(&artist.name, &resolved);
}
artist_info.push((mbid, artist.name.clone()));
resolved_count += 1;
continue;
} else if let Some(skipped) = response.artists.iter().find(|a| {
a.score.unwrap_or(0) >= 90 && has_incompatible_disambiguation(a.disambiguation.as_deref())
}) {
log::info!(
"[Suggestions] Skipped incompatible artist for '{}': {} (disambiguation: {:?})",
artist.name,
skipped.name,
skipped.disambiguation
);
}
}
Err(e) => {
log::warn!("[Suggestions] MusicBrainz search failed for '{}': {}", artist.name, e);
}
}
} else {
log::debug!("[Suggestions] MusicBrainz disabled, skipping '{}'", artist.name);
}
// Cache negative result
{
let cache_opt__ = mb_state.cache.lock().await;
let cache = cache_opt__.as_ref().ok_or("No active session - please log in")?;
let _ = cache.set_artist(&artist.name, &ResolvedArtist::empty());
}
skipped_count += 1;
}
let resolve_elapsed = resolve_start.elapsed();
log::debug!(
"[Suggestions] MBID resolution took {:?}: {} cached, {} resolved, {} skipped (skip_network={})",
resolve_elapsed,
cached_count,
resolved_count,
skipped_count,
skip_network
);
if artist_info.is_empty() {
log::warn!("[Suggestions] No MBIDs resolved, returning empty result");
return Ok(SuggestionResult {
tracks: Vec::new(),
source_artists: Vec::new(),
playlist_artists_count: input.artists.len(),
similar_artists_count: 0,
});
}
// Create the builder (just cloning Arcs, cheap)
let builder = Arc::new(ArtistVectorBuilder::new(
store_state.store.clone(),
mb_state.client.clone(),
mb_state.cache.clone(),
app_state.client.clone(),
RelationshipWeights::default(),
));
// Log config (already extracted above for skip_network check)
log::debug!("[Suggestions] Config: max_artists={}, tracks_per={}, pool_size={}, skip_build={}",
config.max_artists, config.tracks_per_artist, config.max_pool_size, config.skip_vector_build);
let engine = SuggestionsEngine::new(
store_state.store.clone(),
builder,
app_state.client.clone(),
config,
);
// Convert exclude list to HashSet
let exclude_set: HashSet<u64> = input.exclude_track_ids.into_iter().collect();
// Generate suggestions
log::debug!("[Suggestions] Calling engine.generate_suggestions with {} artists", artist_info.len());
let engine_start = std::time::Instant::now();
let result = engine
.generate_suggestions(&artist_info, &exclude_set, input.include_reasons)
.await;
let engine_elapsed = engine_start.elapsed();
let total_elapsed = total_start.elapsed();
match result {
Ok(mut r) => {
log::info!(
"[Suggestions] Engine took {:?}, total {:?}. Result: {} tracks from {} similar artists",
engine_elapsed,
total_elapsed,
r.tracks.len(),
r.similar_artists_count
);
// Filter out tracks from blacklisted artists
let original_count = r.tracks.len();
r.tracks.retain(|track| {
if let Some(artist_id) = track.artist_id {
!blacklist_state.is_blacklisted(artist_id)
} else {
true // Keep tracks without artist ID
}
});
let filtered_count = original_count - r.tracks.len();
if filtered_count > 0 {
log::info!(
"[Suggestions] Filtered {} tracks from blacklisted artists",
filtered_count
);
}
Ok(r)
}
Err(e) => {
log::error!("[Suggestions] Engine failed after {:?}: {}", engine_elapsed, e);
Err(e)
}
}
}
/// Get store statistics for debugging
#[tauri::command]
pub async fn get_vector_store_stats(
store_state: State<'_, ArtistVectorStoreState>,
) -> Result<StoreStats, String> {
let guard = store_state.store.lock().await;
let store = guard.as_ref().ok_or("No active session - please log in")?;
store.get_stats()
}
/// Clean up expired vectors
#[tauri::command]
pub async fn cleanup_vector_store(
max_age_days: Option<i64>,
store_state: State<'_, ArtistVectorStoreState>,
) -> Result<usize, String> {
let max_age_secs = max_age_days.unwrap_or(30) * 24 * 60 * 60;
let mut guard = store_state.store.lock().await;
let store = guard.as_mut().ok_or("No active session - please log in")?;
store.cleanup_expired(max_age_secs)
}
/// Clear all vector store data
#[tauri::command]
pub async fn clear_vector_store(
store_state: State<'_, ArtistVectorStoreState>,
) -> Result<usize, String> {
let mut guard = store_state.store.lock().await;
let store = guard.as_mut().ok_or("No active session - please log in")?;
store.clear_all()
}
-188
View File
@@ -1,188 +0,0 @@
//! Queue management Tauri commands
use tauri::State;
use crate::artist_blacklist::BlacklistState;
use crate::queue::{QueueState, QueueTrack, RepeatMode};
use crate::AppState;
/// Check if a track's artist is blacklisted
fn is_track_blacklisted(track: &QueueTrack, blacklist: &BlacklistState) -> bool {
if let Some(artist_id) = track.artist_id {
blacklist.is_blacklisted(artist_id)
} else {
false
}
}
/// Add a track to the queue
#[tauri::command]
pub fn add_to_queue(
track: QueueTrack,
state: State<'_, AppState>,
blacklist: State<'_, BlacklistState>,
) -> Result<(), String> {
if is_track_blacklisted(&track, &blacklist) {
log::debug!("Skipping blacklisted track: {} by {}", track.title, track.artist);
return Ok(());
}
log::info!("Command: add_to_queue - {} by {}", track.title, track.artist);
state.queue.add_track(track);
Ok(())
}
/// Add a track to play next
#[tauri::command]
pub fn add_to_queue_next(
track: QueueTrack,
state: State<'_, AppState>,
blacklist: State<'_, BlacklistState>,
) -> Result<(), String> {
if is_track_blacklisted(&track, &blacklist) {
log::debug!("Skipping blacklisted track (next): {} by {}", track.title, track.artist);
return Ok(());
}
log::info!("Command: add_to_queue_next - {} by {}", track.title, track.artist);
state.queue.add_track_next(track);
Ok(())
}
/// Add multiple tracks to the queue
#[tauri::command]
pub fn add_tracks_to_queue(
tracks: Vec<QueueTrack>,
state: State<'_, AppState>,
blacklist: State<'_, BlacklistState>,
) -> Result<(), String> {
let filtered: Vec<QueueTrack> = tracks
.into_iter()
.filter(|t| !is_track_blacklisted(t, &blacklist))
.collect();
log::info!("Command: add_tracks_to_queue - {} tracks (after blacklist filter)", filtered.len());
state.queue.add_tracks(filtered);
Ok(())
}
/// Set the entire queue (replaces existing)
#[tauri::command]
pub fn set_queue(
tracks: Vec<QueueTrack>,
start_index: Option<usize>,
state: State<'_, AppState>,
blacklist: State<'_, BlacklistState>,
) -> Result<(), String> {
let filtered: Vec<QueueTrack> = tracks
.into_iter()
.filter(|t| !is_track_blacklisted(t, &blacklist))
.collect();
log::info!("Command: set_queue - {} tracks (after blacklist filter), start at {:?}", filtered.len(), start_index);
state.queue.set_queue(filtered, start_index);
Ok(())
}
/// Clear the queue
#[tauri::command]
pub fn clear_queue(state: State<'_, AppState>) -> Result<(), String> {
log::info!("Command: clear_queue");
state.queue.clear();
Ok(())
}
/// Remove a track from the queue by index
#[tauri::command]
pub fn remove_from_queue(index: usize, state: State<'_, AppState>) -> Result<Option<QueueTrack>, String> {
log::info!("Command: remove_from_queue - index {}", index);
Ok(state.queue.remove_track(index))
}
/// Remove a track from the upcoming queue by its position in the upcoming list
/// (0 = first upcoming track, handles shuffle mode correctly)
#[tauri::command]
pub fn remove_upcoming_track(upcoming_index: usize, state: State<'_, AppState>) -> Result<Option<QueueTrack>, String> {
log::info!("Command: remove_upcoming_track - upcoming_index {}", upcoming_index);
Ok(state.queue.remove_upcoming_track(upcoming_index))
}
/// Move a track from one position to another in the queue
#[tauri::command]
pub fn move_queue_track(from_index: usize, to_index: usize, state: State<'_, AppState>) -> Result<bool, String> {
log::info!("Command: move_queue_track - from {} to {}", from_index, to_index);
Ok(state.queue.move_track(from_index, to_index))
}
/// Get current track in queue
#[tauri::command]
pub fn get_current_queue_track(state: State<'_, AppState>) -> Result<Option<QueueTrack>, String> {
Ok(state.queue.current_track())
}
/// Get next track (for pre-loading/display)
#[tauri::command]
pub fn peek_next_track(state: State<'_, AppState>) -> Result<Option<QueueTrack>, String> {
Ok(state.queue.peek_next())
}
/// Advance to next track and return it
#[tauri::command]
pub fn next_track(state: State<'_, AppState>) -> Result<Option<QueueTrack>, String> {
log::info!("Command: next_track");
Ok(state.queue.next())
}
/// Go to previous track and return it
#[tauri::command]
pub fn previous_track(state: State<'_, AppState>) -> Result<Option<QueueTrack>, String> {
log::info!("Command: previous_track");
Ok(state.queue.previous())
}
/// Jump to a specific track by index
#[tauri::command]
pub fn play_queue_index(index: usize, state: State<'_, AppState>) -> Result<Option<QueueTrack>, String> {
log::info!("Command: play_queue_index - {}", index);
Ok(state.queue.play_index(index))
}
/// Set shuffle mode
#[tauri::command]
pub fn set_shuffle(enabled: bool, state: State<'_, AppState>) -> Result<(), String> {
log::info!("Command: set_shuffle - {}", enabled);
state.queue.set_shuffle(enabled);
Ok(())
}
/// Get shuffle status
#[tauri::command]
pub fn get_shuffle(state: State<'_, AppState>) -> Result<bool, String> {
Ok(state.queue.is_shuffle())
}
/// Set repeat mode
#[tauri::command]
pub fn set_repeat(mode: String, state: State<'_, AppState>) -> Result<(), String> {
log::info!("Command: set_repeat - {}", mode);
let repeat_mode = match mode.to_lowercase().as_str() {
"all" => RepeatMode::All,
"one" => RepeatMode::One,
_ => RepeatMode::Off,
};
state.queue.set_repeat(repeat_mode);
Ok(())
}
/// Get repeat mode
#[tauri::command]
pub fn get_repeat(state: State<'_, AppState>) -> Result<String, String> {
let mode = state.queue.get_repeat();
Ok(match mode {
RepeatMode::Off => "off".to_string(),
RepeatMode::All => "all".to_string(),
RepeatMode::One => "one".to_string(),
})
}
/// Get full queue state for frontend
#[tauri::command]
pub fn get_queue_state(state: State<'_, AppState>) -> Result<QueueState, String> {
Ok(state.queue.get_state())
}
-585
View File
@@ -1,585 +0,0 @@
//! Radio Engine Tauri commands
//!
//! Creates and manages radio sessions for infinite playback discovery
use tauri::State;
use tokio::task;
use crate::api::Track;
use crate::artist_blacklist::BlacklistState;
use crate::playback_context::{ContentSource, ContextType, PlaybackContext};
use crate::queue::QueueTrack;
use crate::radio_engine::{BuildRadioOptions, RadioEngine, RadioPoolBuilder};
use crate::AppState;
/// Create an artist radio session
///
/// This creates a new radio session based on an artist and populates the queue
/// with initial tracks from the radio engine.
#[tauri::command]
pub async fn create_artist_radio(
artist_id: u64,
artist_name: String,
state: State<'_, AppState>,
blacklist_state: State<'_, BlacklistState>,
) -> Result<String, String> {
log::info!("[Radio] Creating artist radio for: {} (ID: {})", artist_name, artist_id);
// Clone client for use in builder
let client = state.client.read().await.clone();
// Build radio pool in async context (RadioPoolBuilder needs client for API calls)
let session_id = task::spawn_blocking(move || -> Result<String, String> {
let radio_db = crate::radio_engine::db::RadioDb::open_default()?;
let builder = RadioPoolBuilder::new(&radio_db, &client, BuildRadioOptions::default());
// This is async but we're in spawn_blocking, so we need to use tokio runtime
let rt = tokio::runtime::Handle::current();
let session = rt.block_on(builder.create_artist_radio(artist_id))?;
Ok(session.id)
})
.await
.map_err(|e| format!("Radio task failed: {}", e))??;
log::info!("[Radio] Artist radio session created: {}", session_id);
// Get client again for fetching tracks
let client = state.client.read().await;
// Generate track IDs from radio engine
let track_ids = task::spawn_blocking({
let session_id = session_id.clone();
move || -> Result<Vec<u64>, String> {
let radio_db = crate::radio_engine::db::RadioDb::open_default()?;
let radio_engine = RadioEngine::new(radio_db);
let mut tracks_with_distance = Vec::new();
// Generate 60 tracks to ensure we get 50 after potential API failures
for _ in 0..60 {
match radio_engine.next_track(&session_id) {
Ok(radio_track) => {
tracks_with_distance.push((radio_track.track_id, radio_track.distance));
}
Err(e) => {
log::warn!("[Radio] Failed to get next radio track: {}", e);
break;
}
}
}
// Find first track from seed artist (distance 0) and move to front
if let Some(seed_idx) = tracks_with_distance.iter().position(|(_, dist)| *dist == 0) {
if seed_idx != 0 {
tracks_with_distance.swap(0, seed_idx);
log::info!("[Radio] Moved seed artist track to position 0 (was at position {})", seed_idx);
}
} else {
log::warn!("[Radio] No seed artist track found in initial tracks");
}
// Take first 50 tracks for initial queue
Ok(tracks_with_distance.into_iter().take(50).map(|(id, _)| id).collect())
}
})
.await
.map_err(|e| format!("Track generation task failed: {}", e))??;
// Fetch full track details from Qobuz, filtering blacklisted artists
let mut tracks = Vec::new();
let mut blacklist_skipped = 0;
for track_id in track_ids {
match client.get_track(track_id).await {
Ok(track) => {
// Check if track's artist is blacklisted
if let Some(ref performer) = track.performer {
if blacklist_state.is_blacklisted(performer.id) {
log::debug!(
"[Radio] Skipping blacklisted artist track: {} - {}",
performer.name,
track.title
);
blacklist_skipped += 1;
continue;
}
}
tracks.push(track);
}
Err(e) => {
log::warn!("[Radio] Failed to fetch track {}: {}", track_id, e);
}
}
}
if blacklist_skipped > 0 {
log::info!("[Radio] Skipped {} tracks from blacklisted artists", blacklist_skipped);
}
if tracks.is_empty() {
return Err("Failed to generate any radio tracks".to_string());
}
log::info!("[Radio] Generated {} initial tracks", tracks.len());
// Convert to QueueTrack format
let queue_tracks: Vec<QueueTrack> = tracks.iter().map(track_to_queue_track).collect();
// Set the queue
state.queue.set_queue(queue_tracks, Some(0));
// Set playback context to radio
let track_ids: Vec<u64> = tracks.iter().map(|t| t.id).collect();
let context = PlaybackContext::new(
ContextType::Radio,
session_id.clone(),
artist_name,
ContentSource::Qobuz,
track_ids,
0,
);
state.context.set_context(context);
log::info!("[Radio] Artist radio ready: {}", session_id);
Ok(session_id)
}
/// Create a track radio session
///
/// This creates a new radio session based on a specific track and populates the queue
/// with initial tracks from the radio engine.
#[tauri::command]
pub async fn create_track_radio(
track_id: u64,
track_name: String,
artist_id: u64,
state: State<'_, AppState>,
blacklist_state: State<'_, BlacklistState>,
) -> Result<String, String> {
log::info!(
"[Radio] Creating track radio for: {} (Track ID: {}, Artist ID: {})",
track_name,
track_id,
artist_id
);
// Clone client for use in builder
let client = state.client.read().await.clone();
// Build radio pool in async context (RadioPoolBuilder needs client for API calls)
let session_id = task::spawn_blocking(move || -> Result<String, String> {
let radio_db = crate::radio_engine::db::RadioDb::open_default()?;
let builder = RadioPoolBuilder::new(&radio_db, &client, BuildRadioOptions::default());
// This is async but we're in spawn_blocking, so we need to use tokio runtime
let rt = tokio::runtime::Handle::current();
let session = rt.block_on(builder.create_track_radio(track_id, artist_id))?;
Ok(session.id)
})
.await
.map_err(|e| format!("Radio task failed: {}", e))??;
log::info!("[Radio] Track radio session created: {}", session_id);
// Get client again for fetching tracks
let client = state.client.read().await;
// Generate track IDs from radio engine
let track_ids = task::spawn_blocking({
let session_id = session_id.clone();
let seed_track_id = track_id;
move || -> Result<Vec<u64>, String> {
let radio_db = crate::radio_engine::db::RadioDb::open_default()?;
let radio_engine = RadioEngine::new(radio_db);
let mut tracks_with_source = Vec::new();
// Generate 60 tracks to ensure we get 50 after potential API failures
for _ in 0..60 {
match radio_engine.next_track(&session_id) {
Ok(radio_track) => {
tracks_with_source.push((radio_track.track_id, radio_track.source.clone()));
}
Err(e) => {
log::warn!("[Radio] Failed to get next radio track: {}", e);
break;
}
}
}
// Find the seed track itself and move to front
if let Some(seed_idx) = tracks_with_source.iter().position(|(id, source)| *id == seed_track_id && source == "seed_track") {
if seed_idx != 0 {
tracks_with_source.swap(0, seed_idx);
log::info!("[Radio] Moved seed track to position 0 (was at position {})", seed_idx);
}
} else {
log::warn!("[Radio] Seed track {} not found in initial tracks", seed_track_id);
}
// Take first 50 tracks for initial queue
Ok(tracks_with_source.into_iter().take(50).map(|(id, _)| id).collect())
}
})
.await
.map_err(|e| format!("Track generation task failed: {}", e))??;
// Fetch full track details from Qobuz, filtering blacklisted artists
let mut tracks = Vec::new();
let mut blacklist_skipped = 0;
for track_id in track_ids {
match client.get_track(track_id).await {
Ok(track) => {
// Check if track's artist is blacklisted
if let Some(ref performer) = track.performer {
if blacklist_state.is_blacklisted(performer.id) {
log::debug!(
"[Radio] Skipping blacklisted artist track: {} - {}",
performer.name,
track.title
);
blacklist_skipped += 1;
continue;
}
}
tracks.push(track);
}
Err(e) => {
log::warn!("[Radio] Failed to fetch track {}: {}", track_id, e);
}
}
}
if blacklist_skipped > 0 {
log::info!("[Radio] Skipped {} tracks from blacklisted artists", blacklist_skipped);
}
if tracks.is_empty() {
return Err("Failed to generate any radio tracks".to_string());
}
log::info!("[Radio] Generated {} initial tracks", tracks.len());
// Convert to QueueTrack format
let queue_tracks: Vec<QueueTrack> = tracks.iter().map(track_to_queue_track).collect();
// Set the queue
state.queue.set_queue(queue_tracks, Some(0));
// Set playback context to radio
let track_ids: Vec<u64> = tracks.iter().map(|t| t.id).collect();
let context = PlaybackContext::new(
ContextType::Radio,
session_id.clone(),
track_name,
ContentSource::Qobuz,
track_ids,
0,
);
state.context.set_context(context);
log::info!("[Radio] Track radio ready: {}", session_id);
Ok(session_id)
}
/// Convert API Track to QueueTrack
fn track_to_queue_track(track: &Track) -> QueueTrack {
let artwork_url = track
.album
.as_ref()
.and_then(|a| a.image.large.clone());
let artist = track
.performer
.as_ref()
.map(|p| p.name.clone())
.unwrap_or_else(|| "Unknown Artist".to_string());
let album = track
.album
.as_ref()
.map(|a| a.title.clone())
.unwrap_or_else(|| "Unknown Album".to_string());
let album_id = track.album.as_ref().map(|a| a.id.clone());
let artist_id = track.performer.as_ref().map(|p| p.id);
// Log if track is not streamable
if !track.streamable {
log::warn!(
"[Radio] Track not streamable: {} - {} (ID: {})",
artist, track.title, track.id
);
}
QueueTrack {
id: track.id,
title: track.title.clone(),
artist,
album,
duration_secs: track.duration as u64,
artwork_url,
hires: track.hires,
bit_depth: track.maximum_bit_depth,
sample_rate: track.maximum_sampling_rate,
is_local: false,
album_id,
artist_id,
streamable: track.streamable,
source: Some("qobuz".to_string()),
}
}
/// Refill the radio queue with more tracks
///
/// Called when the queue is running low (e.g., < 10 tracks remaining).
/// Generates 20 more tracks and appends them to the queue.
#[tauri::command]
pub async fn refill_radio_queue(
session_id: String,
state: State<'_, AppState>,
blacklist_state: State<'_, BlacklistState>,
) -> Result<u32, String> {
log::info!("[Radio] Refilling queue for session: {}", session_id);
// Generate more track IDs from radio engine
let track_ids = task::spawn_blocking({
let session_id = session_id.clone();
move || -> Result<Vec<u64>, String> {
let radio_db = crate::radio_engine::db::RadioDb::open_default()?;
let radio_engine = RadioEngine::new(radio_db);
let mut track_ids = Vec::new();
// Generate 25 tracks to ensure we get ~20 after API failures
for _ in 0..25 {
match radio_engine.next_track(&session_id) {
Ok(radio_track) => {
track_ids.push(radio_track.track_id);
}
Err(e) => {
log::warn!("[Radio] Failed to get next radio track during refill: {}", e);
break;
}
}
}
Ok(track_ids)
}
})
.await
.map_err(|e| format!("Radio refill task failed: {}", e))??;
if track_ids.is_empty() {
log::warn!("[Radio] No more tracks available for refill");
return Ok(0);
}
// Fetch full track details from Qobuz, filtering blacklisted artists
let client = state.client.read().await;
let mut tracks = Vec::new();
let mut blacklist_skipped = 0;
for track_id in track_ids.iter().take(20) {
match client.get_track(*track_id).await {
Ok(track) => {
// Check if track's artist is blacklisted
if let Some(ref performer) = track.performer {
if blacklist_state.is_blacklisted(performer.id) {
log::debug!(
"[Radio] Skipping blacklisted artist track during refill: {} - {}",
performer.name,
track.title
);
blacklist_skipped += 1;
continue;
}
}
tracks.push(track);
}
Err(e) => {
log::warn!("[Radio] Failed to fetch track {} during refill: {}", track_id, e);
}
}
}
if blacklist_skipped > 0 {
log::info!("[Radio] Refill skipped {} tracks from blacklisted artists", blacklist_skipped);
}
let added_count = tracks.len() as u32;
if tracks.is_empty() {
log::warn!("[Radio] Failed to fetch any tracks during refill");
return Ok(0);
}
log::info!("[Radio] Fetched {} tracks for refill", added_count);
// Convert to QueueTrack format and add to queue
let queue_tracks: Vec<QueueTrack> = tracks.iter().map(track_to_queue_track).collect();
for track in queue_tracks {
state.queue.add_track(track);
}
// Update playback context with new track IDs
let new_track_ids: Vec<u64> = tracks.iter().map(|t| t.id).collect();
state.context.append_track_ids(new_track_ids);
log::info!("[Radio] Refill complete: added {} tracks", added_count);
Ok(added_count)
}
/// Get the current queue size (for checking if refill is needed)
#[tauri::command]
pub fn get_queue_remaining(state: State<'_, AppState>) -> u32 {
let queue_state = state.queue.get_state();
queue_state.upcoming.len() as u32
}
/// Create an infinite radio session based on recent tracks
///
/// This is called when "Keep Playing" / autoplay is enabled and the queue ends.
/// Creates a radio based on the last 5 tracks played for coherent recommendations.
#[tauri::command]
pub async fn create_infinite_radio(
recent_track_ids: Vec<u64>,
state: State<'_, AppState>,
blacklist_state: State<'_, BlacklistState>,
) -> Result<String, String> {
if recent_track_ids.is_empty() {
return Err("No recent tracks provided for infinite radio".to_string());
}
log::info!(
"[Radio] Creating infinite radio from {} recent tracks: {:?}",
recent_track_ids.len(),
recent_track_ids
);
// Use the first track's artist as the primary seed (most recently played)
let client = state.client.read().await.clone();
// Fetch the most recent track to get its artist
let primary_track = client
.get_track(recent_track_ids[0])
.await
.map_err(|e| format!("Failed to fetch primary track: {}", e))?;
let artist_id = primary_track
.performer
.as_ref()
.map(|p| p.id)
.ok_or("Primary track has no artist")?;
let artist_name = primary_track
.performer
.as_ref()
.map(|p| p.name.clone())
.unwrap_or_else(|| "Unknown Artist".to_string());
// Build radio pool with the artist as seed
let session_id = task::spawn_blocking({
let client = client.clone();
move || -> Result<String, String> {
let radio_db = crate::radio_engine::db::RadioDb::open_default()?;
let builder = RadioPoolBuilder::new(&radio_db, &client, BuildRadioOptions::default());
let rt = tokio::runtime::Handle::current();
let session = rt.block_on(builder.create_artist_radio(artist_id))?;
Ok(session.id)
}
})
.await
.map_err(|e| format!("Infinite radio task failed: {}", e))??;
log::info!("[Radio] Infinite radio session created: {}", session_id);
// Generate initial tracks
let track_ids = task::spawn_blocking({
let session_id = session_id.clone();
move || -> Result<Vec<u64>, String> {
let radio_db = crate::radio_engine::db::RadioDb::open_default()?;
let radio_engine = RadioEngine::new(radio_db);
let mut track_ids = Vec::new();
// Generate 60 tracks for initial queue
for _ in 0..60 {
match radio_engine.next_track(&session_id) {
Ok(radio_track) => {
track_ids.push(radio_track.track_id);
}
Err(e) => {
log::warn!("[Radio] Failed to get next radio track: {}", e);
break;
}
}
}
Ok(track_ids.into_iter().take(50).collect())
}
})
.await
.map_err(|e| format!("Track generation task failed: {}", e))??;
// Fetch full track details from Qobuz, filtering blacklisted artists
let mut tracks = Vec::new();
let mut blacklist_skipped = 0;
for track_id in track_ids {
match client.get_track(track_id).await {
Ok(track) => {
// Check if track's artist is blacklisted
if let Some(ref performer) = track.performer {
if blacklist_state.is_blacklisted(performer.id) {
log::debug!(
"[Radio] Skipping blacklisted artist track in infinite radio: {} - {}",
performer.name,
track.title
);
blacklist_skipped += 1;
continue;
}
}
tracks.push(track);
}
Err(e) => {
log::warn!("[Radio] Failed to fetch track {}: {}", track_id, e);
}
}
}
if blacklist_skipped > 0 {
log::info!("[Radio] Infinite radio skipped {} tracks from blacklisted artists", blacklist_skipped);
}
if tracks.is_empty() {
return Err("Failed to generate any infinite radio tracks".to_string());
}
log::info!("[Radio] Generated {} infinite radio tracks", tracks.len());
// Convert to QueueTrack format
let queue_tracks: Vec<QueueTrack> = tracks.iter().map(track_to_queue_track).collect();
// Set the queue
state.queue.set_queue(queue_tracks, Some(0));
// Set playback context to radio
let track_ids: Vec<u64> = tracks.iter().map(|t| t.id).collect();
let context = PlaybackContext::new(
ContextType::Radio,
session_id.clone(),
format!("Radio: {}", artist_name),
ContentSource::Qobuz,
track_ids,
0,
);
state.context.set_context(context);
log::info!("[Radio] Infinite radio ready: {}", session_id);
Ok(session_id)
}
-104
View File
@@ -1,104 +0,0 @@
//! Tauri commands for remote metadata fetching (MusicBrainz, Discogs)
//!
//! These commands allow the Tag Editor to search for and fetch
//! album metadata from external services.
use std::sync::Arc;
use tauri::State;
use tokio::sync::Mutex;
use crate::library::remote_metadata::{
RemoteAlbumMetadata, RemoteAlbumSearchResult, RemoteMetadataState, RemoteProvider,
};
/// State wrapper for Tauri
pub struct RemoteMetadataSharedState {
pub inner: Arc<Mutex<RemoteMetadataState>>,
}
/// Search for albums on a remote provider
///
/// # Arguments
/// * `provider` - "musicbrainz" or "discogs"
/// * `query` - Album title to search for
/// * `artist` - Optional artist name to narrow search
/// * `limit` - Maximum results (1-25)
#[tauri::command]
pub async fn remote_metadata_search(
provider: String,
query: String,
artist: Option<String>,
limit: Option<usize>,
state: State<'_, RemoteMetadataSharedState>,
) -> Result<Vec<RemoteAlbumSearchResult>, String> {
log::info!(
"Command: remote_metadata_search provider={} query={} artist={:?}",
provider,
query,
artist
);
let provider = parse_provider(&provider)?;
let limit = limit.unwrap_or(10).min(25);
let state_guard = state.inner.lock().await;
state_guard
.search_albums(provider, &query, artist.as_deref(), limit)
.await
.map_err(|e| format!("{:?}", e))
}
/// Get full album metadata from a remote provider
///
/// # Arguments
/// * `provider` - "musicbrainz" or "discogs"
/// * `provider_id` - The provider-specific ID (MBID or Discogs release ID)
#[tauri::command]
pub async fn remote_metadata_get_album(
provider: String,
provider_id: String,
state: State<'_, RemoteMetadataSharedState>,
) -> Result<RemoteAlbumMetadata, String> {
log::info!(
"Command: remote_metadata_get_album provider={} id={}",
provider,
provider_id
);
let provider = parse_provider(&provider)?;
let state_guard = state.inner.lock().await;
state_guard
.get_album_metadata(provider, &provider_id)
.await
.map_err(|e| format!("{:?}", e))
}
/// Get cache statistics
#[tauri::command]
pub async fn remote_metadata_cache_stats(
state: State<'_, RemoteMetadataSharedState>,
) -> Result<crate::library::remote_metadata::CacheStats, String> {
let state_guard = state.inner.lock().await;
Ok(state_guard.cache.stats().await)
}
/// Clear the remote metadata cache
#[tauri::command]
pub async fn remote_metadata_clear_cache(
state: State<'_, RemoteMetadataSharedState>,
) -> Result<(), String> {
log::info!("Command: remote_metadata_clear_cache");
let state_guard = state.inner.lock().await;
state_guard.cache.clear_all().await;
Ok(())
}
/// Parse provider string to enum
fn parse_provider(provider: &str) -> Result<RemoteProvider, String> {
match provider.to_lowercase().as_str() {
"musicbrainz" | "mb" => Ok(RemoteProvider::MusicBrainz),
"discogs" => Ok(RemoteProvider::Discogs),
_ => Err(format!("Unknown provider: {}", provider)),
}
}
-330
View File
@@ -1,330 +0,0 @@
//! Share-related Tauri commands
use tauri::State;
use crate::share::{ContentType, ShareError, SongLinkResponse};
use crate::AppState;
use std::collections::HashMap;
#[derive(Debug, serde::Deserialize)]
#[serde(rename_all = "camelCase")]
struct ItunesLookupResponse {
result_count: u32,
results: Vec<ItunesTrackResult>,
}
#[derive(Debug, serde::Deserialize)]
#[serde(rename_all = "camelCase")]
struct ItunesTrackResult {
track_view_url: Option<String>,
collection_view_url: Option<String>,
}
/// Get song.link URL for a track using ISRC or a direct URL fallback
/// Qobuz isn't supported by Odesli, so we prefer ISRC but can fall back to URL
#[tauri::command]
pub async fn share_track_songlink(
isrc: Option<String>,
url: Option<String>,
track_id: Option<u64>,
state: State<'_, AppState>,
) -> Result<SongLinkResponse, String> {
let isrc = isrc.unwrap_or_default().trim().to_string();
let url = url.unwrap_or_default().trim().to_string();
if let Some(songlink) = resolve_songlink_from_itunes(&isrc, track_id, &state).await {
return Ok(songlink);
}
if !isrc.is_empty() {
log::info!("Command: share_track_songlink ISRC={}", isrc);
match state.songlink.get_by_isrc(&isrc).await {
Ok(result) => return Ok(result),
Err(err) => {
log::warn!("ISRC lookup failed: {}", err);
if url.is_empty() && track_id.is_none() {
return Err(err.to_string());
}
}
}
}
if url.is_empty() {
return Err(ShareError::MissingIdentifier.to_string());
}
log::info!("Command: share_track_songlink URL={}", url);
state
.songlink
.get_by_url(&url, ContentType::Track)
.await
.map_err(|e| e.to_string())
}
async fn resolve_songlink_from_itunes(
isrc: &str,
track_id: Option<u64>,
state: &State<'_, AppState>,
) -> Option<SongLinkResponse> {
if let Some(url) = lookup_itunes_by_isrc(isrc).await {
return songlink_from_itunes_url(&url);
}
let track_id = track_id?;
let (title, artist) = fetch_track_metadata(track_id, state).await?;
let url = search_itunes_by_term(&title, &artist).await?;
songlink_from_itunes_url(&url)
}
fn songlink_from_itunes_url(itunes_url: &str) -> Option<SongLinkResponse> {
let track_id = extract_itunes_track_id(itunes_url)?;
let page_url = format!("https://song.link/i/{}", track_id);
log::info!("Using Song.link direct URL: {}", page_url);
Some(SongLinkResponse {
page_url,
title: None,
artist: None,
thumbnail_url: None,
platforms: HashMap::new(),
identifier: track_id,
content_type: ContentType::Track.as_str().to_string(),
})
}
fn extract_itunes_track_id(itunes_url: &str) -> Option<String> {
let query = itunes_url.split('?').nth(1)?;
for pair in query.split('&') {
let mut iter = pair.splitn(2, '=');
if iter.next()? == "i" {
return iter.next().map(|v| v.to_string());
}
}
None
}
async fn fetch_track_metadata(
track_id: u64,
state: &State<'_, AppState>,
) -> Option<(String, String)> {
let client = state.client.read().await;
let track = client.get_track(track_id).await.ok()?;
let title = track.title.trim().to_string();
let artist = track
.performer
.map(|a| a.name)
.unwrap_or_else(|| "".to_string())
.trim()
.to_string();
if title.is_empty() || artist.is_empty() {
return None;
}
Some((title, artist))
}
async fn lookup_itunes_by_isrc(isrc: &str) -> Option<String> {
if isrc.trim().is_empty() {
return None;
}
let url = "https://itunes.apple.com/lookup";
let response = reqwest::Client::new()
.get(url)
.query(&[("isrc", isrc), ("country", "US")])
.send()
.await
.ok()?;
if !response.status().is_success() {
return None;
}
let data: ItunesLookupResponse = response.json().await.ok()?;
if data.result_count == 0 {
return None;
}
data.results
.into_iter()
.find_map(|result| result.track_view_url.or(result.collection_view_url))
}
async fn search_itunes_by_term(title: &str, artist: &str) -> Option<String> {
let term = format!("{} {}", artist, title);
let url = "https://itunes.apple.com/search";
let response = reqwest::Client::new()
.get(url)
.query(&[
("term", term),
("entity", "song".to_string()),
("limit", "1".to_string()),
("country", "US".to_string()),
])
.send()
.await
.ok()?;
if !response.status().is_success() {
return None;
}
let data: ItunesLookupResponse = response.json().await.ok()?;
if data.result_count == 0 {
return None;
}
data.results
.into_iter()
.find_map(|result| result.track_view_url.or(result.collection_view_url))
}
/// iTunes album lookup response
#[derive(Debug, serde::Deserialize)]
#[serde(rename_all = "camelCase")]
#[allow(dead_code)]
struct ItunesAlbumResult {
collection_id: Option<u64>,
collection_view_url: Option<String>,
}
#[derive(Debug, serde::Deserialize)]
#[serde(rename_all = "camelCase")]
struct ItunesAlbumLookupResponse {
result_count: u32,
results: Vec<ItunesAlbumResult>,
}
/// Get album.link URL for an album
/// Tries iTunes lookup by UPC first, then by album title/artist search
#[tauri::command]
pub async fn share_album_songlink(
upc: Option<String>,
_album_id: Option<String>,
title: Option<String>,
artist: Option<String>,
state: State<'_, AppState>,
) -> Result<SongLinkResponse, String> {
let upc = upc.unwrap_or_default().trim().to_string();
let title = title.unwrap_or_default().trim().to_string();
let artist = artist.unwrap_or_default().trim().to_string();
// Try iTunes lookup by UPC first
if !upc.is_empty() {
if let Some(songlink) = lookup_itunes_album_by_upc(&upc).await {
return Ok(songlink);
}
log::debug!("UPC lookup failed, trying Odesli API...");
// Try Odesli API with UPC
match state.songlink.get_by_upc(&upc).await {
Ok(result) => return Ok(result),
Err(err) => log::warn!("Odesli UPC lookup failed: {}", err),
}
}
// Try iTunes search by title/artist
if !title.is_empty() && !artist.is_empty() {
if let Some(songlink) = search_itunes_album(&title, &artist).await {
return Ok(songlink);
}
}
Err("Could not find album on music platforms".to_string())
}
async fn lookup_itunes_album_by_upc(upc: &str) -> Option<SongLinkResponse> {
if upc.trim().is_empty() {
return None;
}
log::info!("Looking up iTunes album by UPC: {}", upc);
let url = "https://itunes.apple.com/lookup";
let response = reqwest::Client::new()
.get(url)
.query(&[("upc", upc), ("country", "US")])
.send()
.await
.ok()?;
if !response.status().is_success() {
return None;
}
let data: ItunesAlbumLookupResponse = response.json().await.ok()?;
if data.result_count == 0 {
return None;
}
let album = data.results.into_iter().find(|r| r.collection_id.is_some())?;
let collection_id = album.collection_id?;
albumlink_from_itunes_id(collection_id)
}
async fn search_itunes_album(title: &str, artist: &str) -> Option<SongLinkResponse> {
let term = format!("{} {}", artist, title);
log::info!("Searching iTunes for album: {}", term);
let url = "https://itunes.apple.com/search";
let response = reqwest::Client::new()
.get(url)
.query(&[
("term", term),
("entity", "album".to_string()),
("limit", "1".to_string()),
("country", "US".to_string()),
])
.send()
.await
.ok()?;
if !response.status().is_success() {
return None;
}
let data: ItunesAlbumLookupResponse = response.json().await.ok()?;
if data.result_count == 0 {
return None;
}
let album = data.results.into_iter().find(|r| r.collection_id.is_some())?;
let collection_id = album.collection_id?;
albumlink_from_itunes_id(collection_id)
}
fn albumlink_from_itunes_id(collection_id: u64) -> Option<SongLinkResponse> {
let page_url = format!("https://album.link/i/{}", collection_id);
log::info!("Using Album.link direct URL: {}", page_url);
Some(SongLinkResponse {
page_url,
title: None,
artist: None,
thumbnail_url: None,
platforms: HashMap::new(),
identifier: collection_id.to_string(),
content_type: ContentType::Album.as_str().to_string(),
})
}
/// Generate a Qobuz share URL for a track
#[tauri::command]
pub fn get_qobuz_track_url(track_id: u64) -> String {
format!("https://www.qobuz.com/track/{}", track_id)
}
/// Generate a Qobuz share URL for an album
#[tauri::command]
pub fn get_qobuz_album_url(album_id: String) -> String {
format!("https://open.qobuz.com/album/{}", album_id)
}
/// Generate a Qobuz share URL for an artist
#[tauri::command]
pub fn get_qobuz_artist_url(artist_id: u64) -> String {
format!("https://www.qobuz.com/artist/{}", artist_id)
}
-435
View File
@@ -1,435 +0,0 @@
//! Smart Playlist Tauri commands
//!
//! Generates playlists based on MusicBrainz artist relationships
use tauri::State;
use crate::api::QobuzClient;
use crate::musicbrainz::smart_playlists::{
GeneratedPlaylist, PlaylistGenerationConfig, PlaylistRule,
};
use crate::musicbrainz::MusicBrainzSharedState;
use crate::AppState;
/// Preview a smart playlist (get track list without creating)
#[tauri::command]
pub async fn smart_playlist_preview(
rule: PlaylistRule,
config: Option<PlaylistGenerationConfig>,
mb_state: State<'_, MusicBrainzSharedState>,
app_state: State<'_, AppState>,
) -> Result<GeneratedPlaylist, String> {
let config = config.unwrap_or_default();
// Check if MusicBrainz is enabled
if !mb_state.client.is_enabled().await {
return Err("MusicBrainz integration is disabled".to_string());
}
match &rule {
PlaylistRule::BandMembers {
artist_mbid,
include_past_members,
} => {
generate_band_members_playlist(
artist_mbid,
*include_past_members,
&config,
&mb_state,
&app_state,
)
.await
}
PlaylistRule::ArtistGroups { artist_mbid } => {
generate_artist_groups_playlist(artist_mbid, &config, &mb_state, &app_state).await
}
PlaylistRule::CollaboratorNetwork { artist_mbid, depth } => {
generate_collaborator_playlist(artist_mbid, *depth, &config, &mb_state, &app_state)
.await
}
}
}
/// Generate playlist from band members' solo work
async fn generate_band_members_playlist(
artist_mbid: &str,
include_past_members: bool,
config: &PlaylistGenerationConfig,
mb_state: &State<'_, MusicBrainzSharedState>,
app_state: &State<'_, AppState>,
) -> Result<GeneratedPlaylist, String> {
// Get relationships
let relationships = mb_state
.client
.get_artist_with_relations(artist_mbid)
.await?;
// Get the band name for the playlist title
let band_name = relationships.name.clone();
// Collect member names
let mut member_names: Vec<String> = Vec::new();
if let Some(relations) = &relationships.relations {
for relation in relations {
if relation.relation_type == "member of band" {
if let Some(ref artist) = relation.artist {
// Check direction - we want members of this band
if relation.direction.as_deref() != Some("backward") {
// This is a member
let is_past = relation.ended == Some(true);
if !is_past || include_past_members {
member_names.push(artist.name.clone());
}
}
}
}
}
}
if member_names.is_empty() {
return Ok(GeneratedPlaylist {
suggested_name: format!("{} Members", band_name),
description: "No band members found in MusicBrainz".to_string(),
rule: PlaylistRule::BandMembers {
artist_mbid: artist_mbid.to_string(),
include_past_members,
},
included_artists: vec![],
track_ids: vec![],
total_tracks_found: 0,
});
}
// Search Qobuz for each member and get their tracks
let mut all_track_ids: Vec<u64> = Vec::new();
let mut found_artists: Vec<String> = Vec::new();
let client = app_state.client.read().await;
for member_name in &member_names {
match search_artist_tracks(&client, member_name, config.max_tracks_per_artist).await {
Ok(tracks) => {
if !tracks.is_empty() {
found_artists.push(member_name.clone());
all_track_ids.extend(tracks);
}
}
Err(e) => {
log::warn!("Failed to search tracks for {}: {}", member_name, e);
}
}
}
let total_found = all_track_ids.len();
Ok(GeneratedPlaylist {
suggested_name: format!("{} Members", band_name),
description: format!(
"Solo work by members of {}{}",
band_name,
if include_past_members {
" (including past members)"
} else {
""
}
),
rule: PlaylistRule::BandMembers {
artist_mbid: artist_mbid.to_string(),
include_past_members,
},
included_artists: found_artists,
track_ids: all_track_ids,
total_tracks_found: total_found,
})
}
/// Generate playlist from groups an artist is/was a member of
async fn generate_artist_groups_playlist(
artist_mbid: &str,
config: &PlaylistGenerationConfig,
mb_state: &State<'_, MusicBrainzSharedState>,
app_state: &State<'_, AppState>,
) -> Result<GeneratedPlaylist, String> {
// Get relationships
let relationships = mb_state
.client
.get_artist_with_relations(artist_mbid)
.await?;
let artist_name = relationships.name.clone();
// Collect group names
let mut group_names: Vec<String> = Vec::new();
if let Some(relations) = &relationships.relations {
for relation in relations {
if relation.relation_type == "member of band" {
if let Some(ref artist) = relation.artist {
// Check direction - "backward" means this artist is a member OF that group
if relation.direction.as_deref() == Some("backward") {
group_names.push(artist.name.clone());
}
}
}
}
}
if group_names.is_empty() {
return Ok(GeneratedPlaylist {
suggested_name: format!("{}'s Groups", artist_name),
description: "No groups found in MusicBrainz".to_string(),
rule: PlaylistRule::ArtistGroups {
artist_mbid: artist_mbid.to_string(),
},
included_artists: vec![],
track_ids: vec![],
total_tracks_found: 0,
});
}
// Search Qobuz for each group and get their tracks
let mut all_track_ids: Vec<u64> = Vec::new();
let mut found_artists: Vec<String> = Vec::new();
let client = app_state.client.read().await;
for group_name in &group_names {
match search_artist_tracks(&client, group_name, config.max_tracks_per_artist).await {
Ok(tracks) => {
if !tracks.is_empty() {
found_artists.push(group_name.clone());
all_track_ids.extend(tracks);
}
}
Err(e) => {
log::warn!("Failed to search tracks for {}: {}", group_name, e);
}
}
}
let total_found = all_track_ids.len();
Ok(GeneratedPlaylist {
suggested_name: format!("{}'s Groups", artist_name),
description: format!("Tracks from groups {} is/was a member of", artist_name),
rule: PlaylistRule::ArtistGroups {
artist_mbid: artist_mbid.to_string(),
},
included_artists: found_artists,
track_ids: all_track_ids,
total_tracks_found: total_found,
})
}
/// Generate playlist from collaborators
async fn generate_collaborator_playlist(
artist_mbid: &str,
depth: u8,
config: &PlaylistGenerationConfig,
mb_state: &State<'_, MusicBrainzSharedState>,
app_state: &State<'_, AppState>,
) -> Result<GeneratedPlaylist, String> {
// For now, only support depth=1 (direct collaborators)
if depth > 1 {
return Err("Collaborator depth > 1 not yet supported".to_string());
}
// Get relationships
let relationships = mb_state
.client
.get_artist_with_relations(artist_mbid)
.await?;
let artist_name = relationships.name.clone();
// Collect collaborator names
let mut collaborator_names: Vec<String> = Vec::new();
if let Some(relations) = &relationships.relations {
for relation in relations {
if relation.relation_type == "collaboration" {
if let Some(ref artist) = relation.artist {
collaborator_names.push(artist.name.clone());
}
}
}
}
if collaborator_names.is_empty() {
return Ok(GeneratedPlaylist {
suggested_name: format!("{} Collaborations", artist_name),
description: "No collaborators found in MusicBrainz".to_string(),
rule: PlaylistRule::CollaboratorNetwork {
artist_mbid: artist_mbid.to_string(),
depth,
},
included_artists: vec![],
track_ids: vec![],
total_tracks_found: 0,
});
}
// Search Qobuz for each collaborator
let mut all_track_ids: Vec<u64> = Vec::new();
let mut found_artists: Vec<String> = Vec::new();
let client = app_state.client.read().await;
for collab_name in &collaborator_names {
match search_artist_tracks(&client, collab_name, config.max_tracks_per_artist).await {
Ok(tracks) => {
if !tracks.is_empty() {
found_artists.push(collab_name.clone());
all_track_ids.extend(tracks);
}
}
Err(e) => {
log::warn!("Failed to search tracks for {}: {}", collab_name, e);
}
}
}
let total_found = all_track_ids.len();
Ok(GeneratedPlaylist {
suggested_name: format!("{} Collaborations", artist_name),
description: format!("Tracks from artists who have collaborated with {}", artist_name),
rule: PlaylistRule::CollaboratorNetwork {
artist_mbid: artist_mbid.to_string(),
depth,
},
included_artists: found_artists,
track_ids: all_track_ids,
total_tracks_found: total_found,
})
}
/// Search for an artist on Qobuz and get their top tracks
async fn search_artist_tracks(
client: &QobuzClient,
artist_name: &str,
max_tracks: usize,
) -> Result<Vec<u64>, String> {
// Search for the artist
let search_results = client
.search_artists(artist_name, 5, 0, None)
.await
.map_err(|e| format!("Search failed: {}", e))?;
if search_results.items.is_empty() {
return Ok(vec![]);
}
// Find exact or close match
let artist = search_results
.items
.iter()
.find(|a| a.name.to_lowercase() == artist_name.to_lowercase())
.or_else(|| search_results.items.first());
let Some(artist) = artist else {
return Ok(vec![]);
};
let artist_id = artist.id;
// Get the artist's top tracks by searching with artist name
let track_results = client
.search_tracks(artist_name, max_tracks as u32, 0, None)
.await
.map_err(|e| format!("Track search failed: {}", e))?;
// Filter tracks by this specific artist and extract IDs
let track_ids: Vec<u64> = track_results
.items
.iter()
.filter(|t| {
// Check if performer matches
t.performer
.as_ref()
.map(|p| p.id == artist_id)
.unwrap_or(false)
})
.map(|t| t.id)
.take(max_tracks)
.collect();
Ok(track_ids)
}
/// Get the artist MBID for a given artist name (helper for frontend)
#[tauri::command]
pub async fn smart_playlist_resolve_artist(
artist_name: String,
mb_state: State<'_, MusicBrainzSharedState>,
) -> Result<Option<String>, String> {
if !mb_state.client.is_enabled().await {
return Err("MusicBrainz integration is disabled".to_string());
}
let result = mb_state.client.search_artist(&artist_name).await?;
// Find best match with high confidence
let best_match = result
.artists
.iter()
.find(|a| a.score.unwrap_or(0) >= 90);
Ok(best_match.map(|a| a.id.clone()))
}
/// Get available playlist types for an artist
#[tauri::command]
pub async fn smart_playlist_get_available_types(
artist_mbid: String,
mb_state: State<'_, MusicBrainzSharedState>,
) -> Result<Vec<String>, String> {
if !mb_state.client.is_enabled().await {
return Err("MusicBrainz integration is disabled".to_string());
}
let relationships = mb_state
.client
.get_artist_with_relations(&artist_mbid)
.await?;
let mut available: Vec<String> = Vec::new();
if let Some(relations) = &relationships.relations {
let mut has_members = false;
let mut has_groups = false;
let mut has_collaborators = false;
for relation in relations {
match relation.relation_type.as_str() {
"member of band" => {
if relation.direction.as_deref() == Some("backward") {
has_groups = true;
} else {
has_members = true;
}
}
"collaboration" => {
has_collaborators = true;
}
_ => {}
}
}
if has_members {
available.push("band_members".to_string());
}
if has_groups {
available.push("artist_groups".to_string());
}
if has_collaborators {
available.push("collaborator_network".to_string());
}
}
Ok(available)
}
-19
View File
@@ -1,19 +0,0 @@
//! Visualizer Commands
//!
//! Tauri commands for controlling the audio visualizer.
use tauri::State;
use crate::AppState;
/// Enable or disable the audio visualizer
#[tauri::command]
pub fn set_visualizer_enabled(enabled: bool, state: State<'_, AppState>) -> Result<(), String> {
state.visualizer.set_enabled(enabled);
Ok(())
}
/// Check if the visualizer is enabled
#[tauri::command]
pub fn is_visualizer_enabled(state: State<'_, AppState>) -> bool {
state.visualizer.is_enabled()
}