feat(messaging): add sendable embeds (#119)

This commit is contained in:
Zomatree
2022-01-15 10:43:47 +00:00
committed by GitHub
parent 96fd18f679
commit 8be51dc4f0
4 changed files with 103 additions and 19 deletions

View File

@@ -3,6 +3,7 @@ use crate::util::{
variables::JANUARY_URL, variables::JANUARY_URL,
variables::MAX_EMBED_COUNT, variables::MAX_EMBED_COUNT,
}; };
use crate::database::entities::microservice::autumn::File;
use linkify::{LinkFinder, LinkKind}; use linkify::{LinkFinder, LinkKind};
use regex::Regex; use regex::Regex;
use serde::{Deserialize, Serialize}; use serde::{Deserialize, Serialize};
@@ -92,11 +93,28 @@ pub struct Metadata {
colour: Option<String>, colour: Option<String>,
} }
#[derive(Serialize, Deserialize, Debug, Clone)]
pub struct Text {
#[serde(skip_serializing_if = "Option::is_none")]
pub icon_url: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub url: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub title: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub description: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub media: Option<File>,
#[serde(skip_serializing_if = "Option::is_none")]
pub colour: Option<String>,
}
#[derive(Serialize, Deserialize, Debug, Clone)] #[derive(Serialize, Deserialize, Debug, Clone)]
#[serde(tag = "type")] #[serde(tag = "type")]
pub enum Embed { pub enum Embed {
Website(Metadata), Website(Metadata),
Image(Image), Image(Image),
Text(Text),
None, None,
} }

View File

@@ -1,8 +1,9 @@
use crate::database::*; use crate::database::*;
use crate::util::result::{Error, Result, EmptyResponse}; use crate::util::result::{Error, Result, EmptyResponse};
use crate::routes::channels::message_send::SendableEmbed;
use chrono::Utc; use chrono::Utc;
use mongodb::bson::{doc, Bson, DateTime, Document}; use mongodb::bson::{Bson, Document, doc, to_document};
use rocket::serde::json::Json; use rocket::serde::json::Json;
use serde::{Deserialize, Serialize}; use serde::{Deserialize, Serialize};
use validator::Validate; use validator::Validate;
@@ -10,7 +11,9 @@ use validator::Validate;
#[derive(Validate, Serialize, Deserialize)] #[derive(Validate, Serialize, Deserialize)]
pub struct Data { pub struct Data {
#[validate(length(min = 1, max = 2000))] #[validate(length(min = 1, max = 2000))]
content: String, content: Option<String>,
#[validate(length(min = 0, max = 10))]
embeds: Option<Vec<SendableEmbed>>
} }
#[patch("/<target>/messages/<msg>", data = "<edit>")] #[patch("/<target>/messages/<msg>", data = "<edit>")]
@@ -35,26 +38,48 @@ pub async fn req(user: User, target: Ref, msg: Ref, edit: Json<Data>) -> Result<
} }
let edited = Utc::now(); let edited = Utc::now();
let mut set = doc! { let mut set = doc! { "edited": Bson::DateTime(edited) };
"content": &edit.content, let mut unset = doc! {};
"edited": Bson::DateTime(edited) let mut update = json!({ "edited": Bson::DateTime(edited) });
};
message.content = Content::Text(edit.content.clone()); if let Some(new_content) = &edit.content {
let mut update = json!({ "content": edit.content, "edited": DateTime(edited) }); set.insert("content", new_content.clone());
update.as_object_mut().unwrap().insert("content".to_string(), json!(new_content.clone()));
message.content = Content::Text(new_content.clone());
}
let mut new_embeds: Vec<Embed> = vec![];
if let Some(embeds) = &message.embeds { if let Some(embeds) = &message.embeds {
let new_embeds: Vec<Document> = vec![];
for embed in embeds { for embed in embeds {
match embed { match embed {
Embed::Website(_) | Embed::Image(_) | Embed::None => {} // Otherwise push to new_embeds. Embed::Text(embed) => new_embeds.push(Embed::Text(embed.clone())),
_ => {}
} }
} }
}
if let Some(edited_embeds) = &edit.embeds {
new_embeds.clear();
for embed in edited_embeds {
new_embeds.push(embed.clone().into_embed(message.id.clone()).await?);
}
}
if new_embeds.len() > 0 {
let embed_docs: Vec<Document> = new_embeds
.clone()
.into_iter()
.map(|embed| to_document(&embed).unwrap())
.collect();
let obj = update.as_object_mut().unwrap(); let obj = update.as_object_mut().unwrap();
obj.insert("embeds".to_string(), json!(new_embeds)); obj.insert("embeds".to_string(), json!(embed_docs));
set.insert("embeds", new_embeds); set.insert("embeds", embed_docs);
message.embeds = Some(new_embeds)
} else if edit.embeds.is_some() {
unset.insert("embeds", 1 as u32);
} }
get_collection("messages") get_collection("messages")
@@ -63,7 +88,8 @@ pub async fn req(user: User, target: Ref, msg: Ref, edit: Json<Data>) -> Result<
"_id": &message.id "_id": &message.id
}, },
doc! { doc! {
"$set": set "$set": set,
"$unset": unset
}, },
None, None,
) )

