Skip to content
Snippets Groups Projects
Commit a1a921bb authored by insert's avatar insert
Browse files

Run cargo fmt.

parent bd789b68
No related merge requests found
Showing
with 140 additions and 141 deletions
use crate::database::*;
use crate::util::result::{Error, Result};
use mongodb::bson::to_document;
use serde::{Deserialize, Serialize};
use crate::util::result::{Error, Result};
#[derive(Serialize, Deserialize, Debug)]
#[serde(tag = "type")]
......
use crate::{database::*, notifications::events::ClientboundNotification, util::result::{Error, Result}};
use mongodb::bson::{DateTime, to_bson};
use crate::{
database::*,
notifications::events::ClientboundNotification,
util::result::{Error, Result},
};
use mongodb::bson::{to_bson, DateTime};
use serde::{Deserialize, Serialize};
/*#[derive(Serialize, Deserialize, Debug)]
......@@ -39,13 +43,13 @@ pub struct Message {
impl Message {
pub async fn send(self) -> Result<()> {
get_collection("messages")
.insert_one(
to_bson(&self).unwrap().as_document().unwrap().clone(),
None
)
.insert_one(to_bson(&self).unwrap().as_document().unwrap().clone(), None)
.await
.map_err(|_| Error::DatabaseError { operation: "insert_one", with: "messages" })?;
.map_err(|_| Error::DatabaseError {
operation: "insert_one",
with: "messages",
})?;
let channel = self.channel.clone();
ClientboundNotification::Message(self)
.publish(channel)
......
use crate::database::*;
use crate::util::result::{Error, Result};
use validator::Validate;
use mongodb::bson::{doc, from_bson, from_document, Bson};
use rocket::http::RawStr;
use rocket::request::FromParam;
use mongodb::bson::{Bson, doc, from_bson, from_document};
use serde::{Deserialize, Serialize, de::DeserializeOwned};
use serde::{de::DeserializeOwned, Deserialize, Serialize};
use validator::Validate;
#[derive(Validate, Serialize, Deserialize)]
pub struct Ref {
......@@ -33,12 +33,10 @@ impl Ref {
})?
.ok_or_else(|| Error::UnknownUser)?;
Ok(
from_document::<T>(doc).map_err(|_| Error::DatabaseError {
operation: "from_document",
with: &collection,
})?,
)
Ok(from_document::<T>(doc).map_err(|_| Error::DatabaseError {
operation: "from_document",
with: &collection,
})?)
}
pub async fn fetch_user(&self) -> Result<User> {
......
use crate::database::*;
use mongodb::bson::{Bson, doc, from_bson, from_document};
use mongodb::bson::{doc, from_bson, from_document, Bson};
use rauth::auth::Session;
use rocket::http::Status;
use rocket::request::{self, FromRequest, Outcome, Request};
......
......@@ -2,7 +2,7 @@ use super::super::{get_collection, get_db};
use crate::rocket::futures::StreamExt;
use log::info;
use mongodb::bson::{Bson, doc, from_bson, from_document};
use mongodb::bson::{doc, from_bson, from_document, Bson};
use mongodb::options::FindOptions;
use serde::{Deserialize, Serialize};
......
......@@ -23,28 +23,28 @@ pub async fn calculate(user: &User, target: &Channel) -> ChannelPermissions<[u32
match target {
Channel::SavedMessages { user: owner, .. } => {
if &user.id == owner {
ChannelPermissions([ ChannelPermission::View + ChannelPermission::SendMessage ])
ChannelPermissions([ChannelPermission::View + ChannelPermission::SendMessage])
} else {
ChannelPermissions([ 0 ])
ChannelPermissions([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) {
if let Some(recipient) = recipients.iter().find(|x| *x != &user.id) {
let perms = super::user::calculate(&user, recipient).await;
if perms.get_send_message() {
return ChannelPermissions([ ChannelPermission::View + ChannelPermission::SendMessage ]);
return ChannelPermissions([
ChannelPermission::View + ChannelPermission::SendMessage
]);
}
return ChannelPermissions([ ChannelPermission::View as u32 ]);
return ChannelPermissions([ChannelPermission::View as u32]);
}
}
ChannelPermissions([ 0 ])
ChannelPermissions([0])
}
_ => unreachable!()
_ => unreachable!(),
}
}
pub mod user;
pub mod channel;
pub mod user;
pub use user::get_relationship;
......@@ -31,20 +31,20 @@ pub async fn calculate(user: &User, target: &str) -> UserPermissions<[u32; 1]> {
let mut permissions: u32 = 0;
match get_relationship(&user, &target) {
RelationshipStatus::Friend => {
return UserPermissions([ UserPermission::Access + UserPermission::SendMessage + UserPermission::Invite ])
return UserPermissions([UserPermission::Access
+ UserPermission::SendMessage
+ UserPermission::Invite])
}
RelationshipStatus::Blocked |
RelationshipStatus::BlockedOther => {
return UserPermissions([ UserPermission::Access as u32 ])
RelationshipStatus::Blocked | RelationshipStatus::BlockedOther => {
return UserPermissions([UserPermission::Access as u32])
}
RelationshipStatus::Incoming |
RelationshipStatus::Outgoing => {
RelationshipStatus::Incoming | RelationshipStatus::Outgoing => {
permissions = UserPermission::Access as u32;
}
_ => {}
}
UserPermissions([ permissions ])
UserPermissions([permissions])
}
pub fn get_relationship(a: &User, b: &str) -> RelationshipStatus {
......
......@@ -33,7 +33,7 @@ pub enum ClientboundNotification {
Authenticated,
Ready {
users: Vec<User>,
channels: Vec<Channel>
channels: Vec<Channel>,
},
Message(Message),
......@@ -93,7 +93,6 @@ pub enum ClientboundNotification {
GuildDelete {
id: String,
},*/
UserRelationship {
id: String,
user: String,
......@@ -102,8 +101,8 @@ pub enum ClientboundNotification {
UserPresence {
id: String,
online: bool
}
online: bool,
},
}
impl ClientboundNotification {
......
......@@ -4,7 +4,10 @@ use crate::{
util::result::{Error, Result},
};
use futures::StreamExt;
use mongodb::{bson::{Bson, doc, from_bson, from_document}, options::FindOptions};
use mongodb::{
bson::{doc, from_bson, from_document, Bson},
options::FindOptions,
};
use super::websocket::is_online;
......@@ -36,11 +39,10 @@ pub async fn generate_ready(mut user: User) -> Result<ClientboundNotification> {
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",
})?;
let mut user: User = from_document(doc).map_err(|_| Error::DatabaseError {
operation: "from_document",
with: "user",
})?;
user.relationship = Some(
relationships
......@@ -77,24 +79,21 @@ pub async fn generate_ready(mut user: User) -> Result<ClientboundNotification> {
}
]
},
None
None,
)
.await
.map_err(|_| Error::DatabaseError {
operation: "find",
with: "channels",
})?;
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 {
operation: "from_document",
with: "channel",
})?
);
channels.push(from_document(doc).map_err(|_| Error::DatabaseError {
operation: "from_document",
with: "channel",
})?);
}
}
......
use crate::database::*;
use super::hive::get_hive;
use futures::StreamExt;
use mongodb::bson::doc;
use hive_pubsub::PubSub;
use super::hive::get_hive;
use mongodb::bson::doc;
use mongodb::options::FindOptions;
pub async fn generate_subscriptions(user: &User) -> Result<(), String> {
......@@ -35,13 +35,11 @@ pub async fn generate_subscriptions(user: &User) -> Result<(), String> {
}
]
},
FindOptions::builder()
.projection(doc! { "_id": 1 })
.build()
FindOptions::builder().projection(doc! { "_id": 1 }).build(),
)
.await
.map_err(|_| "Failed to fetch channels.".to_string())?;
while let Some(result) = cursor.next().await {
if let Ok(doc) = result {
hive.subscribe(user.id.clone(), doc.get_str("_id").unwrap().to_string())?;
......
......@@ -64,7 +64,7 @@ async fn accept(stream: TcpStream) {
};
let session: Arc<Mutex<Option<Session>>> = Arc::new(Mutex::new(None));
let mutex_generator = || { session.clone() };
let mutex_generator = || session.clone();
let fwd = rx.map(Ok).forward(write);
let incoming = read.try_for_each(async move |msg| {
let mutex = mutex_generator();
......@@ -79,22 +79,17 @@ async fn accept(stream: TcpStream) {
send(ClientboundNotification::Error(
WebSocketError::AlreadyAuthenticated,
));
return Ok(())
return Ok(());
}
}
if let Ok(validated_session) = Auth::new(get_collection("accounts"))
.verify_session(new_session)
.await {
.await
{
let id = validated_session.user_id.clone();
if let Ok(user) = (
Ref {
id: id.clone()
}
)
.fetch_user()
.await {
if let Ok(user) = (Ref { id: id.clone() }).fetch_user().await {
let was_online = is_online(&id);
{
match USERS.write() {
......@@ -103,10 +98,12 @@ async fn accept(stream: TcpStream) {
}
Err(_) => {
send(ClientboundNotification::Error(
WebSocketError::InternalError { at: "Writing users map.".to_string() },
WebSocketError::InternalError {
at: "Writing users map.".to_string(),
},
));
return Ok(())
return Ok(());
}
}
}
......@@ -115,10 +112,12 @@ async fn accept(stream: TcpStream) {
if let Err(_) = subscriptions::generate_subscriptions(&user).await {
send(ClientboundNotification::Error(
WebSocketError::InternalError { at: "Generating subscriptions.".to_string() },
WebSocketError::InternalError {
at: "Generating subscriptions.".to_string(),
},
));
return Ok(())
return Ok(());
}
send(ClientboundNotification::Authenticated);
......@@ -130,7 +129,7 @@ async fn accept(stream: TcpStream) {
if !was_online {
ClientboundNotification::UserPresence {
id: id.clone(),
online: true
online: true,
}
.publish(id)
.await
......@@ -139,10 +138,12 @@ async fn accept(stream: TcpStream) {
}
Err(_) => {
send(ClientboundNotification::Error(
WebSocketError::InternalError { at: "Generating payload.".to_string() },
WebSocketError::InternalError {
at: "Generating payload.".to_string(),
},
));
return Ok(())
return Ok(());
}
}
} else {
......
......@@ -25,13 +25,16 @@ pub async fn req(user: User, target: Ref) -> Result<()> {
"active": false
}
},
None
None,
)
.await
.map_err(|_| Error::DatabaseError { operation: "update_one", with: "channel" })?;
.map_err(|_| Error::DatabaseError {
operation: "update_one",
with: "channel",
})?;
Ok(())
},
_ => unimplemented!()
}
_ => unimplemented!(),
}
}
......@@ -2,11 +2,14 @@ use crate::database::*;
use crate::util::result::{Error, Result};
use futures::StreamExt;
use validator::Validate;
use mongodb::{
bson::{doc, from_document},
options::FindOptions,
};
use rocket::request::Form;
use serde::{Serialize, Deserialize};
use rocket_contrib::json::JsonValue;
use mongodb::{bson::{doc, from_document}, options::FindOptions};
use serde::{Deserialize, Serialize};
use validator::Validate;
#[derive(Validate, Serialize, Deserialize, FromForm)]
pub struct Options {
......@@ -20,7 +23,8 @@ pub struct Options {
#[get("/<target>/messages?<options..>")]
pub async fn req(user: User, target: Ref, options: Form<Options>) -> Result<JsonValue> {
options.validate()
options
.validate()
.map_err(|error| Error::FailedValidation { error })?;
let target = target.fetch_channel().await?;
......@@ -51,14 +55,19 @@ pub async fn req(user: User, target: Ref, options: Form<Options>) -> Result<Json
.build(),
)
.await
.map_err(|_| Error::DatabaseError { operation: "find", with: "messages" })?;
.map_err(|_| Error::DatabaseError {
operation: "find",
with: "messages",
})?;
let mut messages = vec![];
while let Some(result) = cursor.next().await {
if let Ok(doc) = result {
messages.push(
from_document::<Message>(doc)
.map_err(|_| Error::DatabaseError { operation: "from_document", with: "message" })?
from_document::<Message>(doc).map_err(|_| Error::DatabaseError {
operation: "from_document",
with: "message",
})?,
);
}
}
......
use crate::database::*;
use crate::util::result::{Error, Result};
use serde::{Serialize, Deserialize};
use rocket_contrib::json::Json;
use validator::Validate;
use mongodb::bson::doc;
use rocket_contrib::json::Json;
use serde::{Deserialize, Serialize};
use ulid::Ulid;
use validator::Validate;
#[derive(Validate, Serialize, Deserialize)]
pub struct Data {
......@@ -18,7 +18,8 @@ pub struct Data {
#[post("/<target>/messages", data = "<message>")]
pub async fn req(user: User, target: Ref, message: Json<Data>) -> Result<()> {
message.validate()
message
.validate()
.map_err(|error| Error::FailedValidation { error })?;
let target = target.fetch_channel().await?;
......@@ -33,11 +34,15 @@ pub async fn req(user: User, target: Ref, message: Json<Data>) -> Result<()> {
doc! {
"nonce": &message.nonce
},
None
None,
)
.await
.map_err(|_| Error::DatabaseError { operation: "find_one", with: "message" })?
.is_some() {
.map_err(|_| Error::DatabaseError {
operation: "find_one",
with: "message",
})?
.is_some()
{
Err(Error::AlreadySentMessage)?
}
......
use rocket::Route;
mod fetch_channel;
mod delete_channel;
mod message_send;
mod fetch_channel;
mod message_fetch;
mod message_send;
pub fn routes() -> Vec<Route> {
routes![
......
......@@ -31,10 +31,7 @@ pub async fn req(user: User, username: String) -> Result<JsonValue> {
with: "user",
})?;
match get_relationship(
&user,
&target_id,
) {
match get_relationship(&user, &target_id) {
RelationshipStatus::User => return Err(Error::NoEffect),
RelationshipStatus::Friend => return Err(Error::AlreadyFriends),
RelationshipStatus::Outgoing => return Err(Error::AlreadySentRequest),
......
use crate::{database::*, notifications::websocket::is_online};
use crate::util::result::{Error, Result};
use crate::{database::*, notifications::websocket::is_online};
use rocket_contrib::json::JsonValue;
......
......@@ -6,38 +6,24 @@ use crate::database::Ref;
#[get("/<target>/avatar")]
pub async fn req(target: Ref) -> Option<NamedFile> {
match target.id.chars().nth(25).unwrap() {
'0' |
'1' |
'2' |
'3' |
'4' |
'5' |
'6' |
'7' => NamedFile::open(Path::new("assets/user_red.png")).await.ok(),
'8' |
'9' |
'A' |
'C' |
'B' |
'D' |
'E' |
'F' => NamedFile::open(Path::new("assets/user_green.png")).await.ok(),
'G' |
'H' |
'J' |
'K' |
'M' |
'N' |
'P' |
'Q' => NamedFile::open(Path::new("assets/user_blue.png")).await.ok(),
'R' |
'S' |
'T' |
'V' |
'W' |
'X' |
'Y' |
'Z' => NamedFile::open(Path::new("assets/user_yellow.png")).await.ok(),
_ => unreachable!()
'0' | '1' | '2' | '3' | '4' | '5' | '6' | '7' => {
NamedFile::open(Path::new("assets/user_red.png")).await.ok()
}
'8' | '9' | 'A' | 'C' | 'B' | 'D' | 'E' | 'F' => {
NamedFile::open(Path::new("assets/user_green.png"))
.await
.ok()
}
'G' | 'H' | 'J' | 'K' | 'M' | 'N' | 'P' | 'Q' => {
NamedFile::open(Path::new("assets/user_blue.png"))
.await
.ok()
}
'R' | 'S' | 'T' | 'V' | 'W' | 'X' | 'Y' | 'Z' => {
NamedFile::open(Path::new("assets/user_yellow.png"))
.await
.ok()
}
_ => unreachable!(),
}
}
0% or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment