mirror of
https://github.com/stoatchat/stoatchat.git
synced 2026-07-14 05:26:59 +00:00
Switch to async Rust and break all logic.
This commit is contained in:
@@ -7,6 +7,7 @@ use rocket::request::FromParam;
|
||||
use rocket_contrib::json::JsonValue;
|
||||
use serde::{Deserialize, Serialize};
|
||||
use std::sync::{Arc, Mutex};
|
||||
use rocket::futures::StreamExt;
|
||||
|
||||
#[derive(Serialize, Deserialize, Debug, Clone)]
|
||||
pub struct LastMessage {
|
||||
@@ -76,7 +77,7 @@ lazy_static! {
|
||||
Arc::new(Mutex::new(LruCache::new(4_000_000)));
|
||||
}
|
||||
|
||||
pub fn fetch_channel(id: &str) -> Result<Option<Channel>, String> {
|
||||
pub async fn fetch_channel(id: &str) -> Result<Option<Channel>, String> {
|
||||
{
|
||||
if let Ok(mut cache) = CACHE.lock() {
|
||||
let existing = cache.get(&id.to_string());
|
||||
@@ -90,7 +91,7 @@ pub fn fetch_channel(id: &str) -> Result<Option<Channel>, String> {
|
||||
}
|
||||
|
||||
let col = get_collection("channels");
|
||||
if let Ok(result) = col.find_one(doc! { "_id": id }, None) {
|
||||
if let Ok(result) = col.find_one(doc! { "_id": id }, None).await {
|
||||
if let Some(doc) = result {
|
||||
if let Ok(channel) = from_bson(Bson::Document(doc)) as Result<Channel, _> {
|
||||
let mut cache = CACHE.lock().unwrap();
|
||||
@@ -108,7 +109,7 @@ pub fn fetch_channel(id: &str) -> Result<Option<Channel>, String> {
|
||||
}
|
||||
}
|
||||
|
||||
pub fn fetch_channels(ids: &Vec<String>) -> Result<Vec<Channel>, String> {
|
||||
pub async fn fetch_channels(ids: &Vec<String>) -> Result<Vec<Channel>, String> {
|
||||
let mut missing = vec![];
|
||||
let mut channels = vec![];
|
||||
|
||||
@@ -133,8 +134,8 @@ pub fn fetch_channels(ids: &Vec<String>) -> Result<Vec<Channel>, String> {
|
||||
}
|
||||
|
||||
let col = get_collection("channels");
|
||||
if let Ok(result) = col.find(doc! { "_id": { "$in": missing } }, None) {
|
||||
for item in result {
|
||||
if let Ok(mut result) = col.find(doc! { "_id": { "$in": missing } }, None).await {
|
||||
while let Some(item) = result.next().await {
|
||||
let mut cache = CACHE.lock().unwrap();
|
||||
if let Ok(doc) = item {
|
||||
if let Ok(channel) = from_bson(Bson::Document(doc)) as Result<Channel, _> {
|
||||
@@ -158,7 +159,8 @@ impl<'r> FromParam<'r> for Channel {
|
||||
type Error = &'r RawStr;
|
||||
|
||||
fn from_param(param: &'r RawStr) -> Result<Self, Self::Error> {
|
||||
if let Ok(result) = fetch_channel(param) {
|
||||
Err(param)
|
||||
/*if let Ok(result) = fetch_channel(param).await {
|
||||
if let Some(channel) = result {
|
||||
Ok(channel)
|
||||
} else {
|
||||
@@ -166,7 +168,7 @@ impl<'r> FromParam<'r> for Channel {
|
||||
}
|
||||
} else {
|
||||
Err(param)
|
||||
}
|
||||
}*/
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -2,6 +2,7 @@ use super::channel::fetch_channels;
|
||||
use super::get_collection;
|
||||
|
||||
use lru::LruCache;
|
||||
use rocket::futures::StreamExt;
|
||||
use mongodb::bson::{doc, from_bson, Bson};
|
||||
use rocket::http::RawStr;
|
||||
use rocket::request::FromParam;
|
||||
@@ -61,13 +62,14 @@ impl Guild {
|
||||
})
|
||||
}
|
||||
|
||||
pub fn fetch_channels(&self) -> Result<Vec<super::channel::Channel>, String> {
|
||||
super::channel::fetch_channels(&self.channels)
|
||||
pub async fn fetch_channels(&self) -> Result<Vec<super::channel::Channel>, String> {
|
||||
super::channel::fetch_channels(&self.channels).await
|
||||
}
|
||||
|
||||
pub fn seralise_with_channels(self) -> Result<JsonValue, String> {
|
||||
pub async fn seralise_with_channels(self) -> Result<JsonValue, String> {
|
||||
let channels = self
|
||||
.fetch_channels()?
|
||||
.fetch_channels()
|
||||
.await?
|
||||
.into_iter()
|
||||
.map(|x| x.serialise())
|
||||
.collect();
|
||||
@@ -91,7 +93,7 @@ lazy_static! {
|
||||
Arc::new(Mutex::new(LruCache::new(4_000_000)));
|
||||
}
|
||||
|
||||
pub fn fetch_guild(id: &str) -> Result<Option<Guild>, String> {
|
||||
pub async fn fetch_guild(id: &str) -> Result<Option<Guild>, String> {
|
||||
{
|
||||
if let Ok(mut cache) = CACHE.lock() {
|
||||
let existing = cache.get(&id.to_string());
|
||||
@@ -105,7 +107,7 @@ pub fn fetch_guild(id: &str) -> Result<Option<Guild>, String> {
|
||||
}
|
||||
|
||||
let col = get_collection("guilds");
|
||||
if let Ok(result) = col.find_one(doc! { "_id": id }, None) {
|
||||
if let Ok(result) = col.find_one(doc! { "_id": id }, None).await {
|
||||
if let Some(doc) = result {
|
||||
dbg!(doc.to_string());
|
||||
if let Ok(guild) = from_bson(Bson::Document(doc)) as Result<Guild, _> {
|
||||
@@ -124,7 +126,7 @@ pub fn fetch_guild(id: &str) -> Result<Option<Guild>, String> {
|
||||
}
|
||||
}
|
||||
|
||||
pub fn fetch_guilds(ids: &Vec<String>) -> Result<Vec<Guild>, String> {
|
||||
pub async fn fetch_guilds(ids: &Vec<String>) -> Result<Vec<Guild>, String> {
|
||||
let mut missing = vec![];
|
||||
let mut guilds = vec![];
|
||||
|
||||
@@ -149,8 +151,8 @@ pub fn fetch_guilds(ids: &Vec<String>) -> Result<Vec<Guild>, String> {
|
||||
}
|
||||
|
||||
let col = get_collection("guilds");
|
||||
if let Ok(result) = col.find(doc! { "_id": { "$in": missing } }, None) {
|
||||
for item in result {
|
||||
if let Ok(mut result) = col.find(doc! { "_id": { "$in": missing } }, None).await {
|
||||
if let Some(item) = result.next().await {
|
||||
let mut cache = CACHE.lock().unwrap();
|
||||
if let Ok(doc) = item {
|
||||
dbg!(doc.to_string());
|
||||
@@ -171,11 +173,11 @@ pub fn fetch_guilds(ids: &Vec<String>) -> Result<Vec<Guild>, String> {
|
||||
}
|
||||
}
|
||||
|
||||
pub fn serialise_guilds_with_channels(ids: &Vec<String>) -> Result<Vec<JsonValue>, String> {
|
||||
let guilds = fetch_guilds(&ids)?;
|
||||
pub async fn serialise_guilds_with_channels(ids: &Vec<String>) -> Result<Vec<JsonValue>, String> {
|
||||
let guilds = fetch_guilds(&ids).await?;
|
||||
let cids: Vec<String> = guilds.iter().flat_map(|x| x.channels.clone()).collect();
|
||||
|
||||
let channels = fetch_channels(&cids)?;
|
||||
let channels = fetch_channels(&cids).await?;
|
||||
Ok(guilds
|
||||
.into_iter()
|
||||
.map(|x| {
|
||||
@@ -194,7 +196,7 @@ pub fn serialise_guilds_with_channels(ids: &Vec<String>) -> Result<Vec<JsonValue
|
||||
.collect())
|
||||
}
|
||||
|
||||
pub fn fetch_member(key: MemberKey) -> Result<Option<Member>, String> {
|
||||
pub async fn fetch_member(key: MemberKey) -> Result<Option<Member>, String> {
|
||||
{
|
||||
if let Ok(mut cache) = MEMBER_CACHE.lock() {
|
||||
let existing = cache.get(&key);
|
||||
@@ -214,7 +216,7 @@ pub fn fetch_member(key: MemberKey) -> Result<Option<Member>, String> {
|
||||
"_id.user": &key.1,
|
||||
},
|
||||
None,
|
||||
) {
|
||||
).await {
|
||||
if let Some(doc) = result {
|
||||
if let Ok(member) = from_bson(Bson::Document(doc)) as Result<Member, _> {
|
||||
let mut cache = MEMBER_CACHE.lock().unwrap();
|
||||
@@ -236,7 +238,8 @@ impl<'r> FromParam<'r> for Guild {
|
||||
type Error = &'r RawStr;
|
||||
|
||||
fn from_param(param: &'r RawStr) -> Result<Self, Self::Error> {
|
||||
if let Ok(result) = fetch_guild(param) {
|
||||
Err(param)
|
||||
/*if let Ok(result) = fetch_guild(param) {
|
||||
if let Some(channel) = result {
|
||||
Ok(channel)
|
||||
} else {
|
||||
@@ -244,11 +247,11 @@ impl<'r> FromParam<'r> for Guild {
|
||||
}
|
||||
} else {
|
||||
Err(param)
|
||||
}
|
||||
}*/
|
||||
}
|
||||
}
|
||||
|
||||
pub fn get_invite<U: Into<Option<String>>>(
|
||||
pub async fn get_invite<U: Into<Option<String>>>(
|
||||
code: &String,
|
||||
user: U,
|
||||
) -> Option<(String, String, Invite)> {
|
||||
@@ -282,7 +285,7 @@ pub fn get_invite<U: Into<Option<String>>>(
|
||||
"invites.$": 1,
|
||||
})
|
||||
.build(),
|
||||
) {
|
||||
).await {
|
||||
if let Some(doc) = result {
|
||||
let invite = doc
|
||||
.get_array("invites")
|
||||
|
||||
@@ -3,8 +3,10 @@ use crate::database::channel::Channel;
|
||||
use crate::pubsub::hive;
|
||||
use crate::routes::channel::ChannelType;
|
||||
|
||||
use mongodb::bson::from_bson;
|
||||
use mongodb::bson::{doc, to_bson, Bson, DateTime};
|
||||
//use mongodb::bson::from_bson;
|
||||
//use rocket::futures::StreamExt;
|
||||
//use mongodb::bson::{doc, to_bson, Bson, DateTime};
|
||||
use mongodb::bson::{doc, to_bson, DateTime};
|
||||
use rocket::http::RawStr;
|
||||
use rocket::request::FromParam;
|
||||
use serde::{Deserialize, Serialize};
|
||||
@@ -35,22 +37,12 @@ pub struct Message {
|
||||
// ? pub fn send_message();
|
||||
// ? handle websockets?
|
||||
impl Message {
|
||||
pub fn send(&self, target: &Channel) -> bool {
|
||||
pub async fn send(&self, target: &Channel) -> bool {
|
||||
if get_collection("messages")
|
||||
.insert_one(to_bson(&self).unwrap().as_document().unwrap().clone(), None)
|
||||
.await
|
||||
.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,
|
||||
);*/
|
||||
|
||||
if hive::publish(
|
||||
&target.id,
|
||||
crate::pubsub::events::Notification::message_create(
|
||||
@@ -93,6 +85,7 @@ impl Message {
|
||||
|
||||
if get_collection("channels")
|
||||
.update_one(doc! { "_id": &target.id }, update, None)
|
||||
.await
|
||||
.is_ok()
|
||||
{
|
||||
true
|
||||
@@ -112,7 +105,8 @@ impl<'r> FromParam<'r> for Message {
|
||||
type Error = &'r RawStr;
|
||||
|
||||
fn from_param(param: &'r RawStr) -> Result<Self, Self::Error> {
|
||||
let col = get_collection("messages");
|
||||
Err(param)
|
||||
/*let col = get_collection("messages");
|
||||
let result = col
|
||||
.find_one(doc! { "_id": param.to_string() }, None)
|
||||
.unwrap();
|
||||
@@ -121,6 +115,6 @@ impl<'r> FromParam<'r> for Message {
|
||||
Ok(from_bson(Bson::Document(message)).expect("Failed to unwrap message."))
|
||||
} else {
|
||||
Err(param)
|
||||
}
|
||||
}*/
|
||||
}
|
||||
}
|
||||
|
||||
@@ -5,21 +5,32 @@ use log::info;
|
||||
use mongodb::bson::doc;
|
||||
use mongodb::options::CreateCollectionOptions;
|
||||
|
||||
pub fn create_database() {
|
||||
pub async fn create_database() {
|
||||
info!("Creating database.");
|
||||
let db = get_db();
|
||||
|
||||
db.create_collection("users", None)
|
||||
.await
|
||||
.expect("Failed to create users collection.");
|
||||
|
||||
db.create_collection("channels", None)
|
||||
.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.");
|
||||
|
||||
db.create_collection("migrations", None)
|
||||
.await
|
||||
.expect("Failed to create migrations collection.");
|
||||
|
||||
db.create_collection(
|
||||
@@ -29,7 +40,8 @@ pub fn create_database() {
|
||||
.size(1_000_000)
|
||||
.build(),
|
||||
)
|
||||
.expect("Failed to create pubsub collection.");
|
||||
.await
|
||||
.expect("Failed to create pubsub collection.");
|
||||
|
||||
db.collection("migrations")
|
||||
.insert_one(
|
||||
@@ -39,6 +51,7 @@ pub fn create_database() {
|
||||
},
|
||||
None,
|
||||
)
|
||||
.await
|
||||
.expect("Failed to save migration info.");
|
||||
|
||||
info!("Created database.");
|
||||
|
||||
@@ -3,16 +3,17 @@ use super::get_connection;
|
||||
pub mod init;
|
||||
pub mod scripts;
|
||||
|
||||
pub fn run_migrations() {
|
||||
pub async fn run_migrations() {
|
||||
let client = get_connection();
|
||||
|
||||
let list = client
|
||||
.list_database_names(None, None)
|
||||
.await
|
||||
.expect("Failed to fetch database names.");
|
||||
|
||||
if list.iter().position(|x| x == "revolt").is_none() {
|
||||
init::create_database();
|
||||
init::create_database().await;
|
||||
} else {
|
||||
scripts::migrate_database();
|
||||
scripts::migrate_database().await;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,9 +1,10 @@
|
||||
use super::super::get_collection;
|
||||
|
||||
use log::info;
|
||||
use mongodb::bson::{doc, from_bson, Bson};
|
||||
use mongodb::options::FindOptions;
|
||||
use serde::{Deserialize, Serialize};
|
||||
use crate::rocket::futures::StreamExt;
|
||||
use mongodb::bson::{doc, from_bson, Bson};
|
||||
|
||||
#[derive(Serialize, Deserialize)]
|
||||
struct MigrationInfo {
|
||||
@@ -13,17 +14,18 @@ struct MigrationInfo {
|
||||
|
||||
pub const LATEST_REVISION: i32 = 2;
|
||||
|
||||
pub fn migrate_database() {
|
||||
pub async fn migrate_database() {
|
||||
let migrations = get_collection("migrations");
|
||||
let data = migrations
|
||||
.find_one(None, None)
|
||||
.await
|
||||
.expect("Failed to fetch migration data.");
|
||||
|
||||
if let Some(doc) = data {
|
||||
let info: MigrationInfo =
|
||||
from_bson(Bson::Document(doc)).expect("Failed to read migration information.");
|
||||
|
||||
let revision = run_migrations(info.revision);
|
||||
let revision = run_migrations(info.revision).await;
|
||||
|
||||
migrations
|
||||
.update_one(
|
||||
@@ -37,6 +39,7 @@ pub fn migrate_database() {
|
||||
},
|
||||
None,
|
||||
)
|
||||
.await
|
||||
.expect("Failed to commit migration information.");
|
||||
|
||||
info!("Migration complete. Currently at revision {}.", revision);
|
||||
@@ -45,7 +48,7 @@ pub fn migrate_database() {
|
||||
}
|
||||
}
|
||||
|
||||
pub fn run_migrations(revision: i32) -> i32 {
|
||||
pub async fn run_migrations(revision: i32) -> i32 {
|
||||
info!("Starting database migration.");
|
||||
|
||||
if revision <= 0 {
|
||||
@@ -56,14 +59,15 @@ pub fn run_migrations(revision: i32) -> i32 {
|
||||
info!("Running migration [revision 1]: Add channels to guild object.");
|
||||
|
||||
let col = get_collection("guilds");
|
||||
let guilds = col
|
||||
let mut guilds = col
|
||||
.find(
|
||||
None,
|
||||
FindOptions::builder().projection(doc! { "_id": 1 }).build(),
|
||||
)
|
||||
.await
|
||||
.expect("Failed to fetch guilds.");
|
||||
|
||||
let result = get_collection("channels")
|
||||
let mut result = get_collection("channels")
|
||||
.find(
|
||||
doc! {
|
||||
"type": 2
|
||||
@@ -72,15 +76,17 @@ pub fn run_migrations(revision: i32) -> i32 {
|
||||
.projection(doc! { "_id": 1, "guild": 1 })
|
||||
.build(),
|
||||
)
|
||||
.await
|
||||
.expect("Failed to fetch channels.");
|
||||
|
||||
let mut channels = vec![];
|
||||
for doc in result {
|
||||
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.")
|
||||
@@ -89,7 +95,7 @@ pub fn run_migrations(revision: i32) -> i32 {
|
||||
channels.push((id, gid));
|
||||
}
|
||||
|
||||
for doc in guilds {
|
||||
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.");
|
||||
|
||||
@@ -110,6 +116,7 @@ pub fn run_migrations(revision: i32) -> i32 {
|
||||
},
|
||||
None,
|
||||
)
|
||||
.await
|
||||
.expect("Failed to update guild.");
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,15 +1,17 @@
|
||||
use crate::util::variables::MONGO_URI;
|
||||
|
||||
use mongodb::sync::{Client, Collection, Database};
|
||||
use mongodb::{Client, Collection, Database};
|
||||
use once_cell::sync::OnceCell;
|
||||
|
||||
static DBCONN: OnceCell<Client> = OnceCell::new();
|
||||
|
||||
pub fn connect() {
|
||||
let client = Client::with_uri_str(&MONGO_URI).expect("Failed to init db connection.");
|
||||
pub async fn connect() {
|
||||
let client = Client::with_uri_str(&MONGO_URI)
|
||||
.await
|
||||
.expect("Failed to init db connection.");
|
||||
|
||||
DBCONN.set(client).unwrap();
|
||||
migrations::run_migrations();
|
||||
migrations::run_migrations().await;
|
||||
}
|
||||
|
||||
pub fn get_connection() -> &'static Client {
|
||||
|
||||
@@ -1,11 +1,12 @@
|
||||
use super::{get_collection, MemberPermissions};
|
||||
|
||||
use mongodb::bson::doc;
|
||||
use mongodb::bson::{doc, Document};
|
||||
use mongodb::options::FindOptions;
|
||||
use rocket::futures::StreamExt;
|
||||
|
||||
pub fn find_mutual_guilds(user_id: &str, target_id: &str) -> Vec<String> {
|
||||
pub async fn find_mutual_guilds(user_id: &str, target_id: &str) -> Vec<String> {
|
||||
let col = get_collection("members");
|
||||
if let Ok(result) = col.find(
|
||||
if let Ok(mut result) = col.find(
|
||||
doc! {
|
||||
"$and": [
|
||||
{ "id": user_id },
|
||||
@@ -13,10 +14,10 @@ pub fn find_mutual_guilds(user_id: &str, target_id: &str) -> Vec<String> {
|
||||
]
|
||||
},
|
||||
FindOptions::builder().projection(doc! { "_id": 1 }).build(),
|
||||
) {
|
||||
).await {
|
||||
let mut results = vec![];
|
||||
|
||||
for doc in result {
|
||||
while let Some(doc) = result.next().await {
|
||||
if let Ok(guild) = doc {
|
||||
results.push(guild.get_str("_id").unwrap().to_string());
|
||||
}
|
||||
@@ -28,9 +29,9 @@ pub fn find_mutual_guilds(user_id: &str, target_id: &str) -> Vec<String> {
|
||||
}
|
||||
}
|
||||
|
||||
pub fn find_mutual_friends(user_id: &str, target_id: &str) -> Vec<String> {
|
||||
pub async fn find_mutual_friends(user_id: &str, target_id: &str) -> Vec<String> {
|
||||
let col = get_collection("users");
|
||||
if let Ok(result) = col.find(
|
||||
if let Ok(mut result) = col.find(
|
||||
doc! {
|
||||
"$and": [
|
||||
{ "relations": { "$elemMatch": { "id": user_id, "status": 0 } } },
|
||||
@@ -38,10 +39,10 @@ pub fn find_mutual_friends(user_id: &str, target_id: &str) -> Vec<String> {
|
||||
]
|
||||
},
|
||||
FindOptions::builder().projection(doc! { "_id": 1 }).build(),
|
||||
) {
|
||||
).await {
|
||||
let mut results = vec![];
|
||||
|
||||
for doc in result {
|
||||
while let Some(doc) = result.next().await {
|
||||
if let Ok(user) = doc {
|
||||
results.push(user.get_str("_id").unwrap().to_string());
|
||||
}
|
||||
@@ -53,9 +54,9 @@ pub fn find_mutual_friends(user_id: &str, target_id: &str) -> Vec<String> {
|
||||
}
|
||||
}
|
||||
|
||||
pub fn find_mutual_groups(user_id: &str, target_id: &str) -> Vec<String> {
|
||||
pub async fn find_mutual_groups(user_id: &str, target_id: &str) -> Vec<String> {
|
||||
let col = get_collection("channels");
|
||||
if let Ok(result) = col.find(
|
||||
if let Ok(mut result) = col.find(
|
||||
doc! {
|
||||
"type": 1,
|
||||
"$and": [
|
||||
@@ -64,10 +65,10 @@ pub fn find_mutual_groups(user_id: &str, target_id: &str) -> Vec<String> {
|
||||
]
|
||||
},
|
||||
FindOptions::builder().projection(doc! { "_id": 1 }).build(),
|
||||
) {
|
||||
).await {
|
||||
let mut results = vec![];
|
||||
|
||||
for doc in result {
|
||||
while let Some(doc) = result.next().await {
|
||||
if let Ok(group) = doc {
|
||||
results.push(group.get_str("_id").unwrap().to_string());
|
||||
}
|
||||
@@ -79,7 +80,7 @@ pub fn find_mutual_groups(user_id: &str, target_id: &str) -> Vec<String> {
|
||||
}
|
||||
}
|
||||
|
||||
pub fn has_mutual_connection(user_id: &str, target_id: &str, with_permission: bool) -> bool {
|
||||
pub async fn has_mutual_connection(user_id: &str, target_id: &str, with_permission: bool) -> bool {
|
||||
let mut doc = doc! { "_id": 1 };
|
||||
|
||||
if with_permission {
|
||||
@@ -88,7 +89,7 @@ pub fn has_mutual_connection(user_id: &str, target_id: &str, with_permission: bo
|
||||
|
||||
let opt = FindOptions::builder().projection(doc);
|
||||
|
||||
if let Ok(result) = get_collection("guilds").find(
|
||||
if let Ok(mut result) = get_collection("guilds").find(
|
||||
doc! {
|
||||
"$and": [
|
||||
{ "members": { "$elemMatch": { "id": user_id } } },
|
||||
@@ -100,9 +101,9 @@ pub fn has_mutual_connection(user_id: &str, target_id: &str, with_permission: bo
|
||||
} else {
|
||||
opt.limit(1).build()
|
||||
},
|
||||
) {
|
||||
).await {
|
||||
if with_permission {
|
||||
for item in result {
|
||||
while let Some(item) = result.next().await {
|
||||
// ? logic should match permissions.rs#calculate
|
||||
if let Ok(guild) = item {
|
||||
if guild.get_str("owner").unwrap() == user_id {
|
||||
@@ -118,7 +119,7 @@ pub fn has_mutual_connection(user_id: &str, target_id: &str, with_permission: bo
|
||||
}
|
||||
|
||||
false
|
||||
} else if result.count() > 0 {
|
||||
} else if result.collect::<Vec<Result<Document, _>>>().await.len() > 0 {
|
||||
true
|
||||
} else {
|
||||
false
|
||||
|
||||
@@ -115,7 +115,7 @@ impl PermissionCalculator {
|
||||
}
|
||||
}
|
||||
|
||||
pub fn fetch_data(mut self) -> PermissionCalculator {
|
||||
pub async fn fetch_data(mut self) -> PermissionCalculator {
|
||||
let guild = if let Some(value) = self.guild {
|
||||
Some(value)
|
||||
} else if let Some(channel) = &self.channel {
|
||||
@@ -123,7 +123,7 @@ impl PermissionCalculator {
|
||||
0..=1 => None,
|
||||
2 => {
|
||||
if let Some(id) = &channel.guild {
|
||||
if let Ok(result) = fetch_guild(id) {
|
||||
if let Ok(result) = fetch_guild(id).await {
|
||||
result
|
||||
} else {
|
||||
None
|
||||
@@ -139,7 +139,7 @@ impl PermissionCalculator {
|
||||
};
|
||||
|
||||
if let Some(guild) = &guild {
|
||||
if let Ok(result) = fetch_member(MemberKey(guild.id.clone(), self.user.id.clone())) {
|
||||
if let Ok(result) = fetch_member(MemberKey(guild.id.clone(), self.user.id.clone())).await {
|
||||
self.member = result;
|
||||
}
|
||||
}
|
||||
@@ -148,7 +148,7 @@ impl PermissionCalculator {
|
||||
self
|
||||
}
|
||||
|
||||
pub fn calculate(&self) -> u32 {
|
||||
pub async fn calculate(&self) -> u32 {
|
||||
let mut permissions: u32 = 0;
|
||||
if let Some(guild) = &self.guild {
|
||||
if let Some(_member) = &self.member {
|
||||
@@ -185,7 +185,7 @@ impl PermissionCalculator {
|
||||
|| relationship == Relationship::BlockedOther
|
||||
{
|
||||
permissions = 1;
|
||||
} else if has_mutual_connection(&self.user.id, other, true) {
|
||||
} else if has_mutual_connection(&self.user.id, other, true).await {
|
||||
permissions = 1024 + 128 + 32 + 16 + 1;
|
||||
} else {
|
||||
permissions = 1;
|
||||
@@ -222,7 +222,7 @@ impl PermissionCalculator {
|
||||
permissions
|
||||
}
|
||||
|
||||
pub fn as_permission(&self) -> MemberPermissions<[u32; 1]> {
|
||||
MemberPermissions([self.calculate()])
|
||||
pub async fn as_permission(&self) -> MemberPermissions<[u32; 1]> {
|
||||
MemberPermissions([self.calculate().await])
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,15 +1,16 @@
|
||||
use super::channel::fetch_channels;
|
||||
use super::get_collection;
|
||||
use super::channel::fetch_channels;
|
||||
use super::guild::serialise_guilds_with_channels;
|
||||
|
||||
use lru::LruCache;
|
||||
use mongodb::bson::{doc, from_bson, Bson, DateTime};
|
||||
use rocket::futures::StreamExt;
|
||||
use mongodb::options::FindOptions;
|
||||
use rocket::http::{RawStr, Status};
|
||||
use rocket::request::{self, FromParam, FromRequest, Request};
|
||||
use rocket::Outcome;
|
||||
use rocket_contrib::json::JsonValue;
|
||||
use serde::{Deserialize, Serialize};
|
||||
use rocket_contrib::json::JsonValue;
|
||||
use mongodb::bson::{doc, from_bson, Bson, DateTime, Document};
|
||||
use rocket::request::{self, FromParam, FromRequest, Request, Outcome};
|
||||
|
||||
use std::sync::{Arc, Mutex};
|
||||
|
||||
#[derive(Serialize, Deserialize, Debug, Clone)]
|
||||
@@ -60,7 +61,7 @@ impl User {
|
||||
}
|
||||
}
|
||||
|
||||
pub fn find_guilds(&self) -> Result<Vec<String>, String> {
|
||||
pub async fn find_guilds(&self) -> Result<Vec<String>, String> {
|
||||
let members = get_collection("members")
|
||||
.find(
|
||||
doc! {
|
||||
@@ -68,9 +69,12 @@ impl User {
|
||||
},
|
||||
None,
|
||||
)
|
||||
.await
|
||||
.map_err(|_| "Failed to fetch members.")?;
|
||||
|
||||
Ok(members
|
||||
.collect::<Vec<Result<Document, _>>>()
|
||||
.await
|
||||
.into_iter()
|
||||
.filter_map(|x| match x {
|
||||
Ok(doc) => match doc.get_document("_id") {
|
||||
@@ -85,7 +89,7 @@ impl User {
|
||||
.collect())
|
||||
}
|
||||
|
||||
pub fn find_dms(&self) -> Result<Vec<String>, String> {
|
||||
pub async fn find_dms(&self) -> Result<Vec<String>, String> {
|
||||
let channels = get_collection("channels")
|
||||
.find(
|
||||
doc! {
|
||||
@@ -93,9 +97,12 @@ impl User {
|
||||
},
|
||||
FindOptions::builder().projection(doc! { "_id": 1 }).build(),
|
||||
)
|
||||
.await
|
||||
.map_err(|_| "Failed to fetch channel ids.")?;
|
||||
|
||||
Ok(channels
|
||||
.collect::<Vec<Result<Document, _>>>()
|
||||
.await
|
||||
.into_iter()
|
||||
.filter_map(|x| x.ok())
|
||||
.filter_map(|x| match x.get_str("_id") {
|
||||
@@ -105,11 +112,11 @@ impl User {
|
||||
.collect())
|
||||
}
|
||||
|
||||
pub fn create_payload(self) -> Result<JsonValue, String> {
|
||||
pub async fn create_payload(self) -> Result<JsonValue, String> {
|
||||
let v = vec![];
|
||||
let relations = self.relations.as_ref().unwrap_or(&v);
|
||||
|
||||
let users: Vec<JsonValue> = fetch_users(&relations.iter().map(|x| x.id.clone()).collect())?
|
||||
let users: Vec<JsonValue> = fetch_users(&relations.iter().map(|x| x.id.clone()).collect()).await?
|
||||
.into_iter()
|
||||
.map(|x| {
|
||||
let id = x.id.clone();
|
||||
@@ -117,7 +124,7 @@ impl User {
|
||||
})
|
||||
.collect();
|
||||
|
||||
let channels: Vec<JsonValue> = fetch_channels(&self.find_dms()?)?
|
||||
let channels: Vec<JsonValue> = fetch_channels(&self.find_dms().await?).await?
|
||||
.into_iter()
|
||||
.map(|x| x.serialise())
|
||||
.collect();
|
||||
@@ -125,7 +132,7 @@ impl User {
|
||||
Ok(json!({
|
||||
"users": users,
|
||||
"channels": channels,
|
||||
"guilds": serialise_guilds_with_channels(&self.find_guilds()?)?,
|
||||
"guilds": serialise_guilds_with_channels(&self.find_guilds().await?).await?,
|
||||
"user": self.serialise(super::Relationship::SELF as i32)
|
||||
}))
|
||||
}
|
||||
@@ -136,7 +143,7 @@ lazy_static! {
|
||||
Arc::new(Mutex::new(LruCache::new(4_000_000)));
|
||||
}
|
||||
|
||||
pub fn fetch_user(id: &str) -> Result<Option<User>, String> {
|
||||
pub async fn fetch_user(id: &str) -> Result<Option<User>, String> {
|
||||
{
|
||||
if let Ok(mut cache) = CACHE.lock() {
|
||||
let existing = cache.get(&id.to_string());
|
||||
@@ -150,7 +157,7 @@ pub fn fetch_user(id: &str) -> Result<Option<User>, String> {
|
||||
}
|
||||
|
||||
let col = get_collection("users");
|
||||
if let Ok(result) = col.find_one(doc! { "_id": id }, None) {
|
||||
if let Ok(result) = col.find_one(doc! { "_id": id }, None).await {
|
||||
if let Some(doc) = result {
|
||||
if let Ok(user) = from_bson(Bson::Document(doc)) as Result<User, _> {
|
||||
let mut cache = CACHE.lock().unwrap();
|
||||
@@ -168,7 +175,7 @@ pub fn fetch_user(id: &str) -> Result<Option<User>, String> {
|
||||
}
|
||||
}
|
||||
|
||||
pub fn fetch_users(ids: &Vec<String>) -> Result<Vec<User>, String> {
|
||||
pub async fn fetch_users(ids: &Vec<String>) -> Result<Vec<User>, String> {
|
||||
let mut missing = vec![];
|
||||
let mut users = vec![];
|
||||
|
||||
@@ -193,8 +200,8 @@ pub fn fetch_users(ids: &Vec<String>) -> Result<Vec<User>, String> {
|
||||
}
|
||||
|
||||
let col = get_collection("users");
|
||||
if let Ok(result) = col.find(doc! { "_id": { "$in": missing } }, None) {
|
||||
for item in result {
|
||||
if let Ok(mut result) = col.find(doc! { "_id": { "$in": missing } }, None).await {
|
||||
while let Some(item) = result.next().await {
|
||||
let mut cache = CACHE.lock().unwrap();
|
||||
if let Ok(doc) = item {
|
||||
if let Ok(user) = from_bson(Bson::Document(doc)) as Result<User, _> {
|
||||
@@ -221,16 +228,17 @@ pub enum AuthError {
|
||||
Invalid,
|
||||
}
|
||||
|
||||
#[rocket::async_trait]
|
||||
impl<'a, 'r> FromRequest<'a, 'r> for User {
|
||||
type Error = AuthError;
|
||||
|
||||
fn from_request(request: &'a Request<'r>) -> request::Outcome<Self, Self::Error> {
|
||||
async fn from_request(request: &'a Request<'r>) -> request::Outcome<Self, Self::Error> {
|
||||
let u = request.headers().get("x-user").next();
|
||||
let t = request.headers().get("x-auth-token").next();
|
||||
|
||||
if let Some(uid) = u {
|
||||
if let Some(token) = t {
|
||||
if let Ok(result) = fetch_user(uid) {
|
||||
if let Ok(result) = fetch_user(uid).await {
|
||||
if let Some(user) = result {
|
||||
if let Some(access_token) = &user.access_token {
|
||||
if access_token == token {
|
||||
@@ -260,7 +268,8 @@ impl<'r> FromParam<'r> for User {
|
||||
type Error = &'r RawStr;
|
||||
|
||||
fn from_param(param: &'r RawStr) -> Result<Self, Self::Error> {
|
||||
if let Ok(result) = fetch_user(¶m.to_string()) {
|
||||
Err(param)
|
||||
/*if let Ok(result) = fetch_user(¶m.to_string()).await {
|
||||
if let Some(user) = result {
|
||||
Ok(user)
|
||||
} else {
|
||||
@@ -268,7 +277,7 @@ impl<'r> FromParam<'r> for User {
|
||||
}
|
||||
} else {
|
||||
Err(param)
|
||||
}
|
||||
}*/
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
14
src/main.rs
14
src/main.rs
@@ -1,4 +1,5 @@
|
||||
#![feature(proc_macro_hygiene, decl_macro)]
|
||||
#![feature(async_closure)]
|
||||
|
||||
#[macro_use]
|
||||
extern crate rocket;
|
||||
@@ -17,17 +18,18 @@ pub mod util;
|
||||
use log::info;
|
||||
use rocket_cors::AllowedOrigins;
|
||||
|
||||
fn main() {
|
||||
#[tokio::main]
|
||||
async fn main() {
|
||||
dotenv::dotenv().ok();
|
||||
env_logger::init_from_env(env_logger::Env::default().filter_or("RUST_LOG", "info"));
|
||||
|
||||
info!("Starting REVOLT server.");
|
||||
|
||||
util::variables::preflight_checks();
|
||||
database::connect();
|
||||
database::connect().await;
|
||||
|
||||
pubsub::hive::init_hive();
|
||||
pubsub::websocket::launch_server();
|
||||
//pubsub::websocket::launch_server();
|
||||
|
||||
let cors = rocket_cors::CorsOptions {
|
||||
allowed_origins: AllowedOrigins::All,
|
||||
@@ -36,5 +38,9 @@ fn main() {
|
||||
.to_cors()
|
||||
.unwrap();
|
||||
|
||||
routes::mount(rocket::ignite()).attach(cors).launch();
|
||||
routes::mount(rocket::ignite())
|
||||
.attach(cors)
|
||||
.launch()
|
||||
.await
|
||||
.unwrap();
|
||||
}
|
||||
|
||||
@@ -1,8 +1,8 @@
|
||||
use super::events::Notification;
|
||||
use super::websocket;
|
||||
// use super::websocket;
|
||||
use crate::database::get_collection;
|
||||
|
||||
use hive_pubsub::backend::mongo::{listen_thread, MongodbPubSub};
|
||||
use hive_pubsub::backend::mongo::MongodbPubSub;
|
||||
use hive_pubsub::PubSub;
|
||||
use once_cell::sync::OnceCell;
|
||||
use serde_json::to_string;
|
||||
@@ -12,12 +12,12 @@ static HIVE: OnceCell<MongodbPubSub<String, String, Notification>> = OnceCell::n
|
||||
|
||||
pub fn init_hive() {
|
||||
let hive = MongodbPubSub::new(
|
||||
|ids, notification| {
|
||||
|_ids, notification| {
|
||||
if let Ok(data) = to_string(¬ification) {
|
||||
debug!("Pushing out notification. {}", data);
|
||||
if let Err(err) = websocket::publish(ids, data) {
|
||||
error!("Failed to publish notification through WebSocket! {}", err);
|
||||
}
|
||||
// if let Err(err) = websocket::publish(ids, data) {
|
||||
// error!("Failed to publish notification through WebSocket! {}", err);
|
||||
// }
|
||||
} else {
|
||||
error!("Failed to serialise notification.");
|
||||
}
|
||||
@@ -25,7 +25,7 @@ pub fn init_hive() {
|
||||
get_collection("hive"),
|
||||
);
|
||||
|
||||
listen_thread(hive.clone());
|
||||
//listen_thread(hive.clone());
|
||||
|
||||
if HIVE.set(hive).is_err() {
|
||||
panic!("Failed to set global pubsub instance.");
|
||||
|
||||
@@ -1,3 +1,3 @@
|
||||
pub mod events;
|
||||
pub mod hive;
|
||||
pub mod websocket;
|
||||
// pub mod websocket;
|
||||
|
||||
@@ -57,7 +57,7 @@ impl Handler for Client {
|
||||
FindOneOptions::builder()
|
||||
.projection(doc! { "_id": 1 })
|
||||
.build(),
|
||||
);
|
||||
).await;
|
||||
|
||||
if let Ok(result) = user {
|
||||
if let Some(doc) = result {
|
||||
@@ -29,8 +29,8 @@ pub struct Create {
|
||||
/// (2) check email existence
|
||||
/// (3) add user and send email verification
|
||||
#[post("/create", data = "<info>")]
|
||||
pub fn create(info: Json<Create>) -> Response {
|
||||
if let Err(error) = captcha::verify(&info.captcha) {
|
||||
pub async fn create(info: Json<Create>) -> Response {
|
||||
if let Err(error) = captcha::verify(&info.captcha).await {
|
||||
return Response::BadRequest(json!({ "error": error }));
|
||||
}
|
||||
|
||||
@@ -58,6 +58,7 @@ pub fn create(info: Json<Create>) -> Response {
|
||||
|
||||
if let Some(_) = col
|
||||
.find_one(doc! { "email": info.email.clone() }, None)
|
||||
.await
|
||||
.expect("Failed user lookup")
|
||||
{
|
||||
return Response::Conflict(json!({ "error": "Email already in use!" }));
|
||||
@@ -65,6 +66,7 @@ pub fn create(info: Json<Create>) -> Response {
|
||||
|
||||
if let Some(_) = col
|
||||
.find_one(doc! { "username": info.username.clone() }, None)
|
||||
.await
|
||||
.expect("Failed user lookup")
|
||||
{
|
||||
return Response::Conflict(json!({ "error": "Username already in use!" }));
|
||||
@@ -99,7 +101,8 @@ pub fn create(info: Json<Create>) -> Response {
|
||||
"email_verification": email_verification
|
||||
},
|
||||
None,
|
||||
) {
|
||||
)
|
||||
.await {
|
||||
Ok(_) => {
|
||||
if *USE_EMAIL {
|
||||
let sent = email::send_verification_email(info.email.clone(), code);
|
||||
@@ -128,11 +131,12 @@ pub fn create(info: Json<Create>) -> Response {
|
||||
/// (2) check if it expired yet
|
||||
/// (3) set account as verified
|
||||
#[get("/verify/<code>")]
|
||||
pub fn verify_email(code: String) -> Response {
|
||||
pub async fn verify_email(code: String) -> Response {
|
||||
let col = database::get_collection("users");
|
||||
|
||||
if let Some(u) = col
|
||||
.find_one(doc! { "email_verification.code": code.clone() }, None)
|
||||
.await
|
||||
.expect("Failed user lookup")
|
||||
{
|
||||
let user: User = from_bson(Bson::Document(u)).expect("Failed to unwrap user.");
|
||||
@@ -161,6 +165,7 @@ pub fn verify_email(code: String) -> Response {
|
||||
},
|
||||
None,
|
||||
)
|
||||
.await
|
||||
.expect("Failed to update user!");
|
||||
|
||||
if *USE_EMAIL {
|
||||
@@ -187,8 +192,8 @@ pub struct Resend {
|
||||
/// (2) check for rate limit
|
||||
/// (3) resend the email
|
||||
#[post("/resend", data = "<info>")]
|
||||
pub fn resend_email(info: Json<Resend>) -> Response {
|
||||
if let Err(error) = captcha::verify(&info.captcha) {
|
||||
pub async fn resend_email(info: Json<Resend>) -> Response {
|
||||
if let Err(error) = captcha::verify(&info.captcha).await {
|
||||
return Response::BadRequest(json!({ "error": error }));
|
||||
}
|
||||
|
||||
@@ -199,6 +204,7 @@ pub fn resend_email(info: Json<Resend>) -> Response {
|
||||
doc! { "email_verification.target": info.email.clone() },
|
||||
None,
|
||||
)
|
||||
.await
|
||||
.expect("Failed user lookup.")
|
||||
{
|
||||
let user: User = from_bson(Bson::Document(u)).expect("Failed to unwrap user.");
|
||||
@@ -234,7 +240,9 @@ pub fn resend_email(info: Json<Resend>) -> Response {
|
||||
},
|
||||
},
|
||||
None,
|
||||
).expect("Failed to update user!");
|
||||
)
|
||||
.await
|
||||
.expect("Failed to update user!");
|
||||
|
||||
if let Err(err) = email::send_verification_email(info.email.clone(), code) {
|
||||
return Response::InternalServerError(json!({ "error": err }));
|
||||
@@ -259,8 +267,8 @@ pub struct Login {
|
||||
/// (2) verify password
|
||||
/// (3) return access token
|
||||
#[post("/login", data = "<info>")]
|
||||
pub fn login(info: Json<Login>) -> Response {
|
||||
if let Err(error) = captcha::verify(&info.captcha) {
|
||||
pub async fn login(info: Json<Login>) -> Response {
|
||||
if let Err(error) = captcha::verify(&info.captcha).await {
|
||||
return Response::BadRequest(json!({ "error": error }));
|
||||
}
|
||||
|
||||
@@ -268,6 +276,7 @@ pub fn login(info: Json<Login>) -> Response {
|
||||
|
||||
if let Some(u) = col
|
||||
.find_one(doc! { "email": info.email.clone() }, None)
|
||||
.await
|
||||
.expect("Failed user lookup")
|
||||
{
|
||||
let user: User = from_bson(Bson::Document(u)).expect("Failed to unwrap user.");
|
||||
@@ -286,6 +295,7 @@ pub fn login(info: Json<Login>) -> Response {
|
||||
doc! { "$set": { "access_token": token.clone() } },
|
||||
None,
|
||||
)
|
||||
.await
|
||||
.is_err()
|
||||
{
|
||||
return Response::InternalServerError(
|
||||
@@ -313,10 +323,10 @@ pub struct Token {
|
||||
|
||||
/// login to a Revolt account via token
|
||||
#[post("/token", data = "<info>")]
|
||||
pub fn token(info: Json<Token>) -> Response {
|
||||
pub async fn token(info: Json<Token>) -> Response {
|
||||
let col = database::get_collection("users");
|
||||
|
||||
if let Ok(result) = col.find_one(doc! { "access_token": info.token.clone() }, None) {
|
||||
if let Ok(result) = col.find_one(doc! { "access_token": info.token.clone() }, None).await {
|
||||
if let Some(user) = result {
|
||||
Response::Success(json!({
|
||||
"id": user.get_str("_id").unwrap(),
|
||||
@@ -332,24 +342,3 @@ pub fn token(info: Json<Token>) -> Response {
|
||||
}))
|
||||
}
|
||||
}
|
||||
|
||||
#[options("/create")]
|
||||
pub fn create_preflight() -> Response {
|
||||
Response::Result(super::Status::Ok)
|
||||
}
|
||||
#[options("/verify/<_code>")]
|
||||
pub fn verify_email_preflight(_code: String) -> Response {
|
||||
Response::Result(super::Status::Ok)
|
||||
}
|
||||
#[options("/resend")]
|
||||
pub fn resend_email_preflight() -> Response {
|
||||
Response::Result(super::Status::Ok)
|
||||
}
|
||||
#[options("/login")]
|
||||
pub fn login_preflight() -> Response {
|
||||
Response::Result(super::Status::Ok)
|
||||
}
|
||||
#[options("/token")]
|
||||
pub fn token_preflight() -> Response {
|
||||
Response::Result(super::Status::Ok)
|
||||
}
|
||||
|
||||
@@ -6,11 +6,12 @@ use crate::database::{
|
||||
use crate::util::vec_to_set;
|
||||
|
||||
use chrono::prelude::*;
|
||||
use mongodb::bson::{doc, from_bson, Bson};
|
||||
use mongodb::bson::{doc, from_bson, Bson, Document};
|
||||
use mongodb::options::FindOptions;
|
||||
use num_enum::TryFromPrimitive;
|
||||
use rocket::request::Form;
|
||||
use rocket_contrib::json::Json;
|
||||
use rocket::futures::StreamExt;
|
||||
use serde::{Deserialize, Serialize};
|
||||
use ulid::Ulid;
|
||||
|
||||
@@ -28,9 +29,10 @@ macro_rules! with_permissions {
|
||||
($user: expr, $target: expr) => {{
|
||||
let permissions = PermissionCalculator::new($user.clone())
|
||||
.channel($target.clone())
|
||||
.fetch_data();
|
||||
.fetch_data()
|
||||
.await;
|
||||
|
||||
let value = permissions.as_permission();
|
||||
let value = permissions.as_permission().await;
|
||||
if !value.get_access() {
|
||||
return None;
|
||||
}
|
||||
@@ -48,7 +50,7 @@ pub struct CreateGroup {
|
||||
|
||||
/// create a new group
|
||||
#[post("/create", data = "<info>")]
|
||||
pub fn create_group(user: User, info: Json<CreateGroup>) -> Response {
|
||||
pub async fn create_group(user: User, info: Json<CreateGroup>) -> Response {
|
||||
let name: String = info.name.chars().take(32).collect();
|
||||
let nonce: String = info.nonce.chars().take(32).collect();
|
||||
|
||||
@@ -60,7 +62,7 @@ pub fn create_group(user: User, info: Json<CreateGroup>) -> Response {
|
||||
}
|
||||
|
||||
let col = database::get_collection("channels");
|
||||
if let Some(_) = col.find_one(doc! { "nonce": nonce.clone() }, None).unwrap() {
|
||||
if let Some(_) = col.find_one(doc! { "nonce": nonce.clone() }, None).await.unwrap() {
|
||||
return Response::BadRequest(json!({ "error": "Group already created!" }));
|
||||
}
|
||||
|
||||
@@ -80,8 +82,8 @@ pub fn create_group(user: User, info: Json<CreateGroup>) -> Response {
|
||||
}
|
||||
},
|
||||
FindOptions::builder().limit(query.len() as i64).build(),
|
||||
) {
|
||||
if result.count() != query.len() {
|
||||
).await {
|
||||
if result.collect::<Vec<Result<Document, _>>>().await.len() != query.len() {
|
||||
return Response::BadRequest(json!({ "error": "Specified non-existant user(s)." }));
|
||||
}
|
||||
|
||||
@@ -110,6 +112,7 @@ pub fn create_group(user: User, info: Json<CreateGroup>) -> Response {
|
||||
},
|
||||
None,
|
||||
)
|
||||
.await
|
||||
.is_ok()
|
||||
{
|
||||
Response::Success(json!({ "id": id }))
|
||||
@@ -123,14 +126,14 @@ pub fn create_group(user: User, info: Json<CreateGroup>) -> Response {
|
||||
|
||||
/// fetch channel information
|
||||
#[get("/<target>")]
|
||||
pub fn channel(user: User, target: Channel) -> Option<Response> {
|
||||
pub async fn channel(user: User, target: Channel) -> Option<Response> {
|
||||
with_permissions!(user, target);
|
||||
Some(Response::Success(target.serialise()))
|
||||
}
|
||||
|
||||
/// [groups] add user to channel
|
||||
#[put("/<target>/recipients/<member>")]
|
||||
pub fn add_member(user: User, target: Channel, member: User) -> Option<Response> {
|
||||
pub async fn add_member(user: User, target: Channel, member: User) -> Option<Response> {
|
||||
if target.channel_type != 1 {
|
||||
return Some(Response::BadRequest(json!({ "error": "Not a group DM." })));
|
||||
}
|
||||
@@ -163,6 +166,7 @@ pub fn add_member(user: User, target: Channel, member: User) -> Option<Response>
|
||||
},
|
||||
None,
|
||||
)
|
||||
.await
|
||||
.is_ok()
|
||||
{
|
||||
if (Message {
|
||||
@@ -175,6 +179,7 @@ pub fn add_member(user: User, target: Channel, member: User) -> Option<Response>
|
||||
previous_content: vec![],
|
||||
})
|
||||
.send(&target)
|
||||
.await
|
||||
{
|
||||
/*notifications::send_message_given_channel(
|
||||
Notification::group_user_join(UserJoin {
|
||||
@@ -204,7 +209,7 @@ pub fn add_member(user: User, target: Channel, member: User) -> Option<Response>
|
||||
|
||||
/// [groups] remove user from channel
|
||||
#[delete("/<target>/recipients/<member>")]
|
||||
pub fn remove_member(user: User, target: Channel, member: User) -> Option<Response> {
|
||||
pub async fn remove_member(user: User, target: Channel, member: User) -> Option<Response> {
|
||||
if target.channel_type != 1 {
|
||||
return Some(Response::BadRequest(json!({ "error": "Not a group DM." })));
|
||||
}
|
||||
@@ -238,6 +243,7 @@ pub fn remove_member(user: User, target: Channel, member: User) -> Option<Respon
|
||||
},
|
||||
None,
|
||||
)
|
||||
.await
|
||||
.is_ok()
|
||||
{
|
||||
if (Message {
|
||||
@@ -250,6 +256,7 @@ pub fn remove_member(user: User, target: Channel, member: User) -> Option<Respon
|
||||
previous_content: vec![],
|
||||
})
|
||||
.send(&target)
|
||||
.await
|
||||
{
|
||||
/*notifications::send_message_given_channel(
|
||||
Notification::group_user_leave(UserLeave {
|
||||
@@ -276,7 +283,7 @@ pub fn remove_member(user: User, target: Channel, member: User) -> Option<Respon
|
||||
/// or leave group DM
|
||||
/// or close DM conversation
|
||||
#[delete("/<target>")]
|
||||
pub fn delete(user: User, target: Channel) -> Option<Response> {
|
||||
pub async fn delete(user: User, target: Channel) -> Option<Response> {
|
||||
let permissions = with_permissions!(user, target);
|
||||
|
||||
if !permissions.get_manage_channels() {
|
||||
@@ -286,14 +293,15 @@ pub fn delete(user: User, target: Channel) -> Option<Response> {
|
||||
let col = database::get_collection("channels");
|
||||
let target_id = target.id.clone();
|
||||
|
||||
let try_delete = || {
|
||||
let try_delete = async || {
|
||||
let messages = database::get_collection("messages");
|
||||
|
||||
if messages
|
||||
.delete_many(doc! { "channel": &target_id }, None)
|
||||
.await
|
||||
.is_ok()
|
||||
{
|
||||
if col.delete_one(doc! { "_id": &target_id }, None).is_ok() {
|
||||
if col.delete_one(doc! { "_id": &target_id }, None).await.is_ok() {
|
||||
Some(Response::Result(super::Status::Ok))
|
||||
} else {
|
||||
Some(Response::InternalServerError(
|
||||
@@ -315,6 +323,7 @@ pub fn delete(user: User, target: Channel) -> Option<Response> {
|
||||
doc! { "$set": { "active": false } },
|
||||
None,
|
||||
)
|
||||
.await
|
||||
.is_ok()
|
||||
{
|
||||
Some(Response::Result(super::Status::Ok))
|
||||
@@ -334,7 +343,7 @@ pub fn delete(user: User, target: Channel) -> Option<Response> {
|
||||
let owner = target.owner.as_ref().expect("Missing owner on Group DM.");
|
||||
|
||||
if recipients.len() == 1 {
|
||||
try_delete()
|
||||
try_delete().await
|
||||
} else {
|
||||
recipients.remove(&user.id);
|
||||
let new_owner = if owner == &user.id {
|
||||
@@ -356,6 +365,7 @@ pub fn delete(user: User, target: Channel) -> Option<Response> {
|
||||
},
|
||||
None,
|
||||
)
|
||||
.await
|
||||
.is_ok()
|
||||
{
|
||||
if (Message {
|
||||
@@ -368,6 +378,7 @@ pub fn delete(user: User, target: Channel) -> Option<Response> {
|
||||
previous_content: vec![],
|
||||
})
|
||||
.send(&target)
|
||||
.await
|
||||
{
|
||||
/*notifications::send_message_given_channel(
|
||||
Notification::group_user_leave(UserLeave {
|
||||
@@ -405,6 +416,7 @@ pub fn delete(user: User, target: Channel) -> Option<Response> {
|
||||
},
|
||||
None,
|
||||
)
|
||||
.await
|
||||
.is_ok()
|
||||
{
|
||||
/*notifications::send_message_threaded(
|
||||
@@ -416,7 +428,7 @@ pub fn delete(user: User, target: Channel) -> Option<Response> {
|
||||
}), FIXME
|
||||
);*/
|
||||
|
||||
try_delete()
|
||||
try_delete().await
|
||||
} else {
|
||||
Some(Response::InternalServerError(
|
||||
json!({ "error": "Failed to remove invites." }),
|
||||
@@ -438,7 +450,7 @@ pub struct MessageFetchOptions {
|
||||
|
||||
/// fetch channel messages
|
||||
#[get("/<target>/messages?<options..>")]
|
||||
pub fn messages(
|
||||
pub async fn messages(
|
||||
user: User,
|
||||
target: Channel,
|
||||
options: Form<MessageFetchOptions>,
|
||||
@@ -467,7 +479,7 @@ pub fn messages(
|
||||
};
|
||||
|
||||
let col = database::get_collection("messages");
|
||||
let result = col
|
||||
let mut result = col
|
||||
.find(
|
||||
query,
|
||||
FindOptions::builder()
|
||||
@@ -477,10 +489,11 @@ pub fn messages(
|
||||
})
|
||||
.build(),
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
|
||||
let mut messages = Vec::new();
|
||||
for item in result {
|
||||
while let Some(item) = result.next().await {
|
||||
let message: Message =
|
||||
from_bson(Bson::Document(item.unwrap())).expect("Failed to unwrap message.");
|
||||
messages.push(json!({
|
||||
@@ -502,7 +515,7 @@ pub struct SendMessage {
|
||||
|
||||
/// send a message to a channel
|
||||
#[post("/<target>/messages", data = "<message>")]
|
||||
pub fn send_message(user: User, target: Channel, message: Json<SendMessage>) -> Option<Response> {
|
||||
pub async fn send_message(user: User, target: Channel, message: Json<SendMessage>) -> Option<Response> {
|
||||
let permissions = with_permissions!(user, target);
|
||||
|
||||
if !permissions.get_send_messages() {
|
||||
@@ -525,6 +538,7 @@ pub fn send_message(user: User, target: Channel, message: Json<SendMessage>) ->
|
||||
let col = database::get_collection("messages");
|
||||
if col
|
||||
.find_one(doc! { "nonce": nonce.clone() }, None)
|
||||
.await
|
||||
.unwrap()
|
||||
.is_some()
|
||||
{
|
||||
@@ -544,7 +558,7 @@ pub fn send_message(user: User, target: Channel, message: Json<SendMessage>) ->
|
||||
previous_content: vec![],
|
||||
};
|
||||
|
||||
if message.send(&target) {
|
||||
if message.send(&target).await {
|
||||
Some(Response::Success(json!({ "id": id })))
|
||||
} else {
|
||||
Some(Response::BadRequest(
|
||||
@@ -555,7 +569,7 @@ pub fn send_message(user: User, target: Channel, message: Json<SendMessage>) ->
|
||||
|
||||
/// get a message
|
||||
#[get("/<target>/messages/<message>")]
|
||||
pub fn get_message(user: User, target: Channel, message: Message) -> Option<Response> {
|
||||
pub async fn get_message(user: User, target: Channel, message: Message) -> Option<Response> {
|
||||
let permissions = with_permissions!(user, target);
|
||||
|
||||
if !permissions.get_read_messages() {
|
||||
@@ -587,7 +601,7 @@ pub struct EditMessage {
|
||||
|
||||
/// edit a message
|
||||
#[patch("/<target>/messages/<message>", data = "<edit>")]
|
||||
pub fn edit_message(
|
||||
pub async fn edit_message(
|
||||
user: User,
|
||||
target: Channel,
|
||||
message: Message,
|
||||
@@ -624,7 +638,8 @@ pub fn edit_message(
|
||||
},
|
||||
},
|
||||
None,
|
||||
) {
|
||||
)
|
||||
.await {
|
||||
Ok(_) => {
|
||||
/*notifications::send_message_given_channel(
|
||||
Notification::message_edit(Edit {
|
||||
@@ -646,7 +661,7 @@ pub fn edit_message(
|
||||
|
||||
/// delete a message
|
||||
#[delete("/<target>/messages/<message>")]
|
||||
pub fn delete_message(user: User, target: Channel, message: Message) -> Option<Response> {
|
||||
pub async fn delete_message(user: User, target: Channel, message: Message) -> Option<Response> {
|
||||
let permissions = with_permissions!(user, target);
|
||||
|
||||
if !permissions.get_manage_messages() && message.author != user.id {
|
||||
@@ -655,7 +670,7 @@ pub fn delete_message(user: User, target: Channel, message: Message) -> Option<R
|
||||
|
||||
let col = database::get_collection("messages");
|
||||
|
||||
match col.delete_one(doc! { "_id": &message.id }, None) {
|
||||
match col.delete_one(doc! { "_id": &message.id }, None).await {
|
||||
Ok(_) => {
|
||||
/*notifications::send_message_given_channel(
|
||||
Notification::message_delete(Delete {
|
||||
@@ -671,24 +686,3 @@ pub fn delete_message(user: User, target: Channel, message: Message) -> Option<R
|
||||
)),
|
||||
}
|
||||
}
|
||||
|
||||
#[options("/create")]
|
||||
pub fn create_group_preflight() -> Response {
|
||||
Response::Result(super::Status::Ok)
|
||||
}
|
||||
#[options("/<_target>")]
|
||||
pub fn channel_preflight(_target: String) -> Response {
|
||||
Response::Result(super::Status::Ok)
|
||||
}
|
||||
#[options("/<_target>/recipients/<_member>")]
|
||||
pub fn member_preflight(_target: String, _member: String) -> Response {
|
||||
Response::Result(super::Status::Ok)
|
||||
}
|
||||
#[options("/<_target>/messages")]
|
||||
pub fn messages_preflight(_target: String) -> Response {
|
||||
Response::Result(super::Status::Ok)
|
||||
}
|
||||
#[options("/<_target>/messages/<_message>")]
|
||||
pub fn message_preflight(_target: String, _message: String) -> Response {
|
||||
Response::Result(super::Status::Ok)
|
||||
}
|
||||
|
||||
@@ -12,6 +12,7 @@ use mongodb::options::{FindOneOptions, FindOptions};
|
||||
use rocket::request::Form;
|
||||
use rocket_contrib::json::Json;
|
||||
use serde::{Deserialize, Serialize};
|
||||
use rocket::futures::StreamExt;
|
||||
use ulid::Ulid;
|
||||
|
||||
// ! FIXME: GET RID OF THIS
|
||||
@@ -19,9 +20,10 @@ macro_rules! with_permissions {
|
||||
($user: expr, $target: expr) => {{
|
||||
let permissions = PermissionCalculator::new($user.clone())
|
||||
.guild($target.clone())
|
||||
.fetch_data();
|
||||
.fetch_data()
|
||||
.await;
|
||||
|
||||
let value = permissions.as_permission();
|
||||
let value = permissions.as_permission().await;
|
||||
if !value.get_access() {
|
||||
return None;
|
||||
}
|
||||
@@ -32,9 +34,9 @@ macro_rules! with_permissions {
|
||||
|
||||
/// fetch your guilds
|
||||
#[get("/@me")]
|
||||
pub fn my_guilds(user: User) -> Response {
|
||||
if let Ok(gids) = user.find_guilds() {
|
||||
if let Ok(data) = serialise_guilds_with_channels(&gids) {
|
||||
pub async fn my_guilds(user: User) -> Response {
|
||||
if let Ok(gids) = user.find_guilds().await {
|
||||
if let Ok(data) = serialise_guilds_with_channels(&gids).await {
|
||||
Response::Success(json!(data))
|
||||
} else {
|
||||
Response::InternalServerError(json!({ "error": "Failed to fetch guilds." }))
|
||||
@@ -46,10 +48,10 @@ pub fn my_guilds(user: User) -> Response {
|
||||
|
||||
/// fetch a guild
|
||||
#[get("/<target>")]
|
||||
pub fn guild(user: User, target: Guild) -> Option<Response> {
|
||||
pub async fn guild(user: User, target: Guild) -> Option<Response> {
|
||||
with_permissions!(user, target);
|
||||
|
||||
if let Ok(result) = target.seralise_with_channels() {
|
||||
if let Ok(result) = target.seralise_with_channels().await {
|
||||
Some(Response::Success(result))
|
||||
} else {
|
||||
Some(Response::InternalServerError(
|
||||
@@ -60,20 +62,20 @@ pub fn guild(user: User, target: Guild) -> Option<Response> {
|
||||
|
||||
/// delete or leave a guild
|
||||
#[delete("/<target>")]
|
||||
pub fn remove_guild(user: User, target: Guild) -> Option<Response> {
|
||||
pub async fn remove_guild(user: User, target: Guild) -> Option<Response> {
|
||||
with_permissions!(user, target);
|
||||
|
||||
if user.id == target.owner {
|
||||
let channels = database::get_collection("channels");
|
||||
if let Ok(result) = channels.find(
|
||||
if let Ok(mut result) = channels.find(
|
||||
doc! {
|
||||
"type": 2,
|
||||
"guild": &target.id
|
||||
},
|
||||
FindOptions::builder().projection(doc! { "_id": 1 }).build(),
|
||||
) {
|
||||
).await {
|
||||
let mut values = vec![];
|
||||
for item in result {
|
||||
while let Some(item) = result.next().await {
|
||||
if let Ok(doc) = item {
|
||||
values.push(Bson::String(doc.get_str("_id").unwrap().to_string()));
|
||||
}
|
||||
@@ -88,6 +90,7 @@ pub fn remove_guild(user: User, target: Guild) -> Option<Response> {
|
||||
},
|
||||
None,
|
||||
)
|
||||
.await
|
||||
.is_ok()
|
||||
{
|
||||
if channels
|
||||
@@ -98,6 +101,7 @@ pub fn remove_guild(user: User, target: Guild) -> Option<Response> {
|
||||
},
|
||||
None,
|
||||
)
|
||||
.await
|
||||
.is_ok()
|
||||
{
|
||||
if database::get_collection("members")
|
||||
@@ -107,6 +111,7 @@ pub fn remove_guild(user: User, target: Guild) -> Option<Response> {
|
||||
},
|
||||
None,
|
||||
)
|
||||
.await
|
||||
.is_ok()
|
||||
{
|
||||
if database::get_collection("guilds")
|
||||
@@ -116,6 +121,7 @@ pub fn remove_guild(user: User, target: Guild) -> Option<Response> {
|
||||
},
|
||||
None,
|
||||
)
|
||||
.await
|
||||
.is_ok()
|
||||
{
|
||||
/*notifications::send_message_threaded(
|
||||
@@ -160,6 +166,7 @@ pub fn remove_guild(user: User, target: Guild) -> Option<Response> {
|
||||
},
|
||||
None,
|
||||
)
|
||||
.await
|
||||
.is_ok()
|
||||
{
|
||||
/*notifications::send_message_threaded(
|
||||
@@ -189,7 +196,7 @@ pub struct CreateChannel {
|
||||
|
||||
/// create a new channel
|
||||
#[post("/<target>/channels", data = "<info>")]
|
||||
pub fn create_channel(user: User, target: Guild, info: Json<CreateChannel>) -> Option<Response> {
|
||||
pub async fn create_channel(user: User, target: Guild, info: Json<CreateChannel>) -> Option<Response> {
|
||||
let (permissions, _) = with_permissions!(user, target);
|
||||
|
||||
if !permissions.get_manage_channels() {
|
||||
@@ -208,6 +215,7 @@ pub fn create_channel(user: User, target: Guild, info: Json<CreateChannel>) -> O
|
||||
|
||||
if let Ok(result) =
|
||||
database::get_collection("channels").find_one(doc! { "nonce": &nonce }, None)
|
||||
.await
|
||||
{
|
||||
if result.is_some() {
|
||||
return Some(Response::BadRequest(
|
||||
@@ -228,6 +236,7 @@ pub fn create_channel(user: User, target: Guild, info: Json<CreateChannel>) -> O
|
||||
},
|
||||
None,
|
||||
)
|
||||
.await
|
||||
.is_ok()
|
||||
{
|
||||
if database::get_collection("guilds")
|
||||
@@ -242,6 +251,7 @@ pub fn create_channel(user: User, target: Guild, info: Json<CreateChannel>) -> O
|
||||
},
|
||||
None,
|
||||
)
|
||||
.await
|
||||
.is_ok()
|
||||
{
|
||||
/*notifications::send_message_threaded(
|
||||
@@ -280,7 +290,7 @@ pub struct InviteOptions {
|
||||
|
||||
/// create a new invite
|
||||
#[post("/<target>/channels/<channel>/invite", data = "<_options>")]
|
||||
pub fn create_invite(
|
||||
pub async fn create_invite(
|
||||
user: User,
|
||||
target: Guild,
|
||||
channel: Channel,
|
||||
@@ -307,6 +317,7 @@ pub fn create_invite(
|
||||
},
|
||||
None,
|
||||
)
|
||||
.await
|
||||
.is_ok()
|
||||
{
|
||||
Some(Response::Success(json!({ "code": code })))
|
||||
@@ -319,10 +330,10 @@ pub fn create_invite(
|
||||
|
||||
/// remove an invite
|
||||
#[delete("/<target>/invites/<code>")]
|
||||
pub fn remove_invite(user: User, target: Guild, code: String) -> Option<Response> {
|
||||
pub async fn remove_invite(user: User, target: Guild, code: String) -> Option<Response> {
|
||||
let (permissions, _) = with_permissions!(user, target);
|
||||
|
||||
if let Some((guild_id, _, invite)) = get_invite(&code, None) {
|
||||
if let Some((guild_id, _, invite)) = get_invite(&code, None).await {
|
||||
if invite.creator != user.id && !permissions.get_manage_server() {
|
||||
return Some(Response::LackingPermission(Permission::ManageServer));
|
||||
}
|
||||
@@ -341,6 +352,7 @@ pub fn remove_invite(user: User, target: Guild, code: String) -> Option<Response
|
||||
},
|
||||
None,
|
||||
)
|
||||
.await
|
||||
.is_ok()
|
||||
{
|
||||
Some(Response::Result(super::Status::Ok))
|
||||
@@ -358,7 +370,7 @@ pub fn remove_invite(user: User, target: Guild, code: String) -> Option<Response
|
||||
|
||||
/// fetch all guild invites
|
||||
#[get("/<target>/invites")]
|
||||
pub fn fetch_invites(user: User, target: Guild) -> Option<Response> {
|
||||
pub async fn fetch_invites(user: User, target: Guild) -> Option<Response> {
|
||||
let (permissions, _) = with_permissions!(user, target);
|
||||
|
||||
if !permissions.get_manage_server() {
|
||||
@@ -370,9 +382,9 @@ pub fn fetch_invites(user: User, target: Guild) -> Option<Response> {
|
||||
|
||||
/// view an invite before joining
|
||||
#[get("/join/<code>", rank = 1)]
|
||||
pub fn fetch_invite(user: User, code: String) -> Response {
|
||||
if let Some((guild_id, name, invite)) = get_invite(&code, user.id) {
|
||||
match fetch_channel(&invite.channel) {
|
||||
pub async fn fetch_invite(user: User, code: String) -> Response {
|
||||
if let Some((guild_id, name, invite)) = get_invite(&code, user.id).await {
|
||||
match fetch_channel(&invite.channel).await {
|
||||
Ok(result) => {
|
||||
if let Some(channel) = result {
|
||||
Response::Success(json!({
|
||||
@@ -398,8 +410,8 @@ pub fn fetch_invite(user: User, code: String) -> Response {
|
||||
|
||||
/// join a guild using an invite
|
||||
#[post("/join/<code>", rank = 1)]
|
||||
pub fn use_invite(user: User, code: String) -> Response {
|
||||
if let Some((guild_id, _, invite)) = get_invite(&code, Some(user.id.clone())) {
|
||||
pub async fn use_invite(user: User, code: String) -> Response {
|
||||
if let Some((guild_id, _, invite)) = get_invite(&code, Some(user.id.clone())).await {
|
||||
if let Ok(result) = database::get_collection("members").find_one(
|
||||
doc! {
|
||||
"_id.guild": &guild_id,
|
||||
@@ -408,7 +420,8 @@ pub fn use_invite(user: User, code: String) -> Response {
|
||||
FindOneOptions::builder()
|
||||
.projection(doc! { "_id": 1 })
|
||||
.build(),
|
||||
) {
|
||||
)
|
||||
.await {
|
||||
if result.is_none() {
|
||||
if database::get_collection("members")
|
||||
.insert_one(
|
||||
@@ -420,6 +433,7 @@ pub fn use_invite(user: User, code: String) -> Response {
|
||||
},
|
||||
None,
|
||||
)
|
||||
.await
|
||||
.is_ok()
|
||||
{
|
||||
/*notifications::send_message_threaded(
|
||||
@@ -462,7 +476,7 @@ pub struct CreateGuild {
|
||||
|
||||
/// create a new guild
|
||||
#[post("/create", data = "<info>")]
|
||||
pub fn create_guild(user: User, info: Json<CreateGuild>) -> Response {
|
||||
pub async fn create_guild(user: User, info: Json<CreateGuild>) -> Response {
|
||||
if !user.email_verification.verified {
|
||||
return Response::Unauthorized(json!({ "error": "Email not verified!" }));
|
||||
}
|
||||
@@ -481,6 +495,7 @@ pub fn create_guild(user: User, info: Json<CreateGuild>) -> Response {
|
||||
let col = database::get_collection("guilds");
|
||||
if col
|
||||
.find_one(doc! { "nonce": nonce.clone() }, None)
|
||||
.await
|
||||
.unwrap()
|
||||
.is_some()
|
||||
{
|
||||
@@ -500,6 +515,7 @@ pub fn create_guild(user: User, info: Json<CreateGuild>) -> Response {
|
||||
},
|
||||
None,
|
||||
)
|
||||
.await
|
||||
.is_err()
|
||||
{
|
||||
return Response::InternalServerError(
|
||||
@@ -517,6 +533,7 @@ pub fn create_guild(user: User, info: Json<CreateGuild>) -> Response {
|
||||
},
|
||||
None,
|
||||
)
|
||||
.await
|
||||
.is_err()
|
||||
{
|
||||
return Response::InternalServerError(
|
||||
@@ -539,12 +556,14 @@ pub fn create_guild(user: User, info: Json<CreateGuild>) -> Response {
|
||||
},
|
||||
None,
|
||||
)
|
||||
.await
|
||||
.is_ok()
|
||||
{
|
||||
Response::Success(json!({ "id": id }))
|
||||
} else {
|
||||
channels
|
||||
.delete_one(doc! { "_id": channel_id }, None)
|
||||
.await
|
||||
.expect("Failed to delete the channel we just made.");
|
||||
|
||||
Response::InternalServerError(json!({ "error": "Failed to create guild." }))
|
||||
@@ -553,15 +572,16 @@ pub fn create_guild(user: User, info: Json<CreateGuild>) -> Response {
|
||||
|
||||
/// fetch a guild's member
|
||||
#[get("/<target>/members")]
|
||||
pub fn fetch_members(user: User, target: Guild) -> Option<Response> {
|
||||
pub async fn fetch_members(user: User, target: Guild) -> Option<Response> {
|
||||
with_permissions!(user, target);
|
||||
|
||||
if let Ok(result) =
|
||||
if let Ok(mut result) =
|
||||
database::get_collection("members").find(doc! { "_id.guild": target.id }, None)
|
||||
.await
|
||||
{
|
||||
let mut users = vec![];
|
||||
|
||||
for item in result {
|
||||
while let Some(item) = result.next().await {
|
||||
if let Ok(doc) = item {
|
||||
users.push(json!({
|
||||
"id": doc.get_document("_id").unwrap().get_str("user").unwrap(),
|
||||
@@ -580,10 +600,10 @@ pub fn fetch_members(user: User, target: Guild) -> Option<Response> {
|
||||
|
||||
/// fetch a guild member
|
||||
#[get("/<target>/members/<other>")]
|
||||
pub fn fetch_member(user: User, target: Guild, other: String) -> Option<Response> {
|
||||
pub async fn fetch_member(user: User, target: Guild, other: String) -> Option<Response> {
|
||||
with_permissions!(user, target);
|
||||
|
||||
if let Ok(result) = get_member(MemberKey(target.id, other)) {
|
||||
if let Ok(result) = get_member(MemberKey(target.id, other)).await {
|
||||
if let Some(member) = result {
|
||||
Some(Response::Success(json!({
|
||||
"id": member.id.user,
|
||||
@@ -603,7 +623,7 @@ pub fn fetch_member(user: User, target: Guild, other: String) -> Option<Response
|
||||
|
||||
/// kick a guild member
|
||||
#[delete("/<target>/members/<other>")]
|
||||
pub fn kick_member(user: User, target: Guild, other: String) -> Option<Response> {
|
||||
pub async fn kick_member(user: User, target: Guild, other: String) -> Option<Response> {
|
||||
let (permissions, _) = with_permissions!(user, target);
|
||||
|
||||
if user.id == other {
|
||||
@@ -616,7 +636,7 @@ pub fn kick_member(user: User, target: Guild, other: String) -> Option<Response>
|
||||
return Some(Response::LackingPermission(Permission::KickMembers));
|
||||
}
|
||||
|
||||
if let Ok(result) = get_member(MemberKey(target.id.clone(), other.clone())) {
|
||||
if let Ok(result) = get_member(MemberKey(target.id.clone(), other.clone())).await {
|
||||
if result.is_none() {
|
||||
return Some(Response::BadRequest(
|
||||
json!({ "error": "User not part of guild." }),
|
||||
@@ -636,6 +656,7 @@ pub fn kick_member(user: User, target: Guild, other: String) -> Option<Response>
|
||||
},
|
||||
None,
|
||||
)
|
||||
.await
|
||||
.is_ok()
|
||||
{
|
||||
/*notifications::send_message_threaded(
|
||||
@@ -663,7 +684,7 @@ pub struct BanOptions {
|
||||
|
||||
/// ban a guild member
|
||||
#[put("/<target>/members/<other>/ban?<options..>")]
|
||||
pub fn ban_member(
|
||||
pub async fn ban_member(
|
||||
user: User,
|
||||
target: Guild,
|
||||
other: String,
|
||||
@@ -688,7 +709,7 @@ pub fn ban_member(
|
||||
return Some(Response::LackingPermission(Permission::BanMembers));
|
||||
}
|
||||
|
||||
if let Ok(result) = get_member(MemberKey(target.id.clone(), other.clone())) {
|
||||
if let Ok(result) = get_member(MemberKey(target.id.clone(), other.clone())).await {
|
||||
if result.is_none() {
|
||||
return Some(Response::BadRequest(
|
||||
json!({ "error": "User not part of guild." }),
|
||||
@@ -713,6 +734,7 @@ pub fn ban_member(
|
||||
},
|
||||
None,
|
||||
)
|
||||
.await
|
||||
.is_err()
|
||||
{
|
||||
return Some(Response::BadRequest(
|
||||
@@ -728,6 +750,7 @@ pub fn ban_member(
|
||||
},
|
||||
None,
|
||||
)
|
||||
.await
|
||||
.is_ok()
|
||||
{
|
||||
/*notifications::send_message_threaded(
|
||||
@@ -750,7 +773,7 @@ pub fn ban_member(
|
||||
|
||||
/// unban a guild member
|
||||
#[delete("/<target>/members/<other>/ban")]
|
||||
pub fn unban_member(user: User, target: Guild, other: String) -> Option<Response> {
|
||||
pub async fn unban_member(user: User, target: Guild, other: String) -> Option<Response> {
|
||||
let (permissions, _) = with_permissions!(user, target);
|
||||
|
||||
if user.id == other {
|
||||
@@ -783,6 +806,7 @@ pub fn unban_member(user: User, target: Guild, other: String) -> Option<Response
|
||||
},
|
||||
None,
|
||||
)
|
||||
.await
|
||||
.is_ok()
|
||||
{
|
||||
Some(Response::Result(super::Status::Ok))
|
||||
@@ -792,44 +816,3 @@ pub fn unban_member(user: User, target: Guild, other: String) -> Option<Response
|
||||
))
|
||||
}
|
||||
}
|
||||
|
||||
#[options("/<_target>")]
|
||||
pub fn guild_preflight(_target: String) -> Response {
|
||||
Response::Result(super::Status::Ok)
|
||||
}
|
||||
#[options("/<_target>/channels")]
|
||||
pub fn create_channel_preflight(_target: String) -> Response {
|
||||
Response::Result(super::Status::Ok)
|
||||
}
|
||||
#[options("/<_target>/channels/<_channel>/invite")]
|
||||
pub fn create_invite_preflight(_target: String, _channel: String) -> Response {
|
||||
Response::Result(super::Status::Ok)
|
||||
}
|
||||
#[options("/<_target>/invites/<_code>")]
|
||||
pub fn remove_invite_preflight(_target: String, _code: String) -> Response {
|
||||
Response::Result(super::Status::Ok)
|
||||
}
|
||||
#[options("/<_target>/invites")]
|
||||
pub fn fetch_invites_preflight(_target: String) -> Response {
|
||||
Response::Result(super::Status::Ok)
|
||||
}
|
||||
#[options("/join/<_code>", rank = 1)]
|
||||
pub fn invite_preflight(_code: String) -> Response {
|
||||
Response::Result(super::Status::Ok)
|
||||
}
|
||||
#[options("/create")]
|
||||
pub fn create_guild_preflight() -> Response {
|
||||
Response::Result(super::Status::Ok)
|
||||
}
|
||||
#[options("/<_target>/members")]
|
||||
pub fn fetch_members_preflight(_target: String) -> Response {
|
||||
Response::Result(super::Status::Ok)
|
||||
}
|
||||
#[options("/<_target>/members/<_other>")]
|
||||
pub fn fetch_member_preflight(_target: String, _other: String) -> Response {
|
||||
Response::Result(super::Status::Ok)
|
||||
}
|
||||
#[options("/<_target>/members/<_other>/ban")]
|
||||
pub fn ban_member_preflight(_target: String, _other: String) -> Response {
|
||||
Response::Result(super::Status::Ok)
|
||||
}
|
||||
|
||||
@@ -49,21 +49,25 @@ use rocket::http::ContentType;
|
||||
use rocket::request::Request;
|
||||
use std::io::Cursor;
|
||||
|
||||
impl<'a> rocket::response::Responder<'a> for Permission {
|
||||
fn respond_to(self, _: &Request) -> rocket::response::Result<'a> {
|
||||
use rocket::response::{Responder, Result};
|
||||
|
||||
impl<'a> Responder<'a, 'static> for Permission {
|
||||
fn respond_to(self, _: &Request) -> Result<'static> {
|
||||
let body = format!(
|
||||
"{{\"error\":\"Lacking permission: {:?}.\",\"permission\":{}}}",
|
||||
self, self as u32,
|
||||
);
|
||||
|
||||
rocket::response::Response::build()
|
||||
.header(ContentType::JSON)
|
||||
.sized_body(Cursor::new(format!(
|
||||
"{{\"error\":\"Lacking permission: {:?}.\",\"permission\":{}}}",
|
||||
self, self as u32,
|
||||
)))
|
||||
.sized_body(body.len(), Cursor::new(body))
|
||||
.ok()
|
||||
}
|
||||
}
|
||||
|
||||
pub fn mount(rocket: Rocket) -> Rocket {
|
||||
rocket
|
||||
.mount("/", routes![root::root, root::root_preflight, root::teapot])
|
||||
.mount("/", routes![root::root, root::teapot])
|
||||
.mount(
|
||||
"/account",
|
||||
routes![
|
||||
@@ -72,11 +76,6 @@ pub fn mount(rocket: Rocket) -> Rocket {
|
||||
account::resend_email,
|
||||
account::login,
|
||||
account::token,
|
||||
account::create_preflight,
|
||||
account::verify_email_preflight,
|
||||
account::resend_email_preflight,
|
||||
account::login_preflight,
|
||||
account::token_preflight,
|
||||
],
|
||||
)
|
||||
.mount(
|
||||
@@ -93,12 +92,6 @@ pub fn mount(rocket: Rocket) -> Rocket {
|
||||
user::remove_friend,
|
||||
user::block_user,
|
||||
user::unblock_user,
|
||||
user::user_preflight,
|
||||
user::query_preflight,
|
||||
user::dms_preflight,
|
||||
user::dm_preflight,
|
||||
user::friend_preflight,
|
||||
user::block_user_preflight,
|
||||
],
|
||||
)
|
||||
.mount(
|
||||
@@ -114,11 +107,6 @@ pub fn mount(rocket: Rocket) -> Rocket {
|
||||
channel::send_message,
|
||||
channel::edit_message,
|
||||
channel::delete_message,
|
||||
channel::create_group_preflight,
|
||||
channel::channel_preflight,
|
||||
channel::member_preflight,
|
||||
channel::messages_preflight,
|
||||
channel::message_preflight,
|
||||
],
|
||||
)
|
||||
.mount(
|
||||
@@ -139,16 +127,6 @@ pub fn mount(rocket: Rocket) -> Rocket {
|
||||
guild::kick_member,
|
||||
guild::ban_member,
|
||||
guild::unban_member,
|
||||
guild::guild_preflight,
|
||||
guild::create_channel_preflight,
|
||||
guild::create_invite_preflight,
|
||||
guild::remove_invite_preflight,
|
||||
guild::fetch_invites_preflight,
|
||||
guild::invite_preflight,
|
||||
guild::create_guild_preflight,
|
||||
guild::fetch_members_preflight,
|
||||
guild::fetch_member_preflight,
|
||||
guild::ban_member_preflight,
|
||||
],
|
||||
)
|
||||
}
|
||||
|
||||
@@ -5,7 +5,7 @@ use mongodb::bson::doc;
|
||||
|
||||
/// root
|
||||
#[get("/")]
|
||||
pub fn root() -> Response {
|
||||
pub async fn root() -> Response {
|
||||
Response::Success(json!({
|
||||
"revolt": "0.2.11",
|
||||
"features": {
|
||||
@@ -19,14 +19,9 @@ pub fn root() -> Response {
|
||||
}))
|
||||
}
|
||||
|
||||
#[options("/")]
|
||||
pub fn root_preflight() -> Response {
|
||||
Response::Result(super::Status::Ok)
|
||||
}
|
||||
|
||||
/// I'm a teapot.
|
||||
#[delete("/")]
|
||||
pub fn teapot() -> Response {
|
||||
pub async fn teapot() -> Response {
|
||||
Response::Teapot(json!({
|
||||
"teapot": true,
|
||||
"can_delete": false
|
||||
|
||||
@@ -8,17 +8,18 @@ use mongodb::bson::doc;
|
||||
use mongodb::options::{Collation, FindOneOptions, FindOptions};
|
||||
use rocket_contrib::json::Json;
|
||||
use serde::{Deserialize, Serialize};
|
||||
use rocket::futures::StreamExt;
|
||||
use ulid::Ulid;
|
||||
|
||||
/// retrieve your user information
|
||||
#[get("/@me")]
|
||||
pub fn me(user: User) -> Response {
|
||||
pub async fn me(user: User) -> Response {
|
||||
Response::Success(user.serialise(Relationship::SELF as i32))
|
||||
}
|
||||
|
||||
/// retrieve another user's information
|
||||
#[get("/<target>")]
|
||||
pub fn user(user: User, target: User) -> Response {
|
||||
pub async fn user(user: User, target: User) -> Response {
|
||||
let relationship = get_relationship(&user, &target) as i32;
|
||||
Response::Success(user.serialise(relationship))
|
||||
}
|
||||
@@ -30,7 +31,7 @@ pub struct UserQuery {
|
||||
|
||||
/// find a user by their username
|
||||
#[post("/query", data = "<query>")]
|
||||
pub fn query(user: User, query: Json<UserQuery>) -> Response {
|
||||
pub async fn query(user: User, query: Json<UserQuery>) -> Response {
|
||||
let col = database::get_collection("users");
|
||||
|
||||
if let Ok(result) = col.find_one(
|
||||
@@ -38,7 +39,8 @@ pub fn query(user: User, query: Json<UserQuery>) -> Response {
|
||||
FindOneOptions::builder()
|
||||
.collation(Collation::builder().locale("en").strength(2).build())
|
||||
.build(),
|
||||
) {
|
||||
)
|
||||
.await {
|
||||
if let Some(doc) = result {
|
||||
let id = doc.get_str("_id").unwrap();
|
||||
Response::Success(json!({
|
||||
@@ -96,10 +98,10 @@ pub fn lookup(user: User, query: Json<LookupQuery>) -> Response {
|
||||
|
||||
/// retrieve all of your DMs
|
||||
#[get("/@me/dms")]
|
||||
pub fn dms(user: User) -> Response {
|
||||
pub async fn dms(user: User) -> Response {
|
||||
let col = database::get_collection("channels");
|
||||
|
||||
if let Ok(results) = col.find(
|
||||
if let Ok(mut results) = col.find(
|
||||
doc! {
|
||||
"$or": [
|
||||
{
|
||||
@@ -113,9 +115,10 @@ pub fn dms(user: User) -> Response {
|
||||
"recipients": user.id
|
||||
},
|
||||
FindOptions::builder().projection(doc! {}).build(),
|
||||
) {
|
||||
)
|
||||
.await {
|
||||
let mut channels = Vec::new();
|
||||
for item in results {
|
||||
while let Some(item) = results.next().await {
|
||||
if let Ok(doc) = item {
|
||||
let id = doc.get_str("_id").unwrap();
|
||||
let last_message = doc.get_document("last_message").unwrap();
|
||||
@@ -153,13 +156,14 @@ pub fn dms(user: User) -> Response {
|
||||
|
||||
/// open a DM with a user
|
||||
#[get("/<target>/dm")]
|
||||
pub fn dm(user: User, target: User) -> Response {
|
||||
pub async fn dm(user: User, target: User) -> Response {
|
||||
let col = database::get_collection("channels");
|
||||
|
||||
if let Ok(result) = col.find_one(
|
||||
doc! { "type": channel::ChannelType::DM as i32, "recipients": { "$all": [ user.id.clone(), target.id.clone() ] } },
|
||||
None
|
||||
) {
|
||||
)
|
||||
.await {
|
||||
if let Some(channel) = result {
|
||||
Response::Success( json!({ "id": channel.get_str("_id").unwrap() }))
|
||||
} else {
|
||||
@@ -173,7 +177,9 @@ pub fn dm(user: User, target: User) -> Response {
|
||||
"active": false
|
||||
},
|
||||
None
|
||||
).is_ok() {
|
||||
)
|
||||
.await
|
||||
.is_ok() {
|
||||
Response::Success(json!({ "id": id.to_string() }))
|
||||
} else {
|
||||
Response::InternalServerError(json!({ "error": "Failed to create new channel." }))
|
||||
@@ -186,7 +192,7 @@ pub fn dm(user: User, target: User) -> Response {
|
||||
|
||||
/// retrieve all of your friends
|
||||
#[get("/@me/friend")]
|
||||
pub fn get_friends(user: User) -> Response {
|
||||
pub async fn get_friends(user: User) -> Response {
|
||||
let mut results = Vec::new();
|
||||
if let Some(arr) = user.relations {
|
||||
for item in arr {
|
||||
@@ -202,13 +208,13 @@ pub fn get_friends(user: User) -> Response {
|
||||
|
||||
/// retrieve friend status with user
|
||||
#[get("/<target>/friend")]
|
||||
pub fn get_friend(user: User, target: User) -> Response {
|
||||
pub async fn get_friend(user: User, target: User) -> Response {
|
||||
Response::Success(json!({ "status": get_relationship(&user, &target) as i32 }))
|
||||
}
|
||||
|
||||
/// create or accept a friend request
|
||||
#[put("/<target>/friend")]
|
||||
pub fn add_friend(user: User, target: User) -> Response {
|
||||
pub async fn add_friend(user: User, target: User) -> Response {
|
||||
let col = database::get_collection("users");
|
||||
|
||||
match get_relationship(&user, &target) {
|
||||
@@ -230,6 +236,7 @@ pub fn add_friend(user: User, target: User) -> Response {
|
||||
},
|
||||
None,
|
||||
)
|
||||
.await
|
||||
.is_ok()
|
||||
{
|
||||
if col
|
||||
@@ -245,6 +252,7 @@ pub fn add_friend(user: User, target: User) -> Response {
|
||||
},
|
||||
None,
|
||||
)
|
||||
.await
|
||||
.is_ok()
|
||||
{
|
||||
/*notifications::send_message_threaded(
|
||||
@@ -301,6 +309,7 @@ pub fn add_friend(user: User, target: User) -> Response {
|
||||
},
|
||||
None,
|
||||
)
|
||||
.await
|
||||
.is_ok()
|
||||
{
|
||||
if col
|
||||
@@ -318,6 +327,7 @@ pub fn add_friend(user: User, target: User) -> Response {
|
||||
},
|
||||
None,
|
||||
)
|
||||
.await
|
||||
.is_ok()
|
||||
{
|
||||
/*notifications::send_message_threaded(
|
||||
@@ -360,7 +370,7 @@ pub fn add_friend(user: User, target: User) -> Response {
|
||||
|
||||
/// remove a friend or deny a request
|
||||
#[delete("/<target>/friend")]
|
||||
pub fn remove_friend(user: User, target: User) -> Response {
|
||||
pub async fn remove_friend(user: User, target: User) -> Response {
|
||||
let col = database::get_collection("users");
|
||||
|
||||
match get_relationship(&user, &target) {
|
||||
@@ -379,6 +389,7 @@ pub fn remove_friend(user: User, target: User) -> Response {
|
||||
},
|
||||
None,
|
||||
)
|
||||
.await
|
||||
.is_ok()
|
||||
{
|
||||
if col
|
||||
@@ -395,6 +406,7 @@ pub fn remove_friend(user: User, target: User) -> Response {
|
||||
},
|
||||
None,
|
||||
)
|
||||
.await
|
||||
.is_ok()
|
||||
{
|
||||
/*notifications::send_message_threaded(
|
||||
@@ -438,7 +450,7 @@ pub fn remove_friend(user: User, target: User) -> Response {
|
||||
|
||||
/// block a user
|
||||
#[put("/<target>/block")]
|
||||
pub fn block_user(user: User, target: User) -> Response {
|
||||
pub async fn block_user(user: User, target: User) -> Response {
|
||||
let col = database::get_collection("users");
|
||||
|
||||
match get_relationship(&user, &target) {
|
||||
@@ -456,6 +468,7 @@ pub fn block_user(user: User, target: User) -> Response {
|
||||
},
|
||||
None,
|
||||
)
|
||||
.await
|
||||
.is_ok()
|
||||
{
|
||||
if col
|
||||
@@ -471,6 +484,7 @@ pub fn block_user(user: User, target: User) -> Response {
|
||||
},
|
||||
None,
|
||||
)
|
||||
.await
|
||||
.is_ok()
|
||||
{
|
||||
/*notifications::send_message_threaded(
|
||||
@@ -522,6 +536,7 @@ pub fn block_user(user: User, target: User) -> Response {
|
||||
},
|
||||
None,
|
||||
)
|
||||
.await
|
||||
.is_ok()
|
||||
{
|
||||
if col
|
||||
@@ -539,6 +554,7 @@ pub fn block_user(user: User, target: User) -> Response {
|
||||
},
|
||||
None,
|
||||
)
|
||||
.await
|
||||
.is_ok()
|
||||
{
|
||||
/*notifications::send_message_threaded(
|
||||
@@ -590,6 +606,7 @@ pub fn block_user(user: User, target: User) -> Response {
|
||||
},
|
||||
None,
|
||||
)
|
||||
.await
|
||||
.is_ok()
|
||||
{
|
||||
/*notifications::send_message_threaded(
|
||||
@@ -615,7 +632,7 @@ pub fn block_user(user: User, target: User) -> Response {
|
||||
|
||||
/// unblock a user
|
||||
#[delete("/<target>/block")]
|
||||
pub fn unblock_user(user: User, target: User) -> Response {
|
||||
pub async fn unblock_user(user: User, target: User) -> Response {
|
||||
let col = database::get_collection("users");
|
||||
|
||||
match get_relationship(&user, &target) {
|
||||
@@ -634,6 +651,7 @@ pub fn unblock_user(user: User, target: User) -> Response {
|
||||
},
|
||||
None,
|
||||
)
|
||||
.await
|
||||
.is_ok()
|
||||
{
|
||||
/*notifications::send_message_threaded(
|
||||
@@ -668,6 +686,7 @@ pub fn unblock_user(user: User, target: User) -> Response {
|
||||
},
|
||||
None,
|
||||
)
|
||||
.await
|
||||
.is_ok()
|
||||
{
|
||||
if col
|
||||
@@ -684,6 +703,7 @@ pub fn unblock_user(user: User, target: User) -> Response {
|
||||
},
|
||||
None,
|
||||
)
|
||||
.await
|
||||
.is_ok()
|
||||
{
|
||||
/*notifications::send_message_threaded(
|
||||
@@ -730,28 +750,3 @@ pub fn unblock_user(user: User, target: User) -> Response {
|
||||
| Relationship::NONE => Response::BadRequest(json!({ "error": "This has no effect." })),
|
||||
}
|
||||
}
|
||||
|
||||
#[options("/<_target>")]
|
||||
pub fn user_preflight(_target: String) -> Response {
|
||||
Response::Result(super::Status::Ok)
|
||||
}
|
||||
#[options("/query")]
|
||||
pub fn query_preflight() -> Response {
|
||||
Response::Result(super::Status::Ok)
|
||||
}
|
||||
#[options("/@me/dms")]
|
||||
pub fn dms_preflight() -> Response {
|
||||
Response::Result(super::Status::Ok)
|
||||
}
|
||||
#[options("/<_target>/dm")]
|
||||
pub fn dm_preflight(_target: String) -> Response {
|
||||
Response::Result(super::Status::Ok)
|
||||
}
|
||||
#[options("/<_target>/friend")]
|
||||
pub fn friend_preflight(_target: String) -> Response {
|
||||
Response::Result(super::Status::Ok)
|
||||
}
|
||||
#[options("/<_target>/block")]
|
||||
pub fn block_user_preflight(_target: String) -> Response {
|
||||
Response::Result(super::Status::Ok)
|
||||
}
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
use crate::util::variables::{HCAPTCHA_KEY, USE_HCAPTCHA};
|
||||
|
||||
use reqwest::blocking::Client;
|
||||
use reqwest::Client;
|
||||
use serde::{Deserialize, Serialize};
|
||||
use std::collections::HashMap;
|
||||
|
||||
@@ -9,7 +9,7 @@ struct CaptchaResponse {
|
||||
success: bool,
|
||||
}
|
||||
|
||||
pub fn verify(user_token: &Option<String>) -> Result<(), String> {
|
||||
pub async fn verify(user_token: &Option<String>) -> Result<(), String> {
|
||||
if *USE_HCAPTCHA {
|
||||
if let Some(token) = user_token {
|
||||
let mut map = HashMap::new();
|
||||
@@ -21,9 +21,11 @@ pub fn verify(user_token: &Option<String>) -> Result<(), String> {
|
||||
.post("https://hcaptcha.com/siteverify")
|
||||
.form(&map)
|
||||
.send()
|
||||
.await
|
||||
{
|
||||
let result: CaptchaResponse = response
|
||||
.json()
|
||||
.await
|
||||
.map_err(|_| "Failed to deserialise captcha result.".to_string())?;
|
||||
|
||||
if result.success {
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
use hashbrown::HashSet;
|
||||
use rand::{distributions::Alphanumeric, Rng};
|
||||
use std::collections::HashSet;
|
||||
use std::iter::FromIterator;
|
||||
|
||||
pub mod captcha;
|
||||
|
||||
Reference in New Issue
Block a user