Add serialisation, ready payload and GET guilds.

This commit is contained in:
Paul Makles
2020-08-12 15:40:56 +02:00
parent 74b4238f04
commit 7e7eb34f65
7 changed files with 314 additions and 125 deletions

View File

@@ -4,6 +4,7 @@ use lru::LruCache;
use mongodb::bson::{doc, from_bson, Bson};
use rocket::http::RawStr;
use rocket::request::FromParam;
use rocket_contrib::json::JsonValue;
use serde::{Deserialize, Serialize};
use std::sync::{Arc, Mutex};
@@ -40,6 +41,40 @@ pub struct Channel {
pub description: Option<String>,
}
impl Channel {
pub fn serialise(self) -> JsonValue {
match self.channel_type {
0 => json!({
"id": self.id,
"type": self.channel_type,
"last_message": self.last_message,
"recipients": self.recipients,
}),
1 => {
json!({
"id": self.id,
"type": self.channel_type,
"last_message": self.last_message,
"recipients": self.recipients,
"name": self.name,
"owner": self.owner,
"description": self.description,
})
}
2 => {
json!({
"id": self.id,
"type": self.channel_type,
"guild": self.guild,
"name": self.name,
"description": self.description,
})
}
_ => unreachable!(),
}
}
}
lazy_static! {
static ref CACHE: Arc<Mutex<LruCache<String, Channel>>> =
Arc::new(Mutex::new(LruCache::new(4_000_000)));
@@ -83,13 +118,13 @@ pub fn fetch_channels(ids: &Vec<String>) -> Result<Vec<Channel>, String> {
{
if let Ok(mut cache) = CACHE.lock() {
for gid in ids {
let existing = cache.get(gid);
for id in ids {
let existing = cache.get(id);
if let Some(channel) = existing {
channels.push((*channel).clone());
} else {
missing.push(gid);
missing.push(id);
}
}
} else {

View File

@@ -4,6 +4,7 @@ use lru::LruCache;
use mongodb::bson::{doc, from_bson, Bson};
use rocket::http::RawStr;
use rocket::request::FromParam;
use rocket_contrib::json::JsonValue;
use serde::{Deserialize, Serialize};
use std::sync::{Arc, Mutex};
@@ -49,6 +50,32 @@ pub struct Guild {
pub default_permissions: u32,
}
impl Guild {
pub fn serialise(self) -> JsonValue {
json!({
"id": self.id,
"name": self.name,
"description": self.description,
"owner": self.owner
})
}
pub fn fetch_channels(&self) -> Result<Vec<super::channel::Channel>, String> {
super::channel::fetch_channels(&self.channels)
}
pub fn seralise_with_channels(self) -> Result<JsonValue, String> {
let channels = self.fetch_channels()?
.into_iter()
.map(|x| x.serialise())
.collect();
let mut value = self.serialise();
value.as_object_mut().unwrap().insert("channels".to_string(), channels);
Ok(value)
}
}
#[derive(Hash, Eq, PartialEq)]
pub struct MemberKey(pub String, pub String);
@@ -91,6 +118,52 @@ pub fn fetch_guild(id: &str) -> Result<Option<Guild>, String> {
}
}
pub fn fetch_guilds(ids: &Vec<String>) -> Result<Vec<Guild>, String> {
let mut missing = vec![];
let mut guilds = vec![];
{
if let Ok(mut cache) = CACHE.lock() {
for id in ids {
let existing = cache.get(id);
if let Some(guild) = existing {
guilds.push((*guild).clone());
} else {
missing.push(id);
}
}
} else {
return Err("Failed to lock cache.".to_string());
}
}
if missing.len() == 0 {
return Ok(guilds);
}
let col = get_collection("guilds");
if let Ok(result) = col.find(doc! { "_id": { "$in": missing } }, None) {
for item in result {
let mut cache = CACHE.lock().unwrap();
if let Ok(doc) = item {
if let Ok(guild) = from_bson(Bson::Document(doc)) as Result<Guild, _> {
cache.put(guild.id.clone(), guild.clone());
guilds.push(guild);
} else {
return Err("Failed to deserialize guild!".to_string());
}
} else {
return Err("Failed to fetch guild.".to_string());
}
}
Ok(guilds)
} else {
Err("Failed to fetch channel from database.".to_string())
}
}
pub fn fetch_member(key: MemberKey) -> Result<Option<Member>, String> {
{
if let Ok(mut cache) = MEMBER_CACHE.lock() {

View File

@@ -1,9 +1,13 @@
use super::get_collection;
use super::guild::{Guild, fetch_guilds};
use super::channel::{Channel, fetch_channels};
use lru::LruCache;
use mongodb::bson::{doc, from_bson, Bson, DateTime};
use mongodb::options::FindOptions;
use rocket::http::{RawStr, Status};
use rocket::request::{self, FromParam, FromRequest, Request};
use rocket_contrib::json::JsonValue;
use rocket::Outcome;
use std::sync::{Arc, Mutex};
use serde::{Deserialize, Serialize};
@@ -36,6 +40,116 @@ pub struct User {
pub relations: Option<Vec<UserRelationship>>,
}
impl User {
pub fn serialise(self, relationship: i32) -> JsonValue {
if relationship == super::Relationship::SELF as i32 {
json!({
"id": self.id,
"username": self.username,
"display_name": self.display_name,
"email": self.email,
"verified": self.email_verification.verified,
})
} else {
json!({
"id": self.id,
"username": self.username,
"display_name": self.display_name,
"relationship": relationship
})
}
}
pub fn find_guilds(&self) -> Result<Vec<String>, String> {
let members = get_collection("members")
.find(
doc! {
"_id.user": &self.id
},
None
).map_err(|_| "Failed to fetch members.")?;
Ok(members.into_iter()
.filter_map(|x| match x {
Ok(doc) => {
match doc.get_document("_id") {
Ok(id) => {
match id.get_str("guild") {
Ok(value) => Some(value.to_string()),
Err(_) => None
}
}
Err(_) => None
}
}
Err(_) => None
})
.collect())
}
pub fn find_dms(&self) -> Result<Vec<String>, String> {
let channels = get_collection("channels")
.find(
doc! {
"recipients": &self.id
},
FindOptions::builder()
.projection(doc! { "_id": 1 })
.build()
).map_err(|_| "Failed to fetch channel ids.")?;
Ok(channels.into_iter()
.filter_map(|x| x.ok())
.filter_map(|x| {
match x.get_str("_id") {
Ok(value) => Some(value.to_string()),
Err(_) => None
}
})
.collect())
}
pub 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()
)?
.into_iter()
.map(|x| {
let id = x.id.clone();
x.serialise(
relations.iter()
.find(|y| y.id == id)
.unwrap()
.status as i32
)
})
.collect();
let channels: Vec<JsonValue> = fetch_channels(&self.find_dms()?)?
.into_iter()
.map(|x| x.serialise())
.collect();
let guilds: Vec<JsonValue> = fetch_guilds(&self.find_guilds()?)?
.into_iter()
.map(|x| x.serialise())
.collect();
Ok(json!({
"users": users,
"channels": channels,
"guilds": guilds,
"user": self.serialise(super::Relationship::SELF as i32)
}))
}
}
lazy_static! {
static ref CACHE: Arc<Mutex<LruCache<String, User>>> =
Arc::new(Mutex::new(LruCache::new(4_000_000)));
@@ -73,6 +187,52 @@ pub fn fetch_user(id: &str) -> Result<Option<User>, String> {
}
}
pub fn fetch_users(ids: &Vec<String>) -> Result<Vec<User>, String> {
let mut missing = vec![];
let mut users = vec![];
{
if let Ok(mut cache) = CACHE.lock() {
for id in ids {
let existing = cache.get(id);
if let Some(user) = existing {
users.push((*user).clone());
} else {
missing.push(id);
}
}
} else {
return Err("Failed to lock cache.".to_string());
}
}
if missing.len() == 0 {
return Ok(users);
}
let col = get_collection("users");
if let Ok(result) = col.find(doc! { "_id": { "$in": missing } }, None) {
for item in result {
let mut cache = CACHE.lock().unwrap();
if let Ok(doc) = item {
if let Ok(user) = from_bson(Bson::Document(doc)) as Result<User, _> {
cache.put(user.id.clone(), user.clone());
users.push(user);
} else {
return Err("Failed to deserialize user!".to_string());
}
} else {
return Err("Failed to fetch user.".to_string());
}
}
Ok(users)
} else {
Err("Failed to fetch user from database.".to_string())
}
}
#[derive(Debug)]
pub enum AuthError {
Failed,