From 0453caee435a69309794d54ab99a18150daa4802 Mon Sep 17 00:00:00 2001 From: Amneesh Singh Date: Sat, 26 Mar 2022 11:30:55 +0530 Subject: [PATCH] check referenced message as well Signed-off-by: Amneesh Singh --- .gitignore | 4 ++ Cargo.lock | 10 +++++ Cargo.toml | 1 + singh3.nomad | 1 + src/commands/tags.rs | 74 ++++++++++++++----------------------- src/lib/messages.rs | 87 ++++++++++++++++++++++++++++++++++++++++++++ src/lib/mod.rs | 1 + 7 files changed, 131 insertions(+), 47 deletions(-) create mode 100644 src/lib/messages.rs diff --git a/.gitignore b/.gitignore index ff69d57..1f89fbf 100644 --- a/.gitignore +++ b/.gitignore @@ -1,2 +1,6 @@ target/ result +\#*\# +.\#* +.*~*~ +*~ diff --git a/Cargo.lock b/Cargo.lock index a933bcd..7929c9d 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -532,6 +532,15 @@ version = "0.2.97" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "12b8adadd720df158f4d70dfe7ccc6adb0472d7c55ca83445f6a5ab3e36f8fb6" +[[package]] +name = "linkify" +version = "0.8.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ccbcd666d915aa3ae3c3774999a9e20b2776a018309b8159d07df062b91f45e8" +dependencies = [ + "memchr", +] + [[package]] name = "lock_api" version = "0.4.4" @@ -1120,6 +1129,7 @@ dependencies = [ name = "singh3" version = "0.1.0" dependencies = [ + "linkify", "rand 0.8.4", "regex", "serenity", diff --git a/Cargo.toml b/Cargo.toml index 9bfe411..1759aca 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -9,6 +9,7 @@ tracing = "*" regex = "1" tokio-postgres = "*" rand = "*" +linkify = "*" [dependencies.serenity] version = "0.10.10" diff --git a/singh3.nomad b/singh3.nomad index 1d0bf6d..8cbb861 100644 --- a/singh3.nomad +++ b/singh3.nomad @@ -59,6 +59,7 @@ EOF config { image = "natto17/singh3:latest" force_pull = true + volumes = [ "/tmp:/tmp" ] } template { diff --git a/src/commands/tags.rs b/src/commands/tags.rs index ed08ee6..6794e44 100644 --- a/src/commands/tags.rs +++ b/src/commands/tags.rs @@ -1,4 +1,4 @@ -use crate::lib::components::make_terminal_components; +use crate::lib::{components::make_terminal_components, messages::ExtractInfo}; use core::time::Duration; use serenity::{ builder::CreateEmbed, @@ -11,6 +11,9 @@ use serenity::{ }; use tokio_postgres::Row; +const GUILD_ID: u64 = 874699899067838535; +const ROLE_ID: u64 = 957155053184102400; + #[command] #[aliases("t")] pub async fn tag(ctx: &Context, msg: &Message, args: Args) -> CommandResult { @@ -63,10 +66,10 @@ pub async fn tag(ctx: &Context, msg: &Message, args: Args) -> CommandResult { } #[command] -pub async fn tadd(ctx: &Context, msg: &Message, args: Args) -> CommandResult { - let query: String = args.raw().collect::>().join(" "); - let queries = query.splitn(2, " ").collect::>(); - if queries.len() != 2 && msg.attachments.len() == 0 { +pub async fn tadd(ctx: &Context, msg: &Message, mut args: Args) -> CommandResult { + let tag_value = msg.extract_text(2, true); + + if tag_value.is_none() { msg.reply( ctx, "Please use the proper syntax: `,tadd ` or attach something", @@ -74,13 +77,15 @@ pub async fn tadd(ctx: &Context, msg: &Message, args: Args) -> CommandResult { .await?; return Ok(()); } + + let tag_name = args.single::().unwrap(); let data_read = ctx.data.read().await; let db = data_read .get::() .expect("Expected Database in TypeMap.") .clone(); let check_existense = db - .query("SELECT name FROM tags WHERE name=$1", &[&queries[0]]) + .query("SELECT name FROM tags WHERE name=$1", &[&tag_name]) .await?; if check_existense.len() != 0 { msg.reply(ctx, format!("This tag already exists")).await?; @@ -88,23 +93,7 @@ pub async fn tadd(ctx: &Context, msg: &Message, args: Args) -> CommandResult { } db.execute( "INSERT INTO tags(name, value, owner) VALUES($1, $2, $3)", - &[ - &queries[0], - &format!( - "{}{}", - if queries.len() == 2 { - format!("{}{}", queries[1], '\n') - } else { - "".to_string() - }, - msg.attachments - .iter() - .map(|x| x.url.clone()) - .collect::>() - .join("\n") - ), - &msg.author.id.to_string(), - ], + &[&tag_name, &tag_value, &msg.author.id.to_string()], ) .await?; msg.reply(ctx, "Added").await?; @@ -163,7 +152,9 @@ pub async fn tremove(ctx: &Context, msg: &Message, args: Args) -> CommandResult .await?; if owner.len() == 1 { let owner_id: String = owner[0].get(0); - if owner_id != msg.author.id.to_string() { + if owner_id != msg.author.id.to_string() + && !msg.author.has_role(&ctx.http, GUILD_ID, ROLE_ID).await? + { msg.reply(ctx, "You don't even own this tag").await?; return Ok(()); } @@ -176,50 +167,39 @@ pub async fn tremove(ctx: &Context, msg: &Message, args: Args) -> CommandResult } #[command] -pub async fn tedit(ctx: &Context, msg: &Message, args: Args) -> CommandResult { - let query: String = args.raw().collect::>().join(" "); - let queries = query.splitn(2, " ").collect::>(); - if queries.len() != 2 && msg.attachments.len() == 0 { +pub async fn tedit(ctx: &Context, msg: &Message, mut args: Args) -> CommandResult { + let tag_value = msg.extract_text(2, true); + + if tag_value.is_none() { msg.reply( ctx, - "Please use the proper syntax or attach something\n`,tedit `", + "Please use the proper syntax: `,tadd ` or attach something", ) .await?; return Ok(()); } + + let tag_name = args.single::().unwrap(); let data_read = ctx.data.read().await; let db = data_read .get::() .expect("Expected Database in TypeMap.") .clone(); let owner = db - .query("SELECT owner FROM tags WHERE name=$1", &[&queries[0]]) + .query("SELECT owner FROM tags WHERE name=$1", &[&tag_name]) .await?; if owner.len() == 1 { let owner_id: String = owner[0].get(0); - if owner_id != msg.author.id.to_string() { + if owner_id != msg.author.id.to_string() + && !msg.author.has_role(&ctx.http, GUILD_ID, ROLE_ID).await? + { msg.reply(ctx, "You don't even own this tag").await?; return Ok(()); } } db.execute( "UPDATE tags SET value=$1 WHERE name=$2", - &[ - &format!( - "{}{}", - if queries.len() == 2 { - format!("{}{}", queries[1], '\n') - } else { - "".to_string() - }, - msg.attachments - .iter() - .map(|x| x.url.clone()) - .collect::>() - .join("\n") - ), - &queries[0], - ], + &[&tag_value, &tag_name], ) .await?; msg.reply(ctx, "Changed the value if it existed").await?; diff --git a/src/lib/messages.rs b/src/lib/messages.rs new file mode 100644 index 0000000..7ae85ce --- /dev/null +++ b/src/lib/messages.rs @@ -0,0 +1,87 @@ +use linkify::LinkFinder; +use serenity::model::channel::Message; + +#[derive(Default)] +pub struct URLExtractInfo { + urls: Vec, + n_attachments: u8, + n_links: u16, + rn_attachments: Option, + rn_links: Option, +} + +pub trait ExtractInfo { + fn extract_urls(&self) -> URLExtractInfo; + fn extract_text(&self, skip: usize, with_ref: bool) -> Option; +} + +// Priority: Text > Attachments > Reference +impl ExtractInfo for Message { + fn extract_urls(&self) -> URLExtractInfo { + let mut ret = URLExtractInfo::default(); + let finder = LinkFinder::new(); + let find_links = |x| finder.links(x).map(|x| x.as_str().to_string()).collect(); + + ret.urls = find_links(&self.content); + + ret.n_links = ret.urls.len() as u16; + + ret.urls.extend( + self.attachments + .iter() + .map(|x| x.url.clone()) + .collect::>(), + ); + + ret.n_attachments = self.attachments.len() as u8; + + if let Some(msg) = &self.referenced_message { + let msg_links: Vec = find_links(&msg.content); + + ret.rn_attachments = Some(msg.attachments.len() as u8); + ret.rn_links = Some(msg_links.len() as u16); + ret.urls.extend(msg_links); + ret.urls.extend( + msg.attachments + .iter() + .map(|x| x.url.clone()) + .collect::>(), + ); + } + + ret + } + + fn extract_text(&self, skip: usize, with_ref: bool) -> Option { + let mut ret: String = String::from(""); + + let raw: Vec<&str> = self.content.splitn(skip + 1, " ").collect(); + if raw.len() == skip + 1 { + ret += raw[skip]; + ret += "\n"; + } else if raw.len() < skip { + return None; + } + + ret += &self + .attachments + .iter() + .map(|x| x.url.clone()) + .collect::>() + .join("\n"); + + if let Some(msg) = &self.referenced_message { + let ref_text = msg.extract_text(0, false); + if with_ref && !ref_text.is_none() { + ret += "\n"; + ret += &ref_text.unwrap(); + } + } + + if ret.is_empty() { + return None; + } else { + return Some(ret); + } + } +} diff --git a/src/lib/mod.rs b/src/lib/mod.rs index f188f2c..f1d2008 100644 --- a/src/lib/mod.rs +++ b/src/lib/mod.rs @@ -1 +1,2 @@ pub mod components; +pub mod messages;