View File

@@ -18,6 +18,35 @@ pub struct Reply {
mention: bool mention: bool
} }
#[derive(Validate, Serialize, Deserialize, Clone, Debug)]
pub struct SendableEmbed {
icon_url: Option<String>,
url: Option<String>,
#[validate(length(min = 1, max = 100))]
title: Option<String>,
#[validate(length(min = 1, max = 2000))]
description: Option<String>,
media: Option<String>,
colour: Option<String>,
}
impl SendableEmbed {
pub async fn into_embed(self, message_id: String) -> Result<Embed> {
let media = if let Some(id) = self.media {
Some(File::find_and_use(&id, "attachments", "message", &message_id).await?)
} else { None };
Ok(Embed::Text(Text {
icon_url: self.icon_url,
url: self.url,
title: self.title,
description: self.description,
media,
colour: self.colour
}))
}
}
#[derive(Validate, Serialize, Deserialize)] #[derive(Validate, Serialize, Deserialize)]
pub struct Data { pub struct Data {
#[validate(length(min = 0, max = 2000))] #[validate(length(min = 0, max = 2000))]
@@ -27,7 +56,9 @@ pub struct Data {
nonce: Option<String>, nonce: Option<String>,
replies: Option<Vec<Reply>>, replies: Option<Vec<Reply>>,
#[validate] #[validate]
masquerade: Option<Masquerade> masquerade: Option<Masquerade>,
#[validate(length(min = 1, max = 10))]
embeds: Option<Vec<SendableEmbed>>
} }
lazy_static! { lazy_static! {
@@ -114,6 +145,14 @@ pub async fn message_send(user: User, _r: Ratelimiter, mut idempotency: Idempote
} }
} }
let mut embeds = vec![];
if let Some(sendable_embeds) = message.embeds {
for sendable_embed in sendable_embeds {
embeds.push(sendable_embed.into_embed(id.clone()).await?)
}
}
let msg = Message { let msg = Message {
id, id,
channel: target.id().to_string(), channel: target.id().to_string(),
@@ -122,8 +161,7 @@ pub async fn message_send(user: User, _r: Ratelimiter, mut idempotency: Idempote
content: Content::Text(message.content.clone()), content: Content::Text(message.content.clone()),
nonce: Some(idempotency.key), nonce: Some(idempotency.key),
edited: None, edited: None,
embeds: None, embeds: if embeds.len() > 0 { Some(embeds) } else { None },
attachments: if attachments.len() > 0 { Some(attachments) } else { None }, attachments: if attachments.len() > 0 { Some(attachments) } else { None },
mentions: if mentions.len() > 0 { mentions: if mentions.len() > 0 {
Some(mentions.into_iter().collect::<Vec<String>>()) Some(mentions.into_iter().collect::<Vec<String>>())

View File

@@ -31,8 +31,10 @@ pub async fn run() {
"_id": &id "_id": &id
}, },
doc! { doc! {
"$set": { "$push": {
"embeds": bson "embeds": {
"$each": bson
}
} }
}, },
None, None,