Cleanup, working on getting play to work

This commit is contained in:
Benjamin Sherriff
2023-10-07 22:55:31 -04:00
parent 3ca91c7765
commit 690a327084
9 changed files with 109 additions and 119 deletions

View File

@@ -17,10 +17,10 @@ RUN cargo build --release
FROM debian:bookworm-slim as packages FROM debian:bookworm-slim as packages
WORKDIR /packages WORKDIR /packages
RUN apt-get update && apt-get install -y curl tar xz-utils
ARG TARGETPLATFORM ARG TARGETPLATFORM
# Check if the target platform is linux/x86_64, otherwise log error and exit
RUN if [ "$TARGETPLATFORM" = "linux/amd64" ]; then \ RUN apt-get update && apt-get install -y curl tar xz-utils && \
if [ "$TARGETPLATFORM" = "linux/amd64" ]; then \
echo "amd64" && false; \ echo "amd64" && false; \
elif [ "$TARGETPLATFORM" = "linux/arm/v7" ]; then \ elif [ "$TARGETPLATFORM" = "linux/arm/v7" ]; then \
curl -L https://github.com/yt-dlp/yt-dlp/releases/latest/download/yt-dlp_linux_armv7l > yt-dlp && \ curl -L https://github.com/yt-dlp/yt-dlp/releases/latest/download/yt-dlp_linux_armv7l > yt-dlp && \
@@ -53,9 +53,6 @@ USER root
COPY --from=builder /builder/target/release/service /usr/local/bin/service COPY --from=builder /builder/target/release/service /usr/local/bin/service
COPY --from=packages /packages /usr/bin COPY --from=packages /packages /usr/bin
RUN apt-get update && apt-get install -y \ RUN apt-get update && apt-get install -y libc6 libc6-dev libopus-dev libpq5 libpq-dev python3-pip ffmpeg
libc6 libc6-dev libopus-dev libpq5 libpq-dev python3-pip ffmpeg
# apt-get auto-remove -y && \
# RUN pipx install yt-dlp
CMD ["service"] CMD ["service"]

View File

@@ -1,5 +1,4 @@
CREATE TABLE IF NOT EXISTS guilds ( CREATE TABLE IF NOT EXISTS guilds (
id BIGINT PRIMARY KEY NOT NULL, id BIGINT PRIMARY KEY NOT NULL,
name TEXT NOT NULL, volume DOUBLE PRECISION NOT NULL
volume INTEGER NOT NULL
); );

View File

@@ -6,7 +6,7 @@ use serde::{Serialize, Deserialize};
use serenity::model::prelude::{GuildChannel, ChannelType}; use serenity::model::prelude::{GuildChannel, ChannelType};
use siren::ServiceError; use siren::ServiceError;
use crate::AppState; use crate::{AppState, bot::commands::audio::{play::play_track, join}};
#[get("/guilds")] #[get("/guilds")]
async fn get_guilds(data: web::Data<Arc<AppState>>) -> HttpResponse { async fn get_guilds(data: web::Data<Arc<AppState>>) -> HttpResponse {
@@ -109,32 +109,61 @@ async fn send_message(path: web::Path<(String, String)>, text: web::Json<Channel
HttpResponse::Ok().finish() HttpResponse::Ok().finish()
} }
#[post("/{guild_id}/voice/play")] #[derive(Serialize, Deserialize)]
async fn play(path: web::Path<String>, data: web::Data<Arc<AppState>>) -> HttpResponse { struct PlayRequest {
let guild_id = path.into_inner(); track_url: String
}
#[post("/{guild_id}/voice/{channel_id}/play")]
async fn play(path: web::Path<(String, String)>, play_request: web::Json<PlayRequest>, data: web::Data<Arc<AppState>>) -> HttpResponse {
let (guild_id, channel_id) = path.into_inner();
let guild_id = match guild_id.parse::<u64>() { let guild_id = match guild_id.parse::<u64>() {
Ok(id) => id, Ok(id) => id,
Err(err) => { Err(err) => {
warn!("Could not parse guild id: {:?}", err); warn!("Could not parse guild id: {:?}", err);
return ResponseError::error_response(&ServiceError { return ResponseError::error_response(&ServiceError { status: 422, message: err.to_string() })
status: 422, }
message: err.to_string() };
}) let channel_id = match channel_id.parse::<u64>() {
Ok(id) => id,
Err(err) => {
warn!("Could not parse channel id: {:?}", err);
return ResponseError::error_response(&ServiceError { status: 422, message: err.to_string() })
}
};
let http = Pin::new(&data.http).get_ref();
let guild = match http.get_guild(guild_id).await {
Ok(guild) => guild,
Err(err) => {
warn!("Could not get guild: {:?}", err);
return ResponseError::error_response(&ServiceError { status: 422, message: err.to_string() })
}
};
let channel = match http.get_channel(channel_id).await {
Ok(channel) => channel,
Err(err) => {
warn!("Could not get channel: {:?}", err);
return ResponseError::error_response(&ServiceError { status: 422, message: err.to_string() })
} }
}; };
if let Some(handler_lock) = data.songbird.get(guild_id) { let manager = Arc::clone(&data.songbird);
let handler = handler_lock.lock().await;
if let Err(err) = handler.queue().pause() { match join(Arc::clone(&manager), &guild.id, &channel.id()).await {
warn!("Could not pause track: {:?}", err); Ok(_) => {
return ResponseError::error_response(&ServiceError { match play_track(Arc::clone(&data.songbird), guild.id, play_request.track_url.to_string()).await {
status: 422, Ok(_) => HttpResponse::Ok().finish(),
message: err.to_string() Err(err) => {
}) warn!("Could not play track: {:?}", err);
return ResponseError::error_response(&err)
}
}
},
Err(err) => {
warn!("Could not join channel: {:?}", err);
return ResponseError::error_response(&ServiceError { status: 500, message: err.to_string() })
} }
} }
HttpResponse::Ok().finish()
} }
#[post("/{guild_id}/voice/pause")] #[post("/{guild_id}/voice/pause")]
@@ -173,5 +202,6 @@ pub fn init_routes(config: &mut web::ServiceConfig) {
.service(get_voice_channels) .service(get_voice_channels)
.service(send_message) .service(send_message)
.service(pause) .service(pause)
.service(play)
); );
} }

