Servers: Add invites. Create, view and join.

This commit is contained in:
Paul
2021-06-03 20:00:08 +01:00
parent 812fa2a98f
commit 681b2b8ab6
21 changed files with 335 additions and 81 deletions

12
Cargo.lock generated
View File

@@ -1599,6 +1599,15 @@ dependencies = [
"rand 0.6.5",
]
[[package]]
name = "nanoid"
version = "0.4.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "3ffa00dec017b5b1a8b7cf5e2c008bfda1aa7e0697ac1508b491fdf2622fb4d8"
dependencies = [
"rand 0.8.3",
]
[[package]]
name = "native-tls"
version = "0.2.7"
@@ -2341,7 +2350,7 @@ dependencies = [
"lazy_static",
"lettre",
"mongodb",
"nanoid",
"nanoid 0.3.0",
"regex",
"reqwest",
"rocket",
@@ -2497,6 +2506,7 @@ dependencies = [
"many-to-many",
"md5",
"mongodb",
"nanoid 0.4.0",
"num_enum",
"once_cell",
"rand 0.7.3",

View File

@@ -16,6 +16,7 @@ log = "0.4.11"
ulid = "0.4.1"
rand = "0.7.3"
time = "0.2.16"
nanoid = "0.4.0"
base64 = "0.13.0"
linkify = "0.6.0"
dotenv = "0.15.0"

View File

@@ -3,7 +3,7 @@ use crate::notifications::events::ClientboundNotification;
use crate::util::result::{Error, Result};
use futures::StreamExt;
use mongodb::{
bson::{doc, from_document, to_document, Document},
bson::{doc, to_document, Document},
options::FindOptions,
};
use rocket_contrib::json::JsonValue;
@@ -76,22 +76,6 @@ impl Channel {
}
}
pub async fn get(id: &str) -> Result<Channel> {
let doc = get_collection("channels")
.find_one(doc! { "_id": id }, None)
.await
.map_err(|_| Error::DatabaseError {
operation: "find_one",
with: "channel",
})?
.ok_or_else(|| Error::UnknownChannel)?;
from_document::<Channel>(doc).map_err(|_| Error::DatabaseError {
operation: "from_document",
with: "channel",
})
}
pub async fn publish(self) -> Result<()> {
get_collection("channels")
.insert_one(

View File

@@ -0,0 +1,88 @@
use mongodb::bson::doc;
use mongodb::bson::from_document;
use mongodb::bson::to_document;
use serde::{Deserialize, Serialize};
use crate::database::get_collection;
use crate::util::result::Error;
use crate::util::result::Result;
#[derive(Serialize, Deserialize, Debug, Clone)]
#[serde(tag = "type")]
pub enum Invite {
Server {
#[serde(rename = "_id")]
code: String,
creator: String,
channel: String,
},
Group {
#[serde(rename = "_id")]
code: String,
creator: String,
channel: String,
}, /* User {
code: String,
user: String
} */
}
impl Invite {
pub fn code(&self) -> &String {
match &self {
Invite::Server { code, .. } => code,
Invite::Group { code, .. } => code,
}
}
pub async fn get(code: &str) -> Result<Invite> {
let doc = get_collection("invites")
.find_one(doc! { "_id": code }, None)
.await
.map_err(|_| Error::DatabaseError {
operation: "find_one",
with: "invite",
})?
.ok_or_else(|| Error::UnknownServer)?;
from_document::<Invite>(doc).map_err(|_| Error::DatabaseError {
operation: "from_document",
with: "invite",
})
}
pub async fn save(self) -> Result<()> {
get_collection("invites")
.insert_one(
to_document(&self).map_err(|_| Error::DatabaseError {
operation: "to_bson",
with: "invite",
})?,
None,
)
.await
.map_err(|_| Error::DatabaseError {
operation: "insert_one",
with: "invite",
})?;
Ok(())
}
pub async fn delete(&self) -> Result<()> {
get_collection("invites")
.delete_one(
doc! {
"_id": self.code()
},
None,
)
.await
.map_err(|_| Error::DatabaseError {
operation: "delete_one",
with: "invite",
})?;
Ok(())
}
}

View File

@@ -1,4 +1,5 @@
mod channel;
mod invites;
mod message;
mod microservice;
mod server;
@@ -9,6 +10,7 @@ use microservice::*;
pub use autumn::*;
pub use channel::*;
pub use invites::*;
pub use january::*;
pub use message::*;
pub use server::*;

View File

@@ -17,14 +17,11 @@ pub struct MemberCompositeKey {
pub struct Member {
#[serde(rename = "_id")]
pub id: MemberCompositeKey,
pub nickname: Option<String>,
}
#[derive(Serialize, Deserialize, Debug, Clone)]
pub struct Invite {
pub code: String,
pub creator: String,
pub channel: String,
#[serde(skip_serializing_if = "Option::is_none")]
pub nickname: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub avatar: Option<File>,
}
#[derive(Serialize, Deserialize, Debug, Clone)]
@@ -54,22 +51,6 @@ pub struct Server {
}
impl Server {
pub async fn get(id: &str) -> Result<Server> {
let doc = get_collection("servers")
.find_one(doc! { "_id": id }, None)
.await
.map_err(|_| Error::DatabaseError {
operation: "find_one",
with: "server",
})?
.ok_or_else(|| Error::UnknownServer)?;
from_document::<Server>(doc).map_err(|_| Error::DatabaseError {
operation: "from_document",
with: "server",
})
}
pub async fn publish(self) -> Result<()> {
get_collection("servers")
.insert_one(
@@ -105,4 +86,30 @@ impl Server {
pub async fn delete(&self) -> Result<()> {
unimplemented!()
}
pub async fn join_member(&self, id: &str) -> Result<()> {
get_collection("server_members")
.insert_one(
doc! {
"_id": {
"server": &self.id,
"user": &id
}
},
None,
)
.await
.map_err(|_| Error::DatabaseError {
operation: "insert_one",
with: "server_members",
})?;
ClientboundNotification::ServerMemberJoin {
id: self.id.clone(),
user: id.to_string()
}
.publish(self.id.clone());
Ok(())
}
}

View File

@@ -9,13 +9,20 @@ use validator::Validate;
#[derive(Validate, Serialize, Deserialize)]
pub struct Ref {
#[validate(length(min = 26, max = 26))]
#[validate(length(min = 1, max = 26))]
pub id: String,
}
impl Ref {
pub fn from_unchecked(id: String) -> Ref {
Ref { id }
}
pub fn from(id: String) -> Result<Ref> {
Ok(Ref { id })
let r = Ref { id };
r.validate()
.map_err(|error| Error::FailedValidation { error })?;
Ok(r)
}
pub async fn fetch<T: DeserializeOwned>(&self, collection: &'static str) -> Result<T> {
@@ -51,6 +58,10 @@ impl Ref {
self.fetch("servers").await
}
pub async fn fetch_invite(&self) -> Result<Invite> {
self.fetch("invites").await
}
pub async fn fetch_message(&self, channel: &Channel) -> Result<Message> {
let message: Message = self.fetch("messages").await?;
if &message.channel != channel.id() {

View File

@@ -14,6 +14,7 @@ pub enum ChannelPermission {
ManageMessages = 4,
ManageChannel = 8,
VoiceCall = 16,
InviteOthers = 32,
}
impl_op_ex!(+ |a: &ChannelPermission, b: &ChannelPermission| -> u32 { *a as u32 | *b as u32 });
@@ -27,6 +28,7 @@ bitfield! {
pub get_manage_messages, _: 29;
pub get_manage_channel, _: 28;
pub get_voice_call, _: 27;
pub get_invite_others, _: 26;
}
impl<'a> PermissionCalculator<'a> {
@@ -76,18 +78,21 @@ impl<'a> PermissionCalculator<'a> {
Ok(ChannelPermission::View
+ ChannelPermission::SendMessage
+ ChannelPermission::ManageChannel
+ ChannelPermission::VoiceCall)
+ ChannelPermission::VoiceCall
+ ChannelPermission::InviteOthers)
} else {
Ok(0)
}
}
Channel::TextChannel { server, .. } => {
let server = Server::get(server).await?;
let server = Ref::from_unchecked(server.clone()).fetch_server().await?;
if self.perspective.id == server.owner {
Ok(u32::MAX)
} else {
Ok(ChannelPermission::View + ChannelPermission::SendMessage)
Ok(ChannelPermission::View
+ ChannelPermission::SendMessage
+ ChannelPermission::InviteOthers)
}
}
}

View File

@@ -197,7 +197,13 @@ pub async fn prehandle_hook(notification: &ClientboundNotification) -> Result<()
}
}
ClientboundNotification::ServerMemberJoin { id, user } => {
let server = Ref::from_unchecked(id.clone()).fetch_server().await?;
subscribe_if_exists(user.clone(), id.clone()).ok();
for channel in server.channels {
subscribe_if_exists(user.clone(), channel).ok();
}
}
ClientboundNotification::ServerCreate(server) => {
subscribe_if_exists(server.owner.clone(), server.id.clone()).ok();

View File

@@ -15,7 +15,8 @@ pub async fn req(user: User, target: Ref, member: Ref) -> Result<()> {
.with_channel(&channel)
.for_channel()
.await?;
if !perm.get_view() {
if !perm.get_invite_others() {
Err(Error::MissingPermission)?
}

View File

@@ -0,0 +1,46 @@
use crate::database::*;
use crate::util::result::{Error, Result};
use mongodb::bson::doc;
use nanoid::nanoid;
use rocket_contrib::json::JsonValue;
lazy_static! {
static ref ALPHABET: [char; 54] = [
'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H',
'J', 'K', 'M', 'N', 'P', 'Q', 'R', 'S', 'T', 'V', 'W', 'X', 'Y', 'Z', 'a', 'b', 'c', 'd',
'e', 'f', 'g', 'h', 'j', 'k', 'm', 'n', 'p', 'q', 'r', 's', 't', 'v', 'w', 'x', 'y', 'z'
];
}
#[post("/<target>/invite")]
pub async fn req(user: User, target: Ref) -> Result<JsonValue> {
let target = target.fetch_channel().await?;
let perm = permissions::PermissionCalculator::new(&user)
.with_channel(&target)
.for_channel()
.await?;
if !perm.get_invite_others() {
return Err(Error::MissingPermission);
}
let code = nanoid!(8, &*ALPHABET);
match &target {
Channel::Group { .. } => {
unimplemented!()
}
Channel::TextChannel { id, .. } => {
Invite::Server {
code: code.clone(),
creator: user.id,
channel: id.clone(),
}
.save()
.await?;
Ok(json!({ "code": code }))
}
_ => Err(Error::InvalidOperation),
}
}

View File

@@ -18,8 +18,9 @@ pub async fn req(user: User, target: Ref) -> Result<JsonValue> {
let target = target.fetch_channel().await?;
match target {
Channel::SavedMessages { .. }
| Channel::TextChannel { .. } => return Err(Error::CannotJoinCall),
Channel::SavedMessages { .. } | Channel::TextChannel { .. } => {
return Err(Error::CannotJoinCall)
}
_ => {}
}

View File

@@ -7,6 +7,7 @@ mod fetch_members;
mod group_add_member;
mod group_create;
mod group_remove_member;
mod invite_channel;
mod join_call;
mod message_delete;
mod message_edit;
@@ -21,6 +22,7 @@ pub fn routes() -> Vec<Route> {
fetch_members::req,
delete_channel::req,
edit_channel::req,
invite_channel::req,
message_send::req,
message_query::req,
message_query_stale::req,

View File

@@ -0,0 +1,56 @@
use crate::database::*;
use crate::util::result::Result;
use rocket_contrib::json::JsonValue;
use serde::Serialize;
#[derive(Serialize, Debug, Clone)]
#[serde(tag = "type")]
pub enum InviteResponse {
Server {
server_name: String,
#[serde(skip_serializing_if = "Option::is_none")]
server_icon: Option<File>,
#[serde(skip_serializing_if = "Option::is_none")]
server_banner: Option<File>,
channel_name: String,
#[serde(skip_serializing_if = "Option::is_none")]
channel_description: Option<String>,
user_name: String,
#[serde(skip_serializing_if = "Option::is_none")]
user_avatar: Option<File>
}
}
#[get("/<target>")]
pub async fn req(target: Ref) -> Result<JsonValue> {
let target = target.fetch_invite().await?;
match target {
Invite::Server {
channel,
creator,
..
} => {
let channel = Ref::from_unchecked(channel).fetch_channel().await?;
let creator = Ref::from_unchecked(creator).fetch_user().await?;
if let Channel::TextChannel { server, name, description, .. } = channel {
let server = Ref::from_unchecked(server).fetch_server().await?;
Ok(json!(InviteResponse::Server {
server_name: server.name,
server_icon: server.icon,
server_banner: server.banner,
channel_name: name,
channel_description: description,
user_name: creator.username,
user_avatar: creator.avatar
}))
} else {
unreachable!()
}
}
_ => unreachable!(),
}
}

View File

@@ -0,0 +1,31 @@
use crate::database::*;
use crate::util::result::Result;
use rocket_contrib::json::JsonValue;
#[post("/<target>")]
pub async fn req(user: User, target: Ref) -> Result<JsonValue> {
let target = target.fetch_invite().await?;
match target {
Invite::Server {
channel,
..
} => {
let channel = Ref::from_unchecked(channel).fetch_channel().await?;
let server = if let Channel::TextChannel { server, .. } = &channel {
Ref::from_unchecked(server.clone()).fetch_server().await?
} else {
unreachable!()
};
server.join_member(&user.id).await?;
Ok(json!({
"channel": channel,
"server": server
}))
}
_ => unreachable!(),
}
}

View File

@@ -0,0 +1,8 @@
use rocket::Route;
mod invite_fetch;
mod invite_join;
pub fn routes() -> Vec<Route> {
routes![invite_fetch::req, invite_join::req]
}

View File

@@ -3,6 +3,7 @@ pub use rocket::response::Redirect;
use rocket::Rocket;
mod channels;
mod invites;
mod onboard;
mod push;
mod root;
@@ -17,6 +18,7 @@ pub fn mount(rocket: Rocket) -> Rocket {
.mount("/users", users::routes())
.mount("/channels", channels::routes())
.mount("/servers", servers::routes())
.mount("/invites", invites::routes())
.mount("/push", push::routes())
.mount("/sync", sync::routes())
}

View File

@@ -73,7 +73,7 @@ pub async fn req(user: User, target: Ref, info: Json<Data>) -> Result<JsonValue>
"channels": id
}
},
None
None,
)
.await
.map_err(|_| Error::DatabaseError {

View File

@@ -18,6 +18,7 @@ pub struct Data {
#[post("/create", data = "<info>")]
pub async fn req(user: User, info: Json<Data>) -> Result<JsonValue> {
let info = info.into_inner();
info.validate()
.map_err(|error| Error::FailedValidation { error })?;
@@ -41,26 +42,24 @@ pub async fn req(user: User, info: Json<Data>) -> Result<JsonValue> {
let id = Ulid::new().to_string();
let cid = Ulid::new().to_string();
get_collection("server_members")
.insert_one(
doc! {
"_id": {
"server": &id,
"user": &user.id
}
},
None,
)
.await
.map_err(|_| Error::DatabaseError {
operation: "insert_one",
with: "server_members",
})?;
let server = Server {
id: id.clone(),
nonce: Some(info.nonce.clone()),
owner: user.id.clone(),
name: info.name,
channels: vec![cid.clone()],
icon: None,
banner: None,
};
server.join_member(&user.id).await?;
Channel::TextChannel {
id: cid.clone(),
server: id.clone(),
nonce: Some(info.nonce.clone()),
id: cid,
server: id,
nonce: Some(info.nonce),
name: "general".to_string(),
description: None,
icon: None,
@@ -68,18 +67,6 @@ pub async fn req(user: User, info: Json<Data>) -> Result<JsonValue> {
.publish()
.await?;
let server = Server {
id: id.clone(),
nonce: Some(info.nonce.clone()),
owner: user.id.clone(),
name: info.name.clone(),
channels: vec![cid],
icon: None,
banner: None,
};
server.clone().publish().await?;
Ok(json!(server))

View File

@@ -18,5 +18,9 @@ pub async fn req(user: User, target: Ref) -> Result<()> {
// ! FIXME: either delete server if owner
// ! OR leave server if member
// also need to delete server invites
// and members
// and bans
target.delete().await
}

View File

@@ -57,7 +57,9 @@ pub async fn req(
ClientboundNotification::UserUpdate {
id: user.id.clone(),
data: json!(data.0),
data: json!({
"username": data.username
}),
clear: None,
}
.publish(user.id.clone());