forked from jmug/stoatchat
Compare commits
16 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
222a417fff | ||
|
|
3b85dcce14 | ||
|
|
f42480886b | ||
|
|
23ec2d61f1 | ||
|
|
abd8b1821d | ||
|
|
75a35831da | ||
|
|
99e2f874a1 | ||
|
|
11f7092fcd | ||
|
|
cb882ce1b2 | ||
|
|
5486a68bfa | ||
|
|
4aaf328435 | ||
|
|
9d251f794b | ||
|
|
1d390d483d | ||
|
|
81de29e723 | ||
|
|
984017eb61 | ||
|
|
5ab329dfdd |
432
Cargo.lock
generated
432
Cargo.lock
generated
File diff suppressed because it is too large
Load Diff
10
Cargo.toml
10
Cargo.toml
@@ -1,6 +1,6 @@
|
||||
[package]
|
||||
name = "revolt"
|
||||
version = "0.3.1"
|
||||
version = "0.3.2"
|
||||
authors = ["Paul Makles <paulmakles@gmail.com>"]
|
||||
edition = "2018"
|
||||
|
||||
@@ -12,13 +12,13 @@ many-to-many = "0.1.2"
|
||||
impl_ops = "0.1.1"
|
||||
ctrlc = { version = "3.0", features = ["termination"] }
|
||||
async-tungstenite = { version = "0.10.0", features = ["async-std-runtime"] }
|
||||
rauth = { git = "https://gitlab.insrt.uk/insert/rauth" }
|
||||
rauth = { git = "https://gitlab.insrt.uk/insert/rauth", rev = "8f3ea627" }
|
||||
async-std = { version = "1.8.0", features = ["tokio02", "attributes"] }
|
||||
|
||||
hive_pubsub = { version = "0.4.3", features = ["mongo"] }
|
||||
rocket_cors = { git = "https://github.com/lawliet89/rocket_cors", branch = "master" }
|
||||
rocket_contrib = { git = "https://github.com/SergioBenitez/Rocket", branch = "master" }
|
||||
rocket = { git = "https://github.com/SergioBenitez/Rocket", branch = "master", default-features = false }
|
||||
rocket_cors = { git = "https://github.com/insertish/rocket_cors", branch = "master" }
|
||||
rocket_contrib = { git = "https://github.com/SergioBenitez/Rocket", rev = "031948c1daaa146128d8a435be116476f2adde00" }
|
||||
rocket = { git = "https://github.com/SergioBenitez/Rocket", rev = "031948c1daaa146128d8a435be116476f2adde00", default-features = false }
|
||||
mongodb = { version = "1.1.1", features = ["tokio-runtime"], default-features = false }
|
||||
|
||||
once_cell = "1.4.1"
|
||||
|
||||
@@ -1,12 +1,20 @@
|
||||
use crate::database::*;
|
||||
use crate::notifications::events::ClientboundNotification;
|
||||
use crate::util::result::{Error, Result};
|
||||
use mongodb::bson::{doc, to_document};
|
||||
use mongodb::bson::{doc, from_document, to_document};
|
||||
use rocket_contrib::json::JsonValue;
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
#[derive(Serialize, Deserialize, Debug, Clone)]
|
||||
#[serde(tag = "type")]
|
||||
pub struct LastMessage {
|
||||
#[serde(rename = "_id")]
|
||||
id: String,
|
||||
author: String,
|
||||
short: String,
|
||||
}
|
||||
|
||||
#[derive(Serialize, Deserialize, Debug, Clone)]
|
||||
#[serde(tag = "channel_type")]
|
||||
pub enum Channel {
|
||||
SavedMessages {
|
||||
#[serde(rename = "_id")]
|
||||
@@ -18,6 +26,8 @@ pub enum Channel {
|
||||
id: String,
|
||||
active: bool,
|
||||
recipients: Vec<String>,
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
last_message: Option<LastMessage>,
|
||||
},
|
||||
Group {
|
||||
#[serde(rename = "_id")]
|
||||
@@ -28,6 +38,8 @@ pub enum Channel {
|
||||
owner: String,
|
||||
description: String,
|
||||
recipients: Vec<String>,
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
last_message: Option<LastMessage>,
|
||||
},
|
||||
}
|
||||
|
||||
@@ -40,6 +52,22 @@ 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(
|
||||
@@ -64,12 +92,15 @@ impl Channel {
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub async fn publish_update(&self, partial: JsonValue) -> Result<()> {
|
||||
pub async fn publish_update(&self, data: JsonValue) -> Result<()> {
|
||||
let id = self.id().to_string();
|
||||
ClientboundNotification::ChannelUpdate(partial)
|
||||
.publish(id)
|
||||
.await
|
||||
.ok();
|
||||
ClientboundNotification::ChannelUpdate {
|
||||
id: id.clone(),
|
||||
data,
|
||||
}
|
||||
.publish(id)
|
||||
.await
|
||||
.ok();
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
@@ -35,30 +35,81 @@ impl Message {
|
||||
}
|
||||
}
|
||||
|
||||
pub async fn publish(self) -> Result<()> {
|
||||
pub async fn publish(self, channel: &Channel) -> Result<()> {
|
||||
get_collection("messages")
|
||||
.insert_one(to_bson(&self).unwrap().as_document().unwrap().clone(), None)
|
||||
.await
|
||||
.map_err(|_| Error::DatabaseError {
|
||||
operation: "insert_one",
|
||||
with: "messages",
|
||||
with: "message",
|
||||
})?;
|
||||
|
||||
let channel = self.channel.clone();
|
||||
// ! FIXME: temp code
|
||||
let channels = get_collection("channels");
|
||||
match channel {
|
||||
Channel::DirectMessage { id, .. } => {
|
||||
channels
|
||||
.update_one(
|
||||
doc! { "_id": id },
|
||||
doc! {
|
||||
"$set": {
|
||||
"active": true,
|
||||
"last_message": {
|
||||
"_id": self.id.clone(),
|
||||
"author": self.author.clone(),
|
||||
"short": self.content.chars().take(24).collect::<String>()
|
||||
}
|
||||
}
|
||||
},
|
||||
None,
|
||||
)
|
||||
.await
|
||||
.map_err(|_| Error::DatabaseError {
|
||||
operation: "update_one",
|
||||
with: "channel",
|
||||
})?;
|
||||
}
|
||||
Channel::Group { id, .. } => {
|
||||
channels
|
||||
.update_one(
|
||||
doc! { "_id": id },
|
||||
doc! {
|
||||
"$set": {
|
||||
"last_message": {
|
||||
"_id": self.id.clone(),
|
||||
"author": self.author.clone(),
|
||||
"short": self.content.chars().take(24).collect::<String>()
|
||||
}
|
||||
}
|
||||
},
|
||||
None,
|
||||
)
|
||||
.await
|
||||
.map_err(|_| Error::DatabaseError {
|
||||
operation: "update_one",
|
||||
with: "channel",
|
||||
})?;
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
|
||||
ClientboundNotification::Message(self)
|
||||
.publish(channel)
|
||||
.publish(channel.id().to_string())
|
||||
.await
|
||||
.ok();
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub async fn publish_update(&self, partial: JsonValue) -> Result<()> {
|
||||
pub async fn publish_update(&self, data: JsonValue) -> Result<()> {
|
||||
let channel = self.channel.clone();
|
||||
ClientboundNotification::MessageUpdate(partial)
|
||||
.publish(channel)
|
||||
.await
|
||||
.ok();
|
||||
ClientboundNotification::MessageUpdate {
|
||||
id: self.id.clone(),
|
||||
data,
|
||||
}
|
||||
.publish(channel)
|
||||
.await
|
||||
.ok();
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
@@ -1,5 +1,7 @@
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
use crate::{database::permissions::user::UserPermissions, notifications::websocket::is_online};
|
||||
|
||||
#[derive(Serialize, Deserialize, Debug, Clone, PartialEq)]
|
||||
pub enum RelationshipStatus {
|
||||
None,
|
||||
@@ -32,3 +34,35 @@ pub struct User {
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub online: Option<bool>,
|
||||
}
|
||||
|
||||
impl User {
|
||||
/// Mutate the user object to include relationship as seen by user.
|
||||
pub fn from(mut self, user: &User) -> User {
|
||||
if self.id == user.id {
|
||||
self.relationship = Some(RelationshipStatus::User);
|
||||
return self;
|
||||
}
|
||||
|
||||
if let Some(relations) = &user.relations {
|
||||
if let Some(relationship) = relations.iter().find(|x| self.id == x.id) {
|
||||
self.relationship = Some(relationship.status.clone());
|
||||
return self;
|
||||
}
|
||||
}
|
||||
|
||||
self
|
||||
}
|
||||
|
||||
/// Mutate the user object to appear as seen by user.
|
||||
pub fn with(mut self, permissions: UserPermissions<[u32; 1]>) -> User {
|
||||
if !permissions.get_view_all() {
|
||||
self.relations = None;
|
||||
}
|
||||
|
||||
if permissions.get_view_profile() {
|
||||
self.online = Some(is_online(&self.id));
|
||||
}
|
||||
|
||||
self
|
||||
}
|
||||
}
|
||||
|
||||
@@ -47,8 +47,13 @@ impl Ref {
|
||||
self.fetch("channels").await
|
||||
}
|
||||
|
||||
pub async fn fetch_message(&self) -> Result<Message> {
|
||||
self.fetch("messages").await
|
||||
pub async fn fetch_message(&self, channel: &Channel) -> Result<Message> {
|
||||
let message: Message = self.fetch("messages").await?;
|
||||
if &message.channel != channel.id() {
|
||||
Err(Error::InvalidOperation)
|
||||
} else {
|
||||
Ok(message)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -29,7 +29,10 @@ impl<'a, 'r> FromRequest<'a, 'r> for User {
|
||||
} else {
|
||||
Outcome::Failure((
|
||||
Status::InternalServerError,
|
||||
rauth::util::Error::DatabaseError,
|
||||
rauth::util::Error::DatabaseError {
|
||||
operation: "find_one",
|
||||
with: "user",
|
||||
},
|
||||
))
|
||||
}
|
||||
}
|
||||
|
||||
@@ -9,6 +9,10 @@ pub async fn create_database() {
|
||||
info!("Creating database.");
|
||||
let db = get_db();
|
||||
|
||||
db.create_collection("accounts", None)
|
||||
.await
|
||||
.expect("Failed to create accounts collection.");
|
||||
|
||||
db.create_collection("users", None)
|
||||
.await
|
||||
.expect("Failed to create users collection.");
|
||||
@@ -17,14 +21,6 @@ pub async fn create_database() {
|
||||
.await
|
||||
.expect("Failed to create channels collection.");
|
||||
|
||||
db.create_collection("guilds", None)
|
||||
.await
|
||||
.expect("Failed to create guilds collection.");
|
||||
|
||||
db.create_collection("members", None)
|
||||
.await
|
||||
.expect("Failed to create members collection.");
|
||||
|
||||
db.create_collection("messages", None)
|
||||
.await
|
||||
.expect("Failed to create messages collection.");
|
||||
@@ -43,6 +39,39 @@ pub async fn create_database() {
|
||||
.await
|
||||
.expect("Failed to create pubsub collection.");
|
||||
|
||||
db.run_command(
|
||||
doc! {
|
||||
"createIndexes": "accounts",
|
||||
"indexes": [
|
||||
{
|
||||
"key": {
|
||||
"email": 1
|
||||
},
|
||||
"name": "email",
|
||||
"unique": true,
|
||||
"collation": {
|
||||
"locale": "en",
|
||||
"strength": 2
|
||||
}
|
||||
},
|
||||
{
|
||||
"key": {
|
||||
"email_normalised": 1
|
||||
},
|
||||
"name": "email_normalised",
|
||||
"unique": true,
|
||||
"collation": {
|
||||
"locale": "en",
|
||||
"strength": 2
|
||||
}
|
||||
}
|
||||
]
|
||||
},
|
||||
None,
|
||||
)
|
||||
.await
|
||||
.expect("Failed to create account index.");
|
||||
|
||||
db.run_command(
|
||||
doc! {
|
||||
"createIndexes": "users",
|
||||
|
||||
@@ -1,9 +1,7 @@
|
||||
use super::super::{get_collection, get_db};
|
||||
use crate::database::get_collection;
|
||||
|
||||
use crate::rocket::futures::StreamExt;
|
||||
use log::info;
|
||||
use mongodb::bson::{doc, from_document};
|
||||
use mongodb::options::FindOptions;
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
#[derive(Serialize, Deserialize)]
|
||||
@@ -12,7 +10,7 @@ struct MigrationInfo {
|
||||
revision: i32,
|
||||
}
|
||||
|
||||
pub const LATEST_REVISION: i32 = 3;
|
||||
pub const LATEST_REVISION: i32 = 0;
|
||||
|
||||
pub async fn migrate_database() {
|
||||
let migrations = get_collection("migrations");
|
||||
@@ -55,99 +53,6 @@ pub async fn run_migrations(revision: i32) -> i32 {
|
||||
info!("Running migration [revision 0]: Test migration system.");
|
||||
}
|
||||
|
||||
if revision <= 1 {
|
||||
info!("Running migration [revision 1]: Add channels to guild object.");
|
||||
|
||||
let col = get_collection("guilds");
|
||||
let mut guilds = col
|
||||
.find(
|
||||
None,
|
||||
FindOptions::builder().projection(doc! { "_id": 1 }).build(),
|
||||
)
|
||||
.await
|
||||
.expect("Failed to fetch guilds.");
|
||||
|
||||
let mut result = get_collection("channels")
|
||||
.find(
|
||||
doc! {
|
||||
"type": 2
|
||||
},
|
||||
FindOptions::builder()
|
||||
.projection(doc! { "_id": 1, "guild": 1 })
|
||||
.build(),
|
||||
)
|
||||
.await
|
||||
.expect("Failed to fetch channels.");
|
||||
|
||||
let mut channels = vec![];
|
||||
while let Some(doc) = result.next().await {
|
||||
let channel = doc.expect("Failed to fetch channel.");
|
||||
let id = channel
|
||||
.get_str("_id")
|
||||
.expect("Failed to get channel id.")
|
||||
.to_string();
|
||||
|
||||
let gid = channel
|
||||
.get_str("guild")
|
||||
.expect("Failed to get guild id.")
|
||||
.to_string();
|
||||
|
||||
channels.push((id, gid));
|
||||
}
|
||||
|
||||
while let Some(doc) = guilds.next().await {
|
||||
let guild = doc.expect("Failed to fetch guild.");
|
||||
let id = guild.get_str("_id").expect("Failed to get guild id.");
|
||||
|
||||
let list: Vec<String> = channels
|
||||
.iter()
|
||||
.filter(|x| x.1 == id)
|
||||
.map(|x| x.0.clone())
|
||||
.collect();
|
||||
|
||||
col.update_one(
|
||||
doc! {
|
||||
"_id": id
|
||||
},
|
||||
doc! {
|
||||
"$set": {
|
||||
"channels": list
|
||||
}
|
||||
},
|
||||
None,
|
||||
)
|
||||
.await
|
||||
.expect("Failed to update guild.");
|
||||
}
|
||||
}
|
||||
|
||||
if revision <= 2 {
|
||||
info!("Running migration [revision 2]: Add username index to users.");
|
||||
|
||||
get_db()
|
||||
.run_command(
|
||||
doc! {
|
||||
"createIndexes": "users",
|
||||
"indexes": [
|
||||
{
|
||||
"key": {
|
||||
"username": 1
|
||||
},
|
||||
"name": "username",
|
||||
"unique": true,
|
||||
"collation": {
|
||||
"locale": "en",
|
||||
"strength": 2
|
||||
}
|
||||
}
|
||||
]
|
||||
},
|
||||
None,
|
||||
)
|
||||
.await
|
||||
.expect("Failed to create username index.");
|
||||
}
|
||||
|
||||
// Reminder to update LATEST_REVISION when adding new migrations.
|
||||
LATEST_REVISION
|
||||
}
|
||||
|
||||
@@ -1,4 +1,8 @@
|
||||
use crate::database::*;
|
||||
use crate::util::result::Result;
|
||||
|
||||
use super::PermissionCalculator;
|
||||
|
||||
use num_enum::TryFromPrimitive;
|
||||
use std::ops;
|
||||
|
||||
@@ -21,40 +25,99 @@ bitfield! {
|
||||
impl_op_ex!(+ |a: &ChannelPermission, b: &ChannelPermission| -> u32 { *a as u32 | *b as u32 });
|
||||
impl_op_ex_commutative!(+ |a: &u32, b: &ChannelPermission| -> u32 { *a | *b as u32 });
|
||||
|
||||
pub async fn calculate(user: &User, target: &Channel) -> ChannelPermissions<[u32; 1]> {
|
||||
/*pub async fn calculate(user: &User, target: &Channel) -> Result<u32> {
|
||||
match target {
|
||||
Channel::SavedMessages { user: owner, .. } => {
|
||||
if &user.id == owner {
|
||||
ChannelPermissions([ChannelPermission::View
|
||||
Ok(ChannelPermission::View
|
||||
+ ChannelPermission::SendMessage
|
||||
+ ChannelPermission::ManageMessages])
|
||||
+ ChannelPermission::ManageMessages)
|
||||
} else {
|
||||
ChannelPermissions([0])
|
||||
Ok(0)
|
||||
}
|
||||
}
|
||||
Channel::DirectMessage { recipients, .. } => {
|
||||
if recipients.iter().find(|x| *x == &user.id).is_some() {
|
||||
if let Some(recipient) = recipients.iter().find(|x| *x != &user.id) {
|
||||
let perms = super::user::calculate(&user, recipient).await;
|
||||
let perms = super::user::get(&user, recipient).await?;
|
||||
|
||||
if perms.get_send_message() {
|
||||
return ChannelPermissions([
|
||||
ChannelPermission::View + ChannelPermission::SendMessage
|
||||
]);
|
||||
return Ok(ChannelPermission::View + ChannelPermission::SendMessage);
|
||||
}
|
||||
|
||||
return ChannelPermissions([ChannelPermission::View as u32]);
|
||||
return Ok(ChannelPermission::View as u32);
|
||||
}
|
||||
}
|
||||
|
||||
ChannelPermissions([0])
|
||||
Ok(0)
|
||||
}
|
||||
Channel::Group { recipients, .. } => {
|
||||
if recipients.iter().find(|x| *x == &user.id).is_some() {
|
||||
ChannelPermissions([ChannelPermission::View + ChannelPermission::SendMessage])
|
||||
Ok(ChannelPermission::View + ChannelPermission::SendMessage)
|
||||
} else {
|
||||
ChannelPermissions([0])
|
||||
Ok(0)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub async fn get(user: &User, target: &Channel) -> Result<ChannelPermissions<[u32; 1]>> {
|
||||
Ok(ChannelPermissions([calculate(&user, &target).await?]))
|
||||
}*/
|
||||
|
||||
impl<'a> PermissionCalculator<'a> {
|
||||
pub async fn calculate_channel(self) -> Result<u32> {
|
||||
let channel = if let Some(channel) = self.channel {
|
||||
channel
|
||||
} else {
|
||||
unreachable!()
|
||||
};
|
||||
|
||||
match channel {
|
||||
Channel::SavedMessages { user: owner, .. } => {
|
||||
if &self.perspective.id == owner {
|
||||
Ok(ChannelPermission::View
|
||||
+ ChannelPermission::SendMessage
|
||||
+ ChannelPermission::ManageMessages)
|
||||
} else {
|
||||
Ok(0)
|
||||
}
|
||||
}
|
||||
Channel::DirectMessage { recipients, .. } => {
|
||||
if recipients
|
||||
.iter()
|
||||
.find(|x| *x == &self.perspective.id)
|
||||
.is_some()
|
||||
{
|
||||
if let Some(recipient) = recipients.iter().find(|x| *x != &self.perspective.id)
|
||||
{
|
||||
let perms = self.for_user(recipient).await?;
|
||||
|
||||
if perms.get_send_message() {
|
||||
return Ok(ChannelPermission::View + ChannelPermission::SendMessage);
|
||||
}
|
||||
|
||||
return Ok(ChannelPermission::View as u32);
|
||||
}
|
||||
}
|
||||
|
||||
Ok(0)
|
||||
}
|
||||
Channel::Group { recipients, .. } => {
|
||||
if recipients
|
||||
.iter()
|
||||
.find(|x| *x == &self.perspective.id)
|
||||
.is_some()
|
||||
{
|
||||
Ok(ChannelPermission::View + ChannelPermission::SendMessage)
|
||||
} else {
|
||||
Ok(0)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub async fn for_channel(self) -> Result<ChannelPermissions<[u32; 1]>> {
|
||||
Ok(ChannelPermissions([self.calculate_channel().await?]))
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,4 +1,49 @@
|
||||
pub use crate::database::*;
|
||||
|
||||
pub mod channel;
|
||||
pub mod user;
|
||||
|
||||
pub use user::get_relationship;
|
||||
|
||||
pub struct PermissionCalculator<'a> {
|
||||
perspective: &'a User,
|
||||
|
||||
user: Option<&'a User>,
|
||||
channel: Option<&'a Channel>,
|
||||
|
||||
has_mutual_conncetion: bool,
|
||||
}
|
||||
|
||||
impl<'a> PermissionCalculator<'a> {
|
||||
pub fn new(perspective: &'a User) -> PermissionCalculator {
|
||||
PermissionCalculator {
|
||||
perspective,
|
||||
|
||||
user: None,
|
||||
channel: None,
|
||||
|
||||
has_mutual_conncetion: false,
|
||||
}
|
||||
}
|
||||
|
||||
pub fn with_user(self, user: &'a User) -> PermissionCalculator {
|
||||
PermissionCalculator {
|
||||
user: Some(&user),
|
||||
..self
|
||||
}
|
||||
}
|
||||
|
||||
pub fn with_channel(self, channel: &'a Channel) -> PermissionCalculator {
|
||||
PermissionCalculator {
|
||||
channel: Some(&channel),
|
||||
..self
|
||||
}
|
||||
}
|
||||
|
||||
pub fn with_mutual_connection(self) -> PermissionCalculator<'a> {
|
||||
PermissionCalculator {
|
||||
has_mutual_conncetion: true,
|
||||
..self
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,4 +1,9 @@
|
||||
use crate::database::*;
|
||||
use crate::util::result::{Error, Result};
|
||||
|
||||
use super::PermissionCalculator;
|
||||
|
||||
use mongodb::bson::doc;
|
||||
use num_enum::TryFromPrimitive;
|
||||
use std::ops;
|
||||
|
||||
@@ -6,47 +11,29 @@ use std::ops;
|
||||
#[repr(u32)]
|
||||
pub enum UserPermission {
|
||||
Access = 1,
|
||||
SendMessage = 2,
|
||||
Invite = 4,
|
||||
ViewProfile = 2,
|
||||
SendMessage = 4,
|
||||
Invite = 8,
|
||||
|
||||
ViewAll = 2147483648,
|
||||
}
|
||||
|
||||
bitfield! {
|
||||
pub struct UserPermissions(MSB0 [u32]);
|
||||
u32;
|
||||
pub get_access, _: 31;
|
||||
pub get_send_message, _: 30;
|
||||
pub get_invite, _: 29;
|
||||
pub get_view_profile, _: 30;
|
||||
pub get_send_message, _: 29;
|
||||
pub get_invite, _: 28;
|
||||
|
||||
pub get_view_all, _: 0;
|
||||
}
|
||||
|
||||
impl_op_ex!(+ |a: &UserPermission, b: &UserPermission| -> u32 { *a as u32 | *b as u32 });
|
||||
impl_op_ex!(-|a: &UserPermission, b: &UserPermission| -> u32 { *a as u32 & !(*b as u32) });
|
||||
impl_op_ex!(-|a: &u32, b: &UserPermission| -> u32 { *a & !(*b as u32) });
|
||||
impl_op_ex_commutative!(+ |a: &u32, b: &UserPermission| -> u32 { *a | *b as u32 });
|
||||
|
||||
pub async fn calculate(user: &User, target: &str) -> UserPermissions<[u32; 1]> {
|
||||
// if friends; Access + Message + Invite
|
||||
// if mutually know each other:
|
||||
// and has DMs from users enabled -> Access + Message
|
||||
// otherwise -> Access
|
||||
// otherwise; None
|
||||
|
||||
let mut permissions: u32 = 0;
|
||||
match get_relationship(&user, &target) {
|
||||
RelationshipStatus::Friend => {
|
||||
return UserPermissions([UserPermission::Access
|
||||
+ UserPermission::SendMessage
|
||||
+ UserPermission::Invite])
|
||||
}
|
||||
RelationshipStatus::Blocked | RelationshipStatus::BlockedOther => {
|
||||
return UserPermissions([UserPermission::Access as u32])
|
||||
}
|
||||
RelationshipStatus::Incoming | RelationshipStatus::Outgoing => {
|
||||
permissions = UserPermission::Access as u32;
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
|
||||
UserPermissions([permissions])
|
||||
}
|
||||
|
||||
pub fn get_relationship(a: &User, b: &str) -> RelationshipStatus {
|
||||
if a.id == b {
|
||||
return RelationshipStatus::Friend;
|
||||
@@ -60,3 +47,60 @@ pub fn get_relationship(a: &User, b: &str) -> RelationshipStatus {
|
||||
|
||||
RelationshipStatus::None
|
||||
}
|
||||
|
||||
impl<'a> PermissionCalculator<'a> {
|
||||
pub async fn calculate_user(self, target: &str) -> Result<u32> {
|
||||
if &self.perspective.id == target {
|
||||
return Ok(u32::MAX);
|
||||
}
|
||||
|
||||
let mut permissions: u32 = 0;
|
||||
match get_relationship(&self.perspective, &target) {
|
||||
RelationshipStatus::Friend => return Ok(u32::MAX - UserPermission::ViewAll),
|
||||
RelationshipStatus::Blocked | RelationshipStatus::BlockedOther => {
|
||||
return Ok(UserPermission::Access as u32)
|
||||
}
|
||||
RelationshipStatus::Incoming | RelationshipStatus::Outgoing => {
|
||||
permissions = UserPermission::Access as u32;
|
||||
// ! INFO: if we add boolean switch for permission to
|
||||
// ! message people who have mutual, we need to get
|
||||
// ! rid of this return statement.
|
||||
return Ok(permissions);
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
|
||||
if self.has_mutual_conncetion
|
||||
|| get_collection("channels")
|
||||
.find_one(
|
||||
doc! {
|
||||
"type": "Group",
|
||||
"$and": {
|
||||
"recipients": &self.perspective.id,
|
||||
"recipients": target
|
||||
}
|
||||
},
|
||||
None,
|
||||
)
|
||||
.await
|
||||
.map_err(|_| Error::DatabaseError {
|
||||
operation: "find",
|
||||
with: "channels",
|
||||
})?
|
||||
.is_some()
|
||||
{
|
||||
return Ok(UserPermission::Access as u32);
|
||||
}
|
||||
|
||||
Ok(permissions)
|
||||
}
|
||||
|
||||
pub async fn for_user(self, target: &str) -> Result<UserPermissions<[u32; 1]>> {
|
||||
Ok(UserPermissions([self.calculate_user(&target).await?]))
|
||||
}
|
||||
|
||||
pub async fn for_user_given(self) -> Result<UserPermissions<[u32; 1]>> {
|
||||
let id = &self.user.unwrap().id;
|
||||
Ok(UserPermissions([self.calculate_user(&id).await?]))
|
||||
}
|
||||
}
|
||||
|
||||
31
src/main.rs
31
src/main.rs
@@ -18,10 +18,13 @@ pub mod notifications;
|
||||
pub mod routes;
|
||||
pub mod util;
|
||||
|
||||
use chrono::Duration;
|
||||
use futures::join;
|
||||
use log::info;
|
||||
use rauth;
|
||||
use rauth::auth::Auth;
|
||||
use rauth::options::{EmailVerification, Options, SMTP};
|
||||
use rocket_cors::AllowedOrigins;
|
||||
use util::variables::{PUBLIC_URL, SMTP_FROM, SMTP_HOST, SMTP_PASSWORD, SMTP_USERNAME, USE_EMAIL};
|
||||
|
||||
#[async_std::main]
|
||||
async fn main() {
|
||||
@@ -55,10 +58,32 @@ async fn launch_web() {
|
||||
.to_cors()
|
||||
.expect("Failed to create CORS.");
|
||||
|
||||
let auth = rauth::auth::Auth::new(database::get_collection("accounts"));
|
||||
let auth = Auth::new(
|
||||
database::get_collection("accounts"),
|
||||
Options::new()
|
||||
.base_url(format!("{}/auth", *PUBLIC_URL))
|
||||
.email_verification(if *USE_EMAIL {
|
||||
EmailVerification::Enabled {
|
||||
success_redirect_uri: format!("{}/welcome", *PUBLIC_URL),
|
||||
verification_expiry: Duration::days(1),
|
||||
verification_ratelimit: Duration::minutes(1),
|
||||
|
||||
routes::mount(rauth::routes::mount(rocket::ignite(), "/auth", auth))
|
||||
smtp: SMTP {
|
||||
from: (*SMTP_FROM).to_string(),
|
||||
host: (*SMTP_HOST).to_string(),
|
||||
username: (*SMTP_USERNAME).to_string(),
|
||||
password: (*SMTP_PASSWORD).to_string(),
|
||||
},
|
||||
}
|
||||
} else {
|
||||
EmailVerification::Disabled
|
||||
}),
|
||||
);
|
||||
|
||||
routes::mount(rocket::ignite())
|
||||
.mount("/", rocket_cors::catch_all_options_routes())
|
||||
.mount("/auth", rauth::routes::routes())
|
||||
.manage(auth)
|
||||
.manage(cors.clone())
|
||||
.attach(cors)
|
||||
.launch()
|
||||
|
||||
@@ -39,13 +39,19 @@ pub enum ClientboundNotification {
|
||||
},
|
||||
|
||||
Message(Message),
|
||||
MessageUpdate(JsonValue),
|
||||
MessageUpdate {
|
||||
id: String,
|
||||
data: JsonValue,
|
||||
},
|
||||
MessageDelete {
|
||||
id: String,
|
||||
},
|
||||
|
||||
ChannelCreate(Channel),
|
||||
ChannelUpdate(JsonValue),
|
||||
ChannelUpdate {
|
||||
id: String,
|
||||
data: JsonValue,
|
||||
},
|
||||
ChannelGroupJoin {
|
||||
id: String,
|
||||
user: String,
|
||||
@@ -94,12 +100,6 @@ pub fn prehandle_hook(notification: &ClientboundNotification) {
|
||||
}
|
||||
}
|
||||
}
|
||||
ClientboundNotification::ChannelGroupLeave { id, user } => {
|
||||
get_hive()
|
||||
.hive
|
||||
.unsubscribe(&user.to_string(), &id.to_string())
|
||||
.ok();
|
||||
}
|
||||
ClientboundNotification::UserRelationship { id, user, status } => {
|
||||
if status != &RelationshipStatus::None {
|
||||
subscribe_if_exists(id.clone(), user.clone()).ok();
|
||||
@@ -122,6 +122,12 @@ pub fn posthandle_hook(notification: &ClientboundNotification) {
|
||||
.ok();
|
||||
}
|
||||
}
|
||||
ClientboundNotification::ChannelGroupLeave { id, user } => {
|
||||
get_hive()
|
||||
.hive
|
||||
.unsubscribe(&user.to_string(), &id.to_string())
|
||||
.ok();
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,4 +1,6 @@
|
||||
use crate::notifications::events::ClientboundNotification;
|
||||
use std::collections::HashSet;
|
||||
|
||||
use crate::{database::*, notifications::events::ClientboundNotification};
|
||||
use crate::{
|
||||
database::{entities::User, get_collection},
|
||||
util::result::{Error, Result},
|
||||
@@ -9,55 +11,16 @@ use mongodb::{
|
||||
options::FindOptions,
|
||||
};
|
||||
|
||||
use super::websocket::is_online;
|
||||
|
||||
pub async fn generate_ready(mut user: User) -> Result<ClientboundNotification> {
|
||||
let mut users = vec![];
|
||||
let mut user_ids: HashSet<String> = HashSet::new();
|
||||
|
||||
if let Some(relationships) = &user.relations {
|
||||
let user_ids: Vec<String> = relationships
|
||||
.iter()
|
||||
.map(|relationship| relationship.id.clone())
|
||||
.collect();
|
||||
|
||||
let mut cursor = get_collection("users")
|
||||
.find(
|
||||
doc! {
|
||||
"_id": {
|
||||
"$in": user_ids
|
||||
}
|
||||
},
|
||||
FindOptions::builder()
|
||||
.projection(doc! { "_id": 1, "username": 1 })
|
||||
.build(),
|
||||
)
|
||||
.await
|
||||
.map_err(|_| Error::DatabaseError {
|
||||
operation: "find",
|
||||
with: "users",
|
||||
})?;
|
||||
|
||||
while let Some(result) = cursor.next().await {
|
||||
if let Ok(doc) = result {
|
||||
let mut user: User = from_document(doc).map_err(|_| Error::DatabaseError {
|
||||
operation: "from_document",
|
||||
with: "user",
|
||||
})?;
|
||||
|
||||
user.relationship = Some(
|
||||
relationships
|
||||
.iter()
|
||||
.find(|x| user.id == x.id)
|
||||
.ok_or_else(|| Error::InternalError)?
|
||||
.status
|
||||
.clone(),
|
||||
);
|
||||
|
||||
user.online = Some(is_online(&user.id));
|
||||
|
||||
users.push(user);
|
||||
}
|
||||
}
|
||||
user_ids.extend(
|
||||
relationships
|
||||
.iter()
|
||||
.map(|relationship| relationship.id.clone()),
|
||||
);
|
||||
}
|
||||
|
||||
let mut cursor = get_collection("channels")
|
||||
@@ -65,16 +28,15 @@ pub async fn generate_ready(mut user: User) -> Result<ClientboundNotification> {
|
||||
doc! {
|
||||
"$or": [
|
||||
{
|
||||
"type": "SavedMessages",
|
||||
"channel_type": "SavedMessages",
|
||||
"user": &user.id
|
||||
},
|
||||
{
|
||||
"type": "DirectMessage",
|
||||
"recipients": &user.id,
|
||||
"active": true
|
||||
"channel_type": "DirectMessage",
|
||||
"recipients": &user.id
|
||||
},
|
||||
{
|
||||
"type": "Group",
|
||||
"channel_type": "Group",
|
||||
"recipients": &user.id
|
||||
}
|
||||
]
|
||||
@@ -90,13 +52,61 @@ pub async fn generate_ready(mut user: User) -> Result<ClientboundNotification> {
|
||||
let mut channels = vec![];
|
||||
while let Some(result) = cursor.next().await {
|
||||
if let Ok(doc) = result {
|
||||
channels.push(from_document(doc).map_err(|_| Error::DatabaseError {
|
||||
let channel = from_document(doc).map_err(|_| Error::DatabaseError {
|
||||
operation: "from_document",
|
||||
with: "channel",
|
||||
})?);
|
||||
})?;
|
||||
|
||||
if let Channel::Group { recipients, .. } = &channel {
|
||||
user_ids.extend(recipients.iter().cloned());
|
||||
}
|
||||
|
||||
channels.push(channel);
|
||||
}
|
||||
}
|
||||
|
||||
user_ids.remove(&user.id);
|
||||
if user_ids.len() > 0 {
|
||||
let mut cursor = get_collection("users")
|
||||
.find(
|
||||
doc! {
|
||||
"_id": {
|
||||
"$in": user_ids.into_iter().collect::<Vec<String>>()
|
||||
}
|
||||
},
|
||||
FindOptions::builder()
|
||||
.projection(doc! { "_id": 1, "username": 1 })
|
||||
.build(),
|
||||
)
|
||||
.await
|
||||
.map_err(|_| Error::DatabaseError {
|
||||
operation: "find",
|
||||
with: "users",
|
||||
})?;
|
||||
|
||||
while let Some(result) = cursor.next().await {
|
||||
if let Ok(doc) = result {
|
||||
let other: User = from_document(doc).map_err(|_| Error::DatabaseError {
|
||||
operation: "from_document",
|
||||
with: "user",
|
||||
})?;
|
||||
|
||||
let permissions = PermissionCalculator::new(&user)
|
||||
.with_mutual_connection()
|
||||
.with_user(&other)
|
||||
.for_user_given()
|
||||
.await?;
|
||||
|
||||
users.push(
|
||||
other
|
||||
.from(&user)
|
||||
.with(permissions)
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
user.relationship = Some(RelationshipStatus::User);
|
||||
user.online = Some(true);
|
||||
users.push(user);
|
||||
|
||||
|
||||
@@ -21,16 +21,15 @@ pub async fn generate_subscriptions(user: &User) -> Result<(), String> {
|
||||
doc! {
|
||||
"$or": [
|
||||
{
|
||||
"type": "SavedMessages",
|
||||
"channel_type": "SavedMessages",
|
||||
"user": &user.id
|
||||
},
|
||||
{
|
||||
"type": "DirectMessage",
|
||||
"recipients": &user.id,
|
||||
"active": true
|
||||
"channel_type": "DirectMessage",
|
||||
"recipients": &user.id
|
||||
},
|
||||
{
|
||||
"type": "Group",
|
||||
"channel_type": "Group",
|
||||
"recipients": &user.id
|
||||
}
|
||||
]
|
||||
|
||||
@@ -12,7 +12,10 @@ use futures::{pin_mut, prelude::*};
|
||||
use hive_pubsub::PubSub;
|
||||
use log::{debug, info};
|
||||
use many_to_many::ManyToMany;
|
||||
use rauth::auth::{Auth, Session};
|
||||
use rauth::{
|
||||
auth::{Auth, Session},
|
||||
options::Options,
|
||||
};
|
||||
use std::collections::HashMap;
|
||||
use std::net::SocketAddr;
|
||||
use std::sync::{Arc, Mutex, RwLock};
|
||||
@@ -84,9 +87,10 @@ async fn accept(stream: TcpStream) {
|
||||
}
|
||||
}
|
||||
|
||||
if let Ok(validated_session) = Auth::new(get_collection("accounts"))
|
||||
.verify_session(new_session)
|
||||
.await
|
||||
if let Ok(validated_session) =
|
||||
Auth::new(get_collection("accounts"), Options::new())
|
||||
.verify_session(new_session)
|
||||
.await
|
||||
{
|
||||
let id = validated_session.user_id.clone();
|
||||
if let Ok(user) = (Ref { id: id.clone() }).fetch_user().await {
|
||||
|
||||
@@ -7,7 +7,10 @@ use mongodb::bson::doc;
|
||||
pub async fn req(user: User, target: Ref) -> Result<()> {
|
||||
let target = target.fetch_channel().await?;
|
||||
|
||||
let perm = permissions::channel::calculate(&user, &target).await;
|
||||
let perm = permissions::PermissionCalculator::new(&user)
|
||||
.with_channel(&target)
|
||||
.for_channel()
|
||||
.await?;
|
||||
if !perm.get_view() {
|
||||
Err(Error::LabelMe)?
|
||||
}
|
||||
@@ -101,7 +104,7 @@ pub async fn req(user: User, target: Ref) -> Result<()> {
|
||||
id.clone(),
|
||||
format!("<@{}> left the group.", user.id),
|
||||
)
|
||||
.publish()
|
||||
.publish(&target)
|
||||
.await
|
||||
.ok();
|
||||
|
||||
|
||||
@@ -7,7 +7,10 @@ use rocket_contrib::json::JsonValue;
|
||||
pub async fn req(user: User, target: Ref) -> Result<JsonValue> {
|
||||
let target = target.fetch_channel().await?;
|
||||
|
||||
let perm = permissions::channel::calculate(&user, &target).await;
|
||||
let perm = permissions::PermissionCalculator::new(&user)
|
||||
.with_channel(&target)
|
||||
.for_channel()
|
||||
.await?;
|
||||
if !perm.get_view() {
|
||||
Err(Error::LabelMe)?
|
||||
}
|
||||
|
||||
@@ -11,13 +11,15 @@ pub async fn req(user: User, target: Ref, member: Ref) -> Result<()> {
|
||||
}
|
||||
|
||||
let channel = target.fetch_channel().await?;
|
||||
|
||||
let perm = permissions::channel::calculate(&user, &channel).await;
|
||||
let perm = permissions::PermissionCalculator::new(&user)
|
||||
.with_channel(&channel)
|
||||
.for_channel()
|
||||
.await?;
|
||||
if !perm.get_view() {
|
||||
Err(Error::LabelMe)?
|
||||
}
|
||||
|
||||
if let Channel::Group { id, recipients, .. } = channel {
|
||||
if let Channel::Group { id, recipients, .. } = &channel {
|
||||
if recipients.len() >= *MAX_GROUP_SIZE {
|
||||
Err(Error::GroupTooLarge {
|
||||
max: *MAX_GROUP_SIZE,
|
||||
@@ -56,10 +58,10 @@ pub async fn req(user: User, target: Ref, member: Ref) -> Result<()> {
|
||||
|
||||
Message::create(
|
||||
"00000000000000000000000000".to_string(),
|
||||
id,
|
||||
id.clone(),
|
||||
format!("<@{}> added <@{}> to the group.", user.id, member.id),
|
||||
)
|
||||
.publish()
|
||||
.publish(&channel)
|
||||
.await
|
||||
.ok();
|
||||
|
||||
|
||||
@@ -70,6 +70,7 @@ pub async fn req(user: User, info: Json<Data>) -> Result<JsonValue> {
|
||||
.unwrap_or_else(|| "A group.".to_string()),
|
||||
owner: user.id,
|
||||
recipients: set.into_iter().collect::<Vec<String>>(),
|
||||
last_message: None,
|
||||
};
|
||||
|
||||
channel.clone().publish().await?;
|
||||
|
||||
@@ -16,9 +16,9 @@ pub async fn req(user: User, target: Ref, member: Ref) -> Result<()> {
|
||||
owner,
|
||||
recipients,
|
||||
..
|
||||
} = channel
|
||||
} = &channel
|
||||
{
|
||||
if &user.id != &owner {
|
||||
if &user.id != owner {
|
||||
// figure out if we want to use perm system here
|
||||
Err(Error::LabelMe)?
|
||||
}
|
||||
@@ -55,10 +55,10 @@ pub async fn req(user: User, target: Ref, member: Ref) -> Result<()> {
|
||||
|
||||
Message::create(
|
||||
"00000000000000000000000000".to_string(),
|
||||
id,
|
||||
id.clone(),
|
||||
format!("<@{}> removed <@{}> from the group.", user.id, member.id),
|
||||
)
|
||||
.publish()
|
||||
.publish(&channel)
|
||||
.await
|
||||
.ok();
|
||||
|
||||
|
||||
@@ -7,12 +7,15 @@ use mongodb::bson::doc;
|
||||
pub async fn req(user: User, target: Ref, msg: Ref) -> Result<()> {
|
||||
let channel = target.fetch_channel().await?;
|
||||
|
||||
let perm = permissions::channel::calculate(&user, &channel).await;
|
||||
let perm = permissions::PermissionCalculator::new(&user)
|
||||
.with_channel(&channel)
|
||||
.for_channel()
|
||||
.await?;
|
||||
if !perm.get_view() {
|
||||
Err(Error::LabelMe)?
|
||||
}
|
||||
|
||||
let message = msg.fetch_message().await?;
|
||||
let message = msg.fetch_message(&channel).await?;
|
||||
if message.author != user.id && !perm.get_manage_messages() {
|
||||
match channel {
|
||||
Channel::SavedMessages { .. } => unreachable!(),
|
||||
|
||||
@@ -19,13 +19,15 @@ pub async fn req(user: User, target: Ref, msg: Ref, edit: Json<Data>) -> Result<
|
||||
.map_err(|error| Error::FailedValidation { error })?;
|
||||
|
||||
let channel = target.fetch_channel().await?;
|
||||
|
||||
let perm = permissions::channel::calculate(&user, &channel).await;
|
||||
let perm = permissions::PermissionCalculator::new(&user)
|
||||
.with_channel(&channel)
|
||||
.for_channel()
|
||||
.await?;
|
||||
if !perm.get_view() {
|
||||
Err(Error::LabelMe)?
|
||||
}
|
||||
|
||||
let message = msg.fetch_message().await?;
|
||||
let message = msg.fetch_message(&channel).await?;
|
||||
if message.author != user.id {
|
||||
Err(Error::CannotEditMessage)?
|
||||
}
|
||||
|
||||
@@ -7,11 +7,14 @@ use rocket_contrib::json::JsonValue;
|
||||
pub async fn req(user: User, target: Ref, msg: Ref) -> Result<JsonValue> {
|
||||
let channel = target.fetch_channel().await?;
|
||||
|
||||
let perm = permissions::channel::calculate(&user, &channel).await;
|
||||
let perm = permissions::PermissionCalculator::new(&user)
|
||||
.with_channel(&channel)
|
||||
.for_channel()
|
||||
.await?;
|
||||
if !perm.get_view() {
|
||||
Err(Error::LabelMe)?
|
||||
}
|
||||
|
||||
let message = msg.fetch_message().await?;
|
||||
let message = msg.fetch_message(&channel).await?;
|
||||
Ok(json!(message))
|
||||
}
|
||||
|
||||
@@ -29,7 +29,10 @@ pub async fn req(user: User, target: Ref, options: Form<Options>) -> Result<Json
|
||||
|
||||
let target = target.fetch_channel().await?;
|
||||
|
||||
let perm = permissions::channel::calculate(&user, &target).await;
|
||||
let perm = permissions::PermissionCalculator::new(&user)
|
||||
.with_channel(&target)
|
||||
.for_channel()
|
||||
.await?;
|
||||
if !perm.get_view() {
|
||||
Err(Error::LabelMe)?
|
||||
}
|
||||
|
||||
@@ -24,7 +24,10 @@ pub async fn req(user: User, target: Ref, message: Json<Data>) -> Result<JsonVal
|
||||
|
||||
let target = target.fetch_channel().await?;
|
||||
|
||||
let perm = permissions::channel::calculate(&user, &target).await;
|
||||
let perm = permissions::PermissionCalculator::new(&user)
|
||||
.with_channel(&target)
|
||||
.for_channel()
|
||||
.await?;
|
||||
if !perm.get_send_message() {
|
||||
Err(Error::LabelMe)?
|
||||
}
|
||||
@@ -56,7 +59,7 @@ pub async fn req(user: User, target: Ref, message: Json<Data>) -> Result<JsonVal
|
||||
edited: None,
|
||||
};
|
||||
|
||||
msg.clone().publish().await?;
|
||||
msg.clone().publish(&target).await?;
|
||||
|
||||
Ok(json!(msg))
|
||||
}
|
||||
|
||||
@@ -28,6 +28,10 @@ pub async fn req(session: Session, user: Option<User>, data: Json<Data>) -> Resu
|
||||
data.validate()
|
||||
.map_err(|error| Error::FailedValidation { error })?;
|
||||
|
||||
if data.username == "revolt" {
|
||||
Err(Error::UsernameTaken)?
|
||||
}
|
||||
|
||||
let col = get_collection("users");
|
||||
if col
|
||||
.find_one(
|
||||
|
||||
@@ -12,11 +12,11 @@ pub async fn req(user: User) -> Result<JsonValue> {
|
||||
doc! {
|
||||
"$or": [
|
||||
{
|
||||
"type": "DirectMessage",
|
||||
"channel_type": "DirectMessage",
|
||||
"active": true
|
||||
},
|
||||
{
|
||||
"type": "Group"
|
||||
"channel_type": "Group"
|
||||
}
|
||||
],
|
||||
"recipients": user.id
|
||||
|
||||
@@ -1,37 +1,24 @@
|
||||
use crate::database::*;
|
||||
use crate::util::result::{Error, Result};
|
||||
use crate::{database::*, notifications::websocket::is_online};
|
||||
|
||||
use rocket_contrib::json::JsonValue;
|
||||
|
||||
#[get("/<target>")]
|
||||
pub async fn req(user: User, target: Ref) -> Result<JsonValue> {
|
||||
let mut target = target.fetch_user().await?;
|
||||
let target = target.fetch_user().await?;
|
||||
|
||||
if user.id != target.id {
|
||||
// Check whether we are allowed to fetch this user.
|
||||
let perm = permissions::user::calculate(&user, &target.id).await;
|
||||
if !perm.get_access() {
|
||||
Err(Error::LabelMe)?
|
||||
}
|
||||
let perm = permissions::PermissionCalculator::new(&user)
|
||||
.with_user(&target)
|
||||
.for_user_given()
|
||||
.await?;
|
||||
|
||||
// Only return user relationships if the target is the caller.
|
||||
target.relations = None;
|
||||
|
||||
// Add relevant relationship
|
||||
if let Some(relationships) = &user.relations {
|
||||
target.relationship = relationships
|
||||
.iter()
|
||||
.find(|x| x.id == user.id)
|
||||
.map(|x| x.status.clone())
|
||||
.or_else(|| Some(RelationshipStatus::None));
|
||||
} else {
|
||||
target.relationship = Some(RelationshipStatus::None);
|
||||
}
|
||||
} else {
|
||||
target.relationship = Some(RelationshipStatus::User);
|
||||
if !perm.get_access() {
|
||||
Err(Error::LabelMe)?
|
||||
}
|
||||
|
||||
target.online = Some(is_online(&target.id));
|
||||
|
||||
Ok(json!(target))
|
||||
Ok(json!(
|
||||
target
|
||||
.from(&user)
|
||||
.with(perm)
|
||||
))
|
||||
}
|
||||
|
||||
@@ -9,12 +9,12 @@ use ulid::Ulid;
|
||||
pub async fn req(user: User, target: Ref) -> Result<JsonValue> {
|
||||
let query = if user.id == target.id {
|
||||
doc! {
|
||||
"type": "SavedMessages",
|
||||
"channel_type": "SavedMessages",
|
||||
"user": &user.id
|
||||
}
|
||||
} else {
|
||||
doc! {
|
||||
"type": "DirectMessage",
|
||||
"channel_type": "DirectMessage",
|
||||
"recipients": {
|
||||
"$all": [ &user.id, &target.id ]
|
||||
}
|
||||
@@ -40,6 +40,7 @@ pub async fn req(user: User, target: Ref) -> Result<JsonValue> {
|
||||
id,
|
||||
active: false,
|
||||
recipients: vec![user.id, target.id],
|
||||
last_message: None,
|
||||
}
|
||||
};
|
||||
|
||||
|
||||
@@ -34,6 +34,8 @@ pub enum Error {
|
||||
NotFriends,
|
||||
|
||||
// ? Channel related errors.
|
||||
#[snafu(display("This channel does not exist!"))]
|
||||
UnknownChannel,
|
||||
#[snafu(display("Cannot edit someone else's message."))]
|
||||
CannotEditMessage,
|
||||
#[snafu(display("Cannot remove yourself from a group, use delete channel instead."))]
|
||||
@@ -81,6 +83,7 @@ impl<'r> Responder<'r, 'static> for Error {
|
||||
Error::BlockedByOther => Status::Forbidden,
|
||||
Error::NotFriends => Status::Forbidden,
|
||||
|
||||
Error::UnknownChannel => Status::NotFound,
|
||||
Error::CannotEditMessage => Status::Forbidden,
|
||||
Error::CannotRemoveYourself => Status::BadRequest,
|
||||
Error::GroupTooLarge { .. } => Status::Forbidden,
|
||||
|
||||
Reference in New Issue
Block a user