From bd29978b2a0d0d6def486fcdaa63bc8934d68045 Mon Sep 17 00:00:00 2001 From: salmonik Date: Tue, 5 May 2026 21:12:32 +0200 Subject: fix(daemon): robust auto-advance; ensure next track starts even if playback fails --- src/audio.rs | 418 ++++++++++++++++++++++++++++++++++++++++ src/cli.rs | 186 ++++++++++++++++++ src/config.rs | 180 +++++++++++++++++ src/daemon.rs | 574 +++++++++++++++++++++++++++++++++++++++++++++++++++++++ src/database.rs | 259 +++++++++++++++++++++++++ src/main.rs | 18 ++ src/playback.rs | 131 +++++++++++++ src/scrobbler.rs | 75 ++++++++ 8 files changed, 1841 insertions(+) create mode 100644 src/audio.rs create mode 100644 src/cli.rs create mode 100644 src/config.rs create mode 100644 src/daemon.rs create mode 100644 src/database.rs create mode 100644 src/main.rs create mode 100644 src/playback.rs create mode 100644 src/scrobbler.rs (limited to 'src') diff --git a/src/audio.rs b/src/audio.rs new file mode 100644 index 0000000..86c88f7 --- /dev/null +++ b/src/audio.rs @@ -0,0 +1,418 @@ +use std::path::PathBuf; +use std::sync::atomic::{AtomicBool, Ordering}; +use std::sync::mpsc::{self, Receiver, Sender}; +use std::sync::{Arc, Mutex}; +use std::thread; + +#[allow(dead_code)] +pub enum AudioCommand { + Play(PathBuf), + Pause, + Resume, + Stop, + SetVolume(f32), +} + +pub struct AudioEngine { + command_tx: Sender, + is_playing: Arc, + current_track: Arc>>, + track_ended: Arc, +} + +impl AudioEngine { + pub fn new() -> Self { + let (tx, rx) = mpsc::channel(); + let is_playing = Arc::new(AtomicBool::new(false)); + let is_playing_clone = Arc::clone(&is_playing); + let current_track = Arc::new(Mutex::new(None)); + let current_track_clone = Arc::clone(¤t_track); + let track_ended = Arc::new(AtomicBool::new(false)); + let track_ended_clone = Arc::clone(&track_ended); + + let volume = Arc::new(Mutex::new(1.0f32)); + let volume_clone = Arc::clone(&volume); + + thread::spawn(move || { + audio_thread( + rx, + is_playing_clone, + current_track_clone, + volume_clone, + track_ended_clone, + ); + }); + + AudioEngine { + command_tx: tx, + is_playing, + current_track, + track_ended, + } + } + + pub fn play(&self, path: PathBuf) { + self.track_ended.store(false, Ordering::SeqCst); + if let Ok(mut track) = self.current_track.lock() { + *track = Some(path.clone()); + } + let _ = self.command_tx.send(AudioCommand::Play(path)); + } + + pub fn pause(&self) { + let _ = self.command_tx.send(AudioCommand::Pause); + } + + pub fn resume(&self) { + let _ = self.command_tx.send(AudioCommand::Resume); + } + + pub fn stop(&self) { + let _ = self.command_tx.send(AudioCommand::Stop); + } + + pub fn set_volume(&self, volume: f32) { + let _ = self.command_tx.send(AudioCommand::SetVolume(volume)); + } + + pub fn is_playing(&self) -> bool { + self.is_playing.load(Ordering::SeqCst) + } + + pub fn current_track(&self) -> Option { + self.current_track.lock().ok().and_then(|g| g.clone()) + } + + pub fn poll_track_ended(&self) -> bool { + self.track_ended.swap(false, Ordering::SeqCst) + } +} + +struct AudioData { + format: Box, + decoder: Box, + sample_rate: u32, + channels: u16, + sample_buffer: Vec, + buffer_pos: usize, + resample_ratio: Option, +} + +fn resample_linear(input: &[f32], ratio: f64, channels: usize) -> Vec { + if ratio == 1.0 { + return input.to_vec(); + } + let input_frames = input.len() / channels; + let output_frames = (input_frames as f64 * ratio).ceil() as usize; + let mut output = Vec::with_capacity(output_frames * channels); + for i in 0..output_frames { + let input_pos = i as f64 / ratio; + let idx = input_pos.floor() as usize; + let frac = input_pos.fract() as f32; + for ch in 0..channels { + let cur = if idx * channels + ch < input.len() { + input[idx * channels + ch] + } else { + 0.0 + }; + let next = if (idx + 1) * channels + ch < input.len() { + input[(idx + 1) * channels + ch] + } else { + cur + }; + output.push(cur + frac * (next - cur)); + } + } + output +} + +fn audio_thread( + rx: Receiver, + is_playing: Arc, + current_track: Arc>>, + volume: Arc>, + track_ended: Arc, +) { + use cpal::traits::{DeviceTrait, HostTrait, StreamTrait}; + + let host = cpal::default_host(); + let device = match host.default_output_device() { + Some(d) => d, + None => { + eprintln!("No output device available"); + return; + } + }; + + let config = match device.default_output_config() { + Ok(c) => c, + Err(e) => { + eprintln!("Failed to get output config: {}", e); + return; + } + }; + + let device_sample_rate = config.sample_rate(); + let channels = config.channels(); + eprintln!( + "Default output: {} Hz, {} channels", + device_sample_rate, channels + ); + + let mut current_stream: Option = None; + let audio_data: Arc>> = Arc::new(Mutex::new(None)); + + while let Ok(cmd) = rx.recv() { + match cmd { + AudioCommand::Play(path) => { + is_playing.store(true, Ordering::SeqCst); + if let Ok(mut track) = current_track.lock() { + *track = Some(path.clone()); + } + + // Drop the current stream before creating a new one + current_stream = None; + + match open_audio_file(&path) { + Ok(mut data) => { + eprintln!("File: {} Hz, {} channels", data.sample_rate, data.channels); + + if data.sample_rate != device_sample_rate { + eprintln!( + "Resampling from {} Hz to {} Hz", + data.sample_rate, device_sample_rate + ); + data.resample_ratio = + Some(device_sample_rate as f64 / data.sample_rate as f64); + } + + let stream_config: cpal::StreamConfig = + device.default_output_config().unwrap().into(); + + let audio_data_clone = Arc::clone(&audio_data); + let vol = Arc::clone(&volume); + let ended = Arc::clone(&track_ended); + let is_playing_clone = Arc::clone(&is_playing); + + if let Ok(mut d) = audio_data.lock() { + *d = Some(data); + } + + match device.build_output_stream( + &stream_config, + move |data: &mut [f32], _: &cpal::OutputCallbackInfo| { + let vol = vol.lock().map(|v| *v).unwrap_or(1.0); + + if let Ok(mut audio_data) = audio_data_clone.lock() { + if let Some(ref mut state) = *audio_data { + let channels = state.channels as usize; + let mut offset = 0usize; + + // Keep decoding until we fill the buffer or run out of data + while offset < data.len() { + // First, copy any buffered samples + if state.buffer_pos < state.sample_buffer.len() { + let remaining = + &state.sample_buffer[state.buffer_pos..]; + let to_copy = + remaining.len().min(data.len() - offset); + data[offset..offset + to_copy] + .copy_from_slice(&remaining[..to_copy]); + state.buffer_pos += to_copy; + offset += to_copy; + + // If we've consumed all buffered samples, clear the buffer + if state.buffer_pos >= state.sample_buffer.len() { + state.sample_buffer.clear(); + state.buffer_pos = 0; + } + continue; // Try to fill more of the buffer + } + + // Decode more data + match state.format.next_packet() { + Ok(packet) => { + match state.decoder.decode(&packet) { + Ok(decoded) => { + let spec = *decoded.spec(); + let mut sample_buf = + symphonia::core::audio::SampleBuffer::< + f32, + >::new( + decoded.capacity() as u64, spec + ); + sample_buf + .copy_interleaved_ref(decoded); + let samples = sample_buf.samples(); + + // Resample if needed + let resampled = if let Some(ratio) = + state.resample_ratio + { + resample_linear( + samples, ratio, channels, + ) + } else { + samples.to_vec() + }; + + // Copy what we can to output + let to_copy = resampled + .len() + .min(data.len() - offset); + data[offset..offset + to_copy] + .copy_from_slice( + &resampled[..to_copy], + ); + offset += to_copy; + + // Buffer the rest + if to_copy < resampled.len() { + state.sample_buffer.clear(); + state + .sample_buffer + .extend_from_slice( + &resampled[to_copy..], + ); + state.buffer_pos = 0; + } + } + Err(_) => break, + } + } + Err(_) => break, + } + } + + // Apply volume + for sample in data.iter_mut().take(offset) { + *sample *= vol; + } + + // Fill remaining with silence + for sample in data.iter_mut().skip(offset) { + *sample = 0.0; + } + + // If no more data and offset is 0, track ended + if offset == 0 && state.sample_buffer.is_empty() { + ended.store(true, Ordering::SeqCst); + is_playing_clone.store(false, Ordering::SeqCst); + // Clear audio data so we don't keep triggering ended + if let Ok(mut audio_data) = audio_data_clone.lock() { + *audio_data = None; + } + } + } else { + for sample in data.iter_mut() { + *sample = 0.0; + } + } + } + }, + |err| { + eprintln!("Stream error: {}", err); + }, + None, + ) { + Ok(stream) => { + if let Err(e) = stream.play() { + eprintln!("Failed to start stream: {}", e); + is_playing.store(false, Ordering::SeqCst); + track_ended.store(true, Ordering::SeqCst); + } else { + current_stream = Some(stream); + } + } + Err(e) => { + eprintln!("Failed to create stream: {}", e); + is_playing.store(false, Ordering::SeqCst); + track_ended.store(true, Ordering::SeqCst); + } + } + } + Err(e) => { + eprintln!("Failed to open audio: {}", e); + is_playing.store(false, Ordering::SeqCst); + track_ended.store(true, Ordering::SeqCst); + } + } + } + AudioCommand::Pause => { + if let Some(ref stream) = current_stream { + if let Err(e) = stream.pause() { + eprintln!("Failed to pause stream: {}", e); + } + is_playing.store(false, Ordering::SeqCst); + } + } + AudioCommand::Resume => { + if let Some(ref stream) = current_stream { + if let Err(e) = stream.play() { + eprintln!("Failed to resume stream: {}", e); + } else { + is_playing.store(true, Ordering::SeqCst); + } + } + } + AudioCommand::Stop => { + current_stream = None; + if let Ok(mut d) = audio_data.lock() { + *d = None; + } + is_playing.store(false, Ordering::SeqCst); + if let Ok(mut track) = current_track.lock() { + *track = None; + } + } + AudioCommand::SetVolume(vol) => { + if let Ok(mut volume_ref) = volume.lock() { + *volume_ref = vol; + } + } + } + } +} + +fn open_audio_file(path: &PathBuf) -> Result> { + use symphonia::core::audio::Channels; + use symphonia::core::io::MediaSourceStream; + + let file = std::fs::File::open(path)?; + let mss = MediaSourceStream::new(Box::new(file), Default::default()); + + let hint = symphonia::core::probe::Hint::new(); + let probed = symphonia::default::get_probe().format( + &hint, + mss, + &Default::default(), + &Default::default(), + )?; + + let format = probed.format; + let track = format + .tracks() + .iter() + .find(|t| t.codec_params.sample_rate.is_some()) + .ok_or("No suitable track found")?; + + let sample_rate = track.codec_params.sample_rate.unwrap_or(44100); + let channels = track + .codec_params + .channels + .unwrap_or(Channels::FRONT_LEFT | Channels::FRONT_RIGHT) + .count() as u16; + + let decoder = + symphonia::default::get_codecs().make(&track.codec_params, &Default::default())?; + + Ok(AudioData { + format, + decoder, + sample_rate, + channels, + sample_buffer: Vec::new(), + buffer_pos: 0, + resample_ratio: None, + }) +} diff --git a/src/cli.rs b/src/cli.rs new file mode 100644 index 0000000..13ef67c --- /dev/null +++ b/src/cli.rs @@ -0,0 +1,186 @@ +use crate::config::Config; +use crate::database::Database; +use clap::{Parser, Subcommand}; +use std::path::PathBuf; + +#[derive(Parser)] +#[command(name = "rsp")] +#[command(about = "Rust music player daemon", long_about = None)] +pub struct Cli { + #[command(subcommand)] + pub command: Commands, +} + +#[derive(Subcommand)] +pub enum Commands { + /// Start the daemon + Start, + /// Stop the daemon + Stop, + /// Restart the daemon (kill existing and start new) + Restart, + /// Play a track, album, or artist + Play { + #[arg(value_name = "QUERY")] + query: Option, + }, + /// Pause playback + Pause, + /// Resume playback + Resume, + /// Stop playback + StopPlayback, + /// Skip to next track + Next, + /// Skip to previous track + Previous, + /// Set volume (0-100) + Volume { + #[arg(value_name = "LEVEL")] + level: Option, + }, + /// Shuffle mode + Shuffle { + #[arg(value_name = "MODE")] + mode: Option, + }, + /// Queue management + Queue { + #[arg(value_name = "POSITION")] + position: Option, + #[arg(value_name = "QUERY")] + query: Option, + }, + /// Show player status + Status, + /// Scan music paths to populate database + Scan { + #[arg(long)] + force: bool, + #[arg(long, value_name = "PATHS")] + paths: Option>, + }, + /// Settings management + Settings { + #[command(subcommand)] + command: SettingsCommands, + }, +} + +#[derive(Subcommand)] +pub enum SettingsCommands { + /// Get a setting value + Get { + #[arg(value_name = "KEY")] + key: String, + }, + /// Set a setting value + Set { + #[arg(value_name = "KEY")] + key: String, + #[arg(value_name = "VALUE")] + value: String, + }, + /// List all settings + List, + /// Unset a setting + Unset { + #[arg(value_name = "KEY")] + key: String, + }, +} + +impl Cli { + pub fn run(&self) -> Result<(), Box> { + match &self.command { + Commands::Start => { + crate::daemon::start_daemon()?; + } + Commands::Stop => { + crate::daemon::stop_daemon()?; + } + Commands::Restart => { + crate::daemon::restart_daemon()?; + } + Commands::Play { query } => { + if let Some(q) = query { + crate::daemon::send_command(format!("play {}", q))?; + } else { + crate::daemon::send_command("play".to_string())?; + } + } + Commands::Pause => { + crate::daemon::send_command("pause".to_string())?; + } + Commands::Resume => { + crate::daemon::send_command("resume".to_string())?; + } + Commands::StopPlayback => { + crate::daemon::send_command("stop".to_string())?; + } + Commands::Next => { + crate::daemon::send_command("next".to_string())?; + } + Commands::Previous => { + crate::daemon::send_command("previous".to_string())?; + } + Commands::Volume { level } => { + if let Some(l) = level { + crate::daemon::send_command(format!("volume {}", l))?; + } else { + crate::daemon::send_command("volume".to_string())?; + } + } + Commands::Shuffle { mode } => { + if let Some(m) = mode { + crate::daemon::send_command(format!("shuffle {}", m))?; + } else { + crate::daemon::send_command("shuffle".to_string())?; + } + } + Commands::Queue { position, query } => match (position, query) { + (None, None) => { + crate::daemon::send_command("queue".to_string())?; + } + (pos, Some(q)) => { + let pos = pos.as_deref().unwrap_or("last"); + crate::daemon::send_command(format!("queue {} {}", pos, q))?; + } + _ => {} + }, + Commands::Status => { + crate::daemon::send_command("status".to_string())?; + } + Commands::Scan { force, paths } => { + let config = Config::load()?; + let db = Database::open(&config)?; + if let Some(custom_paths) = paths { + db.scan_paths(custom_paths, *force)?; + } else { + db.scan_paths(&config.music_paths, *force)?; + } + println!("Scan complete"); + } + Commands::Settings { command } => { + let mut config = Config::load()?; + match command { + SettingsCommands::Get { key } => { + println!("{}", config.get(key)?); + } + SettingsCommands::Set { key, value } => { + config.set(key, value)?; + config.save()?; + } + SettingsCommands::List => { + config.list(); + } + SettingsCommands::Unset { key } => { + config.unset(key)?; + config.save()?; + } + } + } + } + Ok(()) + } +} diff --git a/src/config.rs b/src/config.rs new file mode 100644 index 0000000..cda59f4 --- /dev/null +++ b/src/config.rs @@ -0,0 +1,180 @@ +use directories::ProjectDirs; +use serde::{Deserialize, Serialize}; +use std::fs; +use std::path::PathBuf; + +#[derive(Debug, Serialize, Deserialize, Default)] +pub struct Config { + #[serde(skip)] + pub config_path: PathBuf, + pub music_paths: Vec, + pub scan_interval: Option, + pub socket_path: Option, + pub lastfm_api_key: Option, + pub lastfm_api_secret: Option, + pub lastfm_session_key: Option, + pub listenbrainz_token: Option, + pub volume: Option, + pub shuffle: Option, +} + +impl Config { + pub fn load() -> Result> { + let proj_dirs = ProjectDirs::from("com", "rsplayer", "rsplayer") + .ok_or("Failed to get project directories")?; + + let config_dir = if let Ok(xdg) = std::env::var("XDG_CONFIG_HOME") { + PathBuf::from(xdg).join("rsplayer") + } else { + proj_dirs.config_dir().to_path_buf() + }; + + let config_path = config_dir.join("config.toml"); + + if !config_path.exists() { + fs::create_dir_all(&config_dir)?; + let default = Self { + config_path: config_path.clone(), + music_paths: vec![dirs::audio_dir().unwrap_or_else(|| PathBuf::from("~/Music"))], + scan_interval: Some(3600), + socket_path: None, + ..Default::default() + }; + default.save()?; + return Ok(default); + } + + let content = fs::read_to_string(&config_path)?; + let mut config: Self = toml::from_str(&content)?; + config.config_path = config_path; + Ok(config) + } + + pub fn save(&self) -> Result<(), Box> { + let content = toml::to_string_pretty(self)?; + if let Some(parent) = self.config_path.parent() { + fs::create_dir_all(parent)?; + } + fs::write(&self.config_path, content)?; + Ok(()) + } + + pub fn get(&self, key: &str) -> Result> { + match key { + "music_paths" => Ok(self + .music_paths + .iter() + .map(|p| p.display().to_string()) + .collect::>() + .join(", ")), + "scan_interval" => Ok(self + .scan_interval + .map(|i| i.to_string()) + .unwrap_or_else(|| "not set".to_string())), + "socket_path" => Ok(self + .socket_path + .as_ref() + .map(|p| p.display().to_string()) + .unwrap_or_else(|| "default".to_string())), + "lastfm_api_key" => Ok(self + .lastfm_api_key + .clone() + .unwrap_or_else(|| "not set".to_string())), + "lastfm_api_secret" => Ok(self + .lastfm_api_secret + .clone() + .unwrap_or_else(|| "not set".to_string())), + "lastfm_session_key" => Ok(self + .lastfm_session_key + .clone() + .unwrap_or_else(|| "not set".to_string())), + "listenbrainz_token" => Ok(self + .listenbrainz_token + .clone() + .unwrap_or_else(|| "not set".to_string())), + "volume" => Ok(self + .volume + .map(|v| v.to_string()) + .unwrap_or_else(|| "not set".to_string())), + "shuffle" => Ok(self.shuffle.clone().unwrap_or_else(|| "off".to_string())), + _ => Err(format!("Unknown setting: {}", key).into()), + } + } + + pub fn set(&mut self, key: &str, value: &str) -> Result<(), Box> { + match key { + "music_paths" => { + self.music_paths = value.split(',').map(|p| PathBuf::from(p.trim())).collect(); + } + "scan_interval" => { + self.scan_interval = Some(value.parse()?); + } + "socket_path" => { + self.socket_path = Some(PathBuf::from(value)); + } + "lastfm_api_key" => { + self.lastfm_api_key = Some(value.to_string()); + } + "lastfm_api_secret" => { + self.lastfm_api_secret = Some(value.to_string()); + } + "lastfm_session_key" => { + self.lastfm_session_key = Some(value.to_string()); + } + "listenbrainz_token" => { + self.listenbrainz_token = Some(value.to_string()); + } + "volume" => { + self.volume = Some(value.parse()?); + } + "shuffle" => { + if value == "on" || value == "all" || value == "album" { + self.shuffle = Some(value.to_string()); + } else if value == "off" || value == "none" { + self.shuffle = None; + } else { + return Err(format!("Invalid shuffle value: {}", value).into()); + } + } + _ => return Err(format!("Unknown setting: {}", key).into()), + } + Ok(()) + } + + pub fn list(&self) { + println!("music_paths = {:?}", self.music_paths); + println!("scan_interval = {:?}", self.scan_interval); + println!("socket_path = {:?}", self.socket_path); + println!("lastfm_api_key = {:?}", self.lastfm_api_key); + println!("lastfm_api_secret = {:?}", self.lastfm_api_secret); + println!("lastfm_session_key = {:?}", self.lastfm_session_key); + println!("listenbrainz_token = {:?}", self.listenbrainz_token); + println!("volume = {:?}", self.volume); + println!("shuffle = {:?}", self.shuffle); + } + + pub fn unset(&mut self, key: &str) -> Result<(), Box> { + match key { + "music_paths" => self.music_paths.clear(), + "scan_interval" => self.scan_interval = None, + "socket_path" => self.socket_path = None, + "lastfm_api_key" => self.lastfm_api_key = None, + "lastfm_api_secret" => self.lastfm_api_secret = None, + "lastfm_session_key" => self.lastfm_session_key = None, + "listenbrainz_token" => self.listenbrainz_token = None, + "volume" => self.volume = None, + "shuffle" => self.shuffle = None, + _ => return Err(format!("Unknown setting: {}", key).into()), + } + Ok(()) + } + + pub fn get_socket_path(&self) -> PathBuf { + self.socket_path.clone().unwrap_or_else(|| { + let runtime_dir = std::env::var("XDG_RUNTIME_DIR") + .map(PathBuf::from) + .unwrap_or_else(|_| PathBuf::from("/tmp")); + runtime_dir.join("rsplayer").join("daemon.sock") + }) + } +} diff --git a/src/daemon.rs b/src/daemon.rs new file mode 100644 index 0000000..8ac3a89 --- /dev/null +++ b/src/daemon.rs @@ -0,0 +1,574 @@ +use crate::audio::AudioEngine; +use crate::config::Config; +use std::io::{Read, Write}; +use std::os::unix::net::{UnixListener, UnixStream}; +use std::path::{Path, PathBuf}; +use std::sync::atomic::{AtomicBool, Ordering}; +use std::sync::{Arc, Mutex}; +use std::thread; +use std::time::Duration; + +#[derive(Debug, Clone)] +enum ShuffleMode { + None, + All, + Album, +} + +struct Queue { + tracks: Vec, + position: usize, + shuffle: ShuffleMode, + shuffled_indices: Vec, +} + +impl Queue { + fn new() -> Self { + Queue { + tracks: Vec::new(), + position: 0, + shuffle: ShuffleMode::None, + shuffled_indices: Vec::new(), + } + } + + fn add_track(&mut self, path: PathBuf) { + self.tracks.push(path); + self.update_shuffle_indices(); + } + + fn set_shuffle(&mut self, mode: ShuffleMode) { + self.shuffle = mode.clone(); + self.update_shuffle_indices(); + } + + fn update_shuffle_indices(&mut self) { + self.shuffled_indices = (0..self.tracks.len()).collect(); + if let ShuffleMode::All = self.shuffle { + use rand::seq::SliceRandom; + let mut rng = rand::rng(); + self.shuffled_indices.shuffle(&mut rng); + } + } + + fn current(&self) -> Option<&PathBuf> { + if self.tracks.is_empty() { + None + } else if let ShuffleMode::All = self.shuffle { + self.shuffled_indices + .get(self.position) + .and_then(|&idx| self.tracks.get(idx)) + } else if let ShuffleMode::Album = self.shuffle { + // TODO: When database is ready, only shuffle tracks in same album/folder + // For now, behave like All + self.shuffled_indices + .get(self.position) + .and_then(|&idx| self.tracks.get(idx)) + } else { + self.tracks.get(self.position) + } + } + + fn next(&mut self) -> Option { + let max_pos = self.tracks.len().saturating_sub(1); + if self.position < max_pos { + self.position += 1; + self.current().cloned() + } else { + None + } + } + + fn previous(&mut self) -> Option { + if self.position > 0 { + self.position -= 1; + self.current().cloned() + } else { + None + } + } +} + +pub fn start_daemon() -> Result<(), Box> { + let config = Config::load()?; + let socket_path = config.get_socket_path(); + let pid_path = get_pid_path(&config); + + // Check if daemon is already running + if let Ok(pid) = check_running_daemon(&pid_path) { + return Err(format!("Daemon already running with PID {}", pid).into()); + } + + // Clean up stale socket file if it exists + if socket_path.exists() { + std::fs::remove_file(&socket_path).ok(); + } + + // Create runtime directory + if let Some(parent) = socket_path.parent() { + std::fs::create_dir_all(parent)?; + } + if let Some(parent) = pid_path.parent() { + std::fs::create_dir_all(parent)?; + } + + // Write PID file + let pid = std::process::id(); + std::fs::write(&pid_path, pid.to_string())?; + println!("Daemon started with PID {}", pid); + + // Shared shutdown flag - can be triggered by signal or command + let shutdown_flag = Arc::new(AtomicBool::new(false)); + let shutdown_flag_signal = Arc::clone(&shutdown_flag); + + // Handle SIGTERM and SIGINT + ctrlc::set_handler(move || { + println!("Received shutdown signal"); + shutdown_flag_signal.store(true, Ordering::SeqCst); + })?; + + let listener = UnixListener::bind(&socket_path)?; + println!("Listening on {:?}", socket_path); + + let audio_engine = Arc::new(AudioEngine::new()); + let queue = Arc::new(Mutex::new(Queue::new())); + + // Load and apply saved settings + let config = Config::load().unwrap_or_default(); + if let Some(vol) = config.volume { + audio_engine.set_volume(vol as f32 / 100.0); + } + if let Some(ref shuffle_str) = config.shuffle { + if let Ok(mut q) = queue.lock() { + match shuffle_str.as_str() { + "on" | "all" => q.set_shuffle(ShuffleMode::All), + "album" => q.set_shuffle(ShuffleMode::Album), + _ => {} + } + } + } + + // Accept connections until shutdown + listener.set_nonblocking(true)?; + loop { + // Check for shutdown signal + if shutdown_flag.load(Ordering::SeqCst) { + break; + } + + // Check if track ended and play next + if audio_engine.poll_track_ended() { + if let Ok(mut q) = queue.lock() { + if let Some(next_track) = q.next() { + audio_engine.play(next_track); + } else { + audio_engine.stop(); + } + } + } + + match listener.accept() { + Ok((stream, _)) => { + let audio_clone = Arc::clone(&audio_engine); + let shutdown_flag_clone = Arc::clone(&shutdown_flag); + let queue_clone = Arc::clone(&queue); + thread::spawn(move || { + handle_client(stream, audio_clone, shutdown_flag_clone, queue_clone); + }); + } + Err(ref e) if e.kind() == std::io::ErrorKind::WouldBlock => { + thread::sleep(Duration::from_millis(50)); + continue; + } + Err(e) => eprintln!("Connection failed: {}", e), + } + + thread::sleep(Duration::from_millis(50)); + } + + // Cleanup + cleanup_daemon(&socket_path, &pid_path); + println!("Daemon stopped"); + Ok(()) +} + +pub fn stop_daemon() -> Result<(), Box> { + let config = Config::load()?; + let pid_path = get_pid_path(&config); + + match check_running_daemon(&pid_path) { + Ok(pid) => { + // Try to send stop command first for graceful shutdown + if let Ok(()) = send_command_raw("stop_daemon".to_string()) { + // Wait for daemon to stop + for _ in 0..50 { + thread::sleep(Duration::from_millis(100)); + if !is_process_running(pid) { + break; + } + } + } + + // Force kill if still running + if is_process_running(pid) { + unsafe { + libc::kill(pid as i32, libc::SIGTERM); + } + thread::sleep(Duration::from_millis(500)); + + // Force kill if still alive + if is_process_running(pid) { + unsafe { + libc::kill(pid as i32, libc::SIGKILL); + } + } + } + + // Clean up files + let socket_path = config.get_socket_path(); + std::fs::remove_file(&socket_path).ok(); + std::fs::remove_file(&pid_path).ok(); + + println!("Daemon stopped"); + Ok(()) + } + Err(e) => Err(format!("Daemon not running: {}", e).into()), + } +} + +pub fn restart_daemon() -> Result<(), Box> { + // Stop existing daemon + if let Ok(()) = stop_daemon() { + // Wait a bit for cleanup + thread::sleep(Duration::from_millis(500)); + } + + // Start new daemon in background + let current_exe = std::env::current_exe()?; + std::process::Command::new(current_exe) + .arg("start") + .spawn()?; + + println!("Daemon restarted"); + Ok(()) +} + +pub fn send_command(cmd: String) -> Result<(), Box> { + send_command_raw(cmd)?; + Ok(()) +} + +fn send_command_raw(cmd: String) -> Result<(), Box> { + let config = Config::load()?; + let socket_path = config.get_socket_path(); + + let mut stream = UnixStream::connect(socket_path)?; + stream.write_all(cmd.as_bytes())?; + + let mut response = String::new(); + stream.read_to_string(&mut response)?; + print!("{}", response); + + Ok(()) +} + +fn handle_client( + mut stream: UnixStream, + audio: Arc, + shutdown_flag: Arc, + queue: Arc>, +) { + let mut buffer = [0; 1024]; + if let Ok(size) = stream.read(&mut buffer) { + let cmd = String::from_utf8_lossy(&buffer[..size]); + let response = process_command(cmd.trim(), &audio, &shutdown_flag, &queue); + let _ = stream.write_all(response.as_bytes()); + } +} + +fn process_command( + cmd: &str, + audio: &AudioEngine, + shutdown_flag: &Arc, + queue: &Arc>, +) -> String { + match cmd { + "status" => { + if audio.is_playing() { + if let Some(track) = audio.current_track() { + format!("Playing\nTrack: {}\n", track.display()) + } else { + "Playing\n".to_string() + } + } else { + "Stopped\n".to_string() + } + } + "pause" => { + audio.pause(); + "Paused\n".to_string() + } + "resume" => { + audio.resume(); + "Resumed\n".to_string() + } + "stop" => { + audio.stop(); + // Clear queue on stop + if let Ok(mut q) = queue.lock() { + q.tracks.clear(); + q.position = 0; + } + "Stopped\n".to_string() + } + "stop_daemon" => { + // Signal the daemon to shut down + shutdown_flag.store(true, Ordering::SeqCst); + "Shutting down\n".to_string() + } + "next" => { + if let Ok(mut q) = queue.lock() { + if let Some(next_track) = q.next() { + audio.play(next_track); + "Playing next track\n".to_string() + } else { + audio.stop(); + "Queue empty, stopped\n".to_string() + } + } else { + "Error accessing queue\n".to_string() + } + } + "previous" => { + if let Ok(mut q) = queue.lock() { + if let Some(prev_track) = q.previous() { + audio.play(prev_track); + "Playing previous track\n".to_string() + } else { + "No previous track\n".to_string() + } + } else { + "Error accessing queue\n".to_string() + } + } + "shuffle" => { + if let Ok(q) = queue.lock() { + match q.shuffle { + ShuffleMode::None => "Shuffle: off\n".to_string(), + ShuffleMode::All => "Shuffle: on (all)\n".to_string(), + ShuffleMode::Album => "Shuffle: on (album)\n".to_string(), + } + } else { + "Error accessing queue\n".to_string() + } + } + _ if cmd.starts_with("shuffle ") => { + let mode_str = cmd[8..].trim(); + if let Ok(mut q) = queue.lock() { + let result = if mode_str == "on" || mode_str == "all" { + q.set_shuffle(ShuffleMode::All); + "Shuffle: on (all)\n".to_string() + } else if mode_str == "album" { + q.set_shuffle(ShuffleMode::Album); + "Shuffle: on (album)\n".to_string() + } else if mode_str == "off" || mode_str == "none" { + q.set_shuffle(ShuffleMode::None); + "Shuffle: off\n".to_string() + } else { + "Usage: shuffle [on|off|album]\n".to_string() + }; + // Save to config + if let Ok(mut config) = Config::load() { + if mode_str == "off" || mode_str == "none" { + config.shuffle = None; + } else { + config.shuffle = Some(mode_str.to_string()); + } + let _ = config.save(); + } + result + } else { + "Error accessing queue\n".to_string() + } + } + _ if cmd.starts_with("play ") => { + let path_str = &cmd[5..].trim(); + let path = std::path::PathBuf::from(path_str); + if path.is_file() { + // Add to queue and play + if let Ok(mut q) = queue.lock() { + q.add_track(path.clone()); + } + audio.play(path); + format!("Playing: {}\n", path_str) + } else if path.is_dir() { + // Find all audio files in directory + match find_audio_in_dir(&path) { + Some(files) if !files.is_empty() => { + if let Ok(mut q) = queue.lock() { + for file in &files { + q.add_track(file.clone()); + } + // If shuffle is on, shuffled_indices is already set + // Play the first track from the shuffled list + if let Some(track) = q.current().cloned() { + audio.play(track); + } + } + format!("Queued {} tracks from: {}\n", files.len(), path_str) + } + _ => format!("Error: No audio files found in '{}'\n", path_str), + } + } else { + format!("File not found: {}\n", path_str) + } + } + _ if cmd.starts_with("volume ") => { + if let Ok(level) = cmd[7..].trim().parse::() { + audio.set_volume(level as f32 / 100.0); + // Save to config + if let Ok(mut config) = Config::load() { + config.volume = Some(level); + let _ = config.save(); + } + format!("Volume set to {}\n", level) + } else { + "Usage: volume <0-100>\n".to_string() + } + } + _ if cmd.starts_with("shuffle ") => { + let mode_str = cmd[8..].trim(); + if let Ok(mut q) = queue.lock() { + if mode_str == "on" || mode_str == "all" { + q.set_shuffle(ShuffleMode::All); + "Shuffle: on\n".to_string() + } else if mode_str == "off" || mode_str == "none" { + q.set_shuffle(ShuffleMode::None); + "Shuffle: off\n".to_string() + } else { + "Usage: shuffle [on|off]\n".to_string() + } + } else { + "Error accessing queue\n".to_string() + } + } + _ if cmd.starts_with("queue") => { + if let Ok(q) = queue.lock() { + if q.tracks.is_empty() { + "Queue is empty\n".to_string() + } else { + let mut output = String::new(); + let current_position = q.position; + // Use shuffled_indices for display order if shuffle is on + let indices: Vec = if let ShuffleMode::None = q.shuffle { + (0..q.tracks.len()).collect() + } else { + q.shuffled_indices.clone() + }; + for (display_idx, &track_idx) in indices.iter().enumerate() { + if let Some(track) = q.tracks.get(track_idx) { + if display_idx == current_position { + output.push_str(&format!("> {} (playing)\n", track.display())); + } else { + output.push_str(&format!(" {}\n", track.display())); + } + } + } + // Use pager if output is long (more than 24 lines) + if output.lines().count() > 24 { + use std::process::{Command, Stdio}; + let pager = Command::new("less").arg("-R").stdin(Stdio::piped()).spawn(); + if let Ok(mut child) = pager { + use std::io::Write; + let _ = child.stdin.as_mut().unwrap().write_all(output.as_bytes()); + let _ = child.wait(); + "".to_string() + } else { + output + } + } else { + output + } + } + } else { + "Error accessing queue\n".to_string() + } + } + _ => "Unknown command\n".to_string(), + } +} + +fn find_audio_in_dir(dir: &Path) -> Option> { + use std::ffi::OsStr; + + let mut results = Vec::new(); + + if let Ok(entries) = std::fs::read_dir(dir) { + let mut entries: Vec<_> = entries.filter_map(|e| e.ok()).collect(); + entries.sort_by_key(|e| e.file_name()); + + for entry in entries { + let path = entry.path(); + if path.is_file() { + if let Some(ext) = path.extension().and_then(OsStr::to_str) { + if matches!( + ext.to_lowercase().as_str(), + "mp3" | "flac" | "ogg" | "m4a" | "wav" | "opus" + ) { + results.push(path); + } + } + } else if path.is_dir() { + if let Some(mut found) = find_audio_in_dir(&path) { + results.append(&mut found); + } + } + } + } + + if results.is_empty() { + None + } else { + Some(results) + } +} + +/// Get the PID file path for the daemon +fn get_pid_path(_config: &Config) -> std::path::PathBuf { + let runtime_dir = std::env::var("XDG_RUNTIME_DIR") + .map(std::path::PathBuf::from) + .unwrap_or_else(|_| std::path::PathBuf::from("/tmp")); + runtime_dir.join("rsplayer").join("rsplayer.pid") +} + +/// Check if a process with the given PID is running +fn is_process_running(pid: u32) -> bool { + unsafe { + // send signal 0 to check if process exists + libc::kill(pid as i32, 0) == 0 + } +} + +/// Check if daemon is running by reading PID file +fn check_running_daemon(pid_path: &std::path::Path) -> Result> { + if !pid_path.exists() { + return Err("PID file not found".into()); + } + + let contents = std::fs::read_to_string(pid_path)?; + let pid = contents.trim().parse::()?; + + if is_process_running(pid) { + Ok(pid) + } else { + // Stale PID file, clean it up + std::fs::remove_file(pid_path).ok(); + Err("Stale PID file, daemon not running".into()) + } +} + +/// Clean up daemon resources (socket and PID file) +fn cleanup_daemon(socket_path: &std::path::Path, pid_path: &std::path::Path) { + std::fs::remove_file(socket_path).ok(); + std::fs::remove_file(pid_path).ok(); +} diff --git a/src/database.rs b/src/database.rs new file mode 100644 index 0000000..9d1d5f2 --- /dev/null +++ b/src/database.rs @@ -0,0 +1,259 @@ +use directories::ProjectDirs; +use rusqlite::{Connection, Result as SqlResult}; +use std::fs; +use std::path::{Path, PathBuf}; +use std::time::SystemTime; + +#[derive(Debug, Clone)] +#[allow(dead_code)] +pub struct Artist { + pub id: i64, + pub name: String, +} + +#[derive(Debug, Clone)] +#[allow(dead_code)] +pub struct Album { + pub id: i64, + pub artist_id: i64, + pub title: String, +} + +#[derive(Debug, Clone)] +#[allow(dead_code)] +pub struct Track { + pub id: i64, + pub album_id: i64, + pub title: String, + pub path: PathBuf, + pub duration: Option, + pub track_number: Option, + pub artist_name: Option, + pub album_title: Option, +} + +pub struct Database { + conn: Connection, +} + +#[allow(dead_code)] +impl Database { + pub fn open(_config: &crate::config::Config) -> SqlResult { + let proj_dirs = ProjectDirs::from("com", "rsplayer", "rsplayer").ok_or_else(|| { + rusqlite::Error::InvalidPath("Failed to get project directories".into()) + })?; + + let data_dir = if let Ok(xdg) = std::env::var("XDG_CONFIG_HOME") { + PathBuf::from(xdg).join("rsplayer") + } else { + proj_dirs.data_dir().to_path_buf() + }; + + fs::create_dir_all(&data_dir).ok(); + let db_path = data_dir.join("library.db"); + + let conn = Connection::open(&db_path)?; + let db = Database { conn }; + db.init_schema()?; + Ok(db) + } + + fn init_schema(&self) -> SqlResult<()> { + self.conn.execute( + "CREATE TABLE IF NOT EXISTS artists ( + id INTEGER PRIMARY KEY, + name TEXT UNIQUE NOT NULL + )", + [], + )?; + + self.conn.execute( + "CREATE TABLE IF NOT EXISTS albums ( + id INTEGER PRIMARY KEY, + artist_id INTEGER NOT NULL, + title TEXT NOT NULL, + FOREIGN KEY (artist_id) REFERENCES artists(id), + UNIQUE(artist_id, title) + )", + [], + )?; + + self.conn.execute( + "CREATE TABLE IF NOT EXISTS tracks ( + id INTEGER PRIMARY KEY, + album_id INTEGER NOT NULL, + title TEXT NOT NULL, + path TEXT UNIQUE NOT NULL, + duration INTEGER, + track_number INTEGER, + last_scanned INTEGER, + FOREIGN KEY (album_id) REFERENCES albums(id) + )", + [], + )?; + + Ok(()) + } + + pub fn scan_paths(&self, paths: &[PathBuf], force: bool) -> SqlResult<()> { + for path in paths { + self.scan_directory(path, force)?; + } + Ok(()) + } + + fn scan_directory(&self, dir: &Path, force: bool) -> SqlResult<()> { + if !dir.exists() { + return Ok(()); + } + + let now = SystemTime::now() + .duration_since(SystemTime::UNIX_EPOCH) + .unwrap() + .as_secs() as i64; + + self.scan_recursive(dir, now, force)?; + self.cleanup_old_tracks(now)?; + Ok(()) + } + + fn scan_recursive(&self, dir: &Path, scan_time: i64, force: bool) -> SqlResult<()> { + let entries = fs::read_dir(dir).ok(); + if let Some(entries) = entries { + for entry in entries.flatten() { + let path = entry.path(); + if path.is_dir() { + self.scan_recursive(&path, scan_time, force)?; + } else if is_audio_file(&path) { + self.process_audio_file(&path, scan_time, force)?; + } + } + } + Ok(()) + } + + fn process_audio_file(&self, path: &Path, scan_time: i64, force: bool) -> SqlResult<()> { + let path_str = path.to_string_lossy().to_string(); + + if !force { + let count: i64 = self + .conn + .query_row( + "SELECT COUNT(*) FROM tracks WHERE path = ? AND last_scanned = ?", + rusqlite::params![path_str, scan_time], + |row| row.get(0), + ) + .unwrap_or(0); + if count > 0 { + return Ok(()); + } + } + + let metadata = extract_metadata(path); + let (artist_name, album_title, track_title, track_number, duration) = metadata; + let duration_i64 = duration.map(|d| d as i64); + + let artist_id = self.get_or_create_artist(&artist_name)?; + let album_id = self.get_or_create_album(artist_id, &album_title)?; + + self.conn.execute( + "INSERT OR REPLACE INTO tracks (album_id, title, path, duration, track_number, last_scanned) + VALUES (?, ?, ?, ?, ?, ?)", + rusqlite::params![album_id, track_title, path_str, duration_i64, track_number, scan_time], + )?; + + Ok(()) + } + + fn get_or_create_artist(&self, name: &str) -> SqlResult { + self.conn + .execute("INSERT OR IGNORE INTO artists (name) VALUES (?)", [name])?; + self.conn + .query_row("SELECT id FROM artists WHERE name = ?", [name], |row| { + row.get(0) + }) + } + + fn get_or_create_album(&self, artist_id: i64, title: &str) -> SqlResult { + self.conn.execute( + "INSERT OR IGNORE INTO albums (artist_id, title) VALUES (?, ?)", + rusqlite::params![artist_id, title], + )?; + self.conn.query_row( + "SELECT id FROM albums WHERE artist_id = ? AND title = ?", + rusqlite::params![artist_id, title], + |row| row.get(0), + ) + } + + fn cleanup_old_tracks(&self, scan_time: i64) -> SqlResult<()> { + self.conn + .execute("DELETE FROM tracks WHERE last_scanned < ?", [scan_time])?; + Ok(()) + } + + pub fn search_tracks(&self, query: &str) -> SqlResult> { + let mut stmt = self.conn.prepare( + "SELECT t.id, t.album_id, t.title, t.path, t.duration, t.track_number, ar.name, a.title + FROM tracks t + JOIN albums a ON t.album_id = a.id + JOIN artists ar ON a.artist_id = ar.id + WHERE t.title LIKE ? OR a.title LIKE ? OR ar.name LIKE ? + ORDER BY ar.name, a.title, t.track_number", + )?; + + let search = format!("%{}%", query); + let rows = stmt.query_map([&search, &search, &search], |row| { + Ok(Track { + id: row.get(0)?, + album_id: row.get(1)?, + title: row.get(2)?, + path: PathBuf::from(row.get::<_, String>(3)?), + duration: row.get(4)?, + track_number: row.get(5)?, + artist_name: Some(row.get(6)?), + album_title: Some(row.get(7)?), + }) + })?; + + rows.collect() + } +} + +fn is_audio_file(path: &Path) -> bool { + path.extension() + .and_then(|ext| ext.to_str()) + .map(|ext| { + matches!( + ext.to_lowercase().as_str(), + "mp3" | "flac" | "ogg" | "m4a" | "wav" | "opus" + ) + }) + .unwrap_or(false) +} + +fn extract_metadata(path: &Path) -> (String, String, String, Option, Option) { + let file_stem = path + .file_stem() + .and_then(|s| s.to_str()) + .unwrap_or("Unknown"); + let parent = path + .parent() + .and_then(|p| p.file_name()) + .and_then(|s| s.to_str()) + .unwrap_or("Unknown"); + let grandparent = path + .parent() + .and_then(|p| p.parent()) + .and_then(|p| p.file_name()) + .and_then(|s| s.to_str()) + .unwrap_or("Unknown"); + + ( + grandparent.to_string(), + parent.to_string(), + file_stem.to_string(), + None, + None, + ) +} diff --git a/src/main.rs b/src/main.rs new file mode 100644 index 0000000..2b88c44 --- /dev/null +++ b/src/main.rs @@ -0,0 +1,18 @@ +mod audio; +mod cli; +mod config; +mod daemon; +mod database; +mod playback; +mod scrobbler; + +use clap::Parser; +use cli::Cli; + +fn main() { + let cli = Cli::parse(); + if let Err(e) = cli.run() { + eprintln!("Error: {}", e); + std::process::exit(1); + } +} diff --git a/src/playback.rs b/src/playback.rs new file mode 100644 index 0000000..76c0f44 --- /dev/null +++ b/src/playback.rs @@ -0,0 +1,131 @@ +use std::path::PathBuf; + +#[derive(Debug, Clone, PartialEq)] +#[allow(dead_code)] +pub enum PlaybackState { + Stopped, + Playing, + Paused, +} + +#[derive(Debug, Clone)] +#[allow(dead_code)] +pub struct Track { + pub path: PathBuf, + pub title: String, + pub artist: String, + pub album: String, + pub duration: Option, +} + +#[derive(Debug, Clone)] +#[allow(dead_code)] +pub enum ShuffleMode { + None, + All, + Album, +} + +#[allow(dead_code)] +pub struct Player { + state: PlaybackState, + current_track: Option, + queue: Vec, + volume: u8, + shuffle: ShuffleMode, +} + +#[allow(dead_code)] +impl Player { + pub fn new() -> Self { + Player { + state: PlaybackState::Stopped, + current_track: None, + queue: Vec::new(), + volume: 70, + shuffle: ShuffleMode::None, + } + } + + pub fn state(&self) -> &PlaybackState { + &self.state + } + + pub fn volume(&self) -> u8 { + self.volume + } + + pub fn play(&mut self) { + if self.state == PlaybackState::Paused { + self.resume(); + } else if self.current_track.is_none() && !self.queue.is_empty() { + self.current_track = Some(self.queue.remove(0)); + self.state = PlaybackState::Playing; + } + } + + pub fn play_track(&mut self, track: Track) { + self.current_track = Some(track); + self.state = PlaybackState::Playing; + } + + pub fn pause(&mut self) { + if self.state == PlaybackState::Playing { + self.state = PlaybackState::Paused; + } + } + + pub fn resume(&mut self) { + if self.state == PlaybackState::Paused { + self.state = PlaybackState::Playing; + } + } + + pub fn stop(&mut self) { + self.state = PlaybackState::Stopped; + self.current_track = None; + } + + pub fn next(&mut self) { + if !self.queue.is_empty() { + self.current_track = Some(self.queue.remove(0)); + } else { + self.stop(); + } + } + + pub fn previous(&mut self) { + if (self.state == PlaybackState::Playing || self.state == PlaybackState::Paused) + && self.current_track.is_some() + { + self.state = PlaybackState::Playing; + } + } + + pub fn set_volume(&mut self, level: u8) { + self.volume = level.min(100); + } + + pub fn set_shuffle(&mut self, mode: ShuffleMode) { + self.shuffle = mode; + } + + pub fn queue_track(&mut self, track: Track, position: &str) { + match position { + "now" => self.queue.insert(0, track), + "next" => { + let idx = 1.min(self.queue.len()); + self.queue.insert(idx, track); + } + _ => self.queue.push(track), + } + } + + pub fn dequeue_next(&mut self) -> Option { + if !self.queue.is_empty() { + Some(self.queue.remove(0)) + } else { + None + } + } +} diff --git a/src/scrobbler.rs b/src/scrobbler.rs new file mode 100644 index 0000000..09a7f55 --- /dev/null +++ b/src/scrobbler.rs @@ -0,0 +1,75 @@ +use reqwest::Client; + +#[allow(dead_code)] +pub struct Scrobbler { + lastfm_api_key: Option, + lastfm_api_secret: Option, + lastfm_session_key: Option, + listenbrainz_token: Option, + client: Client, +} + +#[allow(dead_code)] +impl Scrobbler { + pub fn new( + lastfm_api_key: Option, + lastfm_api_secret: Option, + lastfm_session_key: Option, + listenbrainz_token: Option, + ) -> Self { + Scrobbler { + lastfm_api_key, + lastfm_api_secret, + lastfm_session_key, + listenbrainz_token, + client: Client::new(), + } + } + + pub fn now_playing(&self, artist: &str, track: &str, album: Option<&str>) { + if let Some(api_key) = &self.lastfm_api_key { + let _ = self.send_lastfm_now_playing(api_key, artist, track, album); + } + } + + pub fn scrobble(&self, artist: &str, track: &str, album: Option<&str>, timestamp: u64) { + if let Some(api_key) = &self.lastfm_api_key { + let _ = self.send_lastfm_scrobble(api_key, artist, track, album, timestamp); + } + if let Some(token) = &self.listenbrainz_token { + let _ = self.send_listenbrainz_scrobble(token, artist, track, album, timestamp); + } + } + + fn send_lastfm_now_playing( + &self, + _api_key: &str, + _artist: &str, + _track: &str, + _album: Option<&str>, + ) -> Result<(), Box> { + Ok(()) + } + + fn send_lastfm_scrobble( + &self, + _api_key: &str, + _artist: &str, + _track: &str, + _album: Option<&str>, + _timestamp: u64, + ) -> Result<(), Box> { + Ok(()) + } + + fn send_listenbrainz_scrobble( + &self, + _token: &str, + _artist: &str, + _track: &str, + _album: Option<&str>, + _timestamp: u64, + ) -> Result<(), Box> { + Ok(()) + } +} -- cgit v1.2.3