Skip to content

Commit

Permalink
Merge branch 'dev' into mfa
Browse files Browse the repository at this point in the history
  • Loading branch information
kozabrada123 authored Oct 16, 2024
2 parents 090367b + 40754c5 commit 0984fc5
Show file tree
Hide file tree
Showing 9 changed files with 303 additions and 31 deletions.
8 changes: 4 additions & 4 deletions Cargo.lock

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

2 changes: 1 addition & 1 deletion Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -67,7 +67,7 @@ rand = "0.8.5"
flate2 = { version = "1.0.33", optional = true }
webpki-roots = "0.26.3"
pubserve = { version = "1.1.0", features = ["async", "send"] }
sqlx-pg-uint = { version = "0.7.2", features = ["serde"], optional = true }
sqlx-pg-uint = { version = "0.8.0", features = ["serde"], optional = true }

[target.'cfg(not(target_arch = "wasm32"))'.dependencies]
rustls = "0.21.12"
Expand Down
6 changes: 5 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -143,7 +143,11 @@ to run the tests for wasm.

## Versioning

This crate uses Semantic Versioning 2.0.0 as its versioning scheme. You can read the specification [here](https://semver.org/spec/v2.0.0.html).
Like other cargo crates, this crate uses Semantic Versioning 2.0.0 as its versioning scheme.
You can read the specification [here](https://semver.org/spec/v2.0.0.html).

Code gated behind the `backend` feature is not considered part of the public API and can change without
affecting semver compatibility. The `backend` feature is explicitly meant for use in [`symfonia`](https://github.com/polyphony-chat/symfonia)

## Contributing

Expand Down
29 changes: 15 additions & 14 deletions src/gateway/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@
// License, v. 2.0. If a copy of the MPL was not distributed with this
// file, You can obtain one at http://mozilla.org/MPL/2.0/.

#![allow(deprecated)] // Since Opcode variants marked as deprecated are being used here, we need to suppress the warnings about them being deprecated

pub mod backends;
pub mod events;
Expand All @@ -19,7 +20,7 @@ pub use message::*;
pub use options::*;

use crate::errors::GatewayError;
use crate::types::Snowflake;
use crate::types::{Opcode, Snowflake};

use std::any::Any;
use std::collections::HashMap;
Expand All @@ -29,51 +30,51 @@ use tokio::sync::Mutex;

// Gateway opcodes
/// Opcode received when the server dispatches a [crate::types::WebSocketEvent]
const GATEWAY_DISPATCH: u8 = 0;
const GATEWAY_DISPATCH: u8 = Opcode::Dispatch as u8;
/// Opcode sent when sending a heartbeat
const GATEWAY_HEARTBEAT: u8 = 1;
const GATEWAY_HEARTBEAT: u8 = Opcode::Heartbeat as u8;
/// Opcode sent to initiate a session
///
/// See [types::GatewayIdentifyPayload]
const GATEWAY_IDENTIFY: u8 = 2;
const GATEWAY_IDENTIFY: u8 = Opcode::Identify as u8;
/// Opcode sent to update our presence
///
/// See [types::GatewayUpdatePresence]
const GATEWAY_UPDATE_PRESENCE: u8 = 3;
const GATEWAY_UPDATE_PRESENCE: u8 = Opcode::PresenceUpdate as u8;
/// Opcode sent to update our state in vc
///
/// Like muting, deafening, leaving, joining..
///
/// See [types::UpdateVoiceState]
const GATEWAY_UPDATE_VOICE_STATE: u8 = 4;
const GATEWAY_UPDATE_VOICE_STATE: u8 = Opcode::VoiceStateUpdate as u8;
/// Opcode sent to resume a session
///
/// See [types::GatewayResume]
const GATEWAY_RESUME: u8 = 6;
const GATEWAY_RESUME: u8 = Opcode::Resume as u8;
/// Opcode received to tell the client to reconnect
const GATEWAY_RECONNECT: u8 = 7;
const GATEWAY_RECONNECT: u8 = Opcode::Reconnect as u8;
/// Opcode sent to request guild member data
///
/// See [types::GatewayRequestGuildMembers]
const GATEWAY_REQUEST_GUILD_MEMBERS: u8 = 8;
const GATEWAY_REQUEST_GUILD_MEMBERS: u8 = Opcode::RequestGuildMembers as u8;
/// Opcode received to tell the client their token / session is invalid
const GATEWAY_INVALID_SESSION: u8 = 9;
const GATEWAY_INVALID_SESSION: u8 = Opcode::InvalidSession as u8;
/// Opcode received when initially connecting to the gateway, starts our heartbeat
///
/// See [types::HelloData]
const GATEWAY_HELLO: u8 = 10;
const GATEWAY_HELLO: u8 = Opcode::Hello as u8;
/// Opcode received to acknowledge a heartbeat
const GATEWAY_HEARTBEAT_ACK: u8 = 11;
const GATEWAY_HEARTBEAT_ACK: u8 = Opcode::HeartbeatAck as u8;
/// Opcode sent to get the voice state of users in a given DM/group channel
///
/// See [types::CallSync]
const GATEWAY_CALL_SYNC: u8 = 13;
const GATEWAY_CALL_SYNC: u8 = Opcode::CallConnect as u8;
/// Opcode sent to get data for a server (Lazy Loading request)
///
/// Sent by the official client when switching to a server
///
/// See [types::LazyRequest]
const GATEWAY_LAZY_REQUEST: u8 = 14;
const GATEWAY_LAZY_REQUEST: u8 = Opcode::GuildSync as u8;

pub type ObservableObject = dyn Send + Sync + Any;

Expand Down
134 changes: 129 additions & 5 deletions src/types/entities/channel.rs
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ use serde_repr::{Deserialize_repr, Serialize_repr};
use std::fmt::{Debug, Formatter};
use std::str::FromStr;

use crate::errors::ChorusError;
use crate::types::{
entities::{GuildMember, User},
utils::Snowflake,
Expand All @@ -31,7 +32,7 @@ use serde::de::{Error, Visitor};
#[cfg(feature = "sqlx")]
use sqlx::types::Json;

use super::{option_arc_rwlock_ptr_eq, option_vec_arc_rwlock_ptr_eq};
use super::{option_arc_rwlock_ptr_eq, option_vec_arc_rwlock_ptr_eq, Emoji};

#[derive(Default, Debug, Serialize, Deserialize, Clone)]
#[cfg_attr(feature = "sqlx", derive(sqlx::FromRow))]
Expand All @@ -42,17 +43,23 @@ use super::{option_arc_rwlock_ptr_eq, option_vec_arc_rwlock_ptr_eq};
/// See <https://discord-userdoccers.vercel.app/resources/channel#channels-resource>
pub struct Channel {
pub application_id: Option<Snowflake>,
pub applied_tags: Option<Vec<String>>,
#[cfg(not(feature = "sqlx"))]
pub applied_tags: Option<Vec<Snowflake>>,
#[cfg(feature = "sqlx")]
pub applied_tags: Option<Json<Vec<Snowflake>>>,
#[cfg(not(feature = "sqlx"))]
pub available_tags: Option<Vec<Tag>>,
#[cfg(feature = "sqlx")]
pub available_tags: Option<Json<Vec<Tag>>>,
pub bitrate: Option<i32>,
#[serde(rename = "type")]
#[cfg_attr(feature = "sqlx", sqlx(rename = "type"))]
pub channel_type: ChannelType,
pub created_at: Option<chrono::DateTime<Utc>>,
pub default_auto_archive_duration: Option<i32>,
pub default_forum_layout: Option<i32>,
// DefaultReaction could be stored in a separate table. However, there are a lot of default emojis. How would we handle that?
pub default_forum_layout: Option<DefaultForumLayout>,
pub default_reaction_emoji: Option<DefaultReaction>,
pub default_sort_order: Option<i32>,
pub default_sort_order: Option<DefaultSortOrder>,
pub default_thread_rate_limit_per_user: Option<i32>,
pub flags: Option<i32>,
pub guild_id: Option<Snowflake>,
Expand Down Expand Up @@ -325,6 +332,15 @@ pub struct DefaultReaction {
pub emoji_name: Option<String>,
}

impl From<Emoji> for DefaultReaction {
fn from(value: Emoji) -> Self {
Self {
emoji_id: Some(value.id),
emoji_name: value.name,
}
}
}

#[derive(
Default,
Clone,
Expand Down Expand Up @@ -401,3 +417,111 @@ pub struct FollowedChannel {
pub channel_id: Snowflake,
pub webhook_id: Snowflake,
}

#[derive(
Debug, Deserialize, Serialize, Clone, PartialEq, Eq, Copy, Hash, PartialOrd, Ord, Default,
)]
#[serde(rename_all = "SCREAMING_SNAKE_CASE")]
#[repr(u8)]
pub enum DefaultForumLayout {
#[default]
Default = 0,
List = 1,
Grid = 2,
}

impl TryFrom<u8> for DefaultForumLayout {
type Error = ChorusError;

fn try_from(value: u8) -> Result<Self, Self::Error> {
match value {
0 => Ok(DefaultForumLayout::Default),
1 => Ok(DefaultForumLayout::List),
2 => Ok(DefaultForumLayout::Grid),
_ => Err(ChorusError::InvalidArguments {
error: "Value is not a valid DefaultForumLayout".to_string(),
}),
}
}
}

#[cfg(feature = "sqlx")]
impl sqlx::Type<sqlx::Postgres> for DefaultForumLayout {
fn type_info() -> <sqlx::Postgres as sqlx::Database>::TypeInfo {
<sqlx_pg_uint::PgU8 as sqlx::Type<sqlx::Postgres>>::type_info()
}
}

#[cfg(feature = "sqlx")]
impl<'q> sqlx::Encode<'q, sqlx::Postgres> for DefaultForumLayout {
fn encode_by_ref(
&self,
buf: &mut <sqlx::Postgres as sqlx::Database>::ArgumentBuffer<'q>,
) -> Result<sqlx::encode::IsNull, sqlx::error::BoxDynError> {
let sqlx_pg_uint = sqlx_pg_uint::PgU8::from(*self as u8);
sqlx_pg_uint.encode_by_ref(buf)
}
}

#[cfg(feature = "sqlx")]
impl<'r> sqlx::Decode<'r, sqlx::Postgres> for DefaultForumLayout {
fn decode(
value: <sqlx::Postgres as sqlx::Database>::ValueRef<'r>,
) -> Result<Self, sqlx::error::BoxDynError> {
let sqlx_pg_uint = sqlx_pg_uint::PgU8::decode(value)?;
DefaultForumLayout::try_from(sqlx_pg_uint.to_uint()).map_err(|e| e.into())
}
}

#[derive(
Debug, Deserialize, Serialize, Clone, PartialEq, Eq, Copy, Hash, PartialOrd, Ord, Default,
)]
#[serde(rename_all = "SCREAMING_SNAKE_CASE")]
#[repr(u8)]
pub enum DefaultSortOrder {
#[default]
LatestActivity = 0,
CreationTime = 1,
}

impl TryFrom<u8> for DefaultSortOrder {
type Error = ChorusError;

fn try_from(value: u8) -> Result<Self, Self::Error> {
match value {
0 => Ok(DefaultSortOrder::LatestActivity),
1 => Ok(DefaultSortOrder::CreationTime),
_ => Err(ChorusError::InvalidArguments {
error: "Value is not a valid DefaultSearchOrder".to_string(),
}),
}
}
}

#[cfg(feature = "sqlx")]
impl sqlx::Type<sqlx::Postgres> for DefaultSortOrder {
fn type_info() -> <sqlx::Postgres as sqlx::Database>::TypeInfo {
<sqlx_pg_uint::PgU8 as sqlx::Type<sqlx::Postgres>>::type_info()
}
}

#[cfg(feature = "sqlx")]
impl<'q> sqlx::Encode<'q, sqlx::Postgres> for DefaultSortOrder {
fn encode_by_ref(
&self,
buf: &mut <sqlx::Postgres as sqlx::Database>::ArgumentBuffer<'q>,
) -> Result<sqlx::encode::IsNull, sqlx::error::BoxDynError> {
let sqlx_pg_uint = sqlx_pg_uint::PgU8::from(*self as u8);
sqlx_pg_uint.encode_by_ref(buf)
}
}

#[cfg(feature = "sqlx")]
impl<'r> sqlx::Decode<'r, sqlx::Postgres> for DefaultSortOrder {
fn decode(
value: <sqlx::Postgres as sqlx::Database>::ValueRef<'r>,
) -> Result<Self, sqlx::error::BoxDynError> {
let sqlx_pg_uint = sqlx_pg_uint::PgU8::decode(value)?;
DefaultSortOrder::try_from(sqlx_pg_uint.to_uint()).map_err(|e| e.into())
}
}
11 changes: 7 additions & 4 deletions src/types/entities/user.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@

use crate::errors::ChorusError;
use crate::types::utils::Snowflake;
use crate::{UInt32, UInt8};
use crate::UInt32;
use chrono::{DateTime, Utc};
use serde::{Deserialize, Serialize};
use serde_aux::prelude::{deserialize_default_from_null, deserialize_option_number_from_string};
Expand Down Expand Up @@ -826,11 +826,14 @@ pub struct MutualGuild {
#[cfg_attr(feature = "sqlx", derive(sqlx::FromRow))]
pub struct UserNote {
/// Actual note contents; max 256 characters
pub note: String,
#[serde(rename = "note")]
pub content: String,
/// The ID of the user the note is on
pub note_user_id: Snowflake,
#[serde(rename = "note_user_id")]
pub target_id: Snowflake,
/// The ID of the user who created the note (always the current user)
pub user_id: Snowflake,
#[serde(rename = "user_id")]
pub author_id: Snowflake,
}

/// Structure which defines an affinity the local user has with another user.
Expand Down
1 change: 1 addition & 0 deletions src/types/schema/channel.rs
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ use serde::{Deserialize, Serialize};

use crate::types::{entities::PermissionOverwrite, ChannelType, DefaultReaction, Snowflake};

// TODO: Needs updating
#[derive(Debug, Deserialize, Serialize, Default, PartialEq, PartialOrd)]
#[serde(rename_all = "snake_case")]
pub struct ChannelCreateSchema {
Expand Down
5 changes: 3 additions & 2 deletions src/types/utils/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,13 +3,14 @@
// file, You can obtain one at http://mozilla.org/MPL/2.0/.

#![allow(unused_imports)]
pub use opcode::*;
pub use regexes::*;
pub use rights::Rights;
pub use snowflake::Snowflake;

pub mod jwt;
pub mod opcode;
mod regexes;
mod rights;
mod snowflake;
pub mod serde;

mod snowflake;
Loading

0 comments on commit 0984fc5

Please sign in to comment.