Strict typing for system messages; add a way to rename group.

This commit is contained in:
Paul
2021-03-31 20:54:47 +01:00
parent 60731e1c70
commit 32cd9d8a13
11 changed files with 147 additions and 30 deletions

2
Cargo.lock generated
View File

@@ -2475,7 +2475,7 @@ dependencies = [
[[package]] [[package]]
name = "revolt" name = "revolt"
version = "0.4.0-alpha.0" version = "0.4.0-alpha.1"
dependencies = [ dependencies = [
"async-std", "async-std",
"async-tungstenite", "async-tungstenite",

View File

@@ -1,6 +1,6 @@
[package] [package]
name = "revolt" name = "revolt"
version = "0.4.0-alpha.0" version = "0.4.0-alpha.1"
authors = ["Paul Makles <paulmakles@gmail.com>"] authors = ["Paul Makles <paulmakles@gmail.com>"]
edition = "2018" edition = "2018"

View File

@@ -17,6 +17,47 @@ use web_push::{
ContentEncoding, SubscriptionInfo, VapidSignatureBuilder, WebPushClient, WebPushMessageBuilder, ContentEncoding, SubscriptionInfo, VapidSignatureBuilder, WebPushClient, WebPushMessageBuilder,
}; };
#[derive(Serialize, Deserialize, Debug, Clone)]
#[serde(tag = "type")]
pub enum MessageEmbed {
Dummy
}
#[derive(Serialize, Deserialize, Debug, Clone)]
#[serde(tag = "type")]
pub enum SystemMessage {
#[serde(rename = "text")]
Text {
content: String
},
#[serde(rename = "user_added")]
UserAdded {
id: String,
by: String
},
#[serde(rename = "user_remove")]
UserRemove {
id: String,
by: String
},
#[serde(rename = "user_left")]
UserLeft {
id: String
},
#[serde(rename = "channel_renamed")]
ChannelRenamed {
name: String,
by: String
},
}
#[derive(Serialize, Deserialize, Debug, Clone)]
#[serde(untagged)]
pub enum Content {
Text(String),
SystemMessage(SystemMessage)
}
#[derive(Serialize, Deserialize, Debug, Clone)] #[derive(Serialize, Deserialize, Debug, Clone)]
pub struct Message { pub struct Message {
#[serde(rename = "_id")] #[serde(rename = "_id")]
@@ -26,15 +67,17 @@ pub struct Message {
pub channel: String, pub channel: String,
pub author: String, pub author: String,
pub content: String, pub content: Content,
#[serde(skip_serializing_if = "Option::is_none")] #[serde(skip_serializing_if = "Option::is_none")]
pub attachment: Option<File>, pub attachment: Option<File>,
#[serde(skip_serializing_if = "Option::is_none")] #[serde(skip_serializing_if = "Option::is_none")]
pub edited: Option<DateTime>, pub edited: Option<DateTime>,
#[serde(skip_serializing_if = "Option::is_none")]
pub embeds: Option<MessageEmbed>,
} }
impl Message { impl Message {
pub fn create(author: String, channel: String, content: String) -> Message { pub fn create(author: String, channel: String, content: Content) -> Message {
Message { Message {
id: Ulid::new().to_string(), id: Ulid::new().to_string(),
nonce: None, nonce: None,
@@ -44,6 +87,7 @@ impl Message {
content, content,
attachment: None, attachment: None,
edited: None, edited: None,
embeds: None
} }
} }
@@ -56,22 +100,28 @@ impl Message {
with: "message", with: "message",
})?; })?;
let mut set = if let Content::Text(text) = &self.content {
doc! {
"last_message": {
"_id": self.id.clone(),
"author": self.author.clone(),
"short": text.chars().take(24).collect::<String>()
}
}
} else {
doc! {}
};
// ! FIXME: temp code // ! FIXME: temp code
let channels = get_collection("channels"); let channels = get_collection("channels");
match &channel { match &channel {
Channel::DirectMessage { id, .. } => { Channel::DirectMessage { id, .. } => {
set.insert("active", true);
channels channels
.update_one( .update_one(
doc! { "_id": id }, doc! { "_id": id },
doc! { doc! {
"$set": { "$set": set
"active": true,
"last_message": {
"_id": self.id.clone(),
"author": self.author.clone(),
"short": self.content.chars().take(24).collect::<String>()
}
}
}, },
None, None,
) )
@@ -86,13 +136,7 @@ impl Message {
.update_one( .update_one(
doc! { "_id": id }, doc! { "_id": id },
doc! { doc! {
"$set": { "$set": set
"last_message": {
"_id": self.id.clone(),
"author": self.author.clone(),
"short": self.content.chars().take(24).collect::<String>()
}
}
}, },
None, None,
) )

View File

@@ -12,7 +12,8 @@ pub enum ChannelPermission {
View = 1, View = 1,
SendMessage = 2, SendMessage = 2,
ManageMessages = 4, ManageMessages = 4,
VoiceCall = 8, ManageChannel = 8,
VoiceCall = 16,
} }
bitfield! { bitfield! {
@@ -21,7 +22,8 @@ bitfield! {
pub get_view, _: 31; pub get_view, _: 31;
pub get_send_message, _: 30; pub get_send_message, _: 30;
pub get_manage_messages, _: 29; pub get_manage_messages, _: 29;
pub get_voice_call, _: 28; pub get_manage_channel, _: 28;
pub get_voice_call, _: 27;
} }
impl_op_ex!(+ |a: &ChannelPermission, b: &ChannelPermission| -> u32 { *a as u32 | *b as u32 }); impl_op_ex!(+ |a: &ChannelPermission, b: &ChannelPermission| -> u32 { *a as u32 | *b as u32 });
@@ -69,7 +71,7 @@ impl<'a> PermissionCalculator<'a> {
.find(|x| *x == &self.perspective.id) .find(|x| *x == &self.perspective.id)
.is_some() .is_some()
{ {
Ok(ChannelPermission::View + ChannelPermission::SendMessage + ChannelPermission::VoiceCall) Ok(ChannelPermission::View + ChannelPermission::SendMessage + ChannelPermission::ManageChannel + ChannelPermission::VoiceCall)
} else { } else {
Ok(0) Ok(0)
} }

View File

@@ -102,8 +102,7 @@ pub async fn req(user: User, target: Ref) -> Result<()> {
Message::create( Message::create(
"00000000000000000000000000".to_string(), "00000000000000000000000000".to_string(),
id.clone(), id.clone(),
// ! FIXME: make a schema for this Content::SystemMessage(SystemMessage::UserLeft { id: user.id })
format!("{{\"type\":\"user_left\",\"id\":\"{}\"}}", user.id),
) )
.publish(&target) .publish(&target)
.await .await

View File

@@ -0,0 +1,71 @@
use crate::database::*;
use crate::util::result::{Error, Result};
use crate::notifications::events::ClientboundNotification;
use validator::Validate;
use rocket_contrib::json::Json;
use serde::{Serialize, Deserialize};
use mongodb::bson::{doc, to_document};
#[derive(Validate, Serialize, Deserialize)]
pub struct Data {
#[validate(length(min = 1, max = 32))]
name: Option<String>,
#[validate(length(min = 0, max = 1024))]
description: Option<String>,
}
#[patch("/<target>", data = "<info>")]
pub async fn req(user: User, target: Ref, info: Json<Data>) -> Result<()> {
info.validate()
.map_err(|error| Error::FailedValidation { error })?;
if info.name.is_none() && info.description.is_none() {
return Ok(())
}
let target = target.fetch_channel().await?;
let perm = permissions::PermissionCalculator::new(&user)
.with_channel(&target)
.for_channel()
.await?;
if !perm.get_manage_channel() {
Err(Error::MissingPermission)?
}
match &target {
Channel::Group { id, .. } => {
let col = get_collection("channels");
col.update_one(
doc! { "_id": &id },
doc! { "$set": to_document(&info.0).map_err(|_| Error::DatabaseError { operation: "to_document", with: "info" })? },
None
)
.await
.map_err(|_| Error::DatabaseError { operation: "update_one", with: "channel" })?;
ClientboundNotification::ChannelUpdate {
id: id.clone(),
data: json!(info.0)
}
.publish(id.clone())
.await
.ok();
if let Some(name) = &info.name {
Message::create(
"00000000000000000000000000".to_string(),
id.clone(),
Content::SystemMessage(SystemMessage::ChannelRenamed { name: name.clone(), by: user.id })
)
.publish(&target)
.await
.ok();
}
Ok(())
}
_ => Err(Error::InvalidOperation)
}
}

View File

@@ -59,8 +59,7 @@ pub async fn req(user: User, target: Ref, member: Ref) -> Result<()> {
Message::create( Message::create(
"00000000000000000000000000".to_string(), "00000000000000000000000000".to_string(),
id.clone(), id.clone(),
// ! FIXME: make a schema for this Content::SystemMessage(SystemMessage::UserAdded { id: member.id, by: user.id })
format!("{{\"type\":\"user_added\",\"id\":\"{}\",\"by\":\"{}\"}}", member.id, user.id),
) )
.publish(&channel) .publish(&channel)
.await .await

View File

@@ -56,8 +56,7 @@ pub async fn req(user: User, target: Ref, member: Ref) -> Result<()> {
Message::create( Message::create(
"00000000000000000000000000".to_string(), "00000000000000000000000000".to_string(),
id.clone(), id.clone(),
// ! FIXME: make a schema for this Content::SystemMessage(SystemMessage::UserRemove { id: member.id, by: user.id })
format!("{{\"type\":\"user_remove\",\"id\":\"{}\",\"by\":\"{}\"}}", member.id, user.id),
) )
.publish(&channel) .publish(&channel)
.await .await

View File

@@ -115,10 +115,11 @@ pub async fn req(user: User, target: Ref, message: Json<Data>) -> Result<JsonVal
channel: target.id().to_string(), channel: target.id().to_string(),
author: user.id, author: user.id,
content: message.content.clone(), content: Content::Text(message.content.clone()),
attachment, attachment,
nonce: Some(message.nonce.clone()), nonce: Some(message.nonce.clone()),
edited: None, edited: None,
embeds: None
}; };
msg.clone().publish(&target).await?; msg.clone().publish(&target).await?;

View File

@@ -1,6 +1,7 @@
use rocket::Route; use rocket::Route;
mod delete_channel; mod delete_channel;
mod edit_channel;
mod fetch_channel; mod fetch_channel;
mod group_add_member; mod group_add_member;
mod group_create; mod group_create;
@@ -17,6 +18,7 @@ pub fn routes() -> Vec<Route> {
routes![ routes![
fetch_channel::req, fetch_channel::req,
delete_channel::req, delete_channel::req,
edit_channel::req,
message_send::req, message_send::req,
message_query::req, message_query::req,
message_query_stale::req, message_query_stale::req,

View File

@@ -9,7 +9,7 @@ use rocket_contrib::json::JsonValue;
#[get("/")] #[get("/")]
pub async fn root() -> JsonValue { pub async fn root() -> JsonValue {
json!({ json!({
"revolt": "0.4.0-alpha.0", "revolt": "0.4.0-alpha.1",
"features": { "features": {
"registration": !*DISABLE_REGISTRATION, "registration": !*DISABLE_REGISTRATION,
"captcha": { "captcha": {