diff --git a/src/main.rs b/src/main.rs index 8083d87..b2b9e94 100644 --- a/src/main.rs +++ b/src/main.rs @@ -8,18 +8,17 @@ use tungstenite::accept; use tungstenite::protocol::WebSocket; use clap::Parser; -use dirs_next; -use crate::db_operations::DatabaseRequest; pub mod db_operations; pub mod file_operations; pub mod message_types; pub mod music_player; pub mod server_handling; -use crate::db_operations::DBObject; -use crate::message_types::{PartialTag, ServerResponse, UIRequest}; +use crate::db_operations::{DBObject, DatabaseRequest}; +use crate::message_types::{PartialTag, UIRequest}; use crate::music_player::MusicPlayer; +use crate::server_handling::{write_to_socket, sanitize_partialtag}; #[derive(Parser, Debug)] #[command(author, version, about, long_about=None)] @@ -197,7 +196,8 @@ fn handle_uirequest( write_to_socket(socket, "Player Paused".to_string(), vec![]).unwrap(); } UIRequest::Skip(skip_direction) => todo!(), - UIRequest::Search(request) => { + UIRequest::Search(unsanitary_req) => { + let request = sanitize_partialtag(unsanitary_req); // TODO: switch this to a debug info!("got a: {:?}", request); let items = dbo @@ -214,7 +214,8 @@ fn handle_uirequest( } } } - UIRequest::SwitchTo(partial_tag) => { + UIRequest::SwitchTo(in_partial_tag) => { + let partial_tag = sanitize_partialtag(in_partial_tag); let items = dbo .get(&DatabaseRequest { search_type: db_operations::SearchType::Like, @@ -254,26 +255,23 @@ fn handle_uirequest( } } } - UIRequest::GetStatus => todo!(), + UIRequest::GetTime => { + info!("Sending time info"); + let message = format!( + "Song length: {:?}\nCurrent Position: {:?}", + music_player.get_track_length(), + music_player.get_played_time()); + write_to_socket( + socket, + message, + vec![]) + .unwrap(); + }, } Ok(()) } -fn write_to_socket( - socket: &mut WebSocket, - message: String, - results: Vec, -) -> Result<(), tungstenite::Error> { - socket.write_message( - serde_json::to_string(&ServerResponse { - message, - search_results: results, - }) - .unwrap() - .into(), - ) -} pub fn init_logger(output_file: String) { // TODO: configure the log levels to something appropriate diff --git a/src/message_types.rs b/src/message_types.rs index cda13ed..e795f9f 100644 --- a/src/message_types.rs +++ b/src/message_types.rs @@ -92,5 +92,5 @@ pub enum UIRequest { Skip(SkipDirection), Search(PartialTag), SwitchTo(PartialTag), - GetStatus, + GetTime, } diff --git a/src/music_player.rs b/src/music_player.rs index 6097aff..3e0a0ff 100644 --- a/src/music_player.rs +++ b/src/music_player.rs @@ -1,7 +1,9 @@ //use rodio::decoder::DecoderError; -use rodio::{Decoder, OutputStreamHandle, Sink}; +use rodio::{Decoder, OutputStreamHandle, Sink, Source}; use std::fs::File; use std::io::BufReader; +use std::time::{Duration, Instant}; +use log::warn; use crate::message_types::ItemTag; @@ -15,6 +17,10 @@ pub struct MusicPlayer<'a> { output_stream_handle: &'a OutputStreamHandle, playing_sink: rodio::Sink, currently_playing: ItemTag, + + current_track_length: Duration, + started_playing: Instant, + paused_length: Duration, } impl<'a> MusicPlayer<'a> { @@ -24,24 +30,50 @@ impl<'a> MusicPlayer<'a> { let file = BufReader::new(File::open(starting_item.path.clone()).unwrap()); let source = Decoder::new(file).unwrap(); + + println!("{:?}", source.total_duration()); + + let tmp_length; + match source.total_duration() { + None => tmp_length = Duration::from_millis(0), + Some(length) => tmp_length = length, + }; + sink.append(source); - let mp = MusicPlayer { + let mut mp = MusicPlayer { output_stream_handle, playing_sink: sink, currently_playing: starting_item, + + current_track_length: Duration::from_millis(0), + started_playing: Instant::now(), + paused_length: Duration::from_millis(0), }; + + mp.current_track_length = tmp_length; + + mp.started_playing = Instant::now(); mp.pause(); return mp; } - pub fn pause(&self) { + /// Check if `MediaPlayer` is paused + pub fn is_paused(&self) -> bool { + return self.playing_sink.is_paused(); + } + + /// Pause the playback of what is currently playing + pub fn pause(&mut self) { + self.paused_length = self.started_playing.elapsed(); self.playing_sink.pause(); } - pub fn play(&self) { + /// Resume playing what is in the `MediaPlayer` + pub fn play(&mut self) { self.playing_sink.play(); + self.started_playing = Instant::now(); println!("playing"); } @@ -58,13 +90,32 @@ impl<'a> MusicPlayer<'a> { let source = Decoder::new(reader); - if source.is_err() { - return Err(MusicPlayerError::DecoderError); - } + match source { + Err(_err) => return Err(MusicPlayerError::DecoderError), + Ok(src) => { + match src.total_duration() { + None => self.current_track_length = Duration::from_millis(0), + Some(length) => self.current_track_length = length, + }; - self.playing_sink.stop(); - self.playing_sink = Sink::try_new(self.output_stream_handle).unwrap(); - self.playing_sink.append(source.unwrap()); - Ok(()) + self.playing_sink.stop(); + self.playing_sink = Sink::try_new(self.output_stream_handle).unwrap(); + self.playing_sink.append(src); + + self.started_playing = Instant::now(); + return Ok(()) + } + } + } + + /// Get the song's current position (time wise) + pub fn get_played_time(&self) -> Duration { + if self.is_paused() {return self.paused_length;} + else {return self.started_playing.elapsed();} + } + + /// Get the song's length + pub fn get_track_length(&self) -> Duration { + return self.current_track_length; } } diff --git a/src/server_handling.rs b/src/server_handling.rs index 81fefb0..ce8e27b 100644 --- a/src/server_handling.rs +++ b/src/server_handling.rs @@ -1,5 +1,7 @@ -use crate::message_types::UIRequest; -use log::{debug, error, info, trace, warn, LevelFilter}; +use crate::message_types::{UIRequest, ItemTag, ServerResponse, PartialTag}; +use log::info; +use tungstenite::protocol::WebSocket; +use std::net::TcpStream; /// Pass a pub fn handle_request(socket_message: String) -> Result { @@ -16,3 +18,44 @@ fn sanitize_input(input: UIRequest) -> Result { // has a type of request (e.g. "title search: value") Ok(UIRequest::Pause) } + +fn sanitize_tag(input: ItemTag) -> ItemTag { + let mut output = ItemTag{ + ..ItemTag::default() + }; + output.path = input.path.replace("'", "''"); + output.title = input.title.replace("'", "''"); + output.album = input.album.replace("'", "''"); + output.artist = input.artist.replace("'", "''"); + output.album_artist = input.album_artist.replace("'", "''"); + return output; +} + +pub fn sanitize_partialtag(input: PartialTag) -> PartialTag { + let mut output = PartialTag{ + ..PartialTag::default() + }; + + if input.path.is_some() {output.path = Some(input.path.unwrap().replace("'", "''"));}; + if input.title.is_some() {output.title = Some(input.title.unwrap().replace("'", "''"));}; + if input.album.is_some() {output.album = Some(input.album.unwrap().replace("'", "''"));}; + if input.artist.is_some() {output.artist = Some(input.artist.unwrap().replace("'", "''"));}; + if input.album_artist.is_some() {output.album_artist = Some(input.album_artist.unwrap().replace("'", "''"));}; + println!("output tag {:?}", output); + return output; +} + +pub fn write_to_socket( + socket: &mut WebSocket, + message: String, + results: Vec, +) -> Result<(), tungstenite::Error> { + socket.write_message( + serde_json::to_string(&ServerResponse { + message, + search_results: results, + }) + .unwrap() + .into(), + ) +}