chore: clippy improvements

This commit is contained in:
Miguel da Mota 2024-03-09 20:09:17 +01:00
parent e1cf394362
commit 9c1f6bee6d
6 changed files with 143 additions and 92 deletions

View file

@ -1,7 +1,8 @@
use crate::music::music_manager;
use serenity::all::{CommandDataOptionValue, CommandInteraction, Context};
use serenity::builder::{CreateCommand, CreateCommandOption, CreateEmbed};
use serenity::model::application::CommandOptionType;
use crate::music::music_manager;
use crate::util::embed::Embed;
@ -28,7 +29,14 @@ pub async unsafe fn run(ctx: &Context, command: &CommandInteraction) -> CreateEm
}
};
music_manager::attempt_to_queue_song(&ctx, &guild_id, &command.user.id, &command.user.name, query.unwrap()).await
music_manager::attempt_to_queue_song(
ctx,
guild_id,
&command.user.id,
&command.user.name,
query.unwrap(),
)
.await
}
pub fn register() -> CreateCommand {

View file

@ -1,7 +1,7 @@
use serenity::all::{CommandInteraction, Context};
use serenity::builder::{CreateCommand, CreateEmbed};
use crate::music::music_manager;
use crate::util::embed::Embed;
use serenity::all::{CommandInteraction, Context};
use serenity::builder::{CreateCommand, CreateEmbed};
pub async unsafe fn run(ctx: &Context, command: &CommandInteraction) -> CreateEmbed {
let username = command.user.name.as_str();
@ -13,7 +13,7 @@ pub async unsafe fn run(ctx: &Context, command: &CommandInteraction) -> CreateEm
}
};
music_manager::attempt_to_stop(&ctx, &guild_id, &command.user.id, &command.user.name).await
music_manager::attempt_to_stop(ctx, guild_id, &command.user.id, &command.user.name).await
}
pub fn register() -> CreateCommand {

View file

@ -1,8 +1,8 @@
use std::sync::Arc;
use crate::music::{music_manager, music_queue};
use serenity::all::{ChannelId, GuildId, Http};
use serenity::async_trait;
use songbird::{Event, EventContext, EventHandler};
use crate::music::{music_manager, music_queue};
use std::sync::Arc;
pub struct TrackEndNotifier {
pub guild_id: GuildId,
@ -14,12 +14,13 @@ pub struct TrackEndNotifier {
#[async_trait]
impl EventHandler for TrackEndNotifier {
async fn act(&self, ctx: &EventContext<'_>) -> Option<Event> {
unsafe { // TODO: Does this need to be unsafe?
if let EventContext::Track(track_list) = ctx {
unsafe {
// TODO: Does this need to be unsafe?
if let EventContext::Track(..) = ctx {
println!("The track ended!");
let music_queue = music_queue::get_queue(&self.guild_id);
let q = &music_queue.queue;
if q.len() == 0 {
if q.is_empty() {
// No more songs in queue, exit the vc
let stopped = match music_manager::stop(&self.cmdctx, &self.guild_id).await {
Ok(stopped) => stopped,

View file

@ -1,26 +1,35 @@
use std::sync::{Arc};
use std::time::Duration;
use serenity::all::{Context, CreateEmbed, GuildId, UserId};
use songbird::{Event, TrackEvent};
use songbird::error::JoinError;
use songbird::input::{Compose, YoutubeDl};
use crate::HttpKey;
use crate::music::{music_events, music_queue};
use crate::util::embed::Embed;
use crate::util::user_util;
use crate::util::user_util::get_vc_id;
use crate::HttpKey;
use serenity::all::{Context, CreateEmbed, GuildId, UserId};
use songbird::error::JoinError;
use songbird::input::{Compose, YoutubeDl};
use songbird::{Event, TrackEvent};
use std::sync::Arc;
use std::time::Duration;
pub async unsafe fn attempt_to_queue_song(ctx: &Context, guild_id: &GuildId, user_id: &UserId, username: &str, query: &str) -> CreateEmbed {
pub async unsafe fn attempt_to_queue_song(
ctx: &Context,
guild_id: &GuildId,
user_id: &UserId,
username: &str,
query: &str,
) -> CreateEmbed {
if !user_util::is_user_connected_to_vc(ctx, guild_id, user_id).await {
return Embed::create(username, "You are not connected to a VC", "Connect to my VC to control the music.");
return Embed::create(
username,
"You are not connected to a VC",
"Connect to my VC to control the music.",
);
}
let connect_to = match get_vc_id(ctx, &guild_id, &user_id).await {
let connect_to = match get_vc_id(ctx, guild_id, user_id).await {
Some(channel_id) => channel_id,
None => {
return Embed::create(username, "Error", "Cannot get channel id");
}
};
let manager = &songbird::get(ctx) // TODO match
@ -28,18 +37,18 @@ pub async unsafe fn attempt_to_queue_song(ctx: &Context, guild_id: &GuildId, use
.expect("Cannot get Songbird.")
.clone();
let self_channel = user_util::get_self_vc_id(ctx, &guild_id).await;
if !user_util::is_self_connected_to_vc(ctx, &guild_id).await {
let self_channel = user_util::get_self_vc_id(ctx, guild_id).await;
if !user_util::is_self_connected_to_vc(ctx, guild_id).await {
// self is connected to vc, check if user is in same vc
if self_channel.is_none() { // TODO This could maybe be removed?
if self_channel.is_none() {
// TODO This could maybe be removed?
// Connect to VC
manager
.join(*guild_id, connect_to)
.await
.expect("Cannot connect>...");
}
} else {
let self_channel = self_channel.expect("Cannot get self channel");
@ -69,22 +78,25 @@ pub async unsafe fn attempt_to_queue_song(ctx: &Context, guild_id: &GuildId, use
YoutubeDl::new(http_client, query.to_string())
};
let currently_playing = music_queue::get_now_playing(&guild_id);
music_queue::add_to_queue(&guild_id, src.clone());
let currently_playing = music_queue::get_now_playing(guild_id);
music_queue::add_to_queue(guild_id, src.clone());
if currently_playing.is_some() {
// Add to queue
return Embed::create(username, "Added to queue", "The song was added to the queue.");
return Embed::create(
username,
"Added to queue",
"The song was added to the queue.",
);
}
let query = music_queue::get_head(&guild_id).expect("Cannot get head of queue");
music_queue::set_now_playing(&guild_id, Some(src.clone()));
let _query = music_queue::get_head(guild_id).expect("Cannot get head of queue");
music_queue::set_now_playing(guild_id, Some(src.clone()));
let handler_lock = match manager.get(*guild_id) {
Some(handler) => handler,
None => {
return Embed::create("", "Error", "Cannot get handler");
},
}
};
// Start playing
@ -105,12 +117,26 @@ pub async unsafe fn attempt_to_queue_song(ctx: &Context, guild_id: &GuildId, use
let title = metadata.title.unwrap_or("Unknown title".to_string());
let author = metadata.artist.unwrap_or("Unknown artist".to_string());
let duration = metadata.duration.unwrap_or(Duration::from_millis(0));
let thumbnail = metadata.thumbnail.unwrap_or("https://http.cat/images/404.jpg".to_string());
let link = metadata.source_url.unwrap_or("https://piped.moonleay.net/404".to_string());
let thumbnail = metadata
.thumbnail
.unwrap_or("https://http.cat/images/404.jpg".to_string());
let link = metadata
.source_url
.unwrap_or("https://piped.moonleay.net/404".to_string());
Embed::create(username, "Added to queue", format!("{} by {} ({}min {}sec) was added to the queue.\n [[Link]({})]",
title, author, duration.as_secs() / 60, duration.as_secs() % 60, link))
.thumbnail(thumbnail)
Embed::create(
username,
"Added to queue",
format!(
"{} by {} ({}min {}sec) was added to the queue.\n [[Link]({})]",
title,
author,
duration.as_secs() / 60,
duration.as_secs() % 60,
link
),
)
.thumbnail(thumbnail)
}
pub async unsafe fn play_song(ctx: &Context, guild_id: &GuildId, target: YoutubeDl) {
@ -124,19 +150,22 @@ pub async unsafe fn play_song(ctx: &Context, guild_id: &GuildId, target: Youtube
return;
}
music_queue::set_now_playing(&guild_id, Some(target.clone()));
music_queue::set_now_playing(guild_id, Some(target.clone()));
let handler_lock = match manager.get(*guild_id) {
Some(handler) => handler,
None => {
return
},
None => return,
};
let mut handler = handler_lock.lock().await;
let _ = handler.play_input(target.into()); // TODO: Add event handlers
}
pub async unsafe fn attempt_to_stop(ctx: &Context, guild_id: &GuildId, user_id: &UserId, username: &str) -> CreateEmbed {
pub async unsafe fn attempt_to_stop(
ctx: &Context,
guild_id: &GuildId,
user_id: &UserId,
username: &str,
) -> CreateEmbed {
if !user_util::is_self_connected_to_vc(ctx, guild_id).await {
// Bot is not connectd to vc; no need to dc
return Embed::create(
@ -145,8 +174,12 @@ pub async unsafe fn attempt_to_stop(ctx: &Context, guild_id: &GuildId, user_id:
"And therefore there is no need to do anything.",
);
}
let self_channel = user_util::get_self_vc_id(ctx, &guild_id).await.expect("Cannot get self channel");
let connect_to = get_vc_id(ctx, &guild_id, &user_id).await.expect("Cannot get channel id");
let self_channel = user_util::get_self_vc_id(ctx, guild_id)
.await
.expect("Cannot get self channel");
let connect_to = get_vc_id(ctx, guild_id, user_id)
.await
.expect("Cannot get channel id");
// Check if user is in the same VC as the bot
if self_channel != connect_to {
@ -161,20 +194,24 @@ pub async unsafe fn attempt_to_stop(ctx: &Context, guild_id: &GuildId, user_id:
Ok(stopped) => stopped,
Err(e) => {
println!("Error while stopping: {:?}", e);
return Embed::create(username, "There was an error", "Tell moonleay to check the logs.".to_string());
return Embed::create(
username,
"There was an error",
"Tell moonleay to check the logs.".to_string(),
);
}
};
return if !stopped {
Embed::create(username, "Can't stop, what ain't running.", "I am not connected. I cant stop doing something, when I'm not doing it".to_string())
if !stopped {
Embed::create(
username,
"Can't stop, what ain't running.",
"I am not connected. I cant stop doing something, when I'm not doing it".to_string(),
)
} else {
music_queue::delete_queue(guild_id); // Clear queue
Embed::create(
username,
"I stopped and left",
"Just like your girlfriend.",
)
Embed::create(username, "I stopped and left", "Just like your girlfriend.")
}
}
@ -188,10 +225,8 @@ pub async fn stop(ctx: &Context, guild_id: &GuildId) -> Result<bool, JoinError>
let has_handler = manager.get(*guild_id).is_some();
if has_handler {
if let Err(e) = manager.remove(*guild_id).await {
return Err(e); // Failed to remove handler
}
return Ok(true) // Handler removed
manager.remove(*guild_id).await?;
return Ok(true); // Handler removed
}
Ok(false) // No handler, so it's already stopped
}

View file

@ -1,7 +1,8 @@
use serenity::all::GuildId;
use songbird::input::YoutubeDl;
pub struct MusicQueue { // God this sucks. This needs to be reprogrammed properly.
pub struct MusicQueue {
// God this sucks. This needs to be reprogrammed properly.
guild_id: GuildId,
pub queue: Vec<YoutubeDl>,
pub now_playing: Option<YoutubeDl>,
@ -20,14 +21,20 @@ pub unsafe fn get_queue(guild_id: &GuildId) -> &MusicQueue {
now_playing: None,
};
MUSIC_QUEUE.push(new_queue);
MUSIC_QUEUE.iter().find(|q| q.guild_id == *guild_id).expect("Cannot get queue")
MUSIC_QUEUE
.iter()
.find(|q| q.guild_id == *guild_id)
.expect("Cannot get queue")
}
}
}
unsafe fn update_queue(guild_id: &GuildId, queue: Vec<YoutubeDl>, now_playing: Option<YoutubeDl>) {
let index = MUSIC_QUEUE.iter().position(|q| q.guild_id == *guild_id).expect("Cannot get index");
MUSIC_QUEUE[index] = MusicQueue{
let index = MUSIC_QUEUE
.iter()
.position(|q| q.guild_id == *guild_id)
.expect("Cannot get index");
MUSIC_QUEUE[index] = MusicQueue {
guild_id: *guild_id,
queue,
now_playing,
@ -35,7 +42,10 @@ unsafe fn update_queue(guild_id: &GuildId, queue: Vec<YoutubeDl>, now_playing: O
}
pub unsafe fn delete_queue(guild_id: &GuildId) {
let index = MUSIC_QUEUE.iter().position(|q| q.guild_id == *guild_id).expect("Cannot get index");
let index = MUSIC_QUEUE
.iter()
.position(|q| q.guild_id == *guild_id)
.expect("Cannot get index");
MUSIC_QUEUE.remove(index);
}
@ -49,7 +59,7 @@ pub unsafe fn add_to_queue(guild_id: &GuildId, input: YoutubeDl) {
pub unsafe fn get_head(guild_id: &GuildId) -> Option<YoutubeDl> {
let queue = get_queue(guild_id);
let mut q = queue.queue.clone();
let result = q.first().map(|s| s.clone());
let result = q.first().cloned();
q.remove(0);
update_queue(guild_id, q, queue.now_playing.clone());
result

View file

@ -1,52 +1,47 @@
use std::collections::HashMap;
use serenity::all::{ChannelId, Context, Guild, GuildId, PartialGuild, UserId, VoiceState};
use std::collections::HashMap;
/// Request a guild by id, get it from cache
pub fn request_guild(ctx: &Context, guild_id: &GuildId) -> Guild {
let guild = match guild_id.to_guild_cached(&ctx.cache) {
match guild_id.to_guild_cached(&ctx.cache) {
Some(guild) => guild.clone(),
None => {
panic!("Cannot get guild with id {:?}!", guild_id);
}
};
guild
}
}
/// Request a guild by id, get it from Discord, not from cache, this is a partial guild
pub async fn request_partial_guild(ctx: &Context, guild_id: &GuildId) -> PartialGuild {
let guild = match ctx.http.get_guild(*guild_id).await {
match ctx.http.get_guild(*guild_id).await {
Ok(guild) => guild,
Err(error) => {
panic!("error whilest getting guild from Discord {}", error);
}
};
guild
}
}
/// Get the voice channel id of a user
pub async fn get_vc_id(ctx: &Context, guild_id: &GuildId, user_id: &UserId) -> Option<ChannelId> {
let guild = request_guild(&ctx, guild_id);
let guild = request_guild(ctx, guild_id);
guild
.voice_states
.get(user_id)
.and_then(|voice_state| voice_state.channel_id)
}
/// Check if the bot is connected to a voice channel
pub async fn is_self_connected_to_vc(ctx: &Context, guild_id: &GuildId) -> bool {
let channel_id = get_self_vc_id(ctx, guild_id);
!channel_id.await.is_none()
channel_id.await.is_some()
}
/// Check if a user is connected to a voice channel
pub async fn is_user_connected_to_vc(ctx: &Context, guild_id: &GuildId, user_id: &UserId) -> bool {
let channel_id = get_vc_id(ctx, guild_id, user_id).await;
!channel_id.is_none()
channel_id.is_some()
}
/// Get the voice channel id of the bot
@ -57,15 +52,17 @@ pub async fn get_self_vc_id(ctx: &Context, guild_id: &GuildId) -> Option<Channel
}
/// Get all voice states of a guild
pub async fn get_voice_states(ctx: &Context, guild_id: &GuildId) -> HashMap<UserId, VoiceState>{
pub async fn get_voice_states(ctx: &Context, guild_id: &GuildId) -> HashMap<UserId, VoiceState> {
let guild = request_guild(ctx, guild_id);
let voice_states = guild.voice_states.clone();
voice_states
guild.voice_states.clone()
}
/// Get the amount of members in a voice channel
pub async fn get_amount_of_members_in_vc(ctx: &Context, guild_id: &GuildId, channel_id: &ChannelId,) -> usize {
pub async fn get_amount_of_members_in_vc(
ctx: &Context,
guild_id: &GuildId,
channel_id: &ChannelId,
) -> usize {
let voice_states = get_voice_states(ctx, guild_id).await;
let amount = voice_states
.iter()