Skip to content

Commit

Permalink
feat: Relationships
Browse files Browse the repository at this point in the history
  • Loading branch information
abdulrahman1s authored Jul 10, 2022
2 parents 436031d + e97858f commit de357de
Show file tree
Hide file tree
Showing 19 changed files with 331 additions and 133 deletions.
95 changes: 8 additions & 87 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

3 changes: 1 addition & 2 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -40,7 +40,6 @@ tower-http = { version = "0.3.0", features = ["cors"] }
rust-argon2 = "1.0.0"
governor = "0.4.2"
validator = { version = "0.15", features = ["derive"] }
rust-crypto = "0.2.36"

# Utility
dotenv = "0.15.0"
Expand All @@ -63,4 +62,4 @@ opg = { git = "https://github.com/abdulrahman1s/opg", rev = "24f72e7cf09da7cd61b


[patch.crates-io]
ormlite-macro = { git = "https://github.com/abdulrahman1s/ormlite" }
ormlite-macro = { git = "https://github.com/abdulrahman1s/ormlite", rev = "9f8ef977d3516c12e2cf7e35e7a484d7f5911c38" }
1 change: 1 addition & 0 deletions src/config.rs
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,7 @@ lazy_static! {
// User related
pub static ref MAX_FRIENDS: u64 = get!("MAX_FRIENDS", "1000").parse().unwrap();
pub static ref MAX_BLOCKED: u64 = get!("MAX_BLOCKED", "1000").parse().unwrap();
pub static ref MAX_FRIEND_REQUESTS: u64 = get!("MAX_FRIEND_REQUESTS", "100").parse().unwrap();

// Group related
pub static ref MAX_GROUPS: u64 = get!("MAX_GROUPS", "100").parse().unwrap();
Expand Down
12 changes: 3 additions & 9 deletions src/extractors/validate.rs
Original file line number Diff line number Diff line change
Expand Up @@ -21,16 +21,10 @@ where
type Rejection = Error;

async fn from_request(req: &mut RequestParts<B>) -> Result<Self, Self::Rejection> {
let data = Json::from_request(req).await;
let data: Json<T> = Json::from_request(req).await?;

if let Ok(data) = data {
let data: Json<T> = data;
data.validate().map_err(|_| Error::InvalidBody)?;

data.validate().map_err(|_| Error::InvalidBody)?;

Ok(Self(data.0))
} else {
Err(Error::InvalidBody)
}
Ok(Self(data.0))
}
}
38 changes: 24 additions & 14 deletions src/gateway/events/authenticate.rs
Original file line number Diff line number Diff line change
@@ -1,12 +1,11 @@
use fred::interfaces::PubsubInterface;

use crate::database::pool;
use crate::gateway::{
client::Client,
payload::{ClientPayload, Payload},
};
use crate::structures::*;
use crate::utils::Permissions;
use fred::interfaces::PubsubInterface;

pub async fn run(client: &Client, payload: ClientPayload) {
if client.user.lock().await.is_some() {
Expand All @@ -33,23 +32,34 @@ pub async fn run(client: &Client, payload: ClientPayload) {
let mut permissions = client.permissions.lock().await;
let mut channels = user.fetch_channels().await.unwrap();
let servers = user.fetch_servers().await.unwrap();
let users: Vec<User> = user
.fetch_relations()
.await
.unwrap()
.into_iter()
.map(|mut u| {
u.relationship = user.relations.0.get(&u.id).copied();
u
})
.collect();

if !servers.is_empty() {
let mut server_ids: String = servers.iter().map(|s| s.id.to_string() + ",").collect();
server_ids.remove(server_ids.len() - 1);

let mut other_channels = Channel::query(&format!(
"SELECT * FROM {} WHERE server_id = ({})",
Channel::table_name(),
server_ids
))
.fetch_all(pool())
.await
.unwrap();
let server_ids: Vec<i64> = servers.iter().map(|s| s.id).collect();

let mut other_channels = Channel::select()
.filter("server_id = ANY($1)")
.bind(server_ids)
.fetch_all(pool())
.await
.unwrap();

channels.append(&mut other_channels);
}

for user in &users {
subscriptions.push(user.id);
}

for server in &servers {
subscriptions.push(server.id);
permissions.insert(
Expand Down Expand Up @@ -83,7 +93,7 @@ pub async fn run(client: &Client, payload: ClientPayload) {
client
.send(Payload::Ready {
user,
users: vec![], // TODO:
users,
servers,
channels,
})
Expand Down
6 changes: 6 additions & 0 deletions src/gateway/upgrade.rs
Original file line number Diff line number Diff line change
Expand Up @@ -143,6 +143,12 @@ async fn handle(ws: WebSocket) {
);
}
}
Payload::UserUpdate(u) => {
// Newly friend, blocked, request
if u.id != target_id && u.id != user.id {
client.subscriptions.subscribe(u.id.to_string()).await.ok();
}
}
_ => {}
}

Expand Down
3 changes: 1 addition & 2 deletions src/routes/auth/sessions/delete.rs
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
use crate::extractors::*;
use crate::structures::*;
use crate::utils::*;
use crypto::util::fixed_time_eq;
use serde::Deserialize;
use validator::Validate;

Expand All @@ -17,7 +16,7 @@ pub async fn delete(
) -> Result<()> {
let session = id.session(user.id).await?;

if !fixed_time_eq(session.token.as_bytes(), data.token.as_bytes()) {
if session.token != data.token {
return Err(Error::InvalidToken);
}

Expand Down
8 changes: 7 additions & 1 deletion src/routes/docs.rs
Original file line number Diff line number Diff line change
Expand Up @@ -49,9 +49,15 @@ pub fn document(app: Router) -> Router {
},

// Users
("users"): { GET: { 200: Vec<User>, tags: {users}} },
("users/@me"): { GET: { 200: User, tags: {users} } },
("users" / { user_id: u64 }): { GET: { 200: User, tags: {users} } },

("users" / { user_id: u64 } / "dm"): { GET: { 200: Channel, tags: {users} } },
("users/@me/relationships" / { user_id: u64 }): {
POST: { 200: None, tags: {users} },
PUT: { 200: None, tags: {users} },
DELETE: { 200: None, tags: {users} }
},

// Channels
("channels"): {
Expand Down
12 changes: 11 additions & 1 deletion src/routes/users/fetch.rs
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,16 @@ pub async fn fetch_me(Extension(user): Extension<User>) -> Json<User> {
user.into()
}

pub async fn fetch_one(Path(id): Path<i64>) -> Result<Json<User>> {
pub async fn fetch_one(
Extension(user): Extension<User>,
Path(id): Path<i64>,
) -> Result<Json<User>> {
if user.id == id {
return Ok(user.into());
}
Ok(id.user().await?.into())
}

pub async fn fetch_many(Extension(user): Extension<User>) -> Result<Json<Vec<User>>> {
Ok(user.fetch_relations().await?.into())
}
7 changes: 6 additions & 1 deletion src/routes/users/mod.rs
Original file line number Diff line number Diff line change
@@ -1,11 +1,16 @@
mod fetch;
pub mod fetch;
pub mod open_dm;
pub mod relationships;

pub fn routes() -> axum::Router {
use crate::middlewares::*;
use axum::{middleware, routing::*, Router};

Router::new()
.nest("/@me/relationships", relationships::routes())
.route("/", get(fetch::fetch_many))
.route("/@me", get(fetch::fetch_me))
.route("/:user_id", get(fetch::fetch_one))
.route("/:user_id/dm", get(open_dm::open_dm))
.layer(middleware::from_fn(ratelimit::handle!(20, 1000 * 5)))
}
Loading

0 comments on commit de357de

Please sign in to comment.