Bladeren bron

final cleaning up, removing debug messages

Zhizhou Ma 3 jaren geleden
bovenliggende
commit
45be2527c5
7 gewijzigde bestanden met toevoegingen van 66 en 23 verwijderingen
  1. 1 1
      .spotify_token_cache.json
  2. 18 3
      src/audio/audio.rs
  3. 39 7
      src/audio/audio_state.rs
  4. 0 2
      src/audio/loader.rs
  5. 3 3
      src/audio/song.rs
  6. 0 1
      src/audio/spotify.rs
  7. 5 6
      src/audio/subprocess.rs

+ 1 - 1
.spotify_token_cache.json

@@ -1 +1 @@
-{"access_token":"BQAlb4fCcG9jZm7Rh87q_BChrYjDFTaDiCwsRnjbUI86jVhEk7bGwpBluwLJojOTJbvZEunezyFHzbaQh6s","expires_in":3600,"expires_at":"2021-06-11T07:35:03.229668200Z","refresh_token":null,"scope":""}
+{"access_token":"BQDtmxHBq0XMlIKy8C0cp9oFRcxGaA64qwR0CbZd4JS-Sr09JkN6ZGIpwUhjxJrhwlCmFvjCup5hwAlYwCM","expires_in":3600,"expires_at":"2021-06-11T08:05:59.739209300Z","refresh_token":null,"scope":""}

+ 18 - 3
src/audio/audio.rs

@@ -26,7 +26,7 @@ use crate::util::{
 };
 
 #[group]
