Messaging: Upsert mentions into unreads.

Messaging: Allow multiple attachment upload.
This commit is contained in:
Paul
2021-06-22 17:42:18 +01:00
parent b10d4f3559
commit ad06ff16c4
28 changed files with 116 additions and 92 deletions

View File

@@ -1,3 +1,3 @@
#!/bin/bash #!/bin/bash
export version=0.5.0-alpha.4 export version=0.5.0-alpha.5
echo "pub const VERSION: &str = \"${version}\";" > src/version.rs echo "pub const VERSION: &str = \"${version}\";" > src/version.rs

View File

@@ -128,7 +128,7 @@ impl Channel {
operation: "delete_many", operation: "delete_many",
with: "channel_invites", with: "channel_invites",
})?; })?;
// Delete any unreads. // Delete any unreads.
get_collection("channel_unreads") get_collection("channel_unreads")
.delete_many( .delete_many(

View File

@@ -6,6 +6,7 @@ use crate::{
}; };
use futures::StreamExt; use futures::StreamExt;
use mongodb::options::UpdateOptions;
use mongodb::{ use mongodb::{
bson::{doc, to_bson, DateTime}, bson::{doc, to_bson, DateTime},
options::FindOptions, options::FindOptions,
@@ -55,7 +56,7 @@ impl Content {
"00000000000000000000000000".to_string(), "00000000000000000000000000".to_string(),
target.id().to_string(), target.id().to_string(),
self, self,
None None,
) )
.publish(&target) .publish(&target)
.await .await
@@ -79,11 +80,16 @@ pub struct Message {
#[serde(skip_serializing_if = "Option::is_none")] #[serde(skip_serializing_if = "Option::is_none")]
pub embeds: Option<Vec<Embed>>, pub embeds: Option<Vec<Embed>>,
#[serde(skip_serializing_if = "Option::is_none")] #[serde(skip_serializing_if = "Option::is_none")]
pub mentions: Option<Vec<String>> pub mentions: Option<Vec<String>>,
} }
impl Message { impl Message {
pub fn create(author: String, channel: String, content: Content, mentions: Option<Vec<String>>) -> Message { pub fn create(
author: String,
channel: String,
content: Content,
mentions: Option<Vec<String>>,
) -> Message {
Message { Message {
id: Ulid::new().to_string(), id: Ulid::new().to_string(),
nonce: None, nonce: None,
@@ -94,7 +100,7 @@ impl Message {
attachments: None, attachments: None,
edited: None, edited: None,
embeds: None, embeds: None,
mentions mentions,
} }
} }
@@ -208,7 +214,7 @@ impl Message {
"mentions": message "mentions": message
} }
}, },
None UpdateOptions::builder().upsert(true).build(),
) )
.await .await
/*.map_err(|_| Error::DatabaseError { /*.map_err(|_| Error::DatabaseError {
@@ -241,7 +247,7 @@ impl Message {
} }
_ => {} _ => {}
} }
// Fetch their corresponding sessions. // Fetch their corresponding sessions.
if let Ok(mut cursor) = get_collection("accounts") if let Ok(mut cursor) = get_collection("accounts")
.find( .find(
@@ -309,7 +315,7 @@ impl Message {
ClientboundNotification::MessageUpdate { ClientboundNotification::MessageUpdate {
id: self.id.clone(), id: self.id.clone(),
channel: self.channel.clone(), channel: self.channel.clone(),
data data,
} }
.publish(channel); .publish(channel);
self.process_embed(); self.process_embed();
@@ -348,7 +354,7 @@ impl Message {
ClientboundNotification::MessageUpdate { ClientboundNotification::MessageUpdate {
id, id,
channel: channel.clone(), channel: channel.clone(),
data: json!({ "embeds": embeds }) data: json!({ "embeds": embeds }),
} }
.publish(channel); .publish(channel);
} }

View File

@@ -3,8 +3,8 @@ use crate::util::{
variables::JANUARY_URL, variables::JANUARY_URL,
}; };
use linkify::{LinkFinder, LinkKind}; use linkify::{LinkFinder, LinkKind};
use serde::{Deserialize, Serialize};
use regex::Regex; use regex::Regex;
use serde::{Deserialize, Serialize};
#[derive(Serialize, Deserialize, Debug, Clone)] #[derive(Serialize, Deserialize, Debug, Clone)]
pub enum ImageSize { pub enum ImageSize {

View File

@@ -39,13 +39,13 @@ pub struct SystemMessageChannels {
pub user_joined: Option<String>, pub user_joined: Option<String>,
pub user_left: Option<String>, pub user_left: Option<String>,
pub user_kicked: Option<String>, pub user_kicked: Option<String>,
pub user_banned: Option<String> pub user_banned: Option<String>,
} }
pub enum RemoveMember { pub enum RemoveMember {
Leave, Leave,
Kick, Kick,
Ban Ban,
} }
#[derive(Serialize, Deserialize, Debug, Clone)] #[derive(Serialize, Deserialize, Debug, Clone)]
@@ -361,14 +361,20 @@ impl Server {
} }
RemoveMember::Kick => { RemoveMember::Kick => {
if let Some(cid) = &channels.user_kicked { if let Some(cid) = &channels.user_kicked {
Some((cid.clone(), SystemMessage::UserKicked { id: id.to_string() })) Some((
cid.clone(),
SystemMessage::UserKicked { id: id.to_string() },
))
} else { } else {
None None
} }
} }
RemoveMember::Ban => { RemoveMember::Ban => {
if let Some(cid) = &channels.user_banned { if let Some(cid) = &channels.user_banned {
Some((cid.clone(), SystemMessage::UserBanned { id: id.to_string() })) Some((
cid.clone(),
SystemMessage::UserBanned { id: id.to_string() },
))
} else { } else {
None None
} }

View File

@@ -1,5 +1,5 @@
use serde::{Deserialize, Serialize};
use std::collections::HashMap; use std::collections::HashMap;
use serde::{Serialize, Deserialize};
pub type UserSettings = HashMap<String, (i64, String)>; pub type UserSettings = HashMap<String, (i64, String)>;
@@ -14,6 +14,6 @@ pub struct ChannelUnread {
#[serde(rename = "_id")] #[serde(rename = "_id")]
pub id: ChannelCompositeKey, pub id: ChannelCompositeKey,
pub last_id: String, pub last_id: Option<String>,
pub mentions: Option<Vec<String>>, pub mentions: Option<Vec<String>>,
} }

View File

@@ -261,7 +261,7 @@ impl User {
doc! { doc! {
"_id.user": &self.id "_id.user": &self.id
}, },
None None,
) )
.await .await
.map_err(|_| Error::DatabaseError { .map_err(|_| Error::DatabaseError {

View File

@@ -8,18 +8,18 @@ use std::ops;
#[derive(Debug, PartialEq, Eq, TryFromPrimitive, Copy, Clone)] #[derive(Debug, PartialEq, Eq, TryFromPrimitive, Copy, Clone)]
#[repr(u32)] #[repr(u32)]
pub enum ServerPermission { pub enum ServerPermission {
View = 0b00000000000000000000000000000001, // 1 View = 0b00000000000000000000000000000001, // 1
ManageRoles = 0b00000000000000000000000000000010, // 2 ManageRoles = 0b00000000000000000000000000000010, // 2
ManageChannels = 0b00000000000000000000000000000100, // 4 ManageChannels = 0b00000000000000000000000000000100, // 4
ManageServer = 0b00000000000000000000000000001000, // 8 ManageServer = 0b00000000000000000000000000001000, // 8
KickMembers = 0b00000000000000000000000000010000, // 16 KickMembers = 0b00000000000000000000000000010000, // 16
BanMembers = 0b00000000000000000000000000100000, // 32 BanMembers = 0b00000000000000000000000000100000, // 32
// 6 bits of space // 6 bits of space
ChangeNickname = 0b00000000000000000001000000000000, // 4096 ChangeNickname = 0b00000000000000000001000000000000, // 4096
ManageNicknames = 0b00000000000000000010000000000000, // 8192 ManageNicknames = 0b00000000000000000010000000000000, // 8192
ChangeAvatar = 0b00000000000000000100000000000000, // 16392 ChangeAvatar = 0b00000000000000000100000000000000, // 16392
RemoveAvatars = 0b00000000000000001000000000000000, // 32784 RemoveAvatars = 0b00000000000000001000000000000000, // 32784
// 16 bits of space // 16 bits of space
} }
impl_op_ex!(+ |a: &ServerPermission, b: &ServerPermission| -> u32 { *a as u32 | *b as u32 }); impl_op_ex!(+ |a: &ServerPermission, b: &ServerPermission| -> u32 { *a as u32 | *b as u32 });

View File

@@ -55,8 +55,7 @@ impl<'a> PermissionCalculator<'a> {
.map(|v| v.to_owned()) .map(|v| v.to_owned())
.unwrap_or_else(|| get_relationship(&self.perspective, &target)) .unwrap_or_else(|| get_relationship(&self.perspective, &target))
{ {
RelationshipStatus::Friend | RelationshipStatus::Friend | RelationshipStatus::User => return Ok(u32::MAX),
RelationshipStatus::User => return Ok(u32::MAX),
RelationshipStatus::Blocked | RelationshipStatus::BlockedOther => { RelationshipStatus::Blocked | RelationshipStatus::BlockedOther => {
return Ok(UserPermission::Access as u32) return Ok(UserPermission::Access as u32)
} }

View File

@@ -5,10 +5,7 @@ use rocket_contrib::json::JsonValue;
use serde::{Deserialize, Serialize}; use serde::{Deserialize, Serialize};
use super::hive::{get_hive, subscribe_if_exists}; use super::hive::{get_hive, subscribe_if_exists};
use crate::{ use crate::{database::*, util::result::Result};
database::*,
util::result::{Result},
};
#[derive(Serialize, Deserialize, Debug, Clone)] #[derive(Serialize, Deserialize, Debug, Clone)]
#[serde(tag = "error")] #[serde(tag = "error")]
@@ -63,14 +60,14 @@ pub enum ClientboundNotification {
Ready { Ready {
users: Vec<User>, users: Vec<User>,
servers: Vec<Server>, servers: Vec<Server>,
channels: Vec<Channel> channels: Vec<Channel>,
}, },
Message(Message), Message(Message),
MessageUpdate { MessageUpdate {
id: String, id: String,
channel: String, channel: String,
data: JsonValue data: JsonValue,
}, },
MessageDelete { MessageDelete {
id: String, id: String,
@@ -106,7 +103,7 @@ pub enum ClientboundNotification {
ChannelAck { ChannelAck {
id: String, id: String,
user: String, user: String,
message_id: String message_id: String,
}, },
ServerUpdate { ServerUpdate {

View File

@@ -113,6 +113,6 @@ pub async fn generate_ready(mut user: User) -> Result<ClientboundNotification> {
Ok(ClientboundNotification::Ready { Ok(ClientboundNotification::Ready {
users, users,
servers, servers,
channels channels,
}) })
} }

View File

@@ -1,6 +1,6 @@
use crate::database::*;
use crate::notifications::events::ClientboundNotification; use crate::notifications::events::ClientboundNotification;
use crate::util::result::{Error, Result}; use crate::util::result::{Error, Result};
use crate::database::*;
use mongodb::bson::doc; use mongodb::bson::doc;
use mongodb::options::UpdateOptions; use mongodb::options::UpdateOptions;
@@ -33,21 +33,20 @@ pub async fn req(user: User, target: Ref, message: Ref) -> Result<()> {
"last_id": &message.id "last_id": &message.id
} }
}, },
UpdateOptions::builder() UpdateOptions::builder().upsert(true).build(),
.upsert(true)
.build()
) )
.await .await
.map_err(|_| Error::DatabaseError { .map_err(|_| Error::DatabaseError {
operation: "update_one", operation: "update_one",
with: "channel_unreads", with: "channel_unreads",
})?; })?;
ClientboundNotification::ChannelAck { ClientboundNotification::ChannelAck {
id: id.to_string(), id: id.to_string(),
user: user.id.clone(), user: user.id.clone(),
message_id: message.id message_id: message.id,
}.publish(user.id); }
.publish(user.id);
Ok(()) Ok(())
} }

View File

@@ -99,8 +99,9 @@ pub async fn req(user: User, target: Ref) -> Result<()> {
.publish(id.clone()); .publish(id.clone());
Content::SystemMessage(SystemMessage::UserLeft { id: user.id }) Content::SystemMessage(SystemMessage::UserLeft { id: user.id })
.send_as_system(&target) .send_as_system(&target)
.await.ok(); .await
.ok();
Ok(()) Ok(())
} }

View File

@@ -117,7 +117,8 @@ pub async fn req(user: User, target: Ref, data: Json<Data>) -> Result<()> {
by: user.id.clone(), by: user.id.clone(),
}) })
.send_as_system(&target) .send_as_system(&target)
.await.ok(); .await
.ok();
} }
if let Some(_) = data.description { if let Some(_) = data.description {
@@ -125,13 +126,15 @@ pub async fn req(user: User, target: Ref, data: Json<Data>) -> Result<()> {
by: user.id.clone(), by: user.id.clone(),
}) })
.send_as_system(&target) .send_as_system(&target)
.await.ok(); .await
.ok();
} }
if let Some(_) = data.icon { if let Some(_) = data.icon {
Content::SystemMessage(SystemMessage::ChannelIconChanged { by: user.id }) Content::SystemMessage(SystemMessage::ChannelIconChanged { by: user.id })
.send_as_system(&target) .send_as_system(&target)
.await.ok(); .await
.ok();
} }
} }

View File

@@ -60,7 +60,8 @@ pub async fn req(user: User, target: Ref, member: Ref) -> Result<()> {
by: user.id, by: user.id,
}) })
.send_as_system(&channel) .send_as_system(&channel)
.await.ok(); .await
.ok();
Ok(()) Ok(())
} else { } else {

View File

@@ -39,8 +39,7 @@ pub async fn req(user: User, info: Json<Data>) -> Result<JsonValue> {
for target in &set { for target in &set {
match get_relationship(&user, target) { match get_relationship(&user, target) {
RelationshipStatus::Friend | RelationshipStatus::Friend | RelationshipStatus::User => {}
RelationshipStatus::User => {},
_ => { _ => {
return Err(Error::NotFriends); return Err(Error::NotFriends);
} }

View File

@@ -56,7 +56,8 @@ pub async fn req(user: User, target: Ref, member: Ref) -> Result<()> {
by: user.id, by: user.id,
}) })
.send_as_system(&channel) .send_as_system(&channel)
.await.ok(); .await
.ok();
Ok(()) Ok(())
} else { } else {

View File

@@ -2,7 +2,7 @@ use crate::database::*;
use crate::util::result::{Error, Result}; use crate::util::result::{Error, Result};
use chrono::Utc; use chrono::Utc;
use mongodb::bson::{Bson, DateTime, Document, doc}; use mongodb::bson::{doc, Bson, DateTime, Document};
use rocket_contrib::json::Json; use rocket_contrib::json::Json;
use serde::{Deserialize, Serialize}; use serde::{Deserialize, Serialize};
use validator::Validate; use validator::Validate;
@@ -45,10 +45,7 @@ pub async fn req(user: User, target: Ref, msg: Ref, edit: Json<Data>) -> Result<
for embed in embeds { for embed in embeds {
match embed { match embed {
Embed::Website(_) | Embed::Website(_) | Embed::Image(_) | Embed::None => {} // Otherwise push to new_embeds.
Embed::Image(_) |
Embed::None => { }
// Otherwise push to new_embeds.
} }
} }
@@ -73,7 +70,5 @@ pub async fn req(user: User, target: Ref, msg: Ref, edit: Json<Data>) -> Result<
with: "message", with: "message",
})?; })?;
message message.publish_update(update).await
.publish_update(update)
.await
} }

View File

@@ -2,11 +2,11 @@ use crate::database::*;
use crate::util::result::{Error, Result}; use crate::util::result::{Error, Result};
use mongodb::{bson::doc, options::FindOneOptions}; use mongodb::{bson::doc, options::FindOneOptions};
use regex::Regex;
use rocket_contrib::json::{Json, JsonValue}; use rocket_contrib::json::{Json, JsonValue};
use serde::{Deserialize, Serialize}; use serde::{Deserialize, Serialize};
use validator::Validate;
use regex::Regex;
use ulid::Ulid; use ulid::Ulid;
use validator::Validate;
#[derive(Validate, Serialize, Deserialize)] #[derive(Validate, Serialize, Deserialize)]
pub struct Data { pub struct Data {
@@ -16,7 +16,7 @@ pub struct Data {
#[validate(length(min = 1, max = 36))] #[validate(length(min = 1, max = 36))]
nonce: String, nonce: String,
#[validate(length(min = 1, max = 128))] #[validate(length(min = 1, max = 128))]
attachment: Option<String>, attachments: Option<Vec<String>>,
} }
lazy_static! { lazy_static! {
@@ -29,7 +29,9 @@ pub async fn req(user: User, target: Ref, message: Json<Data>) -> Result<JsonVal
.validate() .validate()
.map_err(|error| Error::FailedValidation { error })?; .map_err(|error| Error::FailedValidation { error })?;
if message.content.len() == 0 && message.attachment.is_none() { if message.content.len() == 0
&& (message.attachments.is_none() || message.attachments.as_ref().unwrap().len() == 0)
{
return Err(Error::EmptyMessage); return Err(Error::EmptyMessage);
} }
@@ -63,10 +65,19 @@ pub async fn req(user: User, target: Ref, message: Json<Data>) -> Result<JsonVal
} }
let id = Ulid::new().to_string(); let id = Ulid::new().to_string();
let attachments = if let Some(attachment_id) = &message.attachment { let attachments = if let Some(ids) = &message.attachments {
Some(vec![ // ! FIXME: move this to app config
File::find_and_use(attachment_id, "attachments", "message", &id).await?, if ids.len() >= 5 {
]) return Err(Error::TooManyAttachments)
}
let mut attachments = vec![];
for attachment_id in ids {
attachments
.push(File::find_and_use(attachment_id, "attachments", "message", &id).await?);
}
Some(attachments)
} else { } else {
None None
}; };
@@ -77,6 +88,7 @@ pub async fn req(user: User, target: Ref, message: Json<Data>) -> Result<JsonVal
mentions.push(captures[1].to_string()); mentions.push(captures[1].to_string());
} }
let msg = Message { let msg = Message {
id, id,
channel: target.id().to_string(), channel: target.id().to_string(),
@@ -87,7 +99,11 @@ pub async fn req(user: User, target: Ref, message: Json<Data>) -> Result<JsonVal
nonce: Some(message.nonce.clone()), nonce: Some(message.nonce.clone()),
edited: None, edited: None,
embeds: None, embeds: None,
mentions: if mentions.len() > 0 { Some(mentions) } else { None } mentions: if mentions.len() > 0 {
Some(mentions)
} else {
None
},
}; };
msg.clone().publish(&target).await?; msg.clone().publish(&target).await?;

View File

@@ -1,7 +1,6 @@
use crate::util::variables::{ use crate::util::variables::{
APP_URL, AUTUMN_URL, EXTERNAL_WS_URL, HCAPTCHA_SITEKEY, INVITE_ONLY, APP_URL, AUTUMN_URL, EXTERNAL_WS_URL, HCAPTCHA_SITEKEY, INVITE_ONLY, JANUARY_URL, USE_AUTUMN,
JANUARY_URL, USE_AUTUMN, USE_EMAIL, USE_HCAPTCHA, USE_JANUARY, USE_VOSO, VAPID_PUBLIC_KEY, USE_EMAIL, USE_HCAPTCHA, USE_JANUARY, USE_VOSO, VAPID_PUBLIC_KEY, VOSO_URL, VOSO_WS_HOST,
VOSO_URL, VOSO_WS_HOST,
}; };
use mongodb::bson::doc; use mongodb::bson::doc;

View File

@@ -31,11 +31,11 @@ pub async fn req(user: User, server: Ref, target: Ref, data: Json<Data>) -> Resu
let target = target.fetch_user().await?; let target = target.fetch_user().await?;
if target.id == user.id { if target.id == user.id {
return Err(Error::InvalidOperation) return Err(Error::InvalidOperation);
} }
if target.id == server.owner { if target.id == server.owner {
return Err(Error::MissingPermission) return Err(Error::MissingPermission);
} }
let mut document = doc! { let mut document = doc! {

View File

@@ -60,7 +60,7 @@ pub async fn req(user: User, target: Ref, info: Json<Data>) -> Result<JsonValue>
name: info.name, name: info.name,
description: info.description, description: info.description,
icon: None, icon: None,
last_message: None last_message: None,
}; };
channel.clone().publish().await?; channel.clone().publish().await?;

View File

@@ -25,5 +25,7 @@ pub async fn req(user: User, target: Ref, member: String) -> Result<()> {
return Err(Error::MissingPermission); return Err(Error::MissingPermission);
} }
target.remove_member(&member.id.user, RemoveMember::Kick).await target
.remove_member(&member.id.user, RemoveMember::Kick)
.await
} }

View File

@@ -52,14 +52,12 @@ pub async fn req(user: User, info: Json<Data>) -> Result<JsonValue> {
name: info.name, name: info.name,
description: info.description, description: info.description,
channels: vec![cid.clone()], channels: vec![cid.clone()],
system_messages: Some( system_messages: Some(SystemMessageChannels {
SystemMessageChannels { user_joined: Some(cid.clone()),
user_joined: Some(cid.clone()), user_left: Some(cid.clone()),
user_left: Some(cid.clone()), user_kicked: Some(cid.clone()),
user_kicked: Some(cid.clone()), user_banned: Some(cid.clone()),
user_banned: Some(cid.clone()) }),
}
),
icon: None, icon: None,
banner: None, banner: None,
@@ -72,7 +70,7 @@ pub async fn req(user: User, info: Json<Data>) -> Result<JsonValue> {
name: "general".to_string(), name: "general".to_string(),
description: None, description: None,
icon: None, icon: None,
last_message: None last_message: None,
} }
.publish() .publish()
.await?; .await?;

View File

@@ -1,8 +1,8 @@
use crate::database::*; use crate::database::*;
use crate::util::result::Result; use crate::util::result::Result;
use rocket_contrib::json::JsonValue;
use mongodb::bson::doc; use mongodb::bson::doc;
use rocket_contrib::json::JsonValue;
#[get("/unreads")] #[get("/unreads")]
pub async fn req(user: User) -> Result<JsonValue> { pub async fn req(user: User) -> Result<JsonValue> {

View File

@@ -1,8 +1,8 @@
use rocket::Route; use rocket::Route;
mod get_settings; mod get_settings;
mod set_settings;
mod get_unreads; mod get_unreads;
mod set_settings;
pub fn routes() -> Vec<Route> { pub fn routes() -> Vec<Route> {
routes![get_settings::req, set_settings::req, get_unreads::req] routes![get_settings::req, set_settings::req, get_unreads::req]

View File

@@ -28,6 +28,7 @@ pub enum Error {
UnknownAttachment, UnknownAttachment,
CannotEditMessage, CannotEditMessage,
CannotJoinCall, CannotJoinCall,
TooManyAttachments,
EmptyMessage, EmptyMessage,
CannotRemoveYourself, CannotRemoveYourself,
GroupTooLarge { GroupTooLarge {
@@ -81,6 +82,7 @@ impl<'r> Responder<'r, 'static> for Error {
Error::UnknownAttachment => Status::BadRequest, Error::UnknownAttachment => Status::BadRequest,
Error::CannotEditMessage => Status::Forbidden, Error::CannotEditMessage => Status::Forbidden,
Error::CannotJoinCall => Status::BadRequest, Error::CannotJoinCall => Status::BadRequest,
Error::TooManyAttachments => Status::BadRequest,
Error::EmptyMessage => Status::UnprocessableEntity, Error::EmptyMessage => Status::UnprocessableEntity,
Error::CannotRemoveYourself => Status::BadRequest, Error::CannotRemoveYourself => Status::BadRequest,
Error::GroupTooLarge { .. } => Status::Forbidden, Error::GroupTooLarge { .. } => Status::Forbidden,

View File

@@ -1 +1 @@
pub const VERSION: &str = "0.5.0-alpha.4"; pub const VERSION: &str = "0.5.0-alpha.5";