paginate /queue
All checks were successful
tests / fmt (push) Successful in 2m15s
tests / fmt (pull_request) Successful in 1m35s
tests / test (push) Successful in 2m39s
tests / pre-commit (push) Successful in 2m37s
tests / clippy (push) Successful in 2m44s
tests / build (push) Successful in 3m4s
tests / clippy (pull_request) Successful in 2m49s
tests / build (pull_request) Successful in 2m53s
tests / test (pull_request) Successful in 2m51s
tests / pre-commit (pull_request) Successful in 1m34s

This commit is contained in:
2024-06-13 00:49:11 +02:00
parent b4a1efb22a
commit a0ac87959b
14 changed files with 1031 additions and 535 deletions

View File

@@ -9,14 +9,14 @@ pub(crate) async fn delete(
state: State,
) -> Result<(), Box<dyn Error + Send + Sync + 'static>> {
let admin = env::var("ADMIN")?.parse::<u64>()?;
if msg.author.id != Id::from(NonZeroU64::new(admin).unwrap()) {
if msg.author.id != Id::from(NonZeroU64::new(admin).expect("Could not get author id")) {
return Ok(());
}
let n = msg
.content
.split(' ')
.last()
.unwrap()
.unwrap_or("1")
.parse::<u16>()
.unwrap_or(1);
if n > 100 {

View File

@@ -2,8 +2,8 @@ use crate::state::State;
use std::error::Error;
use tracing::debug;
use twilight_model::{
application::interaction::Interaction,
channel::message::MessageFlags,
gateway::payload::incoming::InteractionCreate,
http::interaction::{InteractionResponse, InteractionResponseType},
id::{
marker::{GuildMarker, UserMarker},
@@ -42,7 +42,7 @@ pub(crate) async fn join_channel(
}
pub(crate) async fn join(
interaction: Interaction,
interaction: Box<InteractionCreate>,
state: State,
) -> Result<(), Box<dyn Error + Send + Sync + 'static>> {
debug!(

View File

@@ -1,9 +1,9 @@
use crate::state::State;
use std::error::Error;
use twilight_model::application::interaction::Interaction;
use twilight_model::gateway::payload::incoming::InteractionCreate;
pub(crate) async fn leave(
interaction: Interaction,
interaction: Box<InteractionCreate>,
state: State,
) -> Result<(), Box<dyn Error + Send + Sync + 'static>> {
tracing::debug!(

View File

@@ -10,7 +10,7 @@ pub(crate) use pause::pause;
mod play;
pub(crate) use play::play;
mod queue;
pub(crate) mod queue;
pub(crate) use queue::queue;
mod resume;

View File

@@ -1,14 +1,14 @@
use crate::state::State;
use std::error::Error;
use twilight_model::{
application::interaction::Interaction,
channel::message::MessageFlags,
gateway::payload::incoming::InteractionCreate,
http::interaction::{InteractionResponse, InteractionResponseType},
};
use twilight_util::builder::InteractionResponseDataBuilder;
pub(crate) async fn pause(
interaction: Interaction,
interaction: Box<InteractionCreate>,
state: State,
) -> Result<(), Box<dyn Error + Send + Sync + 'static>> {
tracing::debug!(

View File

@@ -1,20 +1,55 @@
use crate::colors;
use crate::commands::join::join_channel;
use crate::metadata::{Metadata, MetadataMap};
use crate::state::State;
use serde_json::Value;
use serde::{Deserialize, Serialize};
use songbird::input::{Compose, YoutubeDl};
use std::io::{BufRead, BufReader};
use std::{error::Error, ops::Sub, time::Duration};
use tokio::process::Command;
use tracing::debug;
use twilight_model::application::interaction::Interaction;
use twilight_model::channel::message::MessageFlags;
use twilight_model::gateway::payload::incoming::InteractionCreate;
use twilight_model::http::interaction::{InteractionResponse, InteractionResponseType};
use twilight_util::builder::embed::EmbedBuilder;
use twilight_util::builder::InteractionResponseDataBuilder;
use url::Url;
#[derive(Debug, Serialize, Deserialize)]
struct YouTubeTrack {
url: String,
title: String,
channel: String,
playlist: String,
playlist_id: String,
duration_string: String,
}
fn build_playlist_url(playlist_id: &str) -> String {
format!("https://www.youtube.com/playlist?list={}", playlist_id)
}
async fn get_tracks(
url: String,
) -> Result<Vec<YouTubeTrack>, Box<dyn Error + Send + Sync + 'static>> {
let output = Command::new("yt-dlp")
.args(vec![&url, "--flat-playlist", "-j"])
.output()
.await?;
let reader = BufReader::new(output.stdout.as_slice());
let tracks: Vec<YouTubeTrack> = reader
.lines()
.map_while(Result::ok)
.flat_map(|line| serde_json::from_str(&line))
.collect();
tracing::debug!("tracks: {:?}", tracks);
Ok(tracks)
}
pub(crate) async fn play(
interaction: Interaction,
interaction: Box<InteractionCreate>,
state: State,
query: String,
) -> Result<(), Box<dyn Error + Send + Sync + 'static>> {
@@ -25,14 +60,16 @@ pub(crate) async fn play(
);
let content = format!("Adding track(s) to the queue: {}", query);
let yellow = 0xFE_E7_5C;
let embeds = vec![EmbedBuilder::new()
.description(content)
.color(yellow)
.color(colors::YELLOW)
.build()];
let interaction_response_data = InteractionResponseDataBuilder::new().embeds(embeds).build();
let interaction_response_data = InteractionResponseDataBuilder::new()
.flags(MessageFlags::LOADING)
.embeds(embeds)
.build();
let response = InteractionResponse {
kind: InteractionResponseType::ChannelMessageWithSource,
kind: InteractionResponseType::DeferredChannelMessageWithSource,
data: Some(interaction_response_data),
};
state
@@ -59,7 +96,26 @@ pub(crate) async fn play(
debug!("query: {:?}", query);
let urls = get_playlist_urls(query).await?;
let tracks = get_tracks(query).await?;
if tracks.len() > 1 {
let first_track = tracks.first().unwrap();
let content = format!(
"Adding playlist [{}]({})",
first_track.playlist,
build_playlist_url(&first_track.playlist_id)
);
let embeds = vec![EmbedBuilder::new()
.description(content)
.color(colors::BLURPLE)
.build()];
state
.http
.interaction(interaction.application_id)
.update_response(&interaction.token)
.embeds(Some(&embeds))?
.await?;
}
if let Some(call_lock) = state.songbird.get(guild_id) {
let call = call_lock.lock().await;
@@ -67,7 +123,9 @@ pub(crate) async fn play(
}
let mut tracks_added = vec![];
for url in urls {
for track in &tracks {
tracing::debug!("track: {:?}", track);
let url = track.url.clone();
let mut src = YoutubeDl::new(reqwest::Client::new(), url.to_string());
if let Ok(metadata) = src.aux_metadata().await {
debug!("metadata: {:?}", metadata);
@@ -99,59 +157,38 @@ pub(crate) async fn play(
match num_tracks_added {
0 => {}
1 => {
let track = tracks_added.first().unwrap().clone();
let title = track.1.unwrap();
let url = track.0;
let (title, url) = if let Some(track) = tracks_added.first() {
let track = track.clone();
(track.1.unwrap_or("Unknown".to_string()), track.0)
} else {
("Unknown".to_string(), "".to_string())
};
content = format!("Added [{}]({}) to the queue", title, url);
}
_ => {
content = format!("Added {} tracks to the queue:\n", num_tracks_added);
for track in tracks_added.into_iter().take(num_tracks_added.min(3)) {
let title = track.1.unwrap();
let url = track.0;
content.push_str(&format!(" \"[{}]({})\"\n", title, url));
}
let first_track = tracks.first().unwrap();
content.push_str(&format!(
"Adding playlist: [{}]({})\n",
&first_track.playlist,
build_playlist_url(&first_track.playlist_id)
));
content.push_str(&format!(
"Added {} tracks to the queue:\n",
num_tracks_added
));
}
}
let blurple = 0x58_65_F2;
let embeds = vec![EmbedBuilder::new()
.description(content)
.color(blurple)
.color(colors::BLURPLE)
.build()];
state
.http
.interaction(interaction.application_id)
.update_response(&interaction.token)
.embeds(Some(&embeds))
.unwrap()
.embeds(Some(&embeds))?
.await?;
Ok(())
}
async fn get_playlist_urls(
url: String,
) -> Result<Vec<String>, Box<dyn Error + Send + Sync + 'static>> {
let output = Command::new("yt-dlp")
.args(vec![&url, "--flat-playlist", "-j"])
.output()
.await?;
let reader = BufReader::new(output.stdout.as_slice());
let urls = reader
.lines()
.map_while(Result::ok)
.map(|line| {
let entry: Value = serde_json::from_str(&line).unwrap();
entry
.get("webpage_url")
.unwrap()
.as_str()
.unwrap()
.to_string()
})
.collect();
Ok(urls)
}

View File

@@ -1,16 +1,106 @@
use songbird::tracks::TrackHandle;
use twilight_model::channel::message::component::{ActionRow, Button, ButtonStyle};
use twilight_model::channel::message::{Component, Embed, MessageFlags, ReactionType};
use twilight_model::gateway::payload::incoming::InteractionCreate;
use twilight_model::http::interaction::InteractionResponse;
use twilight_model::http::interaction::InteractionResponseType;
use twilight_model::{
application::interaction::Interaction, channel::message::MessageFlags,
http::interaction::InteractionResponse,
};
use twilight_util::builder::embed::EmbedBuilder;
use twilight_util::builder::InteractionResponseDataBuilder;
use crate::colors;
use crate::{metadata::MetadataMap, state::State};
use std::error::Error;
pub(crate) const TRACKS_PER_PAGE: usize = 5;
fn format_duration(duration: std::time::Duration) -> String {
let res = duration.as_secs();
let hours = res / (60 * 60);
let res = res - hours * 60 * 60;
let minutes = res / 60;
let res = res - minutes * 60;
let seconds = res;
let mut s = String::new();
if hours > 0 {
s.push_str(format!("{:02}:", hours).as_str());
}
s.push_str(format!("{:02}:{:02}", minutes, seconds).as_str());
s
}
pub(crate) async fn build_queue_embeds(queue: &[TrackHandle], page: usize) -> Vec<Embed> {
let mut message = String::new();
if queue.is_empty() {
message.push_str("There are no tracks in the queue.\n");
}
for track in queue
.iter()
.skip(TRACKS_PER_PAGE * page)
.take(TRACKS_PER_PAGE)
{
let map = track.typemap().read().await;
let metadata = map
.get::<MetadataMap>()
.expect("Could not get metadata map");
message.push_str(
format!(
"* [{}]({})",
metadata.title.clone().unwrap_or("Unknown".to_string()),
metadata.url,
)
.as_str(),
);
if let Some(duration) = metadata.duration {
message.push_str(" (");
message.push_str(&format_duration(duration));
message.push(')');
}
message.push('\n');
}
message.push('\n');
let max_pages = queue.len() / TRACKS_PER_PAGE;
if max_pages > 0 {
message.push_str(&format!("page {}/{}", 1 + page, 1 + max_pages));
}
vec![EmbedBuilder::new()
.description(&message)
.color(colors::BLURPLE)
.build()]
}
pub(crate) fn build_action_row(page: usize, max_pages: usize) -> Vec<Component> {
if max_pages == 0 {
return Vec::new();
}
vec![Component::ActionRow(ActionRow {
components: vec![
Component::Button(Button {
custom_id: Some(format!("page:{}", page as i32 - 1)),
style: ButtonStyle::Primary,
label: Some("Previous page".to_string()),
emoji: Some(ReactionType::Unicode {
name: "⬅️".to_string(),
}),
url: None,
disabled: page == 0,
}),
Component::Button(Button {
custom_id: Some(format!("page:{}", page + 1)),
style: ButtonStyle::Primary,
label: Some("Next page".to_string()),
emoji: Some(ReactionType::Unicode {
name: "➡️".to_string(),
}),
url: None,
disabled: page >= max_pages,
}),
],
})]
}
pub(crate) async fn queue(
interaction: Interaction,
interaction: Box<InteractionCreate>,
state: State,
) -> Result<(), Box<dyn Error + Send + Sync + 'static>> {
tracing::debug!(
@@ -22,59 +112,42 @@ pub(crate) async fn queue(
let Some(guild_id) = interaction.guild_id else {
return Ok(());
};
let content = "Fetching queue".to_string();
let embeds = vec![EmbedBuilder::new()
.description(content)
.color(colors::YELLOW)
.build()];
let interaction_response_data = InteractionResponseDataBuilder::new()
.embeds(embeds)
.flags(MessageFlags::LOADING)
.build();
let response = InteractionResponse {
kind: InteractionResponseType::DeferredChannelMessageWithSource,
data: Some(interaction_response_data),
};
state
.http
.interaction(interaction.application_id)
.create_response(interaction.id, &interaction.token, &response)
.await?;
let mut queue = Vec::new();
if let Some(call_lock) = state.songbird.get(guild_id) {
let call = call_lock.lock().await;
let queue = call.queue().current_queue();
let mut message = String::new();
if queue.is_empty() {
message.push_str("There are no tracks in the queue.\n");
} else {
message.push_str("Next songs are:\n");
}
for track in queue.iter().take(5) {
let map = track.typemap().read().await;
let metadata = map.get::<MetadataMap>().unwrap();
message.push_str(
format!(
"* [{}]({})",
metadata.title.clone().unwrap_or("Unknown".to_string()),
metadata.url,
)
.as_str(),
);
if let Some(duration) = metadata.duration {
let res = duration.as_secs();
let hours = res / (60 * 60);
let res = res - hours * 60 * 60;
let minutes = res / 60;
let res = res - minutes * 60;
let seconds = res;
message.push_str(" (");
if hours > 0 {
message.push_str(format!("{:02}:", hours).as_str());
}
message.push_str(format!("{:02}:{:02}", minutes, seconds).as_str());
message.push(')');
}
message.push('\n');
}
let embeds = vec![EmbedBuilder::new().description(&message).build()];
let interaction_response_data = InteractionResponseDataBuilder::new()
.flags(MessageFlags::EPHEMERAL)
.embeds(embeds)
.build();
let response = InteractionResponse {
kind: InteractionResponseType::ChannelMessageWithSource,
data: Some(interaction_response_data),
};
state
.http
.interaction(interaction.application_id)
.create_response(interaction.id, &interaction.token, &response)
.await?;
queue = call.queue().current_queue();
}
let embeds = build_queue_embeds(&queue, 0).await;
let action_row = build_action_row(0, queue.len() / TRACKS_PER_PAGE);
state
.http
.interaction(interaction.application_id)
.update_response(&interaction.token)
.embeds(Some(&embeds))?
.components(Some(&action_row))?
.await?;
Ok(())
}

View File

@@ -1,14 +1,14 @@
use crate::state::State;
use std::error::Error;
use twilight_model::{
application::interaction::Interaction,
channel::message::MessageFlags,
gateway::payload::incoming::InteractionCreate,
http::interaction::{InteractionResponse, InteractionResponseType},
};
use twilight_util::builder::InteractionResponseDataBuilder;
pub(crate) async fn resume(
interaction: Interaction,
interaction: Box<InteractionCreate>,
state: State,
) -> Result<(), Box<dyn Error + Send + Sync + 'static>> {
tracing::debug!(

View File

@@ -1,6 +1,6 @@
use twilight_model::{
application::interaction::Interaction,
channel::message::MessageFlags,
gateway::payload::incoming::InteractionCreate,
http::interaction::{InteractionResponse, InteractionResponseType},
};
use twilight_util::builder::InteractionResponseDataBuilder;
@@ -9,7 +9,7 @@ use crate::state::State;
use std::error::Error;
pub(crate) async fn stop(
interaction: Interaction,
interaction: Box<InteractionCreate>,
state: State,
) -> Result<(), Box<dyn Error + Send + Sync + 'static>> {
tracing::debug!(