Rustendo/src/music/music_queue.rs

81 lines
2.3 KiB
Rust

use serenity::all::GuildId;
use songbird::input::YoutubeDl;
use songbird::tracks::TrackHandle;
use tokio::sync::Mutex;
use std::collections::{HashMap, VecDeque};
use std::sync::Arc;
type MusicQueueItem = Arc<Mutex<MusicQueue>>;
#[derive(Debug)]
pub struct MusicQueue {
pub queue: VecDeque<YoutubeDl>,
pub now_playing: Option<YoutubeDl>,
pub now_playing_track_handle: Option<TrackHandle>
}
lazy_static! {
static ref HASHMAP: Mutex<HashMap<GuildId, MusicQueueItem>> = Mutex::new(HashMap::new());
}
async fn get_music_queue(guild_id: &GuildId) -> MusicQueueItem {
let mut queues = HASHMAP.lock().await;
queues
.entry(*guild_id)
.or_insert(Arc::new(Mutex::new(MusicQueue {
queue: VecDeque::new(),
now_playing: None,
now_playing_track_handle: None,
})))
.clone()
}
pub async fn with_music_queue<F, T>(guild_id: &GuildId, f: F) -> T
where
F: FnOnce(&mut MusicQueue) -> T,
T: Send,
{
let queue = get_music_queue(guild_id).await;
let mut queue = queue.lock().await;
f(&mut queue)
}
pub async fn delete_queue(guild_id: &GuildId) {
with_music_queue(guild_id, |queue| {
queue.now_playing = None;
queue.queue.clear();
})
.await;
}
pub async fn add_to_queue(guild_id: &GuildId, input: YoutubeDl) {
with_music_queue(guild_id, |queue| queue.queue.push_back(input)).await;
}
/// Get next track in queue
pub async fn next(guild_id: &GuildId) -> Option<YoutubeDl> {
with_music_queue(guild_id, |queue| queue.queue.pop_front()).await
}
pub async fn set_now_playing(guild_id: &GuildId, now_playing: Option<YoutubeDl>) {
with_music_queue(guild_id, |queue| queue.now_playing = now_playing).await;
}
pub async fn get_now_playing(guild_id: &GuildId) -> Option<YoutubeDl> {
with_music_queue(guild_id, |queue| queue.now_playing.to_owned()).await
}
pub async fn set_now_playing_track_handle(guild_id: &GuildId, track_handle: Option<TrackHandle>) {
with_music_queue(guild_id, |queue| queue.now_playing_track_handle = track_handle).await
}
pub async fn get_now_playing_track_handle(guild_id: &GuildId) -> Option<TrackHandle> {
with_music_queue(guild_id, | queue| queue.now_playing_track_handle.to_owned()).await
}
pub async fn is_empty(guild_id: &GuildId) -> bool {
with_music_queue(guild_id, |queue| queue.queue.is_empty()).await
}