forked from jmug/stoatchat
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)
|
||||
}
|
||||
}*/
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
Reference in New Issue
Block a user