-#[commands(join,disconnect,play,skip,pause,resume,shuffle,clear,splay,queue)]
+#[commands(join,disconnect,play,skip,pause,resume,change_loop,shuffle,clear,splay,queue)]
 struct Audio;
 
 lazy_static! {
@@ -113,7 +113,6 @@ async fn disconnect(ctx: &Context, msg: &Message) -> CommandResult{
 #[command]
 async fn play(ctx: &Context, msg: &Message, args: Args) -> CommandResult{
     let query = args.rest();
-    println!("{}",query);
 
     let audio_state = get_audio_state(ctx, msg).await;
     let audio_state = match audio_state{
@@ -131,7 +130,6 @@ async fn play(ctx: &Context, msg: &Message, args: Args) -> CommandResult{
 #[command]
 async fn splay(ctx: &Context, msg: &Message, args: Args) -> CommandResult{
     let query = args.rest();
-    println!("{}",query);
 
     let audio_state = get_audio_state(ctx, msg).await;
     let audio_state = match audio_state{
@@ -228,6 +226,23 @@ async fn clear(ctx: &Context, msg: &Message) -> CommandResult{
     Ok(())
 }
 
+#[command]
+#[aliases("loop")]
+async fn change_loop(ctx: &Context, msg: &Message) -> CommandResult{
+    let audio_state = get_audio_state(ctx, msg).await;
+    let audio_state = match audio_state{
+        Some(audio_state) => audio_state,
+        None => return Ok(())
+    };
+
+    match AudioState::change_looping(audio_state).await {
+        Ok(true) => message_react(ctx, msg, "🔄").await,
+        Ok(false) => message_react(ctx, msg, "➡").await,
+        Err(why) => send_embed(ctx, msg, &format!("Error: {}", why)).await,
+    };
+    Ok(())
+}
+
 #[command]
 async fn queue(ctx: &Context, msg: &Message) -> CommandResult{
     let audio_state = get_audio_state(ctx, msg).await;

+ 39 - 7
src/audio/audio_state.rs

@@ -1,5 +1,6 @@
 use std::{
     sync::Arc,
+    mem::drop,
 };
 use rand::seq::SliceRandom;
 use super::{
@@ -34,6 +35,7 @@ pub struct AudioState{
     handler: Arc<SerenityMutex<Call>>,
     current_song: Mutex<Option<Song>>,
     track_handle: Mutex<Option<TrackHandle>>,
+    is_looping: Mutex<bool>,
 }
 
 impl AudioState{
@@ -43,6 +45,7 @@ impl AudioState{
             handler,
             current_song: Mutex::new(None),
             track_handle: Mutex::new(None),
+            is_looping: Mutex::new(false),
         };
         let audio_state = Arc::new(audio_state);
         {
@@ -55,10 +58,16 @@ impl AudioState{
     }
 
     async fn play_audio(audio_state: Arc<AudioState>){
-        let mut song = audio_state.queue.pop().await;
-        println!("hi3");
+        let is_looping = audio_state.is_looping.lock().await;
+        let mut song = if *is_looping{
+            let mut current_song = audio_state.current_song.lock().await;
+            current_song.take().expect("logical error: expected current_song to be non-empty")
+        }else{
+            audio_state.queue.pop().await
+        };
+        drop(is_looping);
+
         let url = song.get_url().await;
-        println!("hi4 {}", url);
         let source = ffmpeg_pcm(url).await;
         let source = match source {
             Ok(source) => source,
@@ -70,7 +79,6 @@ impl AudioState{
         let reader = Reader::Extension(source);
         let source = input::Input::float_pcm(true, reader);
 
-        println!("hi4.5");
         let mut handler = audio_state.handler.lock().await;
         
         let handle = handler.play_source(source);
@@ -88,7 +96,6 @@ impl AudioState{
         *current_song = Some(song);
         let mut track_handle = audio_state.track_handle.lock().await;
         *track_handle = Some(handle);
-        println!("hi5");
     }
 
     pub async fn add_audio(audio_state: Arc<AudioState>, query: &str, shuffle: bool){
@@ -126,6 +133,32 @@ impl AudioState{
         audio_state.queue.clear().await
     }
 
+    pub async fn change_looping(audio_state: Arc<AudioState>) -> Result<bool, String>{
+        let current_song = audio_state.current_song.lock().await;
+        if current_song.is_none() {
+            return Err("no song is playing".to_string());
+        }
+        let mut is_looping = audio_state.is_looping.lock().await;
+        *is_looping = !*is_looping;
+        Ok(*is_looping)
+        /*
+        if looping{
+            if *is_looping{
+                Err("already looping".to_string())
+            }else{
+                *is_looping = true;
+                Ok(())
+            }
+        }else{
+            if !*is_looping{
+                Err("not looping at the moment".to_string())
+            }else{
+                *is_looping = false;
+                Ok(())
+            }
+        }*/
+    }
+
     pub async fn cleanup(audio_state: Arc<AudioState>) {
         audio_state.queue.cleanup().await;
     }
@@ -136,7 +169,7 @@ impl AudioState{
             Some(song) => song.get_string().await,
             None => "*Not playing*\n".to_string(),
         };
-        format!("**Current Song:**\n{}\n**Queue:**\n{}", current_song, audio_state.queue.get_string().await)
+        format!("**Current Song:**\n{}\n\n**Queue:**\n{}", current_song, audio_state.queue.get_string().await)
     }
 }
 
@@ -149,7 +182,6 @@ struct SongEndNotifier {
 #[async_trait]
 impl VoiceEventHandler for SongEndNotifier {
     async fn act(&self, _ctx: &EventContext<'_>) -> Option<Event> {
-        println!("SongEndNotifier event has started");
         AudioState::play_audio(self.audio_state.clone()).await;
 
         None

+ 0 - 2
src/audio/loader.rs

@@ -19,8 +19,6 @@ impl Loader{
     }
     async fn loader_loop(mut work: mpsc::Receiver<Work>,){
         while let Some(work) = work.recv().await {
-            println!("hi2");
-            // update this
             let url = ytdl(&work.query).await;
     
             if let Err(err) = work.sender.send(url).await{

+ 3 - 3
src/audio/song.rs

@@ -40,10 +40,10 @@ impl Song{
         let work = Work{
             sender: tx,
             is_loaded: is_loaded.clone(),
-            query: query,
+            query,
         };
         let url_state = SongUrlState::Proc{
-            is_loaded: is_loaded,
+            is_loaded,
             receiver: rx,
             work: work.clone(),
         };
@@ -80,7 +80,7 @@ impl Song{
             Some(artist) => artist,
             None => "unknown",
         };
-        let title = match &metadata.artist{
+        let title = match &metadata.title{
             Some(title) => title,
             None => "unknown",
         };

+ 0 - 1
src/audio/spotify.rs

@@ -66,7 +66,6 @@ pub async fn get_playlist(playlist_id: &str) -> Result<Vec<(Song, Option<Work>)>
             None => continue,
         };
     }
-    println!("spotdl function finished");
     Ok(songs)
 }
 

+ 5 - 6
src/audio/subprocess.rs

@@ -10,13 +10,12 @@ use tokio::process::Command as TokioCommand;
 pub async fn ytdl(query: &str) -> String{
     let mut cmd = TokioCommand::new("youtube-dl");
     let cmd = cmd
-                       .arg("-x")
-                       .arg("--skip-download")
-                       .arg("--get-url")
-                       .arg("--audio-quality").arg("128k")
-                       .arg(query);
+        .arg("-x")
+        .arg("--skip-download")
+        .arg("--get-url")
+        .arg("--audio-quality").arg("128k")
+        .arg(query);
     let out = cmd.output().await.unwrap();
-    println!("ytdl process finished");
     String::from_utf8(out.stdout).unwrap()
 }
 //  -> Result<Box<dyn Read + Send>, String>