|
@@ -16,9 +16,11 @@ use std::time::Duration;
|
|
|
use std::sync::Arc;
|
|
|
use tokio::sync::Mutex;
|
|
|
use tokio::time::sleep;
|
|
|
+use tokio::task::JoinHandle;
|
|
|
|
|
|
pub struct AudioState {
|
|
|
queue: SongQueue,
|
|
|
+ in_flight: usize,
|
|
|
handler: Arc<SerenityMutex<Call>>,
|
|
|
current_song: Option<Song>,
|
|
|
track_handle: Option<TrackHandle>,
|
|
@@ -33,6 +35,7 @@ impl AudioState {
|
|
|
pub fn new(handler: Arc<SerenityMutex<Call>>, ctx: &Context, msg: &Message) -> Arc<Mutex<AudioState>> {
|
|
|
let audio_state = AudioState {
|
|
|
queue: SongQueue::new(),
|
|
|
+ in_flight: 0,
|
|
|
handler,
|
|
|
current_song: None,
|
|
|
track_handle: None,
|
|
@@ -76,9 +79,12 @@ impl AudioState {
|
|
|
let song = match song {
|
|
|
Some(song) => song,
|
|
|
None => {
|
|
|
- let mut handler = state.handler.lock().await;
|
|
|
- if let Err(e) = handler.leave().await {
|
|
|
- println!("Error leaving channel: {:?}", e);
|
|
|
+ state.current_song = None;
|
|
|
+ if state.in_flight == 0 {
|
|
|
+ let mut handler = state.handler.lock().await;
|
|
|
+ if let Err(e) = handler.leave().await {
|
|
|
+ println!("Error leaving channel: {:?}", e);
|
|
|
+ }
|
|
|
}
|
|
|
return;
|
|
|
}
|
|
@@ -124,14 +130,26 @@ impl AudioState {
|
|
|
state.track_handle = Some(handle);
|
|
|
}
|
|
|
|
|
|
- pub async fn add_audio(audio_state: Arc<Mutex<AudioState>>, song: Song) {
|
|
|
- let mut state = audio_state.lock().await;
|
|
|
- state.queue.push(vec![song]);
|
|
|
- if state.current_song.is_none() {
|
|
|
- let audio_state = audio_state.clone();
|
|
|
- tokio::spawn(async {
|
|
|
- AudioState::play_audio(audio_state).await;
|
|
|
- });
|
|
|
+ pub async fn add_audio(audio_state: Arc<Mutex<AudioState>>, song: JoinHandle<Option<Song>>) {
|
|
|
+ {
|
|
|
+ let mut state = audio_state.lock().await;
|
|
|
+ state.in_flight += 1;
|
|
|
+ }
|
|
|
+ {
|
|
|
+ if let Ok(Some(song)) = song.await {
|
|
|
+ let mut state = audio_state.lock().await;
|
|
|
+ state.queue.push(vec![song]);
|
|
|
+ if state.current_song.is_none() {
|
|
|
+ let audio_state = audio_state.clone();
|
|
|
+ tokio::spawn(async {
|
|
|
+ AudioState::play_audio(audio_state).await;
|
|
|
+ });
|
|
|
+ }
|
|
|
+ }
|
|
|
+ }
|
|
|
+ {
|
|
|
+ let mut state = audio_state.lock().await;
|
|
|
+ state.in_flight -= 1;
|
|
|
}
|
|
|
}
|
|
|
|