Skip to content

Commit

Permalink
perf: code cleanup
Browse files Browse the repository at this point in the history
  • Loading branch information
abdulrahman1s committed Jul 20, 2022
1 parent c7ded36 commit 2fcb8dc
Show file tree
Hide file tree
Showing 26 changed files with 102 additions and 101 deletions.
14 changes: 4 additions & 10 deletions src/gateway/events/authenticate.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,3 @@
use crate::database::pool;
use crate::gateway::{
client::Client,
payload::{ClientPayload, Payload},
Expand Down Expand Up @@ -38,26 +37,21 @@ pub async fn run(client: &Client, payload: ClientPayload) {
.unwrap()
.into_iter()
.map(|mut u| {
subscriptions.push(user.id);
u.relationship = user.relations.0.get(&u.id).copied();
u
})
.collect();

if !servers.is_empty() {
let server_ids: Vec<i64> = servers.iter().map(|s| s.id).collect();

let mut other_channels = Channel::select()
let mut servers_channels = Channel::select()
.filter("server_id = ANY($1)")
.bind(server_ids)
.bind(servers.iter().map(|s| s.id).collect::<Vec<i64>>())
.fetch_all(pool())
.await
.unwrap();

channels.append(&mut other_channels);
}

for user in &users {
subscriptions.push(user.id);
channels.append(&mut servers_channels);
}

for server in &servers {
Expand Down
2 changes: 1 addition & 1 deletion src/routes/auth/accounts/verify.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ use crate::utils::*;

#[derive(Deserialize)]
pub struct VerifyQuery {
user_id: u64,
user_id: i64,
code: String,
}

Expand Down
4 changes: 2 additions & 2 deletions src/routes/channels/edit.rs
Original file line number Diff line number Diff line change
Expand Up @@ -20,9 +20,9 @@ pub async fn edit(
) -> Result<Json<Channel>> {
let mut group = id.channel(user.id.into()).await?;

Permissions::fetch(&user, None, group.id.into())
Permissions::fetch_cached(&user, None, Some(&group))
.await?
.has(&[Permissions::MANAGE_CHANNELS])?;
.has(bits![MANAGE_CHANNELS])?;

group.merge(data);

Expand Down
2 changes: 1 addition & 1 deletion src/routes/channels/kick.rs
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ pub async fn kick(

Permissions::fetch_cached(&user, None, Some(&group))
.await?
.has(&[Permissions::KICK_MEMBERS])?;
.has(bits![KICK_MEMBERS])?;

if let Some(recipients) = group.recipients.as_mut() {
let exists = recipients
Expand Down
11 changes: 8 additions & 3 deletions src/routes/invites/create.rs
Original file line number Diff line number Diff line change
Expand Up @@ -6,18 +6,23 @@ use validator::Validate;

#[derive(Deserialize, Validate, OpgModel)]
pub struct CreateInviteOptions {
channel_id: u64,
channel_id: i64,
}

pub async fn create(
Extension(user): Extension<User>,
ValidatedJson(data): ValidatedJson<CreateInviteOptions>,
) -> Result<Json<Invite>> {
let channel = data.channel_id.channel(None).await?;
let server = if let Some(id) = channel.server_id {
Some(id.server(None).await?)
} else {
None
};

Permissions::fetch(&user, channel.server_id, channel.id.into())
Permissions::fetch_cached(&user, server.as_ref(), Some(&channel))
.await?
.has(&[Permissions::INVITE_OTHERS])?;
.has(bits![INVITE_OTHERS])?;

let invite = Invite::new(user.id, channel.id, channel.server_id);

Expand Down
2 changes: 1 addition & 1 deletion src/routes/messages/create.rs
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@ pub async fn create(
) -> Result<Json<Message>> {
Permissions::fetch(&user, None, channel_id.into())
.await?
.has(&[Permissions::VIEW_CHANNEL, Permissions::SEND_MESSAGES])?;
.has(bits![VIEW_CHANNEL, SEND_MESSAGES])?;

let mut msg = Message::new(channel_id, user.id);

Expand Down
4 changes: 2 additions & 2 deletions src/routes/messages/delete.rs
Original file line number Diff line number Diff line change
Expand Up @@ -11,9 +11,9 @@ pub async fn delete(
let p = Permissions::fetch(&user, None, channel_id.into()).await?;

if msg.author_id != user.id {
p.has(&[Permissions::MANAGE_MESSAGES])?;
p.has(bits![MANAGE_MESSAGES])?;
} else {
p.has(&[Permissions::MANAGE_MESSAGES, Permissions::VIEW_CHANNEL])?;
p.has(bits![MANAGE_MESSAGES, VIEW_CHANNEL])?;
}

let attachment_ids: Vec<i64> = msg
Expand Down
2 changes: 1 addition & 1 deletion src/routes/messages/edit.rs
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,7 @@ pub async fn edit(

Permissions::fetch(&user, None, channel_id.into())
.await?
.has(&[Permissions::VIEW_CHANNEL])?;
.has(bits![VIEW_CHANNEL])?;

msg.content = data.content.into();
msg.edited_at = Some(Utc::now().naive_utc());
Expand Down
2 changes: 1 addition & 1 deletion src/routes/messages/fetch.rs
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@ pub async fn fetch_one(

Permissions::fetch(&user, None, channel_id.into())
.await?
.has(&[Permissions::VIEW_CHANNEL, Permissions::READ_MESSAGE_HISTORY])?;
.has(bits![VIEW_CHANNEL, READ_MESSAGE_HISTORY])?;

Ok(Json(msg))
}
2 changes: 1 addition & 1 deletion src/routes/servers/channels/create.rs
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@ pub async fn create(
) -> Result<Json<Channel>> {
Permissions::fetch(&user, server_id.into(), None)
.await?
.has(&[Permissions::MANAGE_CHANNELS])?;
.has(bits![MANAGE_CHANNELS])?;

let count = Channel::count(&format!("server_id = {}", server_id)).await?;

Expand Down
2 changes: 1 addition & 1 deletion src/routes/servers/channels/delete.rs
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@ pub async fn delete(

Permissions::fetch(&user, server_id.into(), id.into())
.await?
.has(&[Permissions::MANAGE_CHANNELS])?;
.has(bits![MANAGE_CHANNELS])?;

channel.remove().await?;

Expand Down
9 changes: 5 additions & 4 deletions src/routes/servers/channels/edit.rs
Original file line number Diff line number Diff line change
Expand Up @@ -18,11 +18,12 @@ pub async fn edit(
Path((server_id, id)): Path<(i64, i64)>,
ValidatedJson(data): ValidatedJson<EditServerChannelOptions>,
) -> Result<Json<Channel>> {
Permissions::fetch(&user, server_id.into(), id.into())
.await?
.has(&[Permissions::MANAGE_CHANNELS])?;

let mut channel = id.channel(None).await?;
let server = server_id.server(None).await?;

Permissions::fetch_cached(&user, Some(&server), Some(&channel))
.await?
.has(bits![MANAGE_CHANNELS])?;

channel.merge(data);

Expand Down
2 changes: 1 addition & 1 deletion src/routes/servers/edit.rs
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,7 @@ pub async fn edit(

Permissions::fetch_cached(&user, Some(&server), None)
.await?
.has(&[Permissions::MANAGE_SERVER])?;
.has(bits![MANAGE_SERVER])?;

server.merge(data);

Expand Down
2 changes: 1 addition & 1 deletion src/routes/servers/invites/delete.rs
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ pub async fn delete(
) -> Result<()> {
Permissions::fetch(&user, server_id.into(), None)
.await?
.has(&[Permissions::MANAGE_INVITES])?;
.has(bits![MANAGE_INVITES])?;

id.invite(server_id.into()).await?.remove().await?;

Expand Down
4 changes: 2 additions & 2 deletions src/routes/servers/members/edit.rs
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@ pub async fn edit(
let p = Permissions::fetch(&user, server_id.into(), None).await?;

if let Some(nickname) = &data.nickname {
p.has(&[Permissions::CHANGE_NICKNAME, Permissions::MANAGE_NICKNAMES])?;
p.has(bits![CHANGE_NICKNAME, MANAGE_NICKNAMES])?;

member.nickname = if nickname.is_empty() {
None
Expand All @@ -31,7 +31,7 @@ pub async fn edit(
}

if let Some(ids) = &data.roles {
p.has(&[Permissions::MANAGE_ROLES])?;
p.has(bits![MANAGE_ROLES])?;

let mut roles = Role::select()
.filter("server_id = $1")
Expand Down
2 changes: 1 addition & 1 deletion src/routes/servers/members/kick.rs
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ pub async fn kick(
if user.id != id {
Permissions::fetch(&user, server_id.into(), None)
.await?
.has(&[Permissions::KICK_MEMBERS])?;
.has(bits![KICK_MEMBERS])?;
}

id.member(server_id).await?.remove().await?;
Expand Down
2 changes: 1 addition & 1 deletion src/routes/servers/roles/create.rs
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,7 @@ pub async fn create(
) -> Result<Json<Role>> {
Permissions::fetch(&user, server_id.into(), None)
.await?
.has(&[Permissions::MANAGE_ROLES])?;
.has(bits![MANAGE_ROLES])?;

let count = Role::count(&format!("server_id = {}", server_id)).await?;

Expand Down
2 changes: 1 addition & 1 deletion src/routes/servers/roles/delete.rs
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ pub async fn delete(
) -> Result<()> {
Permissions::fetch(&user, server_id.into(), None)
.await?
.has(&[Permissions::MANAGE_ROLES])?;
.has(bits![MANAGE_ROLES])?;

id.role(server_id).await?.remove().await?;

Expand Down
2 changes: 1 addition & 1 deletion src/routes/servers/roles/edit.rs
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,7 @@ pub async fn edit(
) -> Result<Json<Role>> {
Permissions::fetch(&user, server_id.into(), None)
.await?
.has(&[Permissions::MANAGE_ROLES])?;
.has(bits![MANAGE_ROLES])?;

let mut role = id.role(server_id).await?;

Expand Down
15 changes: 5 additions & 10 deletions src/structures/server.rs
Original file line number Diff line number Diff line change
@@ -1,7 +1,5 @@
use super::*;
use crate::database::pool;
use crate::utils::permissions::*;
use crate::utils::snowflake;
use crate::utils::{permissions::*, snowflake};
use ormlite::model::*;
use serde::{Deserialize, Serialize};

Expand Down Expand Up @@ -42,32 +40,29 @@ impl Server {
.unwrap()
}

pub async fn fetch_member(&self, user_id: i64) -> Option<Member> {
pub async fn fetch_member(&self, user_id: i64) -> Result<Member, ormlite::Error> {
Member::select()
.filter("id = $1 AND server_id = $2")
.bind(user_id)
.bind(self.id)
.fetch_optional(pool())
.fetch_one(pool())
.await
.unwrap()
}

pub async fn fetch_roles(&self) -> Vec<Role> {
pub async fn fetch_roles(&self) -> Result<Vec<Role>, ormlite::Error> {
Role::select()
.filter("server_id = $1")
.bind(self.id)
.fetch_all(pool())
.await
.unwrap()
}

pub async fn fetch_channels(&self) -> Vec<Channel> {
pub async fn fetch_channels(&self) -> Result<Vec<Channel>, ormlite::Error> {
Channel::select()
.filter("server_id = $1")
.bind(self.id)
.fetch_all(pool())
.await
.unwrap()
}

#[cfg(test)]
Expand Down
1 change: 0 additions & 1 deletion src/structures/user.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,4 @@
use super::*;
use crate::database::pool;
use crate::utils::{snowflake, Badges};
use ormlite::model::*;
use serde::{Deserialize, Serialize};
Expand Down
15 changes: 7 additions & 8 deletions src/utils/badges.rs
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@ use std::fmt;

bitflags! {
#[derive(Default)]
pub struct Badges: u64 {
pub struct Badges: i64 {
const STAFF = 1 << 1;
const DEVELOPER = 1 << 2;
const SUPPORTER = 1 << 3;
Expand All @@ -35,8 +35,7 @@ impl Encode<'_, Postgres> for Badges {

impl<'r> Decode<'r, Postgres> for Badges {
fn decode(value: PgValueRef<'r>) -> Result<Self, BoxDynError> {
let bits: i64 = Decode::<Postgres>::decode(value)?;
Ok(Badges::from_bits(bits as u64).unwrap())
Ok(Badges::from_bits(Decode::<Postgres>::decode(value)?).unwrap())
}
}

Expand All @@ -62,24 +61,24 @@ impl<'de> Visitor<'de> for BadgesVisitor {
where
E: Error,
{
self.visit_u64(v.parse().map_err(E::custom)?)
self.visit_i64(v.parse().map_err(E::custom)?)
}

fn visit_str<E>(self, v: &str) -> Result<Self::Value, E>
where
E: Error,
{
self.visit_u64(v.parse().map_err(E::custom)?)
self.visit_i64(v.parse().map_err(E::custom)?)
}

fn visit_i64<E>(self, v: i64) -> Result<Self::Value, E>
fn visit_u64<E>(self, v: u64) -> Result<Self::Value, E>
where
E: Error,
{
self.visit_u64(v as u64)
self.visit_i64(v as i64)
}

fn visit_u64<E>(self, v: u64) -> Result<Self::Value, E>
fn visit_i64<E>(self, v: i64) -> Result<Self::Value, E>
where
E: Error,
{
Expand Down
2 changes: 1 addition & 1 deletion src/utils/email.rs
Original file line number Diff line number Diff line change
Expand Up @@ -74,7 +74,7 @@ pub async fn send(user: &User) -> bool {
}
}

pub async fn verify(user_id: u64, code: &str) -> bool {
pub async fn verify(user_id: i64, code: &str) -> bool {
match REDIS.get::<String, _>(user_id.to_string()).await {
Ok(token) if code == token => {
REDIS.del::<u32, _>(user_id.to_string()).await.ok();
Expand Down
4 changes: 2 additions & 2 deletions src/utils/error.rs
Original file line number Diff line number Diff line change
Expand Up @@ -23,8 +23,8 @@ quick_error! {
InvalidToken { display("Unauthorized. Provide a valid token and try again") }
EmailAlreadyInUse { display("This email already in use") }

MissingPermissions(missing: Vec<Permissions>) {
display("You lack permissions to perform that action, missing: {:?}", missing)
MissingPermissions(missing: Permissions) {
display("You lack permissions to perform that action, missing: {}", missing.bits())
}

EmptyMessage { display("Cannot send an empty message") }
Expand Down
Loading

0 comments on commit 2fcb8dc

Please sign in to comment.