forked from jmug/stoatchat
Compare commits
4 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
8043690d38 | ||
|
|
0f793f84a2 | ||
|
|
577f25642e | ||
|
|
4fbd6c816d |
@@ -1,6 +1,6 @@
|
||||
[package]
|
||||
name = "revolt"
|
||||
version = "0.1.0"
|
||||
version = "0.2.0"
|
||||
authors = ["Paul Makles <paulmakles@gmail.com>"]
|
||||
edition = "2018"
|
||||
|
||||
|
||||
@@ -4,4 +4,4 @@ port = 5500
|
||||
|
||||
[production]
|
||||
address = "192.168.0.10"
|
||||
port = 5500
|
||||
port = 3000
|
||||
|
||||
@@ -1,4 +1,11 @@
|
||||
use bson::UtcDateTime;
|
||||
use super::get_collection;
|
||||
use crate::guards::channel::ChannelRef;
|
||||
use crate::notifications;
|
||||
use crate::notifications::events::message::Create;
|
||||
use crate::notifications::events::Notification;
|
||||
use crate::routes::channel::ChannelType;
|
||||
|
||||
use bson::{doc, to_bson, UtcDateTime};
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
#[derive(Serialize, Deserialize, Debug)]
|
||||
@@ -11,16 +18,72 @@ pub struct PreviousEntry {
|
||||
pub struct Message {
|
||||
#[serde(rename = "_id")]
|
||||
pub id: String,
|
||||
// pub nonce: String, used internally
|
||||
pub nonce: Option<String>,
|
||||
pub channel: String,
|
||||
pub author: String,
|
||||
|
||||
pub content: String,
|
||||
pub edited: Option<UtcDateTime>,
|
||||
|
||||
pub previous_content: Option<Vec<PreviousEntry>>,
|
||||
pub previous_content: Vec<PreviousEntry>,
|
||||
}
|
||||
|
||||
// ? TODO: write global send message
|
||||
// ? pub fn send_message();
|
||||
// ? handle websockets?
|
||||
impl Message {
|
||||
pub fn send(&self, target: &ChannelRef) -> bool {
|
||||
if get_collection("messages")
|
||||
.insert_one(to_bson(&self).unwrap().as_document().unwrap().clone(), None)
|
||||
.is_ok()
|
||||
{
|
||||
notifications::send_message_given_channel(
|
||||
Notification::message_create(Create {
|
||||
id: self.id.clone(),
|
||||
nonce: self.nonce.clone(),
|
||||
channel: self.channel.clone(),
|
||||
author: self.author.clone(),
|
||||
content: self.content.clone(),
|
||||
}),
|
||||
&target,
|
||||
);
|
||||
|
||||
let short_content: String = self.content.chars().take(24).collect();
|
||||
|
||||
// !! this stuff can be async
|
||||
if target.channel_type == ChannelType::DM as u8
|
||||
|| target.channel_type == ChannelType::GROUPDM as u8
|
||||
{
|
||||
let mut update = doc! {
|
||||
"$set": {
|
||||
"last_message": {
|
||||
"id": &self.id,
|
||||
"user_id": &self.author,
|
||||
"short_content": short_content,
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
if target.channel_type == ChannelType::DM as u8 {
|
||||
update
|
||||
.get_document_mut("$set")
|
||||
.unwrap()
|
||||
.insert("active", true);
|
||||
}
|
||||
|
||||
if get_collection("channels")
|
||||
.update_one(doc! { "_id": &target.id }, update, None)
|
||||
.is_ok()
|
||||
{
|
||||
true
|
||||
} else {
|
||||
false
|
||||
}
|
||||
} else {
|
||||
true
|
||||
}
|
||||
} else {
|
||||
false
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -111,7 +111,7 @@ pub fn has_mutual_connection(user_id: &str, target_id: &str, with_permission: bo
|
||||
|
||||
let permissions = guild.get_i32("default_permissions").unwrap() as u32;
|
||||
|
||||
if MemberPermissions([ permissions ]).get_send_direct_messages() {
|
||||
if MemberPermissions([permissions]).get_send_direct_messages() {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -9,9 +9,9 @@ extern crate bitfield;
|
||||
pub mod database;
|
||||
pub mod email;
|
||||
pub mod guards;
|
||||
pub mod notifications;
|
||||
pub mod routes;
|
||||
pub mod util;
|
||||
pub mod websocket;
|
||||
|
||||
use dotenv;
|
||||
use rocket_cors::AllowedOrigins;
|
||||
@@ -20,9 +20,14 @@ use std::thread;
|
||||
fn main() {
|
||||
dotenv::dotenv().ok();
|
||||
database::connect();
|
||||
notifications::start_worker();
|
||||
|
||||
thread::spawn(|| {
|
||||
websocket::launch_server();
|
||||
notifications::pubsub::launch_subscriber();
|
||||
});
|
||||
|
||||
thread::spawn(|| {
|
||||
notifications::ws::launch_server();
|
||||
});
|
||||
|
||||
let cors = rocket_cors::CorsOptions {
|
||||
|
||||
13
src/notifications/events/groups.rs
Normal file
13
src/notifications/events/groups.rs
Normal file
@@ -0,0 +1,13 @@
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
#[derive(Serialize, Deserialize, Debug, Clone)]
|
||||
pub struct UserJoin {
|
||||
pub id: String,
|
||||
pub user: String,
|
||||
}
|
||||
|
||||
#[derive(Serialize, Deserialize, Debug, Clone)]
|
||||
pub struct UserLeave {
|
||||
pub id: String,
|
||||
pub user: String,
|
||||
}
|
||||
33
src/notifications/events/guilds.rs
Normal file
33
src/notifications/events/guilds.rs
Normal file
@@ -0,0 +1,33 @@
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
#[derive(Serialize, Deserialize, Debug, Clone)]
|
||||
pub struct UserJoin {
|
||||
pub id: String,
|
||||
pub user: String,
|
||||
}
|
||||
|
||||
#[derive(Serialize, Deserialize, Debug, Clone)]
|
||||
pub struct UserLeave {
|
||||
pub id: String,
|
||||
pub user: String,
|
||||
pub banned: bool,
|
||||
}
|
||||
|
||||
#[derive(Serialize, Deserialize, Debug, Clone)]
|
||||
pub struct ChannelCreate {
|
||||
pub id: String,
|
||||
pub channel: String,
|
||||
pub name: String,
|
||||
pub description: String,
|
||||
}
|
||||
|
||||
#[derive(Serialize, Deserialize, Debug, Clone)]
|
||||
pub struct ChannelDelete {
|
||||
pub id: String,
|
||||
pub channel: String,
|
||||
}
|
||||
|
||||
#[derive(Serialize, Deserialize, Debug, Clone)]
|
||||
pub struct Delete {
|
||||
pub id: String,
|
||||
}
|
||||
21
src/notifications/events/message.rs
Normal file
21
src/notifications/events/message.rs
Normal file
@@ -0,0 +1,21 @@
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
#[derive(Serialize, Deserialize, Debug, Clone)]
|
||||
pub struct Create {
|
||||
pub id: String,
|
||||
pub nonce: Option<String>,
|
||||
pub channel: String,
|
||||
pub author: String,
|
||||
pub content: String,
|
||||
}
|
||||
|
||||
#[derive(Serialize, Deserialize, Debug, Clone)]
|
||||
pub struct Edit {
|
||||
pub id: String,
|
||||
pub content: String,
|
||||
}
|
||||
|
||||
#[derive(Serialize, Deserialize, Debug, Clone)]
|
||||
pub struct Delete {
|
||||
pub id: String,
|
||||
}
|
||||
41
src/notifications/events/mod.rs
Normal file
41
src/notifications/events/mod.rs
Normal file
@@ -0,0 +1,41 @@
|
||||
use serde::{Deserialize, Serialize};
|
||||
use serde_json::{json, Value};
|
||||
|
||||
pub mod groups;
|
||||
pub mod guilds;
|
||||
pub mod message;
|
||||
pub mod users;
|
||||
|
||||
#[allow(non_camel_case_types)]
|
||||
#[derive(Serialize, Deserialize, Debug, Clone)]
|
||||
pub enum Notification {
|
||||
message_create(message::Create),
|
||||
message_edit(message::Edit),
|
||||
message_delete(message::Delete),
|
||||
group_user_join(groups::UserJoin),
|
||||
group_user_leave(groups::UserLeave),
|
||||
guild_user_join(guilds::UserJoin),
|
||||
guild_user_leave(guilds::UserLeave),
|
||||
guild_channel_create(guilds::ChannelCreate),
|
||||
guild_channel_delete(guilds::ChannelDelete),
|
||||
guild_delete(guilds::Delete),
|
||||
user_friend_status(users::FriendStatus),
|
||||
}
|
||||
|
||||
impl Notification {
|
||||
pub fn serialize(self) -> String {
|
||||
if let Value::Object(obj) = json!(self) {
|
||||
let (key, value) = obj.iter().next().unwrap();
|
||||
|
||||
if let Value::Object(data) = value {
|
||||
let mut data = data.clone();
|
||||
data.insert("type".to_string(), Value::String(key.to_string()));
|
||||
json!(data).to_string()
|
||||
} else {
|
||||
unreachable!()
|
||||
}
|
||||
} else {
|
||||
unreachable!()
|
||||
}
|
||||
}
|
||||
}
|
||||
7
src/notifications/events/users.rs
Normal file
7
src/notifications/events/users.rs
Normal file
@@ -0,0 +1,7 @@
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
#[derive(Serialize, Deserialize, Debug, Clone)]
|
||||
pub struct FriendStatus {
|
||||
pub id: String,
|
||||
pub status: i32,
|
||||
}
|
||||
74
src/notifications/mod.rs
Normal file
74
src/notifications/mod.rs
Normal file
@@ -0,0 +1,74 @@
|
||||
use crate::guards::channel::ChannelRef;
|
||||
|
||||
use once_cell::sync::OnceCell;
|
||||
use std::sync::mpsc::{channel, Sender};
|
||||
use std::thread;
|
||||
|
||||
pub mod events;
|
||||
pub mod pubsub;
|
||||
pub mod state;
|
||||
pub mod ws;
|
||||
|
||||
pub fn send_message<U: Into<Option<Vec<String>>>, G: Into<Option<String>>>(
|
||||
users: U,
|
||||
guild: G,
|
||||
data: events::Notification,
|
||||
) -> bool {
|
||||
let users = users.into();
|
||||
let guild = guild.into();
|
||||
|
||||
if pubsub::send_message(users.clone(), guild.clone(), data.clone()) {
|
||||
state::send_message(users, guild, data.serialize());
|
||||
|
||||
true
|
||||
} else {
|
||||
false
|
||||
}
|
||||
}
|
||||
|
||||
struct NotificationArguments {
|
||||
users: Option<Vec<String>>,
|
||||
guild: Option<String>,
|
||||
data: events::Notification,
|
||||
}
|
||||
|
||||
static mut SENDER: OnceCell<Sender<NotificationArguments>> = OnceCell::new();
|
||||
|
||||
pub fn start_worker() {
|
||||
let (sender, receiver) = channel();
|
||||
unsafe {
|
||||
SENDER.set(sender).unwrap();
|
||||
}
|
||||
|
||||
thread::spawn(move || {
|
||||
while let Ok(data) = receiver.recv() {
|
||||
send_message(data.users, data.guild, data.data);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
pub fn send_message_threaded<U: Into<Option<Vec<String>>>, G: Into<Option<String>>>(
|
||||
users: U,
|
||||
guild: G,
|
||||
data: events::Notification,
|
||||
) -> bool {
|
||||
unsafe {
|
||||
SENDER
|
||||
.get()
|
||||
.unwrap()
|
||||
.send(NotificationArguments {
|
||||
users: users.into(),
|
||||
guild: guild.into(),
|
||||
data,
|
||||
})
|
||||
.is_ok()
|
||||
}
|
||||
}
|
||||
|
||||
pub fn send_message_given_channel(data: events::Notification, channel: &ChannelRef) {
|
||||
match channel.channel_type {
|
||||
0..=1 => send_message_threaded(channel.recipients.clone(), None, data),
|
||||
2 => send_message_threaded(None, channel.guild.clone(), data),
|
||||
_ => unreachable!(),
|
||||
};
|
||||
}
|
||||
102
src/notifications/pubsub.rs
Normal file
102
src/notifications/pubsub.rs
Normal file
@@ -0,0 +1,102 @@
|
||||
use super::events::Notification;
|
||||
use crate::database::get_collection;
|
||||
|
||||
use bson::{doc, from_bson, to_bson, Bson};
|
||||
use mongodb::options::{CursorType, FindOneOptions, FindOptions};
|
||||
use serde::{Deserialize, Serialize};
|
||||
use std::time::Duration;
|
||||
use ulid::Ulid;
|
||||
|
||||
use once_cell::sync::OnceCell;
|
||||
static SOURCEID: OnceCell<String> = OnceCell::new();
|
||||
|
||||
#[derive(Serialize, Deserialize, Debug)]
|
||||
pub struct PubSubMessage {
|
||||
#[serde(rename = "_id")]
|
||||
id: String,
|
||||
source: String,
|
||||
|
||||
user_recipients: Option<Vec<String>>,
|
||||
target_guild: Option<String>,
|
||||
data: Notification,
|
||||
}
|
||||
|
||||
pub fn send_message(users: Option<Vec<String>>, guild: Option<String>, data: Notification) -> bool {
|
||||
let message = PubSubMessage {
|
||||
id: Ulid::new().to_string(),
|
||||
source: SOURCEID.get().unwrap().to_string(),
|
||||
user_recipients: users.into(),
|
||||
target_guild: guild.into(),
|
||||
data,
|
||||
};
|
||||
|
||||
if get_collection("pubsub")
|
||||
.insert_one(
|
||||
to_bson(&message)
|
||||
.expect("Failed to serialize pubsub message.")
|
||||
.as_document()
|
||||
.expect("Failed to convert to a document.")
|
||||
.clone(),
|
||||
None,
|
||||
)
|
||||
.is_ok()
|
||||
{
|
||||
true
|
||||
} else {
|
||||
false
|
||||
}
|
||||
}
|
||||
|
||||
pub fn launch_subscriber() {
|
||||
let source = Ulid::new().to_string();
|
||||
SOURCEID
|
||||
.set(source.clone())
|
||||
.expect("Failed to create and set source ID.");
|
||||
|
||||
let pubsub = get_collection("pubsub");
|
||||
if let Ok(result) = pubsub.find_one(
|
||||
doc! {},
|
||||
FindOneOptions::builder().sort(doc! { "_id": -1 }).build(),
|
||||
) {
|
||||
let query = if let Some(doc) = result {
|
||||
doc! { "_id": { "$gt": doc.get_str("_id").unwrap() } }
|
||||
} else {
|
||||
doc! {}
|
||||
};
|
||||
|
||||
if let Ok(mut cursor) = pubsub.find(
|
||||
query,
|
||||
FindOptions::builder()
|
||||
.cursor_type(CursorType::TailableAwait)
|
||||
.no_cursor_timeout(true)
|
||||
.max_await_time(Duration::from_secs(1200))
|
||||
.build(),
|
||||
) {
|
||||
loop {
|
||||
while let Some(item) = cursor.next() {
|
||||
if let Ok(doc) = item {
|
||||
if let Ok(message) =
|
||||
from_bson(Bson::Document(doc)) as Result<PubSubMessage, _>
|
||||
{
|
||||
if &message.source != &source {
|
||||
super::state::send_message(
|
||||
message.user_recipients,
|
||||
message.target_guild,
|
||||
message.data.serialize(),
|
||||
);
|
||||
}
|
||||
} else {
|
||||
eprintln!("Failed to deserialize pubsub message.");
|
||||
}
|
||||
} else {
|
||||
eprintln!("Failed to unwrap a document from pubsub.");
|
||||
}
|
||||
}
|
||||
}
|
||||
} else {
|
||||
eprintln!("Failed to open subscriber cursor.");
|
||||
}
|
||||
} else {
|
||||
eprintln!("Failed to fetch latest document from pubsub collection.");
|
||||
}
|
||||
}
|
||||
205
src/notifications/state.rs
Normal file
205
src/notifications/state.rs
Normal file
@@ -0,0 +1,205 @@
|
||||
use crate::database;
|
||||
use crate::util::vec_to_set;
|
||||
|
||||
use bson::doc;
|
||||
use hashbrown::{HashMap, HashSet};
|
||||
use mongodb::options::FindOneOptions;
|
||||
use once_cell::sync::OnceCell;
|
||||
use std::sync::RwLock;
|
||||
use ws::Sender;
|
||||
|
||||
pub enum StateResult {
|
||||
DatabaseError,
|
||||
InvalidToken,
|
||||
Success(String),
|
||||
}
|
||||
|
||||
static mut CONNECTIONS: OnceCell<RwLock<HashMap<String, Sender>>> = OnceCell::new();
|
||||
|
||||
pub fn add_connection(id: String, sender: Sender) {
|
||||
unsafe {
|
||||
CONNECTIONS
|
||||
.get()
|
||||
.unwrap()
|
||||
.write()
|
||||
.unwrap()
|
||||
.insert(id, sender);
|
||||
}
|
||||
}
|
||||
|
||||
pub struct User {
|
||||
connections: HashSet<String>,
|
||||
guilds: HashSet<String>,
|
||||
}
|
||||
|
||||
impl User {
|
||||
pub fn new() -> User {
|
||||
User {
|
||||
connections: HashSet::new(),
|
||||
guilds: HashSet::new(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub struct Guild {
|
||||
users: HashSet<String>,
|
||||
}
|
||||
|
||||
impl Guild {
|
||||
pub fn new() -> Guild {
|
||||
Guild {
|
||||
users: HashSet::new(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub struct GlobalState {
|
||||
users: HashMap<String, User>,
|
||||
guilds: HashMap<String, Guild>,
|
||||
}
|
||||
|
||||
impl GlobalState {
|
||||
pub fn new() -> GlobalState {
|
||||
GlobalState {
|
||||
users: HashMap::new(),
|
||||
guilds: HashMap::new(),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn push_to_guild(&mut self, guild: String, user: String) {
|
||||
if !self.guilds.contains_key(&guild) {
|
||||
self.guilds.insert(guild.clone(), Guild::new());
|
||||
}
|
||||
|
||||
self.guilds.get_mut(&guild).unwrap().users.insert(user);
|
||||
}
|
||||
|
||||
pub fn try_authenticate(&mut self, connection: String, access_token: String) -> StateResult {
|
||||
if let Ok(result) = database::get_collection("users").find_one(
|
||||
doc! {
|
||||
"access_token": access_token,
|
||||
},
|
||||
FindOneOptions::builder()
|
||||
.projection(doc! { "_id": 1 })
|
||||
.build(),
|
||||
) {
|
||||
if let Some(user) = result {
|
||||
let user_id = user.get_str("_id").unwrap();
|
||||
|
||||
if self.users.contains_key(user_id) {
|
||||
self.users
|
||||
.get_mut(user_id)
|
||||
.unwrap()
|
||||
.connections
|
||||
.insert(connection);
|
||||
|
||||
return StateResult::Success(user_id.to_string());
|
||||
}
|
||||
|
||||
if let Ok(results) =
|
||||
database::get_collection("members").find(doc! { "_id.user": &user_id }, None)
|
||||
{
|
||||
let mut guilds = vec![];
|
||||
for result in results {
|
||||
if let Ok(entry) = result {
|
||||
guilds.push(
|
||||
entry
|
||||
.get_document("_id")
|
||||
.unwrap()
|
||||
.get_str("guild")
|
||||
.unwrap()
|
||||
.to_string(),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
let mut user = User::new();
|
||||
for guild in guilds {
|
||||
user.guilds.insert(guild.clone());
|
||||
self.push_to_guild(guild, user_id.to_string());
|
||||
}
|
||||
|
||||
user.connections.insert(connection);
|
||||
self.users.insert(user_id.to_string(), user);
|
||||
|
||||
StateResult::Success(user_id.to_string())
|
||||
} else {
|
||||
StateResult::DatabaseError
|
||||
}
|
||||
} else {
|
||||
StateResult::InvalidToken
|
||||
}
|
||||
} else {
|
||||
StateResult::DatabaseError
|
||||
}
|
||||
}
|
||||
|
||||
pub fn disconnect<U: Into<Option<String>>>(&mut self, user_id: U, connection: String) {
|
||||
if let Some(user_id) = user_id.into() {
|
||||
let user = self.users.get_mut(&user_id).unwrap();
|
||||
user.connections.remove(&connection);
|
||||
|
||||
if user.connections.len() == 0 {
|
||||
for guild in &user.guilds {
|
||||
self.guilds.get_mut(guild).unwrap().users.remove(&user_id);
|
||||
}
|
||||
|
||||
self.users.remove(&user_id);
|
||||
}
|
||||
}
|
||||
|
||||
unsafe {
|
||||
CONNECTIONS
|
||||
.get()
|
||||
.unwrap()
|
||||
.write()
|
||||
.unwrap()
|
||||
.remove(&connection);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub static mut DATA: OnceCell<RwLock<GlobalState>> = OnceCell::new();
|
||||
|
||||
pub fn init() {
|
||||
unsafe {
|
||||
if CONNECTIONS.set(RwLock::new(HashMap::new())).is_err() {
|
||||
panic!("Failed to set global connections map.");
|
||||
}
|
||||
|
||||
if DATA.set(RwLock::new(GlobalState::new())).is_err() {
|
||||
panic!("Failed to set global state.");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub fn send_message(users: Option<Vec<String>>, guild: Option<String>, data: String) {
|
||||
let state = unsafe { DATA.get().unwrap().read().unwrap() };
|
||||
let mut connections = HashSet::new();
|
||||
|
||||
let mut users = vec_to_set(&users.unwrap_or(vec![]));
|
||||
if let Some(guild) = guild {
|
||||
if let Some(entry) = state.guilds.get(&guild) {
|
||||
for user in &entry.users {
|
||||
users.insert(user.to_string());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
for user in users {
|
||||
if let Some(entry) = state.users.get(&user) {
|
||||
for connection in &entry.connections {
|
||||
connections.insert(connection.clone());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
let targets = unsafe { CONNECTIONS.get().unwrap().read().unwrap() };
|
||||
for conn in connections {
|
||||
if let Some(sender) = targets.get(&conn) {
|
||||
if sender.send(data.clone()).is_err() {
|
||||
eprintln!("Failed to send a notification to a websocket. [{}]", &conn);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
119
src/notifications/ws.rs
Normal file
119
src/notifications/ws.rs
Normal file
@@ -0,0 +1,119 @@
|
||||
use super::state::{self, StateResult};
|
||||
|
||||
use serde_json::{from_str, json, Value};
|
||||
use std::env;
|
||||
use ulid::Ulid;
|
||||
use ws::{listen, CloseCode, Error, Handler, Handshake, Message, Result, Sender};
|
||||
|
||||
struct Server {
|
||||
sender: Sender,
|
||||
user_id: Option<String>,
|
||||
id: String,
|
||||
}
|
||||
|
||||
impl Handler for Server {
|
||||
fn on_open(&mut self, _: Handshake) -> Result<()> {
|
||||
state::add_connection(self.id.clone(), self.sender.clone());
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn on_message(&mut self, msg: Message) -> Result<()> {
|
||||
if let Message::Text(text) = msg {
|
||||
if let Ok(data) = from_str(&text) as std::result::Result<Value, _> {
|
||||
if let Value::String(packet_type) = &data["type"] {
|
||||
if packet_type == "authenticate" {
|
||||
if self.user_id.is_some() {
|
||||
self.sender.send(
|
||||
json!({
|
||||
"type": "authenticate",
|
||||
"success": false,
|
||||
"error": "Already authenticated!"
|
||||
})
|
||||
.to_string(),
|
||||
)
|
||||
} else if let Value::String(token) = &data["token"] {
|
||||
let mut state = unsafe { state::DATA.get().unwrap().write().unwrap() };
|
||||
|
||||
match state.try_authenticate(self.id.clone(), token.to_string()) {
|
||||
StateResult::Success(user_id) => {
|
||||
self.user_id = Some(user_id);
|
||||
self.sender.send(
|
||||
json!({
|
||||
"type": "authenticate",
|
||||
"success": true,
|
||||
})
|
||||
.to_string(),
|
||||
)
|
||||
}
|
||||
StateResult::DatabaseError => self.sender.send(
|
||||
json!({
|
||||
"type": "authenticate",
|
||||
"success": false,
|
||||
"error": "Had database error."
|
||||
})
|
||||
.to_string(),
|
||||
),
|
||||
StateResult::InvalidToken => self.sender.send(
|
||||
json!({
|
||||
"type": "authenticate",
|
||||
"success": false,
|
||||
"error": "Invalid token."
|
||||
})
|
||||
.to_string(),
|
||||
),
|
||||
}
|
||||
} else {
|
||||
self.sender.send(
|
||||
json!({
|
||||
"type": "authenticate",
|
||||
"success": false,
|
||||
"error": "Token not present."
|
||||
})
|
||||
.to_string(),
|
||||
)
|
||||
}
|
||||
} else {
|
||||
Ok(())
|
||||
}
|
||||
} else {
|
||||
Ok(())
|
||||
}
|
||||
} else {
|
||||
Ok(())
|
||||
}
|
||||
} else {
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
fn on_close(&mut self, _code: CloseCode, _reason: &str) {
|
||||
unsafe {
|
||||
state::DATA
|
||||
.get()
|
||||
.unwrap()
|
||||
.write()
|
||||
.unwrap()
|
||||
.disconnect(self.user_id.clone(), self.id.clone());
|
||||
}
|
||||
|
||||
println!("User disconnected. [{}]", self.id);
|
||||
}
|
||||
|
||||
fn on_error(&mut self, err: Error) {
|
||||
println!("The server encountered an error: {:?}", err);
|
||||
}
|
||||
}
|
||||
|
||||
pub fn launch_server() {
|
||||
state::init();
|
||||
|
||||
listen(
|
||||
env::var("WS_HOST").unwrap_or("0.0.0.0:9999".to_string()),
|
||||
|sender| Server {
|
||||
sender,
|
||||
user_id: None,
|
||||
id: Ulid::new().to_string(),
|
||||
},
|
||||
)
|
||||
.unwrap()
|
||||
}
|
||||
@@ -5,6 +5,10 @@ use crate::database::{
|
||||
};
|
||||
use crate::guards::auth::UserRef;
|
||||
use crate::guards::channel::ChannelRef;
|
||||
use crate::notifications::{
|
||||
self,
|
||||
events::{groups::*, guilds::ChannelDelete, message::*, Notification},
|
||||
};
|
||||
use crate::util::vec_to_set;
|
||||
|
||||
use bson::{doc, from_bson, Bson, Bson::UtcDatetime};
|
||||
@@ -183,7 +187,7 @@ pub fn add_member(user: UserRef, target: ChannelRef, member: UserRef) -> Option<
|
||||
|
||||
with_permissions!(user, target);
|
||||
|
||||
let recp = target.recipients.unwrap();
|
||||
let recp = target.recipients.as_ref().unwrap();
|
||||
if recp.len() == 50 {
|
||||
return Some(Response::BadRequest(
|
||||
json!({ "error": "Maximum group size is 50." }),
|
||||
@@ -201,7 +205,7 @@ pub fn add_member(user: UserRef, target: ChannelRef, member: UserRef) -> Option<
|
||||
Relationship::Friend => {
|
||||
if database::get_collection("channels")
|
||||
.update_one(
|
||||
doc! { "_id": &target.id },
|
||||
doc! { "_id": target.id.clone() },
|
||||
doc! {
|
||||
"$push": {
|
||||
"recipients": &member.id
|
||||
@@ -211,7 +215,31 @@ pub fn add_member(user: UserRef, target: ChannelRef, member: UserRef) -> Option<
|
||||
)
|
||||
.is_ok()
|
||||
{
|
||||
Some(Response::Result(super::Status::Ok))
|
||||
if (Message {
|
||||
id: Ulid::new().to_string(),
|
||||
nonce: None,
|
||||
channel: target.id.clone(),
|
||||
author: "system".to_string(),
|
||||
content: format!("<@{}> added <@{}> to the group.", &user.id, &member.id),
|
||||
edited: None,
|
||||
previous_content: vec![],
|
||||
})
|
||||
.send(&target)
|
||||
{
|
||||
notifications::send_message_given_channel(
|
||||
Notification::group_user_join(UserJoin {
|
||||
id: target.id.clone(),
|
||||
user: member.id.clone(),
|
||||
}),
|
||||
&target,
|
||||
);
|
||||
|
||||
Some(Response::Result(super::Status::Ok))
|
||||
} else {
|
||||
Some(Response::PartialStatus(
|
||||
json!({ "error": "Failed to send join message, but user has been added." }),
|
||||
))
|
||||
}
|
||||
} else {
|
||||
Some(Response::InternalServerError(
|
||||
json!({ "error": "Failed to add user to group." }),
|
||||
@@ -243,7 +271,7 @@ pub fn remove_member(user: UserRef, target: ChannelRef, member: UserRef) -> Opti
|
||||
return Some(Response::LackingPermission(Permission::KickMembers));
|
||||
}
|
||||
|
||||
let set = vec_to_set(&target.recipients.unwrap());
|
||||
let set = vec_to_set(target.recipients.as_ref().unwrap());
|
||||
if set.get(&member.id).is_none() {
|
||||
return Some(Response::BadRequest(
|
||||
json!({ "error": "User not in group!" }),
|
||||
@@ -262,7 +290,31 @@ pub fn remove_member(user: UserRef, target: ChannelRef, member: UserRef) -> Opti
|
||||
)
|
||||
.is_ok()
|
||||
{
|
||||
Some(Response::Result(super::Status::Ok))
|
||||
if (Message {
|
||||
id: Ulid::new().to_string(),
|
||||
nonce: None,
|
||||
channel: target.id.clone(),
|
||||
author: "system".to_string(),
|
||||
content: format!("<@{}> removed <@{}> from the group.", &user.id, &member.id),
|
||||
edited: None,
|
||||
previous_content: vec![],
|
||||
})
|
||||
.send(&target)
|
||||
{
|
||||
notifications::send_message_given_channel(
|
||||
Notification::group_user_leave(UserLeave {
|
||||
id: target.id.clone(),
|
||||
user: member.id.clone(),
|
||||
}),
|
||||
&target,
|
||||
);
|
||||
|
||||
Some(Response::Result(super::Status::Ok))
|
||||
} else {
|
||||
Some(Response::PartialStatus(
|
||||
json!({ "error": "Failed to send join message, but user has been removed." }),
|
||||
))
|
||||
}
|
||||
} else {
|
||||
Some(Response::InternalServerError(
|
||||
json!({ "error": "Failed to add user to group." }),
|
||||
@@ -295,7 +347,7 @@ pub fn delete(user: UserRef, target: ChannelRef) -> Option<Response> {
|
||||
Some(Response::Result(super::Status::Ok))
|
||||
} else {
|
||||
Some(Response::InternalServerError(
|
||||
json!({ "error": "Failed to delete group." }),
|
||||
json!({ "error": "Failed to delete channel." }),
|
||||
))
|
||||
}
|
||||
} else {
|
||||
@@ -323,15 +375,19 @@ pub fn delete(user: UserRef, target: ChannelRef) -> Option<Response> {
|
||||
}
|
||||
}
|
||||
1 => {
|
||||
let mut recipients =
|
||||
vec_to_set(&target.recipients.expect("Missing recipients on Group DM."));
|
||||
let owner = target.owner.expect("Missing owner on Group DM.");
|
||||
let mut recipients = vec_to_set(
|
||||
target
|
||||
.recipients
|
||||
.as_ref()
|
||||
.expect("Missing recipients on Group DM."),
|
||||
);
|
||||
let owner = target.owner.as_ref().expect("Missing owner on Group DM.");
|
||||
|
||||
if recipients.len() == 1 {
|
||||
try_delete()
|
||||
} else {
|
||||
recipients.remove(&user.id);
|
||||
let new_owner = if owner == user.id {
|
||||
let new_owner = if owner == &user.id {
|
||||
recipients.iter().next().unwrap()
|
||||
} else {
|
||||
&owner
|
||||
@@ -352,7 +408,31 @@ pub fn delete(user: UserRef, target: ChannelRef) -> Option<Response> {
|
||||
)
|
||||
.is_ok()
|
||||
{
|
||||
Some(Response::Result(super::Status::Ok))
|
||||
if (Message {
|
||||
id: Ulid::new().to_string(),
|
||||
nonce: None,
|
||||
channel: target.id.clone(),
|
||||
author: "system".to_string(),
|
||||
content: format!("<@{}> left the group.", &user.id),
|
||||
edited: None,
|
||||
previous_content: vec![],
|
||||
})
|
||||
.send(&target)
|
||||
{
|
||||
notifications::send_message_given_channel(
|
||||
Notification::group_user_leave(UserLeave {
|
||||
id: target.id.clone(),
|
||||
user: user.id.clone(),
|
||||
}),
|
||||
&target,
|
||||
);
|
||||
|
||||
Some(Response::Result(super::Status::Ok))
|
||||
} else {
|
||||
Some(Response::PartialStatus(
|
||||
json!({ "error": "Failed to send leave message, but you have left the group." }),
|
||||
))
|
||||
}
|
||||
} else {
|
||||
Some(Response::InternalServerError(
|
||||
json!({ "error": "Failed to remove you from the group." }),
|
||||
@@ -361,9 +441,10 @@ pub fn delete(user: UserRef, target: ChannelRef) -> Option<Response> {
|
||||
}
|
||||
}
|
||||
2 => {
|
||||
let guild_id = target.guild.unwrap();
|
||||
if database::get_collection("guilds")
|
||||
.update_one(
|
||||
doc! { "_id": target.guild.unwrap() },
|
||||
doc! { "_id": &guild_id },
|
||||
doc! {
|
||||
"$pull": {
|
||||
"invites": {
|
||||
@@ -375,6 +456,15 @@ pub fn delete(user: UserRef, target: ChannelRef) -> Option<Response> {
|
||||
)
|
||||
.is_ok()
|
||||
{
|
||||
notifications::send_message_threaded(
|
||||
None,
|
||||
guild_id.clone(),
|
||||
Notification::guild_channel_delete(ChannelDelete {
|
||||
id: guild_id.clone(),
|
||||
channel: target.id.clone(),
|
||||
}),
|
||||
);
|
||||
|
||||
try_delete()
|
||||
} else {
|
||||
Some(Response::InternalServerError(
|
||||
@@ -453,76 +543,23 @@ pub fn send_message(
|
||||
}
|
||||
|
||||
let id = Ulid::new().to_string();
|
||||
Some(
|
||||
if col
|
||||
.insert_one(
|
||||
doc! {
|
||||
"_id": &id,
|
||||
"nonce": nonce,
|
||||
"channel": &target.id,
|
||||
"author": &user.id,
|
||||
"content": &content,
|
||||
},
|
||||
None,
|
||||
)
|
||||
.is_ok()
|
||||
{
|
||||
let short_content: String = content.chars().take(24).collect();
|
||||
let col = database::get_collection("channels");
|
||||
let message = Message {
|
||||
id: id.clone(),
|
||||
nonce: Some(nonce),
|
||||
channel: target.id.clone(),
|
||||
author: user.id,
|
||||
content,
|
||||
edited: None,
|
||||
previous_content: vec![],
|
||||
};
|
||||
|
||||
// !! this stuff can be async
|
||||
if target.channel_type == ChannelType::DM as u8
|
||||
|| target.channel_type == ChannelType::GROUPDM as u8
|
||||
{
|
||||
let mut update = doc! {
|
||||
"$set": {
|
||||
"last_message": {
|
||||
"id": &id,
|
||||
"user_id": &user.id,
|
||||
"short_content": short_content,
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
if target.channel_type == ChannelType::DM as u8 {
|
||||
update
|
||||
.get_document_mut("$set")
|
||||
.unwrap()
|
||||
.insert("active", true);
|
||||
}
|
||||
|
||||
if col
|
||||
.update_one(doc! { "_id": &target.id }, update, None)
|
||||
.is_ok()
|
||||
{
|
||||
Response::Success(json!({ "id": id }))
|
||||
} else {
|
||||
Response::InternalServerError(json!({ "error": "Failed to update channel." }))
|
||||
}
|
||||
} else {
|
||||
Response::Success(json!({ "id": id }))
|
||||
}
|
||||
|
||||
/*websocket::queue_message(
|
||||
get_recipients(&target),
|
||||
json!({
|
||||
"type": "message",
|
||||
"data": {
|
||||
"id": id.clone(),
|
||||
"nonce": nonce,
|
||||
"channel": target.id,
|
||||
"author": user.id,
|
||||
"content": content,
|
||||
},
|
||||
})
|
||||
.to_string(),
|
||||
);*/
|
||||
} else {
|
||||
Response::InternalServerError(json!({
|
||||
"error": "Failed database query."
|
||||
}))
|
||||
},
|
||||
)
|
||||
if message.send(&target) {
|
||||
Some(Response::Success(json!({ "id": id })))
|
||||
} else {
|
||||
Some(Response::BadRequest(
|
||||
json!({ "error": "Failed to send message." }),
|
||||
))
|
||||
}
|
||||
}
|
||||
|
||||
/// get a message
|
||||
@@ -534,28 +571,21 @@ pub fn get_message(user: UserRef, target: ChannelRef, message: Message) -> Optio
|
||||
return Some(Response::LackingPermission(Permission::ReadMessages));
|
||||
}
|
||||
|
||||
let prev =
|
||||
// ! CHECK IF USER HAS PERMISSION TO VIEW EDITS OF MESSAGES
|
||||
if let Some(previous) = message.previous_content {
|
||||
let mut entries = vec![];
|
||||
for entry in previous {
|
||||
entries.push(json!({
|
||||
"content": entry.content,
|
||||
"time": entry.time.timestamp(),
|
||||
}));
|
||||
}
|
||||
|
||||
Some(entries)
|
||||
} else {
|
||||
None
|
||||
};
|
||||
// ! CHECK IF USER HAS PERMISSION TO VIEW EDITS OF MESSAGES
|
||||
let mut entries = vec![];
|
||||
for entry in message.previous_content {
|
||||
entries.push(json!({
|
||||
"content": entry.content,
|
||||
"time": entry.time.timestamp(),
|
||||
}));
|
||||
}
|
||||
|
||||
Some(Response::Success(json!({
|
||||
"id": message.id,
|
||||
"author": message.author,
|
||||
"content": message.content,
|
||||
"edited": if let Some(t) = message.edited { Some(t.timestamp()) } else { None },
|
||||
"previous_content": prev,
|
||||
"previous_content": entries,
|
||||
})))
|
||||
}
|
||||
|
||||
@@ -597,7 +627,7 @@ pub fn edit_message(
|
||||
},
|
||||
"$push": {
|
||||
"previous_content": {
|
||||
"content": message.content,
|
||||
"content": &message.content,
|
||||
"time": time,
|
||||
}
|
||||
},
|
||||
@@ -605,19 +635,13 @@ pub fn edit_message(
|
||||
None,
|
||||
) {
|
||||
Ok(_) => {
|
||||
/*websocket::queue_message(
|
||||
get_recipients(&target),
|
||||
json!({
|
||||
"type": "message_update",
|
||||
"data": {
|
||||
"id": message.id,
|
||||
"channel": target.id,
|
||||
"content": edit.content.clone(),
|
||||
"edited": edited.timestamp()
|
||||
},
|
||||
})
|
||||
.to_string(),
|
||||
);*/
|
||||
notifications::send_message_given_channel(
|
||||
Notification::message_edit(Edit {
|
||||
id: message.id.clone(),
|
||||
content: message.content,
|
||||
}),
|
||||
&target,
|
||||
);
|
||||
|
||||
Some(Response::Result(super::Status::Ok))
|
||||
}
|
||||
@@ -642,17 +666,12 @@ pub fn delete_message(user: UserRef, target: ChannelRef, message: Message) -> Op
|
||||
|
||||
match col.delete_one(doc! { "_id": &message.id }, None) {
|
||||
Ok(_) => {
|
||||
/*websocket::queue_message(
|
||||
get_recipients(&target),
|
||||
json!({
|
||||
"type": "message_delete",
|
||||
"data": {
|
||||
"id": message.id,
|
||||
"channel": target.id
|
||||
},
|
||||
})
|
||||
.to_string(),
|
||||
);*/
|
||||
notifications::send_message_given_channel(
|
||||
Notification::message_delete(Delete {
|
||||
id: message.id.clone(),
|
||||
}),
|
||||
&target,
|
||||
);
|
||||
|
||||
Some(Response::Result(super::Status::Ok))
|
||||
}
|
||||
|
||||
@@ -4,6 +4,10 @@ use crate::database::{self, channel::Channel, Permission, PermissionCalculator};
|
||||
use crate::guards::auth::UserRef;
|
||||
use crate::guards::channel::ChannelRef;
|
||||
use crate::guards::guild::{get_invite, get_member, GuildRef};
|
||||
use crate::notifications::{
|
||||
self,
|
||||
events::{guilds::*, Notification},
|
||||
};
|
||||
use crate::util::gen_token;
|
||||
|
||||
use bson::{doc, from_bson, Bson};
|
||||
@@ -180,6 +184,14 @@ pub fn remove_guild(user: UserRef, target: GuildRef) -> Option<Response> {
|
||||
)
|
||||
.is_ok()
|
||||
{
|
||||
notifications::send_message_threaded(
|
||||
None,
|
||||
target.id.clone(),
|
||||
Notification::guild_delete(Delete {
|
||||
id: target.id.clone(),
|
||||
}),
|
||||
);
|
||||
|
||||
Some(Response::Result(super::Status::Ok))
|
||||
} else {
|
||||
Some(Response::InternalServerError(
|
||||
@@ -212,6 +224,16 @@ pub fn remove_guild(user: UserRef, target: GuildRef) -> Option<Response> {
|
||||
)
|
||||
.is_ok()
|
||||
{
|
||||
notifications::send_message_threaded(
|
||||
None,
|
||||
target.id.clone(),
|
||||
Notification::guild_user_leave(UserLeave {
|
||||
id: target.id.clone(),
|
||||
user: user.id.clone(),
|
||||
banned: false,
|
||||
}),
|
||||
);
|
||||
|
||||
Some(Response::Result(super::Status::Ok))
|
||||
} else {
|
||||
Some(Response::InternalServerError(
|
||||
@@ -268,13 +290,24 @@ pub fn create_channel(
|
||||
"nonce": &nonce,
|
||||
"type": 2,
|
||||
"guild": &target.id,
|
||||
"name": name,
|
||||
"description": description,
|
||||
"name": &name,
|
||||
"description": &description,
|
||||
},
|
||||
None,
|
||||
)
|
||||
.is_ok()
|
||||
{
|
||||
notifications::send_message_threaded(
|
||||
None,
|
||||
target.id.clone(),
|
||||
Notification::guild_channel_create(ChannelCreate {
|
||||
id: target.id.clone(),
|
||||
channel: id.clone(),
|
||||
name: name.clone(),
|
||||
description: description.clone(),
|
||||
}),
|
||||
);
|
||||
|
||||
Some(Response::Success(json!({ "id": &id })))
|
||||
} else {
|
||||
Some(Response::BadRequest(
|
||||
@@ -442,6 +475,15 @@ pub fn use_invite(user: UserRef, code: String) -> Response {
|
||||
)
|
||||
.is_ok()
|
||||
{
|
||||
notifications::send_message_threaded(
|
||||
None,
|
||||
guild_id.clone(),
|
||||
Notification::guild_user_join(UserJoin {
|
||||
id: guild_id.clone(),
|
||||
user: user.id.clone(),
|
||||
}),
|
||||
);
|
||||
|
||||
Response::Success(json!({
|
||||
"guild": &guild_id,
|
||||
"channel": &invite.channel,
|
||||
@@ -636,6 +678,16 @@ pub fn kick_member(user: UserRef, target: GuildRef, other: String) -> Option<Res
|
||||
)
|
||||
.is_ok()
|
||||
{
|
||||
notifications::send_message_threaded(
|
||||
None,
|
||||
target.id.clone(),
|
||||
Notification::guild_user_leave(UserLeave {
|
||||
id: target.id.clone(),
|
||||
user: other.clone(),
|
||||
banned: false,
|
||||
}),
|
||||
);
|
||||
|
||||
Some(Response::Result(super::Status::Ok))
|
||||
} else {
|
||||
Some(Response::InternalServerError(
|
||||
@@ -712,6 +764,16 @@ pub fn ban_member(
|
||||
)
|
||||
.is_ok()
|
||||
{
|
||||
notifications::send_message_threaded(
|
||||
None,
|
||||
target.id.clone(),
|
||||
Notification::guild_user_leave(UserLeave {
|
||||
id: target.id.clone(),
|
||||
user: other.clone(),
|
||||
banned: true,
|
||||
}),
|
||||
);
|
||||
|
||||
Some(Response::Result(super::Status::Ok))
|
||||
} else {
|
||||
Some(Response::InternalServerError(
|
||||
|
||||
@@ -19,6 +19,8 @@ pub enum Response {
|
||||
Success(JsonValue),
|
||||
#[response()]
|
||||
Redirect(Redirect),
|
||||
#[response(status = 207)]
|
||||
PartialStatus(JsonValue),
|
||||
#[response(status = 400)]
|
||||
BadRequest(JsonValue),
|
||||
#[response(status = 401)]
|
||||
@@ -51,8 +53,7 @@ impl<'a> rocket::response::Responder<'a> for Permission {
|
||||
.header(ContentType::JSON)
|
||||
.sized_body(Cursor::new(format!(
|
||||
"{{\"error\":\"Lacking permission: {:?}.\",\"permission\":{}}}",
|
||||
self,
|
||||
self as u32,
|
||||
self, self as u32,
|
||||
)))
|
||||
.ok()
|
||||
}
|
||||
|
||||
@@ -6,6 +6,6 @@ use bson::doc;
|
||||
#[get("/")]
|
||||
pub fn root() -> Response {
|
||||
Response::Success(json!({
|
||||
"revolt": "0.0.1"
|
||||
"revolt": "0.1.0"
|
||||
}))
|
||||
}
|
||||
|
||||
@@ -1,6 +1,10 @@
|
||||
use super::Response;
|
||||
use crate::database::{self, get_relationship, get_relationship_internal, mutual, Relationship};
|
||||
use crate::guards::auth::UserRef;
|
||||
use crate::notifications::{
|
||||
self,
|
||||
events::{users::*, Notification},
|
||||
};
|
||||
use crate::routes::channel;
|
||||
|
||||
use bson::doc;
|
||||
@@ -32,7 +36,7 @@ pub fn user(user: UserRef, target: UserRef) -> Response {
|
||||
Response::Success(json!({
|
||||
"id": target.id,
|
||||
"username": target.username,
|
||||
"relationship": get_relationship(&user, &target) as u8,
|
||||
"relationship": get_relationship(&user, &target) as i32,
|
||||
"mutual": {
|
||||
"guilds": mutual::find_mutual_guilds(&user.id, &target.id),
|
||||
"friends": mutual::find_mutual_friends(&user.id, &target.id),
|
||||
@@ -67,7 +71,7 @@ pub fn lookup(user: UserRef, query: Json<LookupQuery>) -> Response {
|
||||
results.push(json!({
|
||||
"id": id,
|
||||
"username": doc.get_str("username").unwrap(),
|
||||
"relationship": get_relationship_internal(&user.id, &id, &relationships) as u8
|
||||
"relationship": get_relationship_internal(&user.id, &id, &relationships) as i32
|
||||
}));
|
||||
}
|
||||
}
|
||||
@@ -186,7 +190,7 @@ pub fn get_friends(user: UserRef) -> Response {
|
||||
/// retrieve friend status with user
|
||||
#[get("/<target>/friend")]
|
||||
pub fn get_friend(user: UserRef, target: UserRef) -> Response {
|
||||
Response::Success(json!({ "status": get_relationship(&user, &target) as u8 }))
|
||||
Response::Success(json!({ "status": get_relationship(&user, &target) as i32 }))
|
||||
}
|
||||
|
||||
/// create or accept a friend request
|
||||
@@ -218,8 +222,8 @@ pub fn add_friend(user: UserRef, target: UserRef) -> Response {
|
||||
if col
|
||||
.update_one(
|
||||
doc! {
|
||||
"_id": target.id,
|
||||
"relations.id": user.id
|
||||
"_id": target.id.clone(),
|
||||
"relations.id": user.id.clone()
|
||||
},
|
||||
doc! {
|
||||
"$set": {
|
||||
@@ -230,7 +234,25 @@ pub fn add_friend(user: UserRef, target: UserRef) -> Response {
|
||||
)
|
||||
.is_ok()
|
||||
{
|
||||
Response::Success(json!({ "status": Relationship::Friend as u8 }))
|
||||
notifications::send_message_threaded(
|
||||
vec![target.id.clone()],
|
||||
None,
|
||||
Notification::user_friend_status(FriendStatus {
|
||||
id: user.id.clone(),
|
||||
status: Relationship::Friend as i32,
|
||||
}),
|
||||
);
|
||||
|
||||
notifications::send_message_threaded(
|
||||
vec![user.id.clone()],
|
||||
None,
|
||||
Notification::user_friend_status(FriendStatus {
|
||||
id: target.id.clone(),
|
||||
status: Relationship::Friend as i32,
|
||||
}),
|
||||
);
|
||||
|
||||
Response::Success(json!({ "status": Relationship::Friend as i32 }))
|
||||
} else {
|
||||
Response::InternalServerError(
|
||||
json!({ "error": "Failed to commit! Try re-adding them as a friend." }),
|
||||
@@ -269,12 +291,12 @@ pub fn add_friend(user: UserRef, target: UserRef) -> Response {
|
||||
if col
|
||||
.update_one(
|
||||
doc! {
|
||||
"_id": target.id
|
||||
"_id": target.id.clone()
|
||||
},
|
||||
doc! {
|
||||
"$push": {
|
||||
"relations": {
|
||||
"id": user.id,
|
||||
"id": user.id.clone(),
|
||||
"status": Relationship::Incoming as i32
|
||||
}
|
||||
}
|
||||
@@ -283,7 +305,25 @@ pub fn add_friend(user: UserRef, target: UserRef) -> Response {
|
||||
)
|
||||
.is_ok()
|
||||
{
|
||||
Response::Success(json!({ "status": Relationship::Outgoing as u8 }))
|
||||
notifications::send_message_threaded(
|
||||
vec![user.id.clone()],
|
||||
None,
|
||||
Notification::user_friend_status(FriendStatus {
|
||||
id: target.id.clone(),
|
||||
status: Relationship::Outgoing as i32,
|
||||
}),
|
||||
);
|
||||
|
||||
notifications::send_message_threaded(
|
||||
vec![target.id.clone()],
|
||||
None,
|
||||
Notification::user_friend_status(FriendStatus {
|
||||
id: user.id.clone(),
|
||||
status: Relationship::Incoming as i32,
|
||||
}),
|
||||
);
|
||||
|
||||
Response::Success(json!({ "status": Relationship::Outgoing as i32 }))
|
||||
} else {
|
||||
Response::InternalServerError(
|
||||
json!({ "error": "Failed to commit! Try re-adding them as a friend." }),
|
||||
@@ -327,12 +367,12 @@ pub fn remove_friend(user: UserRef, target: UserRef) -> Response {
|
||||
if col
|
||||
.update_one(
|
||||
doc! {
|
||||
"_id": target.id
|
||||
"_id": target.id.clone()
|
||||
},
|
||||
doc! {
|
||||
"$pull": {
|
||||
"relations": {
|
||||
"id": user.id
|
||||
"id": user.id.clone()
|
||||
}
|
||||
}
|
||||
},
|
||||
@@ -340,7 +380,25 @@ pub fn remove_friend(user: UserRef, target: UserRef) -> Response {
|
||||
)
|
||||
.is_ok()
|
||||
{
|
||||
Response::Success(json!({ "status": Relationship::NONE as u8 }))
|
||||
notifications::send_message_threaded(
|
||||
vec![user.id.clone()],
|
||||
None,
|
||||
Notification::user_friend_status(FriendStatus {
|
||||
id: target.id.clone(),
|
||||
status: Relationship::NONE as i32,
|
||||
}),
|
||||
);
|
||||
|
||||
notifications::send_message_threaded(
|
||||
vec![target.id.clone()],
|
||||
None,
|
||||
Notification::user_friend_status(FriendStatus {
|
||||
id: user.id.clone(),
|
||||
status: Relationship::NONE as i32,
|
||||
}),
|
||||
);
|
||||
|
||||
Response::Success(json!({ "status": Relationship::NONE as i32 }))
|
||||
} else {
|
||||
Response::InternalServerError(
|
||||
json!({ "error": "Failed to commit! Target remains in same state." }),
|
||||
@@ -365,7 +423,9 @@ pub fn block_user(user: UserRef, target: UserRef) -> Response {
|
||||
let col = database::get_collection("users");
|
||||
|
||||
match get_relationship(&user, &target) {
|
||||
Relationship::Friend | Relationship::Incoming | Relationship::Outgoing => {
|
||||
Relationship::Friend
|
||||
| Relationship::Incoming
|
||||
| Relationship::Outgoing => {
|
||||
if col
|
||||
.update_one(
|
||||
doc! {
|
||||
@@ -384,8 +444,8 @@ pub fn block_user(user: UserRef, target: UserRef) -> Response {
|
||||
if col
|
||||
.update_one(
|
||||
doc! {
|
||||
"_id": target.id,
|
||||
"relations.id": user.id
|
||||
"_id": target.id.clone(),
|
||||
"relations.id": user.id.clone()
|
||||
},
|
||||
doc! {
|
||||
"$set": {
|
||||
@@ -396,7 +456,91 @@ pub fn block_user(user: UserRef, target: UserRef) -> Response {
|
||||
)
|
||||
.is_ok()
|
||||
{
|
||||
Response::Success(json!({ "status": Relationship::Blocked as u8 }))
|
||||
notifications::send_message_threaded(
|
||||
vec![user.id.clone()],
|
||||
None,
|
||||
Notification::user_friend_status(FriendStatus {
|
||||
id: target.id.clone(),
|
||||
status: Relationship::Blocked as i32,
|
||||
}),
|
||||
);
|
||||
|
||||
notifications::send_message_threaded(
|
||||
vec![target.id.clone()],
|
||||
None,
|
||||
Notification::user_friend_status(FriendStatus {
|
||||
id: user.id.clone(),
|
||||
status: Relationship::BlockedOther as i32,
|
||||
}),
|
||||
);
|
||||
|
||||
Response::Success(json!({ "status": Relationship::Blocked as i32 }))
|
||||
} else {
|
||||
Response::InternalServerError(
|
||||
json!({ "error": "Failed to commit! Try blocking the user again, remove it first." }),
|
||||
)
|
||||
}
|
||||
} else {
|
||||
Response::InternalServerError(
|
||||
json!({ "error": "Failed to commit to database, try again." }),
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
Relationship::NONE => {
|
||||
if col
|
||||
.update_one(
|
||||
doc! {
|
||||
"_id": user.id.clone(),
|
||||
},
|
||||
doc! {
|
||||
"$push": {
|
||||
"relations": {
|
||||
"id": target.id.clone(),
|
||||
"status": Relationship::Blocked as i32,
|
||||
}
|
||||
}
|
||||
},
|
||||
None,
|
||||
)
|
||||
.is_ok()
|
||||
{
|
||||
if col
|
||||
.update_one(
|
||||
doc! {
|
||||
"_id": target.id.clone(),
|
||||
},
|
||||
doc! {
|
||||
"$push": {
|
||||
"relations": {
|
||||
"id": user.id.clone(),
|
||||
"status": Relationship::BlockedOther as i32,
|
||||
}
|
||||
}
|
||||
},
|
||||
None,
|
||||
)
|
||||
.is_ok()
|
||||
{
|
||||
notifications::send_message_threaded(
|
||||
vec![user.id.clone()],
|
||||
None,
|
||||
Notification::user_friend_status(FriendStatus {
|
||||
id: target.id.clone(),
|
||||
status: Relationship::Blocked as i32,
|
||||
}),
|
||||
);
|
||||
|
||||
notifications::send_message_threaded(
|
||||
vec![target.id.clone()],
|
||||
None,
|
||||
Notification::user_friend_status(FriendStatus {
|
||||
id: user.id.clone(),
|
||||
status: Relationship::BlockedOther as i32,
|
||||
}),
|
||||
);
|
||||
|
||||
Response::Success(json!({ "status": Relationship::Blocked as i32 }))
|
||||
} else {
|
||||
Response::InternalServerError(
|
||||
json!({ "error": "Failed to commit! Try blocking the user again, remove it first." }),
|
||||
@@ -427,16 +571,23 @@ pub fn block_user(user: UserRef, target: UserRef) -> Response {
|
||||
)
|
||||
.is_ok()
|
||||
{
|
||||
Response::Success(json!({ "status": Relationship::Blocked as u8 }))
|
||||
notifications::send_message_threaded(
|
||||
vec![user.id.clone()],
|
||||
None,
|
||||
Notification::user_friend_status(FriendStatus {
|
||||
id: target.id.clone(),
|
||||
status: Relationship::Blocked as i32,
|
||||
}),
|
||||
);
|
||||
|
||||
Response::Success(json!({ "status": Relationship::Blocked as i32 }))
|
||||
} else {
|
||||
Response::InternalServerError(
|
||||
json!({ "error": "Failed to commit to database, try again." }),
|
||||
)
|
||||
}
|
||||
}
|
||||
Relationship::SELF | Relationship::NONE => {
|
||||
Response::BadRequest(json!({ "error": "This has no effect." }))
|
||||
}
|
||||
Relationship::SELF => Response::BadRequest(json!({ "error": "This has no effect." })),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -463,7 +614,16 @@ pub fn unblock_user(user: UserRef, target: UserRef) -> Response {
|
||||
)
|
||||
.is_ok()
|
||||
{
|
||||
Response::Success(json!({ "status": Relationship::BlockedOther as u8 }))
|
||||
notifications::send_message_threaded(
|
||||
vec![user.id.clone()],
|
||||
None,
|
||||
Notification::user_friend_status(FriendStatus {
|
||||
id: target.id.clone(),
|
||||
status: Relationship::BlockedOther as i32,
|
||||
}),
|
||||
);
|
||||
|
||||
Response::Success(json!({ "status": Relationship::BlockedOther as i32 }))
|
||||
} else {
|
||||
Response::InternalServerError(
|
||||
json!({ "error": "Failed to commit to database, try again." }),
|
||||
@@ -490,12 +650,12 @@ pub fn unblock_user(user: UserRef, target: UserRef) -> Response {
|
||||
if col
|
||||
.update_one(
|
||||
doc! {
|
||||
"_id": target.id
|
||||
"_id": target.id.clone()
|
||||
},
|
||||
doc! {
|
||||
"$pull": {
|
||||
"relations": {
|
||||
"id": user.id
|
||||
"id": user.id.clone()
|
||||
}
|
||||
}
|
||||
},
|
||||
@@ -503,7 +663,25 @@ pub fn unblock_user(user: UserRef, target: UserRef) -> Response {
|
||||
)
|
||||
.is_ok()
|
||||
{
|
||||
Response::Success(json!({ "status": Relationship::NONE as u8 }))
|
||||
notifications::send_message_threaded(
|
||||
vec![user.id.clone()],
|
||||
None,
|
||||
Notification::user_friend_status(FriendStatus {
|
||||
id: target.id.clone(),
|
||||
status: Relationship::NONE as i32,
|
||||
}),
|
||||
);
|
||||
|
||||
notifications::send_message_threaded(
|
||||
vec![target.id.clone()],
|
||||
None,
|
||||
Notification::user_friend_status(FriendStatus {
|
||||
id: user.id.clone(),
|
||||
status: Relationship::NONE as i32,
|
||||
}),
|
||||
);
|
||||
|
||||
Response::Success(json!({ "status": Relationship::NONE as i32 }))
|
||||
} else {
|
||||
Response::InternalServerError(
|
||||
json!({ "error": "Failed to commit! Target remains in same state." }),
|
||||
|
||||
@@ -1,193 +0,0 @@
|
||||
extern crate ws;
|
||||
|
||||
use crate::database;
|
||||
|
||||
use hashbrown::HashMap;
|
||||
use std::sync::RwLock;
|
||||
use ulid::Ulid;
|
||||
|
||||
use bson::doc;
|
||||
use serde_json::{from_str, json, Value};
|
||||
|
||||
use ws::{listen, CloseCode, Error, Handler, Handshake, Message, Result, Sender};
|
||||
|
||||
struct Cell {
|
||||
id: String,
|
||||
out: Sender,
|
||||
}
|
||||
|
||||
use once_cell::sync::OnceCell;
|
||||
static mut CLIENTS: OnceCell<RwLock<HashMap<String, Vec<Cell>>>> = OnceCell::new();
|
||||
|
||||
struct Server {
|
||||
out: Sender,
|
||||
id: Option<String>,
|
||||
internal: String,
|
||||
}
|
||||
|
||||
impl Handler for Server {
|
||||
fn on_open(&mut self, _: Handshake) -> Result<()> {
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn on_message(&mut self, msg: Message) -> Result<()> {
|
||||
if let Message::Text(text) = msg {
|
||||
let data: Value = from_str(&text).unwrap();
|
||||
|
||||
if let Value::String(packet_type) = &data["type"] {
|
||||
match packet_type.as_str() {
|
||||
"authenticate" => {
|
||||
if self.id.is_some() {
|
||||
self.out.send(
|
||||
json!({
|
||||
"type": "authenticate",
|
||||
"success": false,
|
||||
"error": "Already authenticated!"
|
||||
})
|
||||
.to_string(),
|
||||
)
|
||||
} else if let Value::String(token) = &data["token"] {
|
||||
let col = database::get_collection("users");
|
||||
|
||||
match col.find_one(doc! { "access_token": token }, None).unwrap() {
|
||||
Some(u) => {
|
||||
let id = u.get_str("_id").expect("Missing id.");
|
||||
|
||||
unsafe {
|
||||
let mut map = CLIENTS.get_mut().unwrap().write().unwrap();
|
||||
let cell = Cell {
|
||||
id: self.internal.clone(),
|
||||
out: self.out.clone(),
|
||||
};
|
||||
if map.contains_key(&id.to_string()) {
|
||||
map.get_mut(&id.to_string()).unwrap().push(cell);
|
||||
} else {
|
||||
map.insert(id.to_string(), vec![cell]);
|
||||
}
|
||||
}
|
||||
|
||||
println!(
|
||||
"Websocket client connected. [ID: {} // {}]",
|
||||
id.to_string(),
|
||||
self.internal
|
||||
);
|
||||
|
||||
self.id = Some(id.to_string());
|
||||
self.out.send(
|
||||
json!({
|
||||
"type": "authenticate",
|
||||
"success": true
|
||||
})
|
||||
.to_string(),
|
||||
)
|
||||
}
|
||||
None => self.out.send(
|
||||
json!({
|
||||
"type": "authenticate",
|
||||
"success": false,
|
||||
"error": "Invalid authentication token."
|
||||
})
|
||||
.to_string(),
|
||||
),
|
||||
}
|
||||
} else {
|
||||
self.out.send(
|
||||
json!({
|
||||
"type": "authenticate",
|
||||
"success": false,
|
||||
"error": "Missing authentication token."
|
||||
})
|
||||
.to_string(),
|
||||
)
|
||||
}
|
||||
}
|
||||
_ => Ok(()),
|
||||
}
|
||||
} else {
|
||||
Ok(())
|
||||
}
|
||||
} else {
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
fn on_close(&mut self, code: CloseCode, reason: &str) {
|
||||
match code {
|
||||
CloseCode::Normal => println!("The client is done with the connection."),
|
||||
CloseCode::Away => println!("The client is leaving the site."),
|
||||
CloseCode::Abnormal => {
|
||||
println!("Closing handshake failed! Unable to obtain closing status from client.")
|
||||
}
|
||||
_ => println!("The client encountered an error: {}", reason),
|
||||
}
|
||||
|
||||
if let Some(id) = &self.id {
|
||||
println!(
|
||||
"Websocket client disconnected. [ID: {} // {}]",
|
||||
id, self.internal
|
||||
);
|
||||
unsafe {
|
||||
let mut map = CLIENTS.get_mut().unwrap().write().unwrap();
|
||||
let arr = map.get_mut(&id.clone()).unwrap();
|
||||
|
||||
if arr.len() == 1 {
|
||||
map.remove(&id.clone());
|
||||
} else {
|
||||
let index = arr.iter().position(|x| x.id == self.internal).unwrap();
|
||||
arr.remove(index);
|
||||
println!(
|
||||
"User [{}] is still connected {} times",
|
||||
self.id.as_ref().unwrap(),
|
||||
arr.len()
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn on_error(&mut self, err: Error) {
|
||||
println!("The server encountered an error: {:?}", err);
|
||||
}
|
||||
}
|
||||
|
||||
pub fn launch_server() {
|
||||
unsafe {
|
||||
if CLIENTS.set(RwLock::new(HashMap::new())).is_err() {
|
||||
panic!("Failed to set CLIENTS map!");
|
||||
}
|
||||
}
|
||||
|
||||
listen("192.168.0.10:9999", |out| Server {
|
||||
out: out,
|
||||
id: None,
|
||||
internal: Ulid::new().to_string(),
|
||||
})
|
||||
.unwrap()
|
||||
}
|
||||
|
||||
pub fn send_message(id: String, message: String) -> std::result::Result<(), ()> {
|
||||
unsafe {
|
||||
let map = CLIENTS.get().unwrap().read().unwrap();
|
||||
if map.contains_key(&id) {
|
||||
let arr = map.get(&id).unwrap();
|
||||
|
||||
for item in arr {
|
||||
if item.out.send(message.clone()).is_err() {
|
||||
return Err(());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
// ! TODO: WRITE THREADED QUEUE SYSTEM
|
||||
// ! FETCH RECIPIENTS HERE INSTEAD OF IN METHOD
|
||||
|
||||
pub fn queue_message(ids: Vec<String>, message: String) {
|
||||
for id in ids {
|
||||
send_message(id, message.clone())
|
||||
.expect("uhhhhhhhhhh can i get uhhhhhhhhhhhhhhhhhh mcdonald cheese burger with fries");
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user