From 9c1f6bee6dd53e1962596f9758cbb5f8e589a4f6 Mon Sep 17 00:00:00 2001 From: Miguel da Mota Date: Sat, 9 Mar 2024 20:09:17 +0100 Subject: [PATCH] chore: clippy improvements --- src/commands/play.rs | 18 +++-- src/commands/stop.rs | 6 +- src/music/music_events.rs | 13 ++-- src/music/music_manager.rs | 141 +++++++++++++++++++++++-------------- src/music/music_queue.rs | 24 +++++-- src/util/user_util.rs | 33 ++++----- 6 files changed, 143 insertions(+), 92 deletions(-) diff --git a/src/commands/play.rs b/src/commands/play.rs index 8fceb13..8613fd2 100644 --- a/src/commands/play.rs +++ b/src/commands/play.rs @@ -1,14 +1,15 @@ +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; pub async unsafe fn run(ctx: &Context, command: &CommandInteraction) -> CreateEmbed { let username = command.user.name.as_str(); let options = &command.data.options; - + let query = options.first().and_then(|option| { if let CommandDataOptionValue::String(query) = &option.value { Some(query) @@ -16,7 +17,7 @@ pub async unsafe fn run(ctx: &Context, command: &CommandInteraction) -> CreateEm None } }); - + if query.is_none() { return Embed::create(username, "Error 400", "There is no query provided"); } @@ -27,8 +28,15 @@ pub async unsafe fn run(ctx: &Context, command: &CommandInteraction) -> CreateEm return Embed::create(username, "GuildId not found", "Could not find guild id."); } }; - - 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 { diff --git a/src/commands/stop.rs b/src/commands/stop.rs index beee7ea..8a65e35 100644 --- a/src/commands/stop.rs +++ b/src/commands/stop.rs @@ -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 { diff --git a/src/music/music_events.rs b/src/music/music_events.rs index dbf84a0..abde30f 100644 --- a/src/music/music_events.rs +++ b/src/music/music_events.rs @@ -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 { - 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, @@ -30,7 +31,7 @@ impl EventHandler for TrackEndNotifier { }; if stopped { println!("Stopped playing successfully."); - } else { + } else { println!("Failed to stop playing."); } return None; diff --git a/src/music/music_manager.rs b/src/music/music_manager.rs index 26c0496..18c1e88 100644 --- a/src/music/music_manager.rs +++ b/src/music/music_manager.rs @@ -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"); @@ -52,7 +61,7 @@ pub async unsafe fn attempt_to_queue_song(ctx: &Context, guild_id: &GuildId, use ); } } - + // Get query let do_search = !query.starts_with("http"); let http_client = { @@ -61,30 +70,33 @@ pub async unsafe fn attempt_to_queue_song(ctx: &Context, guild_id: &GuildId, use .cloned() .expect("Guaranteed to exist in the typemap.") }; - + // Create source let mut src = if do_search { YoutubeDl::new_search(http_client, query.to_string()) } else { 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 @@ -99,18 +111,32 @@ pub async unsafe fn attempt_to_queue_song(ctx: &Context, guild_id: &GuildId, use cmdctx: Arc::new(ctx.clone()), }, ); - + // Get metadata let metadata = src.aux_metadata().await.expect("Cannot get metadata"); 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) { @@ -118,25 +144,28 @@ pub async unsafe fn play_song(ctx: &Context, guild_id: &GuildId, target: Youtube .await .expect("Cannot get Songbird.") .clone(); - + if !user_util::is_self_connected_to_vc(ctx, guild_id).await { println!("Bot is not connected to a VC, cannot play."); 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()) - } else { - music_queue::delete_queue(guild_id); // Clear queue - + if !stopped { Embed::create( username, - "I stopped and left", - "Just like your girlfriend.", + "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.") } } @@ -188,10 +225,8 @@ pub async fn stop(ctx: &Context, guild_id: &GuildId) -> Result 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 + Ok(false) // No handler, so it's already stopped } diff --git a/src/music/music_queue.rs b/src/music/music_queue.rs index 77b20aa..3d6a2ff 100644 --- a/src/music/music_queue.rs +++ b/src/music/music_queue.rs @@ -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, pub now_playing: Option, @@ -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, now_playing: Option) { - 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, 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 { 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 @@ -63,4 +73,4 @@ pub unsafe fn set_now_playing(guild_id: &GuildId, now_playing: Option pub unsafe fn get_now_playing(guild_id: &GuildId) -> &Option { let queue = get_queue(guild_id); &queue.now_playing -} \ No newline at end of file +} diff --git a/src/util/user_util.rs b/src/util/user_util.rs index 8e7bf74..32c5423 100644 --- a/src/util/user_util.rs +++ b/src/util/user_util.rs @@ -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 { - 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 HashMap{ +pub async fn get_voice_states(ctx: &Context, guild_id: &GuildId) -> HashMap { 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()