diff --git a/Cargo.lock b/Cargo.lock index d7a4155..a7dd08b 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1463,7 +1463,7 @@ checksum = "cda74da7e1a664f795bb1f8a87ec406fb89a02522cf6e50620d016add6dbbf5c" [[package]] name = "titlebot" -version = "0.2.0" +version = "0.2.1" dependencies = [ "anyhow", "futures", diff --git a/Cargo.toml b/Cargo.toml index 6b09dc7..e4ecb23 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "titlebot" -version = "0.2.0" +version = "0.2.1" authors = ["Yash Karandikar "] edition = "2018" diff --git a/src/main.rs b/src/main.rs index 8534baa..3b5717d 100644 --- a/src/main.rs +++ b/src/main.rs @@ -6,6 +6,23 @@ use rspotify::model::{Id, PlayableItem}; use rspotify::prelude::BaseClient; use rspotify::{ClientCredsSpotify, Credentials}; use anyhow::anyhow; +use std::sync::Arc; + + +#[allow(unused_macros)] +macro_rules! cloned { + ($i:ident => $e:expr) => {{ + let $i = $i.clone(); + $e + }}; + (($($i:ident),+) => $e:expr) => {{ + $( + let $i = $i.clone(); + )* + + $e + }} +} fn calculate_playtime(secs: u64) -> (u64, u64) { let mut dur_sec = secs; @@ -81,7 +98,7 @@ async fn main() -> anyhow::Result<()> { }, config.nickname.as_ref().unwrap(), config.channels.join(", "), config.umodes.as_ref().unwrap()); let mut spotify = ClientCredsSpotify::new(Credentials::from_env().unwrap()); spotify.request_token().await.unwrap(); - let mut client = Client::from_config(config).await?; + let mut client = Arc::new(Client::from_config(config).await?); client.identify()?; let vlog = match std::env::var("TITLEBOT_VERBOSE_LOG") { Ok(o) => o.eq_ignore_ascii_case("true"), @@ -92,10 +109,10 @@ async fn main() -> anyhow::Result<()> { } println!("Connected!"); - let mut stream = client.stream()?; + let mut stream = Arc::get_mut(&mut client).unwrap().stream()?; let url_regex = Regex::new(r"https?://\w+\.\w+[/\S+]*").unwrap(); - let title_regex = Regex::new(r"(?<=)(.*)(?=)").unwrap(); + let title_regex = Arc::new(Regex::new(r"(?<=)(.*)(?=)").unwrap()); let spotify_regex = Regex::new(r"(?:https?|spotify):(?://open\.spotify\.com/)?(track|artist|album|playlist)[/:]([a-zA-Z0-9]*)").unwrap(); let hclient = reqwest::Client::new(); @@ -126,10 +143,12 @@ async fn main() -> anyhow::Result<()> { } } } else if let Some(m) = url_regex.find(&message) { - let url = &message[m.0..m.1]; - if let Ok(title) = resolve_url(&hclient, url, &title_regex).await { - client.send_privmsg(&channel, title)?; - } + let url = message[m.0..m.1].to_string(); + tokio::spawn(cloned!((client, hclient, title_regex, url) => async move { + if let Ok(title) = resolve_url(&hclient, &url, &title_regex).await { + client.send_privmsg(&channel, title).unwrap(); + } + })); } } }