Skip to content

Commit

Permalink
fuck it use both version of reqwest
Browse files Browse the repository at this point in the history
  • Loading branch information
cycle-five committed Aug 4, 2024
1 parent 0d628f4 commit a0b3c40
Show file tree
Hide file tree
Showing 13 changed files with 261 additions and 105 deletions.
193 changes: 148 additions & 45 deletions Cargo.lock

Large diffs are not rendered by default.

21 changes: 15 additions & 6 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -30,9 +30,10 @@ features = [

[workspace.dependencies.serenity]
# Broken? try self-host.
git = "https://github.com/CycleFive/serenity"
# git = "https://github.com/CycleFive/serenity"
#git = "https://github.com/serenity-rs/serenity"
version = "0.12"
branch = "current"
#branch = "current"
default-features = false
features = [
"builder",
Expand All @@ -52,8 +53,8 @@ features = [

[workspace.dependencies.songbird]
# Broken? try self-hosted?
git = "https://github.com/cycle-five/songbird"
branch = "current"
#git = "https://github.com/cycle-five/songbird"
#branch = "current"
version = "0.4.3"
features = ["driver", "serenity", "rustls", "receive", "builtin-queue"]

Expand All @@ -71,7 +72,16 @@ crack-core = { path = "./crack-core", default-features = true, version = "0.3" }
crack-osint = { path = "./crack-osint", default-features = true, version = "0.1" }
crack-gpt = { path = "../crack-gpt", default-features = true, version = "0.2" }
crack-bf = { path = "../crack-bf", default-features = true, version = "0.1" }
poise = { branch = "current", git = "https://github.com/cycle-five/poise", default-features = true }
# poise = { branch = "current", git = "https://github.com/cycle-five/poise", default-features = true }
reqwest_old = { version = "=0.11", default-features = false, package = "reqwest", features = [
"blocking",
"json",
"multipart",
"rustls-tls",
"cookies",
] }

poise = { branch = "current", git = "https://github.com/serenity-rs/poise", default-features = true }
vergen = { version = "9", features = ["git", "cargo", "si", "build", "gitcl"] }
tracing = "0.1"
reqwest = { version = "0.12", default-features = false, features = [
Expand All @@ -84,7 +94,6 @@ reqwest = { version = "0.12", default-features = false, features = [
"http2",
"macos-system-configuration",
] }

# Config for 'cargo dist'
[workspace.metadata.dist]
# The preferred cargo-dist version to use in CI (Cargo.toml SemVer syntax)
Expand Down
2 changes: 2 additions & 0 deletions crack-core/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,7 @@ rusty_ytdl = { git = "https://github.com/cycle-five/rusty_ytdl", default-feature
"blocking",
"ffmpeg",
] }
rustls = "0.23"
audiopus = "0.3.0-rc.0"
async-trait = "0.1"
anyhow = "1.0"
Expand Down Expand Up @@ -63,6 +64,7 @@ crack-osint = { path = "../crack-osint", optional = true }
crack-bf = { path = "../crack-bf", optional = true }

reqwest = { workspace = true }
reqwest_old = { workspace = true }
tracing = { workspace = true }
sqlx = { workspace = true }
serenity = { workspace = true }
Expand Down
4 changes: 3 additions & 1 deletion crack-core/src/commands/music/doplay.rs
Original file line number Diff line number Diff line change
Expand Up @@ -648,6 +648,8 @@ pub async fn queue_aux_metadata(
aux_metadata: &[MyAuxMetadata],
mut msg: Message,
) -> CrackedResult<()> {
use crate::http_utils;

let guild_id = ctx.guild_id().ok_or(CrackedError::NoGuildId)?;
let search_results = aux_metadata;

Expand Down Expand Up @@ -683,7 +685,7 @@ pub async fn queue_aux_metadata(
};

let ytdl = YoutubeDl::new(
client.clone(),
http_utils::get_client_old().clone(),
metadata_final.metadata().source_url.clone().unwrap(),
);

Expand Down
5 changes: 3 additions & 2 deletions crack-core/src/commands/music/dosearch.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,6 @@ use crate::{
Context, Error,
};
use poise::ReplyHandle;
use reqwest::Client;
use serenity::builder::CreateEmbed;
use songbird::input::YoutubeDl;

Expand Down Expand Up @@ -38,7 +37,9 @@ async fn do_yt_search_internal(
ctx: Context<'_>,
search_query: String,
) -> Result<ReplyHandle, CrackedError> {
let mut ytdl = YoutubeDl::new(Client::new(), search_query);
use crate::http_utils;

let mut ytdl = YoutubeDl::new(http_utils::get_client_old().clone(), search_query);
let results = ytdl.search(None).await?;

let embeds = results
Expand Down
55 changes: 30 additions & 25 deletions crack-core/src/commands/music/play_utils/query.rs
Original file line number Diff line number Diff line change
Expand Up @@ -154,7 +154,7 @@ impl QueryType {
// FIXME: Don't hardcode this.
let prefix = "/data/downloads";
let extension = if mp3 { "mp3" } else { "webm" };
let client = http_utils::get_client().clone();
//let client = http_utils::get_client().clone();
// tracing::warn!("query_type: {:?}", query_type);
match self {
QueryType::YoutubeSearch(_) => Err(Box::new(CrackedError::Other(
Expand Down Expand Up @@ -191,7 +191,10 @@ impl QueryType {
},
QueryType::Keywords(query) => {
tracing::warn!("In Keywords");
let mut ytdl = YoutubeDl::new(client, format!("ytsearch:{}", query));
let mut ytdl = YoutubeDl::new(
http_utils::get_client_old().clone(),
format!("ytsearch:{}", query),
);
let metadata = ytdl.aux_metadata().await.unwrap();
let url = metadata.source_url.unwrap();
let (output, metadata) = download_file_ytdlp(&url, mp3).await?;
Expand Down Expand Up @@ -230,7 +233,7 @@ impl QueryType {
.map(|x| x.build_query())
.collect::<Vec<String>>();
let url = format!("ytsearch:{}", keywords_list.first().unwrap());
let mut ytdl = YoutubeDl::new(client, url.clone());
let mut ytdl = YoutubeDl::new(http_utils::get_client_old().clone(), url.clone());
let metadata = ytdl.aux_metadata().await.unwrap();
let (output, _metadata) = download_file_ytdlp(&url, mp3).await?;
let file_name = format!(
Expand All @@ -246,7 +249,7 @@ impl QueryType {
QueryType::KeywordList(keywords_list) => {
tracing::warn!("In KeywordList");
let url = format!("ytsearch:{}", keywords_list.join(" "));
let mut ytdl = YoutubeDl::new(client, url.clone());
let mut ytdl = YoutubeDl::new(http_utils::get_client_old().clone(), url.clone());
tracing::warn!("ytdl: {:?}", ytdl);
let metadata = ytdl.aux_metadata().await.unwrap();
let (output, _metadata) = download_file_ytdlp(&url, mp3).await?;
Expand Down Expand Up @@ -312,8 +315,8 @@ impl QueryType {
call: Arc<Mutex<Call>>,
keywords: String,
) -> Result<Vec<TrackHandle>, CrackedError> {
let reqwest_client = ctx.data().http_client.clone();
let search_results = YoutubeDl::new_search(reqwest_client, keywords)
//let reqwest_client = ctx.data().http_client.clone();
let search_results = YoutubeDl::new_search(http_utils::get_client_old().clone(), keywords)
.search(None)
.await?;
// let user_id = ctx.author().id;
Expand Down Expand Up @@ -394,9 +397,10 @@ impl QueryType {
QueryType::YoutubeSearch(query) => {
tracing::trace!("Mode::End, QueryType::YoutubeSearch");

let res = YoutubeDl::new_search(http_utils::get_client().clone(), query.clone())
.search(None)
.await?;
let res =
YoutubeDl::new_search(http_utils::get_client_old().clone(), query.clone())
.search(None)
.await?;
let user_id = ctx.author().id;
create_search_response(&ctx, guild_id, user_id, query.clone(), res).await?;
Ok(true)
Expand Down Expand Up @@ -459,7 +463,7 @@ impl QueryType {
match self {
QueryType::VideoLink(url) | QueryType::PlaylistLink(url) => {
// FIXME
let mut src = YoutubeDl::new(http_utils::get_client().clone(), url.clone());
let mut src = YoutubeDl::new(http_utils::get_client_old().clone(), url.clone());
let metadata = src.aux_metadata().await?;
queue_track_back(ctx, &call, &QueryType::NewYoutubeDl((src, metadata))).await?;
Ok(true)
Expand Down Expand Up @@ -598,11 +602,12 @@ impl QueryType {
) -> CrackedResult<(SongbirdInput, Vec<MyAuxMetadata>)> {
use colored::Colorize;
let client = client.unwrap_or_else(|| http_utils::get_client().clone());
let client_old = http_utils::get_client_old().clone();
tracing::warn!("{}", format!("query_type: {:?}", self).red());
match self {
QueryType::YoutubeSearch(query) => {
tracing::error!("In YoutubeSearch");
let mut ytdl = YoutubeDl::new_search(client, query.clone());
let mut ytdl = YoutubeDl::new_search(client_old, query.clone());
let mut res = Vec::new();
let asdf = ytdl.search(None).await?;
for metadata in asdf {
Expand All @@ -621,7 +626,7 @@ impl QueryType {
// .map(MyAuxMetadata)
// .collect::<Vec<_>>();
// Ok((search.into(), metadata))
let mut ytdl = YoutubeDl::new(client, query.clone());
let mut ytdl = YoutubeDl::new(client_old, query.clone());
let metadata = ytdl.aux_metadata().await?;
let my_metadata = MyAuxMetadata(metadata);
Ok((ytdl.into(), vec![my_metadata]))
Expand All @@ -640,7 +645,7 @@ impl QueryType {
QueryType::File(file) => {
tracing::warn!("In File");
Ok((
HttpRequest::new(client, file.url.to_owned()).into(),
HttpRequest::new(client_old, file.url.to_owned()).into(),
vec![MyAuxMetadata::default()],
))
},
Expand All @@ -664,7 +669,7 @@ impl QueryType {
RustyYoutubeClient::search_result_to_aux_metadata(&r),
));
}
let ytdl = YoutubeDl::new(client.clone(), url.clone());
let ytdl = YoutubeDl::new(client_old.clone(), url.clone());
tracing::warn!("ytdl: {:?}", ytdl);
Ok((ytdl.into(), metadata))
},
Expand All @@ -675,7 +680,7 @@ impl QueryType {
.map(|x| x.build_query())
.collect::<Vec<String>>();
let mut ytdl = YoutubeDl::new(
client,
client_old.clone(),
format!("ytsearch:{}", keywords_list.first().unwrap()),
);
tracing::warn!("ytdl: {:?}", ytdl);
Expand All @@ -685,8 +690,10 @@ impl QueryType {
},
QueryType::KeywordList(keywords_list) => {
tracing::warn!("In KeywordList");
let mut ytdl =
YoutubeDl::new(client, format!("ytsearch:{}", keywords_list.join(" ")));
let mut ytdl = YoutubeDl::new(
client_old.clone(),
format!("ytsearch:{}", keywords_list.join(" ")),
);
tracing::warn!("ytdl: {:?}", ytdl);
let metdata = match ytdl.aux_metadata().await {
Ok(metadata) => metadata,
Expand All @@ -705,12 +712,9 @@ impl QueryType {

/// Download a file and upload it as an mp3.
async fn download_file_ytdlp_mp3(url: &str) -> Result<(Output, AuxMetadata), Error> {
let metadata = YoutubeDl::new(
reqwest::ClientBuilder::new().use_rustls_tls().build()?,
url.to_string(),
)
.aux_metadata()
.await?;
let metadata = YoutubeDl::new(http_utils::get_client_old().clone(), url.to_string())
.aux_metadata()
.await?;

let args = [
"--extract-audio",
Expand Down Expand Up @@ -739,7 +743,7 @@ async fn download_file_ytdlp(url: &str, mp3: bool) -> Result<(Output, AuxMetadat
return download_file_ytdlp_mp3(url).await;
}

let metadata = YoutubeDl::new(http_utils::get_client().clone(), url.to_string())
let metadata = YoutubeDl::new(http_utils::get_client_old().clone(), url.to_string())
.aux_metadata()
.await?;

Expand Down Expand Up @@ -821,7 +825,8 @@ pub async fn query_type_from_url(
"LINK".blue(),
url.underline().blue()
);
let mut ytdl = YoutubeDl::new(ctx.data().http_client.clone(), url.to_string());
let mut ytdl =
YoutubeDl::new(http_utils::get_client_old().clone(), url.to_string());
// This can fail whenever yt-dlp cannot parse a track from the URL.
let metadata = match ytdl.aux_metadata().await {
Ok(metadata) => metadata,
Expand Down
22 changes: 14 additions & 8 deletions crack-core/src/commands/music_utils.rs
Original file line number Diff line number Diff line change
Expand Up @@ -39,26 +39,30 @@ pub async fn set_global_handlers(
// };

// unregister existing events and register idle notifier
call.lock().await.remove_all_global_events();
//call.lock().await.remove_all_global_events();
//register_voice_handlers(buffer, call.clone(), ctx.serenity_context().clone()).await?;

let mut handler = call.lock().await;

let guild_settings = data
.get_guild_settings(guild_id)
.await
.ok_or(CrackedError::NoGuildSettings)?;
handler.remove_all_global_events();

let guild_settings = match data.get_guild_settings(guild_id).await {
Some(settings) => settings,
None => {
drop(handler);
return Err(CrackedError::NoGuildSettings);
},
};

let timeout = guild_settings.timeout;
if timeout > 0 {
let premium = guild_settings.premium;
handler.add_global_event(
Event::Periodic(Duration::from_secs(5), None),
Event::Periodic(Duration::from_secs(60), None),
IdleHandler {
http: ctx.serenity_context().http.clone(),
serenity_ctx: Arc::new(ctx.serenity_context().clone()),
guild_id,
channel_id,
guild_id: Some(guild_id),
limit: timeout as usize,
count: Default::default(),
no_timeout: Arc::new(AtomicBool::new(premium)),
Expand All @@ -77,6 +81,8 @@ pub async fn set_global_handlers(
},
);

drop(handler);

Ok(())
}

Expand Down
8 changes: 8 additions & 0 deletions crack-core/src/config.rs
Original file line number Diff line number Diff line change
Expand Up @@ -55,11 +55,19 @@ async fn on_error(error: poise::FrameworkError<'_, Data, Error>) {
}
}

/// Installs the AWS LC provider for rustls.
pub fn install_crypto_provider() {
rustls::crypto::aws_lc_rs::default_provider()
.install_default()
.expect("Failed to install AWS LC provider");
}

/// Create the poise framework from the bot config.
pub async fn poise_framework(
config: BotConfig,
event_log_async: EventLogAsync,
) -> Result<Client, Error> {
// install_crypto_provider();
// FrameworkOptions contains all of poise's configuration option in one struct
// Every option can be omitted to use its default value

Expand Down
28 changes: 16 additions & 12 deletions crack-core/src/handlers/idle.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
use self::serenity::{async_trait, http::Http};
use self::serenity::async_trait;
use poise::serenity_prelude as serenity;
use songbird::{tracks::PlayMode, Event, EventContext, EventHandler};
use std::sync::{
Expand All @@ -10,11 +10,9 @@ use crate::messaging::messages::IDLE_ALERT;

/// Handler for the idle event.
pub struct IdleHandler {
pub http: Arc<Http>,
//pub manager: Arc<Songbird>,
pub serenity_ctx: Arc<serenity::Context>,
pub guild_id: serenity::GuildId,
pub channel_id: serenity::ChannelId,
pub guild_id: Option<serenity::GuildId>,
pub limit: usize,
pub count: Arc<AtomicUsize>,
pub no_timeout: Arc<AtomicBool>,
Expand Down Expand Up @@ -46,20 +44,26 @@ impl EventHandler for IdleHandler {
}
tracing::warn!(
"is_playing: {:?}, time_not_playing: {:?}",
self.count,
bot_is_playing,
self.count.load(Ordering::Relaxed)
);

if !self.no_timeout.load(Ordering::Relaxed)
&& self.limit > 0
&& self.count.fetch_add(5, Ordering::Relaxed) >= self.limit
&& self.count.fetch_add(60, Ordering::Relaxed) >= self.limit
{
let guild_id = self.guild_id?;

if manager.remove(guild_id).await.is_ok() {
self.channel_id.say(&self.http, IDLE_ALERT).await.unwrap();
return Some(Event::Cancel);
}
match manager.remove(self.guild_id).await {
Ok(_) => {
self.channel_id
.say(&self.serenity_ctx, IDLE_ALERT)
.await
.unwrap();
return Some(Event::Cancel);
},
Err(e) => {
tracing::error!("Error removing bot from voice channel: {:?}", e);
},
};
}
None
}
Expand Down
Loading

0 comments on commit a0b3c40

Please sign in to comment.