View File

@@ -1,13 +1,13 @@
use std::collections::HashMap;
use std::sync::Arc; use std::sync::Arc;
use log::debug; use log::{debug, warn};
use serenity::client::Cache; use serenity::client::Cache;
use serenity::model::application::interaction::{InteractionResponseType, application_command::ApplicationCommandInteraction}; use serenity::model::application::interaction::{InteractionResponseType, application_command::ApplicationCommandInteraction};
use serenity::model::prelude::{GuildId, ChannelId}; use serenity::model::prelude::{GuildId, ChannelId};
use serenity::model::user::User; use serenity::model::user::User;
use serenity::prelude::*; use serenity::prelude::*;
use siren::ServiceError;
use songbird::{Call, Songbird}; use songbird::{Call, Songbird};
use songbird::input::{Restartable, Input, Metadata, error::Error as SongbirdError}; use songbird::input::{Restartable, Input, Metadata, error::Error as SongbirdError};
@@ -18,36 +18,29 @@ pub mod skip;
pub mod stop; pub mod stop;
pub mod volume; pub mod volume;
#[derive(Clone, Debug)] pub async fn join_by_user(cache: &Arc<Cache>, manager: Arc<Songbird>, guild_id_option: &Option<GuildId>, user: &User) -> Result<(), ServiceError> {
pub struct AudioConfigs;
impl TypeMapKey for AudioConfigs {
type Value = Arc<RwLock<HashMap<GuildId, AudioConfig>>>;
}
#[derive(Clone, Debug)]
pub struct AudioConfig {
pub volume: f32
}
pub async fn join(cache: &Arc<Cache>, manager: Arc<Songbird>, guild_id_option: &Option<GuildId>, user: &User) -> Result<(), String> {
let guild_id = match guild_id_option { let guild_id = match guild_id_option {
Some(g) => g, Some(g) => g,
None => { None => return Err(ServiceError { status: 422, message: format!("{}", "No guild ID set") })
return Err(format!("{}", "No guild ID set"));
}
}; };
let channel_id = match find_voice_channel(cache, &guild_id, &user) { let channel_id = match find_voice_channel(cache, &guild_id, &user) {
Ok(channel) => channel, Ok(channel) => channel,
Err(err) => return Err(format!("{}", err)) Err(err) => return Err(ServiceError { status: 500, message: err.to_string() })
}; };
debug!("<{}> Joining channel {}", guild_id.0, channel_id); join(manager, guild_id, &channel_id).await
}
pub async fn join(manager: Arc<Songbird>, guild_id: &GuildId, channel_id: &ChannelId) -> Result<(), ServiceError> {
debug!("<{}> Joining channel {}", guild_id.0, channel_id.0);
let (_handle_lock, success) = manager.join(guild_id.to_owned(), channel_id.to_owned()).await; let (_handle_lock, success) = manager.join(guild_id.to_owned(), channel_id.to_owned()).await;
match success { match success {
Ok(s) => Ok(s), Ok(s) => Ok(s),
Err(err) => Err(format!("{}", err)) Err(err) => {
warn!("Failed to join channel: {:?}", err);
Err(ServiceError { status: 500, message: err.to_string() })
}
} }
} }

View File

@@ -3,18 +3,16 @@ use std::sync::Arc;
use log::{debug, warn, error}; use log::{debug, warn, error};
use serenity::model::prelude::GuildId; use serenity::model::prelude::GuildId;
use serenity::model::user::User;
use serenity::{prelude::*, async_trait}; use serenity::{prelude::*, async_trait};
use serenity::builder::CreateApplicationCommand; use serenity::builder::CreateApplicationCommand;
use serenity::model::application::interaction::application_command::ApplicationCommandInteraction; use serenity::model::application::interaction::application_command::ApplicationCommandInteraction;
use siren::ServiceError; use siren::ServiceError;
use songbird::EventHandler; use songbird::{EventHandler, Songbird};
use crate::AppState; use crate::bot::commands::audio::{leave, add_song, get_songbird};
use crate::bot::commands::audio::{join, leave, add_song, get_songbird};
use crate::db::guilds::QueryGuild; use crate::db::guilds::QueryGuild;
use super::{create_response, edit_response}; use super::{create_response, edit_response, join_by_user};
pub async fn run(ctx: &Context, command: &ApplicationCommandInteraction) { pub async fn run(ctx: &Context, command: &ApplicationCommandInteraction) {
// Get the track url // Get the track url
@@ -54,7 +52,7 @@ pub async fn run(ctx: &Context, command: &ApplicationCommandInteraction) {
} }
let manager = get_songbird(ctx).await; let manager = get_songbird(ctx).await;
match join(&ctx.cache, manager,&command.guild_id, &command.user).await { match join_by_user(&ctx.cache, manager,&command.guild_id, &command.user).await {
Ok(_) => { Ok(_) => {
let guild_id = match command.guild_id { let guild_id = match command.guild_id {
Some(g) => g, Some(g) => g,
@@ -66,37 +64,20 @@ pub async fn run(ctx: &Context, command: &ApplicationCommandInteraction) {
} }
}; };
debug!("Play command executed with track: {:?}", track_url); debug!("Play command executed with track: {:?}", track_url);
let manager = get_songbird(ctx).await; let manager = get_songbird(ctx).await;
if let Some(handler_lock) = manager.get(guild_id) { match play_track(manager, guild_id, track_url).await {
let is_queue_empty = { Ok(_) => {
let call_handler = handler_lock.lock().await; if let Err(why) = edit_response(&ctx, &command, "Playing track".to_string()).await {
call_handler.queue().is_empty() error!("Failed to edit response message: {}", why);
};
let guild = QueryGuild::get(guild_id.0 as i64).unwrap();
match add_song(handler_lock.clone(), &track_url, is_queue_empty, Some(guild.volume)).await {
Ok(added_song) => {
let track_title = added_song.title.unwrap();
debug!("Added track: {}", track_title);
if let Err(why) = edit_response(&ctx, &command, format!("Added track to queue: {}", track_title)).await {
error!("Failed to edit response message: {}", why);
}
let mut handler = handler_lock.lock().await;
handler.remove_all_global_events();
handler.add_global_event(songbird::Event::Track(songbird::TrackEvent::End), TrackEndNotifier { guild_id, call: manager })
} }
Err(why) => { },
warn!("Failed to add song: {}", why); Err(err) => {
if let Err(why) = edit_response(&ctx, &command, format!("Failed to add song: {}", why)).await { warn!("Failed to play track: {}", err);
error!("Failed to edit response message: {}", why); if let Err(why) = edit_response(&ctx, &command, format!("Failed to play track: {}", err)).await {
} error!("Failed to edit response message: {}", why);
if let Err(why) = leave(manager, &command.guild_id).await {
error!("Failed to leave voice channel: {}", why);
}
return;
} }
}; }
} };
}, },
Err(err) => { Err(err) => {
warn!("{}", err); warn!("{}", err);
@@ -107,38 +88,31 @@ pub async fn run(ctx: &Context, command: &ApplicationCommandInteraction) {
} }
} }
pub async fn play(state: Arc<AppState>, guild_id: Option<GuildId>, user: &User, track_url: String) -> Result<(), ServiceError> { pub async fn play_track(manager: Arc<Songbird>, guild_id: GuildId, track_url: String) -> Result<(), ServiceError> {
match join(&state.cache, Arc::clone(&state.songbird), &guild_id, user).await { if let Some(handler_lock) = manager.get(guild_id) {
Ok(_) => { let is_queue_empty = {
let guild_id = match guild_id { let call_handler = handler_lock.lock().await;
Some(g) => g, call_handler.queue().is_empty()
None => { };
return Err(ServiceError { let guild = QueryGuild::get(guild_id.0 as i64)?;
status: 422, match add_song(handler_lock.clone(), &track_url, is_queue_empty, Some(guild.volume as f32)).await {
message: "No guild ID set".to_string() Ok(added_song) => {
}); let track_title = added_song.title.unwrap();
} debug!("Added track: {}", track_title);
}; let mut handler = handler_lock.lock().await;
if let Some(handler_lock) = state.songbird.get(guild_id) { handler.remove_all_global_events();
let is_queue_empty = { handler.add_global_event(songbird::Event::Track(songbird::TrackEvent::End), TrackEndNotifier { guild_id, call: manager })
let call_handler = handler_lock.lock().await; },
call_handler.queue().is_empty() Err(err) => {
}; warn!("Failed to add song: {}", err);
let guild = QueryGuild::get(guild_id.0 as i64)?; if let Err(why) = leave(manager, &Some(guild_id)).await {
match add_song(handler_lock.clone(), &track_url, is_queue_empty, Some(guild.volume)).await { error!("Failed to leave voice channel: {}", why);
Ok(_) => {},
Err(_) => {}
} }
return Err(ServiceError { status: 422, message: err.to_string() })
} }
Ok(())
},
Err(err) => {
return Err(ServiceError {
status: 422,
message: err.to_string()
});
} }
} }
Ok(())
} }
pub fn register(command: &mut CreateApplicationCommand) -> &mut CreateApplicationCommand { pub fn register(command: &mut CreateApplicationCommand) -> &mut CreateApplicationCommand {

View File

@@ -57,7 +57,7 @@ pub async fn run(ctx: &Context, command: &ApplicationCommandInteraction) {
return; return;
} }
}; };
let _ = InsertGuild::update_audio(guild_id.0 as i64, bound_volume); let _ = InsertGuild::update_audio(guild_id.0 as i64, bound_volume as f64);
let manager = get_songbird(ctx).await; let manager = get_songbird(ctx).await;
if let Some(handler_lock) = manager.get(guild_id) { if let Some(handler_lock) = manager.get(guild_id) {
let handler = handler_lock.lock().await; let handler = handler_lock.lock().await;

View File

@@ -74,7 +74,7 @@ impl EventHandler for Handler {
warn!("No ready guilds found"); warn!("No ready guilds found");
} }
for guild in ready.guilds { for guild in ready.guilds {
let _ = InsertGuild::insert(InsertGuild { id: (guild.id.0 as i64), name: "".to_string(), volume: 100.0 }); let _ = InsertGuild::insert(InsertGuild { id: (guild.id.0 as i64), volume: 100.0 });
let commands = guild.id.set_application_commands(&ctx.http, |commands| { let commands = guild.id.set_application_commands(&ctx.http, |commands| {
commands.create_application_command(|command: &mut serenity::builder::CreateApplicationCommand| { commands::ping::register(command) }) commands.create_application_command(|command: &mut serenity::builder::CreateApplicationCommand| { commands::ping::register(command) })
.create_application_command(|command: &mut serenity::builder::CreateApplicationCommand| { commands::audio::play::register(command) }) .create_application_command(|command: &mut serenity::builder::CreateApplicationCommand| { commands::audio::play::register(command) })

View File

@@ -8,8 +8,7 @@ use crate::db::{schema::guilds, connection};
#[diesel(table_name = guilds)] #[diesel(table_name = guilds)]
pub struct QueryGuild { pub struct QueryGuild {
pub id: i64, pub id: i64,
pub name: String, pub volume: f64
pub volume: f32
} }
impl QueryGuild { impl QueryGuild {
@@ -24,8 +23,7 @@ impl QueryGuild {
#[diesel(table_name = guilds)] #[diesel(table_name = guilds)]
pub struct InsertGuild { pub struct InsertGuild {
pub id: i64, pub id: i64,
pub name: String, pub volume: f64
pub volume: f32
} }
impl InsertGuild { impl InsertGuild {
@@ -35,7 +33,7 @@ impl InsertGuild {
Ok(guild) Ok(guild)
} }
pub fn update_audio(id: i64, volume: f32) -> Result<QueryGuild, ServiceError> { pub fn update_audio(id: i64, volume: f64) -> Result<QueryGuild, ServiceError> {
let mut conn = connection()?; let mut conn = connection()?;
let guild = diesel::update(guilds::table.filter(guilds::id.eq(id))).set(guilds::volume.eq(volume)).get_result(&mut conn)?; let guild = diesel::update(guilds::table.filter(guilds::id.eq(id))).set(guilds::volume.eq(volume)).get_result(&mut conn)?;
Ok(guild) Ok(guild)

View File

@@ -34,7 +34,6 @@ diesel::table! {
diesel::table! { diesel::table! {
guilds (id) { guilds (id) {
id -> BigInt, id -> BigInt,
name -> Text, volume -> Float8,
volume -> Float,
} }
} }