Compare commits

...
58 Commits
Author SHA1 Message Date
Paul Makles 49035f4817 feat: ratelimit user edit route and discriminator changes 2023-06-15 19:24:53 +01:00
Paul Makles c0ebaa0bd3 chore: include discriminator in ban list response 2023-06-15 19:23:47 +01:00
Paul Makles b98b244fc3 fix: enable staging for API spec generation 2023-06-15 15:21:00 +01:00
Paul Makles c8d5128b0c chore: add additional sanitisation 2023-06-11 12:26:18 +01:00
Paul Makles 0578a05a05 feat: add remove "displayname" field 2023-06-11 12:05:08 +01:00
Paul Makles 9a412b3e08 fix: actually update the display name 2023-06-11 11:50:21 +01:00
Paul Makles 8deec1f80a fix: display name is optional 2023-06-11 10:56:03 +01:00
Paul Makles 26afbeed84 chore: extend discriminator block list 2023-06-11 10:49:51 +01:00
Paul Makles 9975de01bc chore: remove webhooks from production 2023-06-11 10:09:50 +01:00
Paul Makles ac525466b8 chore: cut a new release (0.6.0) 2023-06-11 10:04:15 +01:00
Paul Makles c7a04e4559 fix: conflict resolution in migration
fix: write new username and display name
chore: restrict discriminator search space
2023-06-11 09:53:41 +01:00
Paul Makles 5bbe30edbc feat(core/database): migrate to discriminators 2023-06-11 09:16:24 +01:00
Paul Makles 31c7dc0577 feat: add discriminator and display name fields 2023-06-09 16:34:18 +01:00
Paul Makles aba5c7d8af fix: shouldn't prefix dep: 2023-06-04 19:45:47 +01:00
Paul Makles 2f4ea4cabb refactor(core/models): transitively apply feature flags 2023-06-04 19:45:31 +01:00
Paul Makles 7e801a31bd fix: make sure feature flags are respected 2023-06-04 19:43:56 +01:00
Paul Makles eb4870c9d5 fix: explicitly target Rust 1.70.0 for images 2023-06-04 19:42:42 +01:00
Paul Makles b1fdd7fc74 merge: pull request #251 from revoltchat/fix/zomatree/send-message-null 2023-06-04 19:29:07 +01:00
Paul MaklesandToastXC bf3e027067 feat: channel model implementation (#250)
Co-authored-by: ToastXC <100072983+toastxc@users.noreply.github.com>
2023-06-04 18:52:49 +01:00
Zomatree a7a7e49e18 fix: send message route not accepting null 2023-06-04 18:46:49 +01:00
Paul Makles 3c834d06d4 fix: must not restrict lowerbound for embeds 2023-06-03 17:49:31 +01:00
Paul Makles f5e6086d2a fix(core/database): test matches incorrect entry
[skip ci]
2023-06-03 17:15:43 +01:00
Paul Makles 3365a8e482 chore: force bind to 0.0.0.0 because it's just ignoring all environment variables??? 2023-06-03 17:05:25 +01:00
Paul Makles 268c2d1355 fix: re-order crate publishing 2023-06-03 14:11:44 +01:00
Paul Makles e9d6b963df chore: bump version to 0.6.0-rc.1 2023-06-03 14:06:04 +01:00
Paul Makles f9d9447203 feat: add additional validation for github webhook 2023-06-03 14:02:16 +01:00
Paul Makles a0002d0b43 feat: reintroduce permission checks for send 2023-06-03 14:00:17 +01:00
Paul Makles 23188032ca refactor(delta): port routes to core webhook models 2023-06-03 13:01:43 +01:00
Paul Makles f9f5a30e2c refactor(quark): strip webhook code 2023-06-03 13:01:28 +01:00
Paul Makles e393e17b59 feat(core/result): add rocket and okapi support 2023-06-03 13:01:12 +01:00
Paul Makles a29d8f6aab refactor(core/models): swap dependency order with db
feat(core/models): implement webhook model
2023-06-03 13:01:01 +01:00
Paul Makles 1dbbc3ed8d feat(core/database): implement webhook model 2023-06-03 13:00:05 +01:00
Paul Makles 410acb5b5c merge: branch 'master' into webhooks 2023-06-02 18:55:32 +01:00
Paul Makles 53c9160cd6 feat: implement creating strikes
feat: add moderator_id to strikes
fix: use correct collection for strikes
2023-05-31 19:04:20 +01:00
Zomatree 175866ce00 Merge remote-tracking branch 'revoltchat/master' into webhooks 2023-04-25 20:38:09 +01:00
Zomatree 8c5de18991 restrict webhooks to text and group dm channels 2023-04-25 20:30:16 +01:00
Zomatree 57f00a283b make request function names the same as file name 2023-04-20 17:52:10 +01:00
Zomatree 312e1dd41f update code to be inline with reviews 2023-04-20 17:45:48 +01:00
Zomatree 426d836a09 Merge remote-tracking branch 'revoltchat/master' into webhooks 2023-04-18 19:50:04 +01:00
Zomatree 2fad66d24a only send a subsect of the webhook in a message 2023-04-18 19:39:34 +01:00
Zomatree 83429f9f65 fix broken merge conflict 2023-04-01 23:09:29 +01:00
Angelo Kontaxis a60ae78176 Merge branch 'master' into webhooks 2023-04-01 22:52:11 +01:00
Zomatree 7b39f4e9d9 change how webhook information is in the webhook 2023-04-01 22:49:34 +01:00
Zomatree 01577fd798 avoid leaking the token in events 2023-03-11 23:24:10 +00:00
Zomatree fca91e1560 update upstream code 2023-03-01 11:49:28 +00:00
Angelo Kontaxis 3c881a40a6 Merge branch 'master' into webhooks 2023-02-23 17:26:59 +00:00
Zomatree c7849a82bf Merge branch 'master' of github.com:revoltchat/backend into webhooks 2023-01-27 17:27:32 +00:00
Zomatree 781d51df6f add seperate non token webhook routes 2023-01-27 17:26:32 +00:00
Zomatree 758b1e43e7 no longer make mesage_send.rs public 2023-01-24 22:54:09 +00:00
Zomatree 5cc8231c36 deduplicate message sending 2023-01-24 22:52:18 +00:00
Zomatree 7b447faefa add pull request events 2023-01-21 22:57:12 +00:00
Zomatree a017256e95 add more events 2023-01-20 20:15:12 +00:00
Zomatree 1050891d87 Merge branch 'master' of github.com:revoltchat/backend into webhooks 2023-01-20 20:04:18 +00:00
Zomatree a246cff7f0 Merge branch 'master' of github.com:revoltchat/backend into webhooks 2023-01-18 21:03:15 +00:00
Zomatree c218db5047 add push event 2022-12-30 22:44:36 +00:00
Zomatree c7f2f3614f star event 2022-12-30 18:08:43 +00:00
Zomatree c826d8cf07 add github webhook support 2022-11-27 06:52:44 +00:00
Zomatree 5cb2320760 inital webhook support 2022-11-26 23:07:22 +00:00
100 changed files with 5277 additions and 655 deletions
+3
View File
@@ -59,6 +59,9 @@ REVOLT_UNSAFE_NO_EMAIL=1
## Application Settings
##
# Whether to enable staging only features
REVOLT_IS_STAGING=1
# Whether to only allow users to sign up if they have an invite code
REVOLT_INVITE_ONLY=0
Generated
+62 -34
View File
@@ -806,6 +806,12 @@ dependencies = [
"uuid",
]
[[package]]
name = "decancer"
version = "1.6.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "808127a7de612079ec37bfc1abc48ed77a6015a971a8bd7d4178d79147cbc839"
[[package]]
name = "derivative"
version = "2.2.0"
@@ -2837,7 +2843,7 @@ dependencies = [
[[package]]
name = "revolt-bonfire"
version = "0.5.20"
version = "0.6.3"
dependencies = [
"async-std",
"async-tungstenite",
@@ -2854,7 +2860,7 @@ dependencies = [
[[package]]
name = "revolt-database"
version = "0.0.2"
version = "0.6.3"
dependencies = [
"async-recursion",
"async-std",
@@ -2867,7 +2873,12 @@ dependencies = [
"mongodb",
"nanoid",
"once_cell",
"rand 0.8.5",
"redis-kiss",
"regex",
"revolt-models",
"revolt-permissions",
"revolt-presence",
"revolt-result",
"revolt_optional_struct",
"rocket",
@@ -2875,11 +2886,12 @@ dependencies = [
"serde",
"serde_json",
"ulid 1.0.0",
"unicode-segmentation",
]
[[package]]
name = "revolt-delta"
version = "0.5.20"
version = "0.6.3"
dependencies = [
"async-channel",
"async-std",
@@ -2901,7 +2913,9 @@ dependencies = [
"reqwest",
"revolt-database",
"revolt-models",
"revolt-permissions",
"revolt-quark",
"revolt-result",
"revolt_rocket_okapi",
"rocket",
"rocket_authifier",
@@ -2911,27 +2925,29 @@ dependencies = [
"serde_json",
"ulid 0.4.1",
"url",
"validator 0.14.0",
"validator 0.16.0",
"vergen",
]
[[package]]
name = "revolt-models"
version = "0.0.2"
version = "0.6.3"
dependencies = [
"revolt-database",
"revolt-presence",
"revolt-permissions",
"revolt_optional_struct",
"schemars",
"serde",
"validator 0.16.0",
]
[[package]]
name = "revolt-permissions"
version = "0.0.2"
version = "0.6.3"
dependencies = [
"async-std",
"async-trait",
"auto_ops",
"bson",
"num_enum 0.6.1",
"once_cell",
"schemars",
@@ -2940,7 +2956,7 @@ dependencies = [
[[package]]
name = "revolt-presence"
version = "0.0.2"
version = "0.6.3"
dependencies = [
"async-std",
"log",
@@ -2951,7 +2967,7 @@ dependencies = [
[[package]]
name = "revolt-quark"
version = "0.5.20"
version = "0.6.3"
dependencies = [
"async-lock",
"async-recursion",
@@ -2964,6 +2980,7 @@ dependencies = [
"bson",
"dashmap",
"deadqueue",
"decancer",
"dotenv",
"futures",
"impl_ops",
@@ -2981,6 +2998,8 @@ dependencies = [
"redis-kiss",
"regex",
"reqwest",
"revolt-database",
"revolt-models",
"revolt-presence",
"revolt-result",
"revolt_okapi",
@@ -2995,16 +3014,20 @@ dependencies = [
"serde",
"serde_json",
"ulid 0.5.0",
"validator 0.14.0",
"validator 0.16.0",
"web-push",
]
[[package]]
name = "revolt-result"
version = "0.0.2"
version = "0.6.3"
dependencies = [
"revolt_okapi",
"revolt_rocket_okapi",
"rocket",
"schemars",
"serde",
"serde_json",
]
[[package]]
@@ -4315,6 +4338,12 @@ dependencies = [
"tinyvec",
]
[[package]]
name = "unicode-segmentation"
version = "1.10.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "1dd624098567895118886609431a7c3b8f516e41d30e0643f03d94592a147e36"
[[package]]
name = "unicode-xid"
version = "0.0.4"
@@ -4378,23 +4407,6 @@ dependencies = [
"serde",
]
[[package]]
name = "validator"
version = "0.14.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "6d0f08911ab0fee2c5009580f04615fa868898ee57de10692a45da0c3bcc3e5e"
dependencies = [
"idna",
"lazy_static",
"regex",
"serde",
"serde_derive",
"serde_json",
"url",
"validator_derive",
"validator_types",
]
[[package]]
name = "validator"
version = "0.15.0"
@@ -4411,10 +4423,26 @@ dependencies = [
]
[[package]]
name = "validator_derive"
version = "0.14.0"
name = "validator"
version = "0.16.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "d85135714dba11a1bd0b3eb1744169266f1a38977bf4e3ff5e2e1acb8c2b7eee"
checksum = "32ad5bf234c7d3ad1042e5252b7eddb2c4669ee23f32c7dd0e9b7705f07ef591"
dependencies = [
"idna",
"lazy_static",
"regex",
"serde",
"serde_derive",
"serde_json",
"url",
"validator_derive",
]
[[package]]
name = "validator_derive"
version = "0.16.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "bc44ca3088bb3ba384d9aecf40c6a23a676ce23e09bdaca2073d99c207f864af"
dependencies = [
"if_chain",
"lazy_static",
@@ -4428,9 +4456,9 @@ dependencies = [
[[package]]
name = "validator_types"
version = "0.14.0"
version = "0.16.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "ded9d97e1d42327632f5f3bae6403c04886e2de3036261ef42deebd931a6a291"
checksum = "111abfe30072511849c5910134e8baf8dc05de4c0e5903d681cbd5c9c4d611e3"
dependencies = [
"proc-macro2",
"syn 1.0.107",
+1 -1
View File
@@ -1,5 +1,5 @@
# Build Stage
FROM --platform="${BUILDPLATFORM}" rust:slim
FROM --platform="${BUILDPLATFORM}" rust:1.70.0-slim
USER 0:0
WORKDIR /home/rust/src
+5 -2
View File
@@ -2,11 +2,14 @@ disallowed-methods = [
# Shouldn't need to access these directly
"revolt_database::models::bots::model::Bot::remove_field",
# Prefer to use Object::update()
# Prefer to use Object::create()
"revolt_database::models::safety_strikes::ops::AbstractAccountStrikes::insert_account_strike",
# Prefer to use Object::update(&self)
"revolt_database::models::bots::ops::AbstractBots::update_bot",
"revolt_database::models::safety_strikes::ops::AbstractAccountStrikes::update_account_strike",
# Prefer to use Object::delete()
# Prefer to use Object::delete(&self)
"revolt_database::models::bots::ops::AbstractBots::delete_bot",
"revolt_database::models::safety_strikes::ops::AbstractAccountStrikes::delete_account_strike",
]
+1 -1
View File
@@ -1,6 +1,6 @@
[package]
name = "revolt-bonfire"
version = "0.5.20"
version = "0.6.3"
license = "AGPL-3.0-or-later"
edition = "2021"
+14 -3
View File
@@ -1,6 +1,6 @@
[package]
name = "revolt-database"
version = "0.0.2"
version = "0.6.3"
edition = "2021"
license = "AGPL-3.0-or-later"
authors = [ "Paul Makles <me@insrt.uk>" ]
@@ -15,17 +15,21 @@ mongodb = [ "dep:mongodb", "bson" ]
# ... Other
async-std-runtime = [ "async-std" ]
rocket-impl = [ "rocket", "schemars" ]
redis-is-patched = [ "revolt-presence/redis-is-patched" ]
# Default Features
default = [ "mongodb", "async-std-runtime" ]
[dependencies]
# Core
revolt-result = { version = "0.0.2", path = "../result" }
revolt-permissions = { version = "0.0.2", path = "../permissions", features = [ "serde" ] }
revolt-result = { version = "0.6.3", path = "../result" }
revolt-models = { version = "0.6.3", path = "../models" }
revolt-presence = { version = "0.6.3", path = "../presence" }
revolt-permissions = { version = "0.6.3", path = "../permissions", features = [ "serde", "bson" ] }
# Utility
log = "0.4"
rand = "0.8.5"
ulid = "1.0.0"
nanoid = "0.4.0"
once_cell = "1.17"
@@ -36,10 +40,17 @@ revolt_optional_struct = "0.2.0"
serde = { version = "1", features = ["derive"] }
iso8601-timestamp = { version = "0.2.10", features = ["serde", "bson"] }
# Events
redis-kiss = { version = "0.1.4" }
# Database
bson = { optional = true, version = "2.1.0" }
mongodb = { optional = true, version = "2.1.0", default-features = false }
# Database Migration
unicode-segmentation = "1.10.1"
regex = "1"
# Async Language Features
futures = "0.3.19"
async-trait = "0.1.51"
@@ -2,7 +2,10 @@ use std::{collections::HashMap, sync::Arc};
use futures::lock::Mutex;
use crate::{AccountStrike, Bot, File, Member, MemberCompositeKey, Server, User, UserSettings};
use crate::{
AccountStrike, Bot, Channel, File, Member, MemberCompositeKey, Server, User, UserSettings,
Webhook,
};
database_derived!(
/// Reference implementation
@@ -10,18 +13,18 @@ database_derived!(
pub struct ReferenceDb {
pub account_strikes: Arc<Mutex<HashMap<String, AccountStrike>>>,
pub bots: Arc<Mutex<HashMap<String, Bot>>>,
pub channel_webhooks: Arc<Mutex<HashMap<String, Webhook>>>,
pub user_settings: Arc<Mutex<HashMap<String, UserSettings>>>,
pub users: Arc<Mutex<HashMap<String, User>>>,
pub server_members: Arc<Mutex<HashMap<MemberCompositeKey, Member>>>,
pub servers: Arc<Mutex<HashMap<String, Server>>>,
pub files: Arc<Mutex<HashMap<String, File>>>,
pub server_bans: Arc<Mutex<HashMap<String, ()>>>,
pub safety_reports: Arc<Mutex<HashMap<String, ()>>>,
pub safety_snapshots: Arc<Mutex<HashMap<String, ()>>>,
pub emoji: Arc<Mutex<HashMap<String, ()>>>,
pub messages: Arc<Mutex<HashMap<String, ()>>>,
pub channels: Arc<Mutex<HashMap<String, ()>>>,
pub channels: Arc<Mutex<HashMap<String, Channel>>>,
pub channel_invites: Arc<Mutex<HashMap<String, ()>>>,
pub channel_unreads: Arc<Mutex<HashMap<String, ()>>>,
}
+269
View File
@@ -0,0 +1,269 @@
use authifier::AuthifierEvent;
use serde::{Deserialize, Serialize};
use revolt_models::v0::{
Channel, FieldsChannel, FieldsWebhook, PartialChannel, PartialWebhook, Webhook,
};
use revolt_result::Error;
use crate::Database;
/// WebSocket Client Errors
#[derive(Serialize, Deserialize, Debug, Clone)]
#[serde(tag = "error")]
pub enum WebSocketError {
LabelMe,
InternalError { at: String },
InvalidSession,
OnboardingNotFinished,
AlreadyAuthenticated,
MalformedData { msg: String },
}
/// Ping Packet
#[derive(Serialize, Deserialize, Debug, Clone)]
#[serde(untagged)]
pub enum Ping {
Binary(Vec<u8>),
Number(usize),
}
/// Untagged Error
#[derive(Serialize)]
#[serde(untagged)]
pub enum ErrorEvent {
Error(WebSocketError),
APIError(Error),
}
/// Protocol Events
#[derive(Serialize, Deserialize, Debug, Clone)]
#[serde(tag = "type")]
pub enum EventV1 {
/// Multiple events
Bulk { v: Vec<EventV1> },
/// Successfully authenticated
Authenticated,
/* /// Basic data to cache
Ready {
users: Vec<User>,
servers: Vec<Server>,
channels: Vec<Channel>,
members: Vec<Member>,
emojis: Option<Vec<Emoji>>,
},
/// Ping response
Pong { data: Ping },
/// New message
Message(Message),
/// Update existing message
MessageUpdate {
id: String,
channel: String,
data: PartialMessage,
},
/// Append information to existing message
MessageAppend {
id: String,
channel: String,
append: AppendMessage,
},
/// Delete message
MessageDelete { id: String, channel: String },
/// New reaction to a message
MessageReact {
id: String,
channel_id: String,
user_id: String,
emoji_id: String,
},
/// Remove user's reaction from message
MessageUnreact {
id: String,
channel_id: String,
user_id: String,
emoji_id: String,
},
/// Remove a reaction from message
MessageRemoveReaction {
id: String,
channel_id: String,
emoji_id: String,
},
/// Bulk delete messages
BulkMessageDelete { channel: String, ids: Vec<String> },
/// New server
ServerCreate {
id: String,
server: Server,
channels: Vec<Channel>,
},
/// Update existing server
ServerUpdate {
id: String,
data: PartialServer,
clear: Vec<FieldsServer>,
},
/// Delete server
ServerDelete { id: String },
/// Update existing server member
ServerMemberUpdate {
id: MemberCompositeKey,
data: PartialMember,
clear: Vec<FieldsMember>,
},
/// User joins server
ServerMemberJoin { id: String, user: String },
/// User left server
ServerMemberLeave { id: String, user: String },
/// Server role created or updated
ServerRoleUpdate {
id: String,
role_id: String,
data: PartialRole,
clear: Vec<FieldsRole>,
},
/// Server role deleted
ServerRoleDelete { id: String, role_id: String },
/// Update existing user
UserUpdate {
id: String,
data: PartialUser,
clear: Vec<FieldsUser>,
event_id: Option<String>,
},
/// Relationship with another user changed
UserRelationship {
id: String,
user: User,
// ! this field can be deprecated
status: RelationshipStatus,
},
/// Settings updated remotely
UserSettingsUpdate { id: String, update: UserSettings },
/// User has been platform banned or deleted their account
///
/// Clients should remove the following associated data:
/// - Messages
/// - DM Channels
/// - Relationships
/// - Server Memberships
///
/// User flags are specified to explain why a wipe is occurring though not all reasons will necessarily ever appear.
UserPlatformWipe { user_id: String, flags: i32 },
/// New emoji
EmojiCreate(Emoji),
/// Delete emoji
EmojiDelete { id: String },
/// New report
ReportCreate(Report), */
/// New channel
ChannelCreate(Channel),
/// Update existing channel
ChannelUpdate {
id: String,
data: PartialChannel,
clear: Vec<FieldsChannel>,
},
/// Delete channel
ChannelDelete { id: String },
/// User joins a group
ChannelGroupJoin { id: String, user: String },
/// User leaves a group
ChannelGroupLeave { id: String, user: String },
/// User started typing in a channel
ChannelStartTyping { id: String, user: String },
/// User stopped typing in a channel
ChannelStopTyping { id: String, user: String },
/// User acknowledged message in channel
ChannelAck {
id: String,
user: String,
message_id: String,
},
/// New webhook
WebhookCreate(Webhook),
/// Update existing webhook
WebhookUpdate {
id: String,
data: PartialWebhook,
remove: Vec<FieldsWebhook>,
},
/// Delete webhook
WebhookDelete { id: String },
/// Auth events
Auth(AuthifierEvent),
}
impl EventV1 {
/// Publish helper wrapper
pub async fn p(self, channel: String) {
#[cfg(not(debug_assertions))]
redis_kiss::p(channel, self).await;
#[cfg(debug_assertions)]
info!("Publishing event to {channel}: {self:?}");
#[cfg(debug_assertions)]
redis_kiss::publish(channel, self).await.unwrap();
}
/// Publish user event
pub async fn p_user(self, id: String, db: &Database) {
self.clone().p(id.clone()).await;
// ! FIXME: this should be captured by member list in the future
// ! and not immediately fanned out to users
if let Ok(members) = db.fetch_all_memberships(&id).await {
for member in members {
self.clone().p(member.id.server).await;
}
}
}
/// Publish private event
pub async fn private(self, id: String) {
self.p(format!("{id}!")).await;
}
/// Publish internal global event
pub async fn global(self) {
self.p("global".to_string()).await;
}
}
+1
View File
@@ -0,0 +1 @@
pub mod client;
+2
View File
@@ -80,6 +80,8 @@ mod models;
pub mod util;
pub use models::*;
pub mod events;
/// Utility function to check if a boolean value is false
pub fn if_false(t: &bool) -> bool {
!t
@@ -44,6 +44,10 @@ pub async fn create_database(db: &MongoDb) {
.await
.expect("Failed to create channel_unreads collection.");
db.create_collection("channel_webhooks", None)
.await
.expect("Failed to create channel_webhooks collection.");
db.create_collection("migrations", None)
.await
.expect("Failed to create migrations collection.");
@@ -72,6 +76,10 @@ pub async fn create_database(db: &MongoDb) {
.await
.expect("Failed to create bots collection.");
db.create_collection("ratelimit_events", None)
.await
.expect("Failed to create ratelimit_events collection.");
db.create_collection(
"pubsub",
CreateCollectionOptions::builder()
@@ -91,6 +99,18 @@ pub async fn create_database(db: &MongoDb) {
"username": 1_i32
},
"name": "username",
"unique": false,
"collation": {
"locale": "en",
"strength": 2_i32
}
},
{
"key": {
"username": 1_i32,
"discriminator": 1_i32
},
"name": "username_discriminator",
"unique": true,
"collation": {
"locale": "en",
@@ -193,5 +213,24 @@ pub async fn create_database(db: &MongoDb) {
.await
.expect("Failed to save migration info.");
db.run_command(
doc! {
"createIndexes": "ratelimit_events",
"indexes": [
{
"key": {
"_id": 1_i32,
"target_id": 1_i32,
"event_type": 1_i32,
},
"name": "compound_key"
}
]
},
None,
)
.await
.expect("Failed to create ratelimit_events index.");
info!("Created database.");
}
@@ -1,14 +1,16 @@
use std::{ops::BitXor, time::Duration};
use std::{collections::HashSet, ops::BitXor, time::Duration};
use crate::{
mongodb::{
bson::{doc, from_bson, from_document, to_document, Bson, DateTime, Document},
options::FindOptions,
},
MongoDb,
MongoDb, DISCRIMINATOR_SEARCH_SPACE,
};
use futures::StreamExt;
use rand::seq::SliceRandom;
use serde::{Deserialize, Serialize};
use unicode_segmentation::UnicodeSegmentation;
#[derive(Serialize, Deserialize)]
struct MigrationInfo {
@@ -16,7 +18,7 @@ struct MigrationInfo {
revision: i32,
}
pub const LATEST_REVISION: i32 = 22;
pub const LATEST_REVISION: i32 = 26;
pub async fn migrate_database(db: &MongoDb) {
let migrations = db.col::<Document>("migrations");
@@ -751,8 +753,231 @@ pub async fn run_migrations(db: &MongoDb, revision: i32) -> i32 {
.unwrap();
}
if revision <= 22 {
info!("Running migration [revision 22 / 31-05-2023]: Add moderator_id to account strikes.");
db.col::<Document>("safety_strikes")
.update_many(
doc! {},
doc! {
"$set": {
"moderator_id": "01EX2NCWQ0CHS3QJF0FEQS1GR4"
}
},
None,
)
.await
.expect("Failed to update server members.");
}
if revision <= 23 {
info!("Running migration [revision 23 / 10-06-2023]: Generate discriminators for users.");
db.db()
.run_command(
doc! {
"dropIndexes": "users",
"index": "username"
},
None,
)
.await
.expect("Failed to drop existing username index.");
#[derive(Serialize, Deserialize)]
struct UserInformation {
#[serde(rename = "_id")]
id: String,
username: String,
}
let re_username = regex::Regex::new(r"^(\p{L}|[\d_.-])+$").unwrap();
let users: Vec<UserInformation> = db
.col::<UserInformation>("users")
.find(doc! {}, None)
.await
.unwrap()
.map(|doc| doc.expect("id and username"))
.collect()
.await;
let search_space: Vec<String> = DISCRIMINATOR_SEARCH_SPACE.iter().cloned().collect();
let mut claimed: HashSet<String> = HashSet::new();
for i in 0..users.len() {
let info = &users[i];
let mut discriminator = {
let mut rng = rand::thread_rng();
search_space.choose(&mut rng).unwrap()
};
if re_username.is_match(&info.username) {
while claimed.contains(&format!("{}#{}", info.username, discriminator)) {
let new_discriminator = {
let mut rng = rand::thread_rng();
search_space.choose(&mut rng).unwrap()
};
info!(
"Re-rolled {} to {new_discriminator} from {discriminator}",
info.username
);
discriminator = new_discriminator;
}
claimed.insert(format!("{}#{}", info.username, discriminator));
info!(
"({}/{}) Migrating user \"{}\" to #{} - compliant",
i + 1,
users.len(),
info.username,
discriminator
);
db.col::<UserInformation>("users")
.update_one(
doc! {
"_id": &info.id
},
doc! {
"$set": {
"discriminator": discriminator
}
},
None,
)
.await
.unwrap();
} else {
let mut sanitised = info
.username
.graphemes(true)
.filter(|s| re_username.is_match(s))
.collect::<String>();
while sanitised.len() < 2 {
sanitised += "_";
}
while claimed.contains(&format!("{}#{}", sanitised, discriminator)) {
let new_discriminator = {
let mut rng = rand::thread_rng();
search_space.choose(&mut rng).unwrap()
};
info!("Re-rolled {sanitised} to {new_discriminator} from {discriminator}");
discriminator = new_discriminator;
}
claimed.insert(format!("{}#{}", sanitised, discriminator));
info!(
"({}/{}) Migrating user \"{}\" to #{} - sanitised: \"{}\"",
i + 1,
users.len(),
info.username,
discriminator,
sanitised
);
db.col::<UserInformation>("users")
.update_one(
doc! {
"_id": &info.id
},
doc! {
"$set": {
"username": sanitised,
"discriminator": discriminator,
"display_name": &info.username
}
},
None,
)
.await
.unwrap();
}
}
}
if revision <= 24 {
info!("Running migration [revision 24 / 09-06-2023]: Add collection `channel_webhooks` if not exists, update users index.");
db.db()
.create_collection("channel_webhooks", None)
.await
.ok();
db.db()
.run_command(
doc! {
"createIndexes": "users",
"indexes": [
{
"key": {
"username": 1_i32
},
"name": "username",
"unique": false,
"collation": {
"locale": "en",
"strength": 2_i32
}
},
{
"key": {
"username": 1_i32,
"discriminator": 1_i32
},
"name": "username_discriminator",
"unique": true,
"collation": {
"locale": "en",
"strength": 2_i32
}
}
]
},
None,
)
.await
.expect("Failed to create username index.");
}
if revision <= 25 {
info!("Running migration [revision 25 / 15-06-2023]: Add collection `ratelimit_events` with index.");
db.db()
.create_collection("ratelimit_events", None)
.await
.ok();
db.db()
.run_command(
doc! {
"createIndexes": "ratelimit_events",
"indexes": [
{
"key": {
"_id": 1_i32,
"target_id": 1_i32,
"event_type": 1_i32,
},
"name": "compound_key"
}
]
},
None,
)
.await
.expect("Failed to create ratelimit_events index.");
}
// Need to migrate fields on attachments, change `user_id`, `object_id`, etc to `parent`.
// Reminder to update LATEST_REVISION when adding new migrations.
LATEST_REVISION
LATEST_REVISION.max(revision)
}
@@ -0,0 +1,5 @@
mod model;
mod ops;
pub use model::*;
pub use ops::*;
@@ -0,0 +1,158 @@
use revolt_result::Result;
use crate::events::client::EventV1;
use crate::{Database, File};
auto_derived_partial!(
/// Webhook
pub struct Webhook {
/// Webhook Id
#[serde(rename = "_id")]
pub id: String,
/// The name of the webhook
pub name: String,
/// The avatar of the webhook
#[serde(skip_serializing_if = "Option::is_none")]
pub avatar: Option<File>,
/// The channel this webhook belongs to
pub channel_id: String,
/// The private token for the webhook
pub token: Option<String>,
},
"PartialWebhook"
);
auto_derived!(
/// Optional fields on webhook object
pub enum FieldsWebhook {
Avatar,
}
);
#[allow(clippy::disallowed_methods)]
impl Webhook {
pub async fn create(&self, db: &Database) -> Result<()> {
db.insert_webhook(self).await?;
// Avoid leaking the token to people who receive the event
let mut webhook = self.clone();
webhook.token = None;
EventV1::WebhookCreate(webhook.into())
.p(self.channel_id.clone())
.await;
Ok(())
}
pub fn assert_token(&self, token: &str) -> Result<()> {
if self.token.as_deref() == Some(token) {
Ok(())
} else {
Err(create_error!(InvalidCredentials))
}
}
pub async fn update(
&mut self,
db: &Database,
mut partial: PartialWebhook,
remove: Vec<FieldsWebhook>,
) -> Result<()> {
for field in &remove {
self.remove_field(field)
}
self.apply_options(partial.clone());
db.update_webhook(&self.id, &partial, &remove).await?;
partial.token = None; // Avoid leaking the token to people who receive the event
EventV1::WebhookUpdate {
id: self.id.clone(),
data: partial.into(),
remove: remove.into_iter().map(|v| v.into()).collect(),
}
.p(self.channel_id.clone())
.await;
Ok(())
}
pub fn remove_field(&mut self, field: &FieldsWebhook) {
match field {
FieldsWebhook::Avatar => self.avatar = None,
}
}
pub async fn delete(&self, db: &Database) -> Result<()> {
db.delete_webhook(&self.id).await?;
EventV1::WebhookDelete {
id: self.id.clone(),
}
.p(self.channel_id.clone())
.await;
Ok(())
}
}
#[cfg(test)]
mod tests {
use crate::{FieldsWebhook, PartialWebhook, Webhook};
#[async_std::test]
async fn crud() {
database_test!(|db| async move {
let webhook_id = "webhook";
let channel_id = "channel";
let webhook = Webhook {
id: webhook_id.to_string(),
name: "Webhook Name".to_string(),
channel_id: channel_id.to_string(),
avatar: Some(Default::default()),
..Default::default()
};
db.insert_webhook(&webhook).await.unwrap();
let mut updated_webhook = webhook.clone();
updated_webhook
.update(
&db,
PartialWebhook {
name: Some("New Name".to_string()),
..Default::default()
},
vec![FieldsWebhook::Avatar],
)
.await
.unwrap();
let fetched_webhook = db.fetch_webhook(webhook_id).await.unwrap();
let fetched_webhooks = db.fetch_webhooks_for_channel(channel_id).await.unwrap();
assert_eq!(updated_webhook, fetched_webhook);
assert_ne!(webhook, fetched_webhook);
assert_eq!(1, fetched_webhooks.len());
assert_eq!(fetched_webhook, fetched_webhooks[0]);
webhook.delete(&db).await.unwrap();
assert!(db.fetch_webhook(webhook_id).await.is_err());
assert_eq!(
0,
db.fetch_webhooks_for_channel(channel_id)
.await
.unwrap()
.len()
)
});
}
}
@@ -0,0 +1,29 @@
use revolt_result::Result;
use crate::{FieldsWebhook, PartialWebhook, Webhook};
mod mongodb;
mod reference;
#[async_trait]
pub trait AbstractWebhooks: Sync + Send {
/// Insert new webhook into the database
async fn insert_webhook(&self, webhook: &Webhook) -> Result<()>;
/// Fetch webhook by id
async fn fetch_webhook(&self, webhook_id: &str) -> Result<Webhook>;
/// Fetch webhooks for channel
async fn fetch_webhooks_for_channel(&self, channel_id: &str) -> Result<Vec<Webhook>>;
/// Update webhook with new information
async fn update_webhook(
&self,
webhook_id: &str,
partial: &PartialWebhook,
remove: &[FieldsWebhook],
) -> Result<()>;
/// Delete webhook by id
async fn delete_webhook(&self, webhook_id: &str) -> Result<()>;
}
@@ -0,0 +1,77 @@
use futures::StreamExt;
use revolt_result::Result;
use crate::{FieldsWebhook, PartialWebhook, Webhook};
use crate::{IntoDocumentPath, MongoDb};
use super::AbstractWebhooks;
static COL: &str = "channel_webhooks";
#[async_trait]
impl AbstractWebhooks for MongoDb {
/// Insert new webhook into the database
async fn insert_webhook(&self, webhook: &Webhook) -> Result<()> {
query!(self, insert_one, COL, &webhook).map(|_| ())
}
/// Fetch webhook by id
async fn fetch_webhook(&self, webhook_id: &str) -> Result<Webhook> {
query!(self, find_one_by_id, COL, webhook_id)?.ok_or_else(|| create_error!(NotFound))
}
/// Fetch webhooks for channel
async fn fetch_webhooks_for_channel(&self, channel_id: &str) -> Result<Vec<Webhook>> {
Ok(self
.col::<Webhook>(COL)
.find(
doc! {
"channel_id": channel_id,
},
None,
)
.await
.map_err(|_| create_database_error!("find", COL))?
.filter_map(|s| async {
if cfg!(debug_assertions) {
Some(s.unwrap())
} else {
s.ok()
}
})
.collect()
.await)
}
/// Update webhook with new information
async fn update_webhook(
&self,
webhook_id: &str,
partial: &PartialWebhook,
remove: &[FieldsWebhook],
) -> Result<()> {
query!(
self,
update_one_by_id,
COL,
webhook_id,
partial,
remove.iter().map(|x| x as &dyn IntoDocumentPath).collect(),
None
)
.map(|_| ())
}
/// Delete webhook by id
async fn delete_webhook(&self, webhook_id: &str) -> Result<()> {
query!(self, delete_one_by_id, COL, webhook_id).map(|_| ())
}
}
impl IntoDocumentPath for FieldsWebhook {
fn as_path(&self) -> Option<&'static str> {
Some(match self {
FieldsWebhook::Avatar => "avatar",
})
}
}
@@ -0,0 +1,70 @@
use revolt_result::Result;
use crate::ReferenceDb;
use crate::{FieldsWebhook, PartialWebhook, Webhook};
use super::AbstractWebhooks;
#[async_trait]
impl AbstractWebhooks for ReferenceDb {
/// Insert new webhook into the database
async fn insert_webhook(&self, webhook: &Webhook) -> Result<()> {
let mut webhooks = self.channel_webhooks.lock().await;
if webhooks.contains_key(&webhook.id) {
Err(create_database_error!("insert", "webhook"))
} else {
webhooks.insert(webhook.id.to_string(), webhook.clone());
Ok(())
}
}
/// Fetch webhook by id
async fn fetch_webhook(&self, webhook_id: &str) -> Result<Webhook> {
let webhooks = self.channel_webhooks.lock().await;
webhooks
.get(webhook_id)
.cloned()
.ok_or_else(|| create_error!(NotFound))
}
/// Fetch webhooks for channel
async fn fetch_webhooks_for_channel(&self, channel_id: &str) -> Result<Vec<Webhook>> {
let webhooks = self.channel_webhooks.lock().await;
Ok(webhooks
.values()
.filter(|webhook| webhook.channel_id == channel_id)
.cloned()
.collect())
}
/// Update webhook with new information
async fn update_webhook(
&self,
webhook_id: &str,
partial: &PartialWebhook,
remove: &[FieldsWebhook],
) -> Result<()> {
let mut webhooks = self.channel_webhooks.lock().await;
if let Some(webhook) = webhooks.get_mut(webhook_id) {
for field in remove {
#[allow(clippy::disallowed_methods)]
webhook.remove_field(field);
}
webhook.apply_options(partial.clone());
Ok(())
} else {
Err(create_error!(NotFound))
}
}
/// Delete webhook by id
async fn delete_webhook(&self, webhook_id: &str) -> Result<()> {
let mut webhooks = self.channel_webhooks.lock().await;
if webhooks.remove(webhook_id).is_some() {
Ok(())
} else {
Err(create_error!(NotFound))
}
}
}
@@ -0,0 +1,5 @@
mod model;
mod ops;
pub use model::*;
pub use ops::*;
@@ -0,0 +1,529 @@
use std::collections::HashMap;
use revolt_permissions::OverrideField;
use revolt_result::Result;
use serde::{Deserialize, Serialize};
use crate::{events::client::EventV1, Database, File, IntoDocumentPath};
auto_derived!(
pub enum Channel {
/// Personal "Saved Notes" channel which allows users to save messages
SavedMessages {
/// Unique Id
#[serde(rename = "_id")]
id: String,
/// Id of the user this channel belongs to
user: String,
},
/// Direct message channel between two users
DirectMessage {
/// Unique Id
#[serde(rename = "_id")]
id: String,
/// Whether this direct message channel is currently open on both sides
active: bool,
/// 2-tuple of user ids participating in direct message
recipients: Vec<String>,
/// Id of the last message sent in this channel
#[serde(skip_serializing_if = "Option::is_none")]
last_message_id: Option<String>,
},
/// Group channel between 1 or more participants
Group {
/// Unique Id
#[serde(rename = "_id")]
id: String,
/// Display name of the channel
name: String,
/// User id of the owner of the group
owner: String,
/// Channel description
#[serde(skip_serializing_if = "Option::is_none")]
description: Option<String>,
/// Array of user ids participating in channel
recipients: Vec<String>,
/// Custom icon attachment
#[serde(skip_serializing_if = "Option::is_none")]
icon: Option<File>,
/// Id of the last message sent in this channel
#[serde(skip_serializing_if = "Option::is_none")]
last_message_id: Option<String>,
/// Permissions assigned to members of this group
/// (does not apply to the owner of the group)
#[serde(skip_serializing_if = "Option::is_none")]
permissions: Option<i64>,
/// Whether this group is marked as not safe for work
#[serde(skip_serializing_if = "crate::if_false", default)]
nsfw: bool,
},
/// Text channel belonging to a server
TextChannel {
/// Unique Id
#[serde(rename = "_id")]
id: String,
/// Id of the server this channel belongs to
server: String,
/// Display name of the channel
name: String,
/// Channel description
#[serde(skip_serializing_if = "Option::is_none")]
description: Option<String>,
/// Custom icon attachment
#[serde(skip_serializing_if = "Option::is_none")]
icon: Option<File>,
/// Id of the last message sent in this channel
#[serde(skip_serializing_if = "Option::is_none")]
last_message_id: Option<String>,
/// Default permissions assigned to users in this channel
#[serde(skip_serializing_if = "Option::is_none")]
default_permissions: Option<OverrideField>,
/// Permissions assigned based on role to this channel
#[serde(
default = "HashMap::<String, OverrideField>::new",
skip_serializing_if = "HashMap::<String, OverrideField>::is_empty"
)]
role_permissions: HashMap<String, OverrideField>,
/// Whether this channel is marked as not safe for work
#[serde(skip_serializing_if = "crate::if_false", default)]
nsfw: bool,
},
/// Voice channel belonging to a server
VoiceChannel {
/// Unique Id
#[serde(rename = "_id")]
id: String,
/// Id of the server this channel belongs to
server: String,
/// Display name of the channel
name: String,
#[serde(skip_serializing_if = "Option::is_none")]
/// Channel description
description: Option<String>,
/// Custom icon attachment
#[serde(skip_serializing_if = "Option::is_none")]
icon: Option<File>,
/// Default permissions assigned to users in this channel
#[serde(skip_serializing_if = "Option::is_none")]
default_permissions: Option<OverrideField>,
/// Permissions assigned based on role to this channel
#[serde(
default = "HashMap::<String, OverrideField>::new",
skip_serializing_if = "HashMap::<String, OverrideField>::is_empty"
)]
role_permissions: HashMap<String, OverrideField>,
/// Whether this channel is marked as not safe for work
#[serde(skip_serializing_if = "crate::if_false", default)]
nsfw: bool,
},
}
);
auto_derived!(
#[derive(Default)]
pub struct PartialChannel {
#[serde(skip_serializing_if = "Option::is_none")]
pub name: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub owner: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub description: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub icon: Option<File>,
#[serde(skip_serializing_if = "Option::is_none")]
pub nsfw: Option<bool>,
#[serde(skip_serializing_if = "Option::is_none")]
pub active: Option<bool>,
#[serde(skip_serializing_if = "Option::is_none")]
pub permissions: Option<i64>,
#[serde(skip_serializing_if = "Option::is_none")]
pub role_permissions: Option<HashMap<String, OverrideField>>,
#[serde(skip_serializing_if = "Option::is_none")]
pub default_permissions: Option<OverrideField>,
#[serde(skip_serializing_if = "Option::is_none")]
pub last_message_id: Option<String>,
}
/// Optional fields on channel object
pub enum FieldsChannel {
Description,
Icon,
DefaultPermissions,
}
);
impl Channel {
/// Create a channel
pub async fn create(&self, db: &Database) -> Result<()> {
db.insert_channel(self).await?;
Ok(())
}
/// Add user to a group
pub async fn add_user_to_group(
&mut self,
db: &Database,
user_id: &str,
_by_id: &str,
) -> Result<()> {
if let Channel::Group { recipients, .. } = self {
if recipients.contains(&String::from(user_id)) {
return Err(create_error!(AlreadyInGroup));
}
recipients.push(String::from(user_id));
}
match &self {
Channel::Group { id, .. } => {
db.add_user_to_group(id, user_id).await?;
EventV1::ChannelGroupJoin {
id: id.to_string(),
user: user_id.to_string(),
}
.p(id.to_string())
.await;
EventV1::ChannelCreate(self.clone().into())
.private(user_id.to_string())
.await;
/* TODO: SystemMessage::UserAdded {
id: user.to_string(),
by: by.to_string(),
}
.into_message(id.to_string())
.create(db, self, None)
.await
.ok(); */
Ok(())
}
_ => Err(create_error!(InvalidOperation)),
}
}
/// Map out whether it is a direct DM
pub fn is_direct_dm(&self) -> bool {
matches!(self, Channel::DirectMessage { .. })
}
/// Check whether has a user as a recipient
pub fn contains_user(&self, user_id: &str) -> bool {
match self {
Channel::Group { recipients, .. } => recipients.contains(&String::from(user_id)),
_ => false,
}
}
/// Get list of recipients
pub fn users(&self) -> Result<Vec<String>> {
match self {
Channel::Group { recipients, .. } => Ok(recipients.to_owned()),
_ => Err(create_error!(NotFound)),
}
}
/// Get a reference to this channel's id
pub fn id(&self) -> String {
match self {
Channel::DirectMessage { id, .. }
| Channel::Group { id, .. }
| Channel::SavedMessages { id, .. }
| Channel::TextChannel { id, .. }
| Channel::VoiceChannel { id, .. } => id.clone(),
}
}
/// Set role permission on a channel
pub async fn set_role_permission(
&mut self,
db: &Database,
role_id: &str,
permissions: OverrideField,
) -> Result<()> {
match self {
Channel::TextChannel {
id,
server,
role_permissions,
..
}
| Channel::VoiceChannel {
id,
server,
role_permissions,
..
} => {
db.set_channel_role_permission(id, role_id, permissions)
.await?;
role_permissions.insert(role_id.to_string(), permissions);
EventV1::ChannelUpdate {
id: id.clone(),
data: PartialChannel {
role_permissions: Some(role_permissions.clone()),
..Default::default()
}
.into(),
clear: vec![],
}
.p(server.clone())
.await;
Ok(())
}
_ => Err(create_error!(InvalidOperation)),
}
}
/// Update channel data
pub async fn update<'a>(
&mut self,
db: &Database,
partial: PartialChannel,
remove: Vec<FieldsChannel>,
) -> Result<()> {
for field in &remove {
self.remove_field(field);
}
self.apply_options(partial.clone());
db.update_channel(&self.id(), &partial, remove.clone())
.await?;
Ok(())
}
/// Remove a field from Channel object
pub fn remove_field(&mut self, field: &FieldsChannel) {
match field {
FieldsChannel::Description => match self {
Self::Group { description, .. }
| Self::TextChannel { description, .. }
| Self::VoiceChannel { description, .. } => {
description.take();
}
_ => {}
},
FieldsChannel::Icon => match self {
Self::Group { icon, .. }
| Self::TextChannel { icon, .. }
| Self::VoiceChannel { icon, .. } => {
icon.take();
}
_ => {}
},
FieldsChannel::DefaultPermissions => match self {
Self::TextChannel {
default_permissions,
..
}
| Self::VoiceChannel {
default_permissions,
..
} => {
default_permissions.take();
}
_ => {}
},
}
}
/// Remove multiple fields from Channel object
pub fn remove_fields(&mut self, partial: Vec<FieldsChannel>) {
for field in partial {
self.remove_field(&field)
}
}
/// Apply partial channel to channel
pub fn apply_options(&mut self, partial: PartialChannel) {
match self {
Self::SavedMessages { .. } => {}
Self::DirectMessage { active, .. } => {
if let Some(v) = partial.active {
*active = v;
}
}
Self::Group {
name,
owner,
description,
icon,
nsfw,
permissions,
..
} => {
if let Some(v) = partial.name {
*name = v;
}
if let Some(v) = partial.owner {
*owner = v;
}
if let Some(v) = partial.description {
description.replace(v);
}
if let Some(v) = partial.icon {
icon.replace(v);
}
if let Some(v) = partial.nsfw {
*nsfw = v;
}
if let Some(v) = partial.permissions {
permissions.replace(v);
}
}
Self::TextChannel {
name,
description,
icon,
nsfw,
default_permissions,
role_permissions,
..
}
| Self::VoiceChannel {
name,
description,
icon,
nsfw,
default_permissions,
role_permissions,
..
} => {
if let Some(v) = partial.name {
*name = v;
}
if let Some(v) = partial.description {
description.replace(v);
}
if let Some(v) = partial.icon {
icon.replace(v);
}
if let Some(v) = partial.nsfw {
*nsfw = v;
}
if let Some(v) = partial.role_permissions {
*role_permissions = v;
}
if let Some(v) = partial.default_permissions {
default_permissions.replace(v);
}
}
}
}
/// Remove user from a group
pub async fn remove_user_from_group(
&self,
db: &Database,
user_id: &str,
_by_id: Option<&str>,
silent: bool,
) -> Result<()> {
match &self {
Channel::Group {
id,
owner,
recipients,
..
} => {
if user_id == owner {
if let Some(new_owner) = recipients.iter().find(|x| *x != user_id) {
db.update_channel(
id,
&PartialChannel {
owner: Some(new_owner.into()),
..Default::default()
},
vec![],
)
.await?;
/* TODO: SystemMessage::ChannelOwnershipChanged {
from: owner.to_string(),
to: new_owner.into(),
}
.into_message(id.to_string())
.create(db, self, None)
.await
.ok(); */
} else {
db.delete_channel(self).await?;
return Ok(());
}
}
EventV1::ChannelGroupLeave {
id: id.to_string(),
user: user_id.to_string(),
}
.p(id.to_string())
.await;
if !silent {
/* TODO: if let Some(_by) = by_id {
SystemMessage::UserRemove {
id: user_id.to_string(),
by: by.to_string(),
}
} else {
SystemMessage::UserLeft {
id: user_id.to_string(),
}
}
.into_message(id.to_string())
.create(db, self, None)
.await
.ok(); */
}
Ok(())
}
_ => Err(create_error!(InvalidOperation)),
}
}
/// Delete a channel
pub async fn delete(&self, db: &Database) -> Result<()> {
db.delete_channel(self).await
}
}
impl IntoDocumentPath for FieldsChannel {
fn as_path(&self) -> Option<&'static str> {
Some(match self {
FieldsChannel::Description => "description",
FieldsChannel::Icon => "icon",
FieldsChannel::DefaultPermissions => "default_permissions",
})
}
}
@@ -0,0 +1,50 @@
use crate::{revolt_result::Result, Channel, FieldsChannel, PartialChannel};
use revolt_permissions::OverrideField;
mod mongodb;
mod reference;
#[async_trait]
pub trait AbstractChannels: Sync + Send {
/// Insert a new channel in the database
async fn insert_channel(&self, channel: &Channel) -> Result<()>;
/// Fetch a channel from the database
async fn fetch_channel(&self, channel_id: &str) -> Result<Channel>;
/// Fetch all channels from the database
async fn fetch_channels<'a>(&self, ids: &'a [String]) -> Result<Vec<Channel>>;
/// Fetch all direct messages for a user
async fn find_direct_messages(&self, user_id: &str) -> Result<Vec<Channel>>;
// Fetch saved messages channel
async fn find_saved_messages_channel(&self, user_id: &str) -> Result<Channel>;
// Fetch direct message channel (DM or Saved Messages)
async fn find_direct_message_channel(&self, user_a: &str, user_b: &str) -> Result<Channel>;
/// Insert a user to a group
async fn add_user_to_group(&self, channel_id: &str, user_id: &str) -> Result<()>;
/// Insert channel role permissions
async fn set_channel_role_permission(
&self,
channel_id: &str,
role_id: &str,
permissions: OverrideField,
) -> Result<()>;
// Update channel
async fn update_channel(
&self,
id: &str,
channel_id: &PartialChannel,
remove: Vec<FieldsChannel>,
) -> Result<()>;
// Remove a user from a group
async fn remove_user_from_group(&self, channel_id: &str, user_id: &str) -> Result<()>;
// Delete a channel
async fn delete_channel(&self, channel_id: &Channel) -> Result<()>;
}
@@ -0,0 +1,193 @@
use super::AbstractChannels;
use crate::{Channel, FieldsChannel, IntoDocumentPath, MongoDb, PartialChannel};
use bson::Document;
use futures::StreamExt;
use revolt_permissions::OverrideField;
use revolt_result::Result;
static COL: &str = "channels";
#[async_trait]
impl AbstractChannels for MongoDb {
/// Insert a new channel in the database
async fn insert_channel(&self, channel: &Channel) -> Result<()> {
query!(self, insert_one, COL, &channel).map(|_| ())
}
/// Fetch a channel from the database
async fn fetch_channel(&self, channel_id: &str) -> Result<Channel> {
query!(self, find_one_by_id, COL, channel_id)?.ok_or_else(|| create_error!(NotFound))
}
/// Fetch all channels from the database
async fn fetch_channels<'a>(&self, ids: &'a [String]) -> Result<Vec<Channel>> {
Ok(self
.col::<Channel>(COL)
.find(
doc! {
"_id": {
"$in": ids
}
},
None,
)
.await
.map_err(|_| create_database_error!("fetch", "channels"))?
.filter_map(|s| async {
if cfg!(debug_assertions) {
Some(s.unwrap())
} else {
s.ok()
}
})
.collect()
.await)
}
/// Fetch all direct messages for a user
async fn find_direct_messages(&self, user_id: &str) -> Result<Vec<Channel>> {
query!(
self,
find,
COL,
doc! {
"$or": [
{
"$or": [
{
"channel_type": "DirectMessage"
},
{
"channel_type": "Group"
}
],
"recipients": user_id
},
{
"channel_type": "SavedMessages",
"user": user_id
}
]
}
)
}
// Fetch saved messages channel
async fn find_saved_messages_channel(&self, user_id: &str) -> Result<Channel> {
query!(
self,
find_one,
COL,
doc! {
"channel_type": "SavedMessages",
"user": user_id
}
)?
.ok_or_else(|| create_error!(InternalError))
}
// Fetch direct message channel (DM or Saved Messages)
async fn find_direct_message_channel(&self, user_a: &str, user_b: &str) -> Result<Channel> {
let doc = match (user_a, user_b) {
self_user if self_user.0 == self_user.1 => {
doc! {
"channel_type": "SavedMessages",
"user": self_user.0
}
}
users => {
doc! {
"channel_type": "DirectMessage",
"recipients": {
"$all": [ users.0, users.1 ]
}
}
}
};
query!(self, find_one, COL, doc)?.ok_or_else(|| create_error!(NotFound))
}
/// Insert a user to a group
async fn add_user_to_group(&self, channel: &str, user: &str) -> Result<()> {
self.col::<Document>(COL)
.update_one(
doc! {
"_id": channel
},
doc! {
"$push": {
"recipients": user
}
},
None,
)
.await
.map(|_| ())
.map_err(|_| create_database_error!("update_one", "channel"))
}
/// Insert channel role permissions
async fn set_channel_role_permission(
&self,
channel: &str,
role: &str,
permissions: OverrideField,
) -> Result<()> {
self.col::<Document>(COL)
.update_one(
doc! { "_id": channel },
doc! {
"$set": {
"role_permissions.".to_owned() + role: permissions
}
},
None,
)
.await
.map(|_| ())
.map_err(|_| create_database_error!("update_one", "channel"))
}
// Update channel
async fn update_channel(
&self,
id: &str,
channel: &PartialChannel,
remove: Vec<FieldsChannel>,
) -> Result<()> {
query!(
self,
update_one_by_id,
COL,
id,
channel,
remove.iter().map(|x| x as &dyn IntoDocumentPath).collect(),
None
)
.map(|_| ())
}
// Remove a user from a group
async fn remove_user_from_group(&self, channel: &str, user: &str) -> Result<()> {
self.col::<Document>(COL)
.update_one(
doc! {
"_id": channel
},
doc! {
"$pull": {
"recipients": user
}
},
None,
)
.await
.map(|_| ())
.map_err(|_| create_database_error!("update_one", "channels"))
}
// Delete a channel
async fn delete_channel(&self, channel: &Channel) -> Result<()> {
query!(self, delete_one_by_id, COL, &channel.id()).map(|_| ())
}
}
@@ -0,0 +1,157 @@
use std::collections::hash_map::Entry;
use super::AbstractChannels;
use crate::ReferenceDb;
use crate::{Channel, FieldsChannel, PartialChannel};
use revolt_permissions::OverrideField;
use revolt_result::Result;
#[async_trait]
impl AbstractChannels for ReferenceDb {
/// Insert a new channel in the database
async fn insert_channel(&self, channel: &Channel) -> Result<()> {
let mut channels = self.channels.lock().await;
if let Entry::Vacant(entry) = channels.entry(channel.id()) {
entry.insert(channel.clone());
Ok(())
} else {
Err(create_database_error!("insert", "channel"))
}
}
/// Fetch a channel from the database
async fn fetch_channel(&self, channel_id: &str) -> Result<Channel> {
let channels = self.channels.lock().await;
channels
.get(channel_id)
.cloned()
.ok_or_else(|| create_error!(NotFound))
}
/// Fetch all channels from the database
async fn fetch_channels<'a>(&self, ids: &'a [String]) -> Result<Vec<Channel>> {
let channels = self.channels.lock().await;
ids.iter()
.map(|id| {
channels
.get(id)
.cloned()
.ok_or_else(|| create_error!(NotFound))
})
.collect()
}
/// Fetch all direct messages for a user
async fn find_direct_messages(&self, user_id: &str) -> Result<Vec<Channel>> {
let channels = self.channels.lock().await;
Ok(channels
.values()
.filter(|channel| channel.contains_user(user_id))
.cloned()
.collect())
}
// Fetch saved messages channel
async fn find_saved_messages_channel(&self, user_id: &str) -> Result<Channel> {
let channels = self.channels.lock().await;
channels
.get(user_id)
.cloned()
.ok_or_else(|| create_database_error!("fetch", "channel"))
}
// Fetch direct message channel (DM or Saved Messages)
async fn find_direct_message_channel(&self, user_a: &str, user_b: &str) -> Result<Channel> {
let channels = self.channels.lock().await;
for (_, data) in channels.iter() {
if data.contains_user(user_a) && data.contains_user(user_b) {
return Ok(data.to_owned());
}
}
Err(create_error!(NotFound))
}
/// Insert a user to a group
async fn add_user_to_group(&self, channel_id: &str, user_id: &str) -> Result<()> {
let mut channels = self.channels.lock().await;
if let Some(Channel::Group { recipients, .. }) = channels.get_mut(channel_id) {
recipients.push(String::from(user_id));
Ok(())
} else {
Err(create_error!(InvalidOperation))
}
}
/// Insert channel role permissions
async fn set_channel_role_permission(
&self,
channel_id: &str,
role_id: &str,
permissions: OverrideField,
) -> Result<()> {
let mut channels = self.channels.lock().await;
if let Some(mut channel) = channels.get_mut(channel_id) {
match &mut channel {
Channel::TextChannel {
role_permissions, ..
}
| Channel::VoiceChannel {
role_permissions, ..
} => {
if role_permissions.get(role_id).is_some() {
role_permissions.remove(role_id);
role_permissions.insert(String::from(role_id), permissions);
Ok(())
} else {
Err(create_error!(NotFound))
}
}
_ => Err(create_error!(NotFound)),
}
} else {
Err(create_error!(NotFound))
}
}
// Update channel
async fn update_channel(
&self,
id: &str,
channel: &PartialChannel,
remove: Vec<FieldsChannel>,
) -> Result<()> {
let mut channels = self.channels.lock().await;
if let Some(channel_data) = channels.get_mut(id) {
channel_data.apply_options(channel.to_owned());
channel_data.remove_fields(remove);
Ok(())
} else {
Err(create_error!(NotFound))
}
}
// Remove a user from a group
async fn remove_user_from_group(&self, channel: &str, user: &str) -> Result<()> {
let mut channels = self.channels.lock().await;
if let Some(channel_data) = channels.get_mut(channel) {
if channel_data.users()?.contains(&String::from(user)) {
channel_data.users()?.retain(|x| x != user);
return Ok(());
} else {
return Err(create_error!(NotFound));
}
}
Err(create_error!(NotFound))
}
// Delete a channel
async fn delete_channel(&self, channel: &Channel) -> Result<()> {
let mut channels = self.channels.lock().await;
if channels.remove(&channel.id()).is_some() {
Ok(())
} else {
Err(create_error!(NotFound))
}
}
}
+9
View File
@@ -1,6 +1,9 @@
mod admin_migrations;
mod bots;
mod channel_webhooks;
mod channels;
mod files;
mod ratelimit_events;
mod safety_strikes;
mod server_members;
mod servers;
@@ -9,7 +12,10 @@ mod users;
pub use admin_migrations::*;
pub use bots::*;
pub use channel_webhooks::*;
pub use channels::*;
pub use files::*;
pub use ratelimit_events::*;
pub use safety_strikes::*;
pub use server_members::*;
pub use servers::*;
@@ -23,7 +29,10 @@ pub trait AbstractDatabase:
+ Send
+ admin_migrations::AbstractMigrations
+ bots::AbstractBots
+ channels::AbstractChannels
+ channel_webhooks::AbstractWebhooks
+ files::AbstractAttachments
+ ratelimit_events::AbstractRatelimitEvents
+ safety_strikes::AbstractAccountStrikes
+ server_members::AbstractServerMembers
+ servers::AbstractServers
@@ -0,0 +1,5 @@
mod model;
mod ops;
pub use model::*;
pub use ops::*;
@@ -0,0 +1,25 @@
use std::fmt;
auto_derived!(
/// Ratelimit Event
pub struct RatelimitEvent {
/// Id
#[serde(rename = "_id")]
pub id: String,
/// Relevant Object Id
pub target_id: String,
/// Type of event
pub event_type: RatelimitEventType,
}
/// Event type
pub enum RatelimitEventType {
DiscriminatorChange,
}
);
impl fmt::Display for RatelimitEventType {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
fmt::Debug::fmt(self, f)
}
}
@@ -0,0 +1,20 @@
use std::time::Duration;
use crate::{revolt_result::Result, RatelimitEvent, RatelimitEventType};
mod mongodb;
mod reference;
#[async_trait]
pub trait AbstractRatelimitEvents: Sync + Send {
/// Insert a new ratelimit event
async fn insert_ratelimit_event(&self, event: &RatelimitEvent) -> Result<()>;
/// Count number of events in given duration and check if we've hit the limit
async fn has_ratelimited(
&self,
target_id: &str,
event_type: RatelimitEventType,
period: Duration,
count: usize,
) -> Result<bool>;
}
@@ -0,0 +1,40 @@
use std::time::{Duration, SystemTime};
use super::AbstractRatelimitEvents;
use crate::{MongoDb, RatelimitEvent, RatelimitEventType};
use revolt_result::Result;
use ulid::Ulid;
static COL: &str = "ratelimit_events";
#[async_trait]
impl AbstractRatelimitEvents for MongoDb {
/// Insert a new ratelimit event
async fn insert_ratelimit_event(&self, event: &RatelimitEvent) -> Result<()> {
query!(self, insert_one, COL, &event).map(|_| ())
}
/// Count number of events in given duration and check if we've hit the limit
async fn has_ratelimited(
&self,
target_id: &str,
event_type: RatelimitEventType,
period: Duration,
count: usize,
) -> Result<bool> {
self.col::<RatelimitEvent>(COL)
.count_documents(
doc! {
"_id": {
"$gte": Ulid::from_datetime(SystemTime::now() - period).to_string()
},
"target_id": target_id,
"event_type": event_type.to_string()
},
None,
)
.await
.map(|c| c as usize >= count)
.map_err(|_| create_database_error!("count_documents", COL))
}
}
@@ -0,0 +1,28 @@
use std::time::Duration;
use super::AbstractRatelimitEvents;
use crate::RatelimitEvent;
use crate::RatelimitEventType;
use crate::ReferenceDb;
use revolt_result::Result;
#[async_trait]
impl AbstractRatelimitEvents for ReferenceDb {
/// Insert a new ratelimit event
async fn insert_ratelimit_event(&self, _event: &RatelimitEvent) -> Result<()> {
// TODO: implement
unimplemented!()
}
/// Count number of events in given duration and check if we've hit the limit
async fn has_ratelimited(
&self,
_target_id: &str,
_event_type: RatelimitEventType,
_period: Duration,
_count: usize,
) -> Result<bool> {
// TODO: implement
unimplemented!()
}
}
@@ -8,8 +8,10 @@ auto_derived_partial!(
/// Strike Id
#[serde(rename = "_id")]
pub id: String,
/// User Id of reported user
/// Id of reported user
pub user_id: String,
/// Id of moderator
pub moderator_id: String,
/// Attached reason
pub reason: String,
@@ -19,6 +21,23 @@ auto_derived_partial!(
#[allow(clippy::disallowed_methods)]
impl AccountStrike {
pub async fn create(
db: &Database,
user_id: String,
reason: String,
moderator_id: String,
) -> Result<AccountStrike> {
let strike = AccountStrike {
id: ulid::Ulid::new().to_string(),
user_id,
moderator_id,
reason,
};
db.insert_account_strike(&strike).await?;
Ok(strike)
}
/// Update this strike
pub async fn update(&mut self, db: &Database, partial: PartialAccountStrike) -> Result<()> {
db.update_account_strike(&self.id, &partial).await?;
@@ -42,16 +61,15 @@ mod tests {
async fn crud() {
database_test!(|db| async move {
let user_id = "user";
let strike_a = "a";
let strike_b = "b";
let strike = AccountStrike {
id: strike_a.to_string(),
user_id: user_id.to_string(),
reason: "reason 1".to_string(),
};
db.insert_account_strike(&strike).await.unwrap();
let strike = AccountStrike::create(
&db,
user_id.to_string(),
"reason 1".to_string(),
"moderator_id".to_string(),
)
.await
.unwrap();
let mut updated_strike = strike.clone();
updated_strike
@@ -65,11 +83,12 @@ mod tests {
.await
.unwrap();
db.insert_account_strike(&AccountStrike {
id: strike_b.to_string(),
user_id: user_id.to_string(),
reason: "reason 2".to_string(),
})
let strike2 = AccountStrike::create(
&db,
user_id.to_string(),
"reason 2".to_string(),
"moderator_id".to_string(),
)
.await
.unwrap();
@@ -81,12 +100,12 @@ mod tests {
.map(|strike| strike.id)
.collect::<HashSet<String>>();
assert!(ids.contains(strike_a));
assert!(ids.contains(strike_b));
assert!(ids.contains(&strike.id));
assert!(ids.contains(&strike2.id));
let fetched_strike = strikes
.into_iter()
.find(|strike| strike.id == strike_a)
.find(|entry| entry.id == strike.id)
.unwrap();
assert_eq!(fetched_strike, updated_strike);
@@ -6,7 +6,7 @@ use crate::{AccountStrike, PartialAccountStrike};
use super::AbstractAccountStrikes;
static COL: &str = "bots";
static COL: &str = "safety_strikes";
#[async_trait]
impl AbstractAccountStrikes for MongoDb {
@@ -1,5 +1,8 @@
use std::collections::HashSet;
use crate::{Database, File};
use once_cell::sync::Lazy;
use revolt_result::{Error, ErrorType, Result};
auto_derived_partial!(
@@ -10,6 +13,11 @@ auto_derived_partial!(
pub id: String,
/// Username
pub username: String,
/// Discriminator
pub discriminator: String,
/// Display name
#[serde(skip_serializing_if = "Option::is_none")]
pub display_name: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
/// Avatar attachment
pub avatar: Option<File>,
@@ -195,3 +203,17 @@ impl User {
.await
}
}
pub static DISCRIMINATOR_SEARCH_SPACE: Lazy<HashSet<String>> = Lazy::new(|| {
let mut set = (2..9999)
.map(|v| format!("{:0>4}", v))
.collect::<HashSet<String>>();
for discrim in [
123, 1234, 1111, 2222, 3333, 4444, 5555, 6666, 7777, 8888, 9999,
] {
set.remove(&format!("{:0>4}", discrim));
}
set.into_iter().collect()
});
@@ -0,0 +1 @@
pub mod v0;
+336
View File
@@ -0,0 +1,336 @@
use revolt_models::v0::*;
impl From<crate::AccountStrike> for AccountStrike {
fn from(value: crate::AccountStrike) -> Self {
AccountStrike {
id: value.id,
user_id: value.user_id,
reason: value.reason,
}
}
}
impl crate::Bot {
pub fn into_public_bot(self, user: crate::User) -> PublicBot {
#[cfg(debug_assertions)]
assert_eq!(self.id, user.id);
PublicBot {
id: self.id,
username: user.username,
avatar: user.avatar.map(|x| x.id).unwrap_or_default(),
description: user
.profile
.map(|profile| profile.content)
.unwrap_or_default(),
}
}
}
impl From<crate::Bot> for Bot {
fn from(value: crate::Bot) -> Self {
Bot {
id: value.id,
owner_id: value.owner,
token: value.token,
public: value.public,
analytics: value.analytics,
discoverable: value.discoverable,
interactions_url: value.interactions_url,
terms_of_service_url: value.terms_of_service_url,
privacy_policy_url: value.privacy_policy_url,
flags: value.flags.unwrap_or_default() as u32,
}
}
}
impl From<crate::Webhook> for Webhook {
fn from(value: crate::Webhook) -> Self {
Webhook {
id: value.id,
name: value.name,
avatar: value.avatar.map(|file| file.into()),
channel_id: value.channel_id,
token: value.token,
}
}
}
impl From<crate::PartialWebhook> for PartialWebhook {
fn from(value: crate::PartialWebhook) -> Self {
PartialWebhook {
id: value.id,
name: value.name,
avatar: value.avatar.map(|file| file.into()),
channel_id: value.channel_id,
token: value.token,
}
}
}
impl From<FieldsWebhook> for crate::FieldsWebhook {
fn from(_value: FieldsWebhook) -> Self {
Self::Avatar
}
}
impl From<crate::FieldsWebhook> for FieldsWebhook {
fn from(_value: crate::FieldsWebhook) -> Self {
Self::Avatar
}
}
impl From<crate::Channel> for Channel {
fn from(value: crate::Channel) -> Self {
match value {
crate::Channel::SavedMessages { id, user } => Channel::SavedMessages { id, user },
crate::Channel::DirectMessage {
id,
active,
recipients,
last_message_id,
} => Channel::DirectMessage {
id,
active,
recipients,
last_message_id,
},
crate::Channel::Group {
id,
name,
owner,
description,
recipients,
icon,
last_message_id,
permissions,
nsfw,
} => Channel::Group {
id,
name,
owner,
description,
recipients,
icon: icon.map(|file| file.into()),
last_message_id,
permissions,
nsfw,
},
crate::Channel::TextChannel {
id,
server,
name,
description,
icon,
last_message_id,
default_permissions,
role_permissions,
nsfw,
} => Channel::TextChannel {
id,
server,
name,
description,
icon: icon.map(|file| file.into()),
last_message_id,
default_permissions,
role_permissions,
nsfw,
},
crate::Channel::VoiceChannel {
id,
server,
name,
description,
icon,
default_permissions,
role_permissions,
nsfw,
} => Channel::VoiceChannel {
id,
server,
name,
description,
icon: icon.map(|file| file.into()),
default_permissions,
role_permissions,
nsfw,
},
}
}
}
impl From<crate::PartialChannel> for PartialChannel {
fn from(value: crate::PartialChannel) -> Self {
PartialChannel {
name: value.name,
owner: value.owner,
description: value.description,
icon: value.icon.map(|file| file.into()),
nsfw: value.nsfw,
active: value.active,
permissions: value.permissions,
role_permissions: value.role_permissions,
default_permissions: value.default_permissions,
last_message_id: value.last_message_id,
}
}
}
impl From<FieldsChannel> for crate::FieldsChannel {
fn from(value: FieldsChannel) -> Self {
match value {
FieldsChannel::Description => crate::FieldsChannel::Description,
FieldsChannel::Icon => crate::FieldsChannel::Icon,
FieldsChannel::DefaultPermissions => crate::FieldsChannel::DefaultPermissions,
}
}
}
impl From<crate::FieldsChannel> for FieldsChannel {
fn from(value: crate::FieldsChannel) -> Self {
match value {
crate::FieldsChannel::Description => FieldsChannel::Description,
crate::FieldsChannel::Icon => FieldsChannel::Icon,
crate::FieldsChannel::DefaultPermissions => FieldsChannel::DefaultPermissions,
}
}
}
impl From<crate::File> for File {
fn from(value: crate::File) -> Self {
File {
id: value.id,
tag: value.tag,
filename: value.filename,
metadata: value.metadata.into(),
content_type: value.content_type,
size: value.size,
deleted: value.deleted,
reported: value.reported,
message_id: value.message_id,
user_id: value.user_id,
server_id: value.server_id,
object_id: value.object_id,
}
}
}
impl From<crate::Metadata> for Metadata {
fn from(value: crate::Metadata) -> Self {
match value {
crate::Metadata::File => Metadata::File,
crate::Metadata::Text => Metadata::Text,
crate::Metadata::Image { width, height } => Metadata::Image {
width: width as usize,
height: height as usize,
},
crate::Metadata::Video { width, height } => Metadata::Video {
width: width as usize,
height: height as usize,
},
crate::Metadata::Audio => Metadata::Audio,
}
}
}
impl crate::User {
pub async fn into<P>(self, perspective: P) -> User
where
P: Into<Option<crate::User>>,
{
let relationship = if let Some(perspective) = perspective.into() {
perspective
.relations
.unwrap_or_default()
.into_iter()
.find(|relationship| relationship.id == self.id)
.map(|relationship| relationship.status.into())
.unwrap_or_default()
} else {
RelationshipStatus::None
};
// do permission stuff here
// TODO: implement permissions =)
let can_see_profile = false;
User {
username: self.username,
discriminator: self.discriminator,
display_name: self.display_name,
avatar: self.avatar.map(|file| file.into()),
relations: vec![],
badges: self.badges.unwrap_or_default() as u32,
status: None,
profile: None,
flags: self.flags.unwrap_or_default() as u32,
privileged: self.privileged,
bot: self.bot.map(|bot| bot.into()),
relationship,
online: can_see_profile && revolt_presence::is_online(&self.id).await,
id: self.id,
}
}
}
impl From<crate::RelationshipStatus> for RelationshipStatus {
fn from(value: crate::RelationshipStatus) -> Self {
match value {
crate::RelationshipStatus::None => RelationshipStatus::None,
crate::RelationshipStatus::User => RelationshipStatus::User,
crate::RelationshipStatus::Friend => RelationshipStatus::Friend,
crate::RelationshipStatus::Outgoing => RelationshipStatus::Outgoing,
crate::RelationshipStatus::Incoming => RelationshipStatus::Incoming,
crate::RelationshipStatus::Blocked => RelationshipStatus::Blocked,
crate::RelationshipStatus::BlockedOther => RelationshipStatus::BlockedOther,
}
}
}
impl From<crate::Relationship> for Relationship {
fn from(value: crate::Relationship) -> Self {
Self {
user_id: value.id,
status: value.status.into(),
}
}
}
impl From<crate::Presence> for Presence {
fn from(value: crate::Presence) -> Self {
match value {
crate::Presence::Online => Presence::Online,
crate::Presence::Idle => Presence::Idle,
crate::Presence::Focus => Presence::Focus,
crate::Presence::Busy => Presence::Busy,
crate::Presence::Invisible => Presence::Invisible,
}
}
}
impl From<crate::UserStatus> for UserStatus {
fn from(value: crate::UserStatus) -> Self {
UserStatus {
text: value.text,
presence: value.presence.map(|presence| presence.into()),
}
}
}
impl From<crate::UserProfile> for UserProfile {
fn from(value: crate::UserProfile) -> Self {
UserProfile {
content: value.content,
background: value.background.map(|file| file.into()),
}
}
}
impl From<crate::BotInformation> for BotInformation {
fn from(value: crate::BotInformation) -> Self {
BotInformation {
owner_id: value.owner,
}
}
}
+1
View File
@@ -1,2 +1,3 @@
pub mod bridge;
pub mod permissions;
pub mod reference;
+6 -1
View File
@@ -7,7 +7,7 @@ use schemars::{
JsonSchema,
};
use crate::{Bot, Database};
use crate::{Bot, Database, Webhook};
/// Reference to some object in the database
#[derive(Serialize, Deserialize)]
@@ -26,6 +26,11 @@ impl Reference {
pub async fn as_bot(&self, db: &Database) -> Result<Bot> {
db.fetch_bot(&self.id).await
}
/// Fetch webhook from Ref
pub async fn as_webhook(&self, db: &Database) -> Result<Webhook> {
db.fetch_webhook(&self.id).await
}
}
#[cfg(feature = "rocket-impl")]
+12 -10
View File
@@ -1,6 +1,6 @@
[package]
name = "revolt-models"
version = "0.0.2"
version = "0.6.3"
edition = "2021"
license = "AGPL-3.0-or-later"
authors = [ "Paul Makles <me@insrt.uk>" ]
@@ -9,21 +9,23 @@ description = "Revolt Backend: API Models"
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
[features]
serde = [ "dep:serde" ]
schemas = [ "dep:schemars" ]
from_database = [ "revolt-database", "revolt-presence" ]
serde = [ "dep:serde", "revolt-permissions/serde" ]
schemas = [ "dep:schemars", "revolt-permissions/schemas" ]
validator = [ "dep:validator" ]
partials = [ "dep:revolt_optional_struct", "serde", "schemas" ]
redis-is-patched = [ "revolt-presence/redis-is-patched" ]
default = [ "serde", "from_database" ]
default = [ "serde", "partials" ]
[dependencies]
# Repo
revolt-database = { version = "0.0.2", path = "../database", optional = true }
revolt-presence = { version = "0.0.2", path = "../presence", optional = true }
# Core
revolt-permissions = { version = "0.6.3", path = "../permissions" }
# Serialisation
revolt_optional_struct = { version = "0.2.0", optional = true }
serde = { version = "1", features = ["derive"], optional = true }
# Spec Generation
schemars = { version = "0.8.8", optional = true }
# Validation
validator = { version = "0.16.0", optional = true, features = ["derive"] }
+29
View File
@@ -6,6 +6,13 @@ extern crate serde;
#[macro_use]
extern crate schemars;
#[cfg(feature = "partials")]
#[macro_use]
extern crate revolt_optional_struct;
#[cfg(feature = "validator")]
pub use validator;
macro_rules! auto_derived {
( $( $item:item )+ ) => {
$(
@@ -17,6 +24,28 @@ macro_rules! auto_derived {
};
}
#[cfg(feature = "partials")]
macro_rules! auto_derived_partial {
( $item:item, $name:expr ) => {
#[derive(
OptionalStruct, Debug, Clone, Eq, PartialEq, Serialize, Deserialize, JsonSchema,
)]
#[optional_derive(Debug, Clone, Eq, PartialEq, Serialize, Deserialize, JsonSchema)]
#[optional_name = $name]
#[opt_skip_serializing_none]
#[opt_some_priority]
$item
};
}
#[cfg(not(feature = "partials"))]
macro_rules! auto_derived_partial {
( $item:item, $name:expr ) => {
#[derive(Debug, Clone, Eq, PartialEq, Serialize, Deserialize, JsonSchema)]
$item
};
}
pub mod v0;
/// Utility function to check if a boolean value is false
+12 -14
View File
@@ -2,29 +2,27 @@ auto_derived!(
/// Account Strike
pub struct AccountStrike {
/// Strike Id
#[serde(rename = "_id")]
#[cfg_attr(feature = "serde", serde(rename = "_id"))]
pub id: String,
/// User Id of reported user
/// Id of reported user
pub user_id: String,
/// Attached reason
pub reason: String,
}
/// # Strike Data
/// New strike information
pub struct DataCreateStrike {
/// Id of reported user
pub user_id: String,
/// Attached reason
pub reason: String,
}
/// New strike information
pub struct DataEditAccountStrike {
/// New attached reason
pub reason: String,
}
);
#[cfg(feature = "from_database")]
impl From<revolt_database::AccountStrike> for AccountStrike {
fn from(value: revolt_database::AccountStrike) -> Self {
AccountStrike {
id: value.id,
user_id: value.user_id,
reason: value.reason,
}
}
}
+6 -42
View File
@@ -4,11 +4,11 @@ auto_derived!(
/// Bot
pub struct Bot {
/// Bot Id
#[serde(rename = "_id")]
#[cfg_attr(feature = "serde", serde(rename = "_id"))]
pub id: String,
/// User Id of the bot owner
#[serde(rename = "owner")]
#[cfg_attr(feature = "serde", serde(rename = "owner"))]
pub owner_id: String,
/// Token used to authenticate requests for this bot
pub token: String,
@@ -66,16 +66,16 @@ auto_derived!(
pub struct PublicBot {
/// Bot Id
#[serde(rename = "_id")]
id: String,
pub id: String,
/// Bot Username
username: String,
pub username: String,
/// Profile Avatar
#[serde(skip_serializing_if = "String::is_empty")]
avatar: String,
pub avatar: String,
/// Profile Description
#[serde(skip_serializing_if = "String::is_empty")]
description: String,
pub description: String,
}
/// Bot Response
@@ -86,39 +86,3 @@ auto_derived!(
pub user: User,
}
);
#[cfg(feature = "from_database")]
impl PublicBot {
pub fn from(bot: revolt_database::Bot, user: revolt_database::User) -> Self {
#[cfg(debug_assertions)]
assert_eq!(bot.id, user.id);
PublicBot {
id: bot.id,
username: user.username,
avatar: user.avatar.map(|x| x.id).unwrap_or_default(),
description: user
.profile
.map(|profile| profile.content)
.unwrap_or_default(),
}
}
}
#[cfg(feature = "from_database")]
impl From<revolt_database::Bot> for Bot {
fn from(value: revolt_database::Bot) -> Self {
Bot {
id: value.id,
owner_id: value.owner,
token: value.token,
public: value.public,
analytics: value.analytics,
discoverable: value.discoverable,
interactions_url: value.interactions_url,
terms_of_service_url: value.terms_of_service_url,
privacy_policy_url: value.privacy_policy_url,
flags: value.flags.unwrap_or_default() as u32,
}
}
}
@@ -0,0 +1,90 @@
use super::File;
auto_derived_partial!(
/// Webhook
pub struct Webhook {
/// Webhook Id
pub id: String,
/// The name of the webhook
pub name: String,
/// The avatar of the webhook
#[cfg_attr(feature = "serde", serde(skip_serializing_if = "Option::is_none"))]
pub avatar: Option<File>,
/// The channel this webhook belongs to
pub channel_id: String,
/// The private token for the webhook
pub token: Option<String>,
},
"PartialWebhook"
);
auto_derived!(
/// Information about the webhook bundled with Message
pub struct MessageWebhook {
// The name of the webhook - 1 to 32 chars
pub name: String,
// The id of the avatar of the webhook, if it has one
pub avatar: Option<String>,
}
/// New webhook information
#[cfg_attr(feature = "validator", derive(validator::Validate))]
pub struct DataEditWebhook {
/// Webhook name
#[cfg_attr(feature = "validator", validate(length(min = 1, max = 32)))]
pub name: Option<String>,
/// Avatar ID
#[cfg_attr(feature = "validator", validate(length(min = 1, max = 128)))]
pub avatar: Option<String>,
/// Fields to remove from webhook
#[cfg_attr(feature = "serde", serde(default))]
pub remove: Vec<FieldsWebhook>,
}
/// Webhook information
pub struct ResponseWebhook {
/// Webhook Id
pub id: String,
/// Webhook name
pub name: String,
/// Avatar ID
pub avatar: Option<String>,
/// The channel this webhook belongs to
pub channel_id: String,
}
/// Optional fields on webhook object
pub enum FieldsWebhook {
Avatar,
}
);
impl From<Webhook> for MessageWebhook {
fn from(value: Webhook) -> Self {
MessageWebhook {
name: value.name,
avatar: value.avatar.map(|file| file.id),
}
}
}
impl From<Webhook> for ResponseWebhook {
fn from(value: Webhook) -> Self {
ResponseWebhook {
id: value.id,
name: value.name,
avatar: value.avatar.map(|file| file.id),
channel_id: value.channel_id,
}
}
}
+208
View File
@@ -0,0 +1,208 @@
use super::File;
use revolt_permissions::OverrideField;
use std::collections::HashMap;
auto_derived!(
/// Channel
pub enum Channel {
/// Personal "Saved Notes" channel which allows users to save messages
SavedMessages {
/// Unique Id
#[cfg_attr(feature = "serde", serde(rename = "_id"))]
id: String,
/// Id of the user this channel belongs to
user: String,
},
/// Direct message channel between two users
DirectMessage {
/// Unique Id
#[cfg_attr(feature = "serde", serde(rename = "_id"))]
id: String,
/// Whether this direct message channel is currently open on both sides
active: bool,
/// 2-tuple of user ids participating in direct message
recipients: Vec<String>,
/// Id of the last message sent in this channel
#[cfg_attr(feature = "serde", serde(skip_serializing_if = "Option::is_none"))]
last_message_id: Option<String>,
},
/// Group channel between 1 or more participants
Group {
/// Unique Id
#[cfg_attr(feature = "serde", serde(rename = "_id"))]
id: String,
/// Display name of the channel
name: String,
/// User id of the owner of the group
owner: String,
/// Channel description
#[cfg_attr(feature = "serde", serde(skip_serializing_if = "Option::is_none"))]
description: Option<String>,
/// Array of user ids participating in channel
recipients: Vec<String>,
/// Custom icon attachment
#[cfg_attr(feature = "serde", serde(skip_serializing_if = "Option::is_none"))]
icon: Option<File>,
/// Id of the last message sent in this channel
#[cfg_attr(feature = "serde", serde(skip_serializing_if = "Option::is_none"))]
last_message_id: Option<String>,
/// Permissions assigned to members of this group
/// (does not apply to the owner of the group)
#[cfg_attr(feature = "serde", serde(skip_serializing_if = "Option::is_none"))]
permissions: Option<i64>,
/// Whether this group is marked as not safe for work
#[cfg_attr(
feature = "serde",
serde(skip_serializing_if = "crate::if_false", default)
)]
nsfw: bool,
},
/// Text channel belonging to a server
TextChannel {
/// Unique Id
#[cfg_attr(feature = "serde", serde(rename = "_id"))]
id: String,
/// Id of the server this channel belongs to
server: String,
/// Display name of the channel
name: String,
/// Channel description
#[cfg_attr(feature = "serde", serde(skip_serializing_if = "Option::is_none"))]
description: Option<String>,
/// Custom icon attachment
#[cfg_attr(feature = "serde", serde(skip_serializing_if = "Option::is_none"))]
icon: Option<File>,
/// Id of the last message sent in this channel
#[cfg_attr(feature = "serde", serde(skip_serializing_if = "Option::is_none"))]
last_message_id: Option<String>,
/// Default permissions assigned to users in this channel
#[cfg_attr(feature = "serde", serde(skip_serializing_if = "Option::is_none"))]
default_permissions: Option<OverrideField>,
/// Permissions assigned based on role to this channel
#[cfg_attr(
feature = "serde",
serde(
default = "HashMap::<String, OverrideField>::new",
skip_serializing_if = "HashMap::<String, OverrideField>::is_empty"
)
)]
role_permissions: HashMap<String, OverrideField>,
/// Whether this channel is marked as not safe for work
#[cfg_attr(
feature = "serde",
serde(skip_serializing_if = "crate::if_false", default)
)]
nsfw: bool,
},
/// Voice channel belonging to a server
VoiceChannel {
/// Unique Id
#[cfg_attr(feature = "serde", serde(rename = "_id"))]
id: String,
/// Id of the server this channel belongs to
server: String,
/// Display name of the channel
name: String,
#[cfg_attr(feature = "serde", serde(skip_serializing_if = "Option::is_none"))]
/// Channel description
description: Option<String>,
/// Custom icon attachment
#[cfg_attr(feature = "serde", serde(skip_serializing_if = "Option::is_none"))]
icon: Option<File>,
/// Default permissions assigned to users in this channel
#[cfg_attr(feature = "serde", serde(skip_serializing_if = "Option::is_none"))]
default_permissions: Option<OverrideField>,
/// Permissions assigned based on role to this channel
#[cfg_attr(
feature = "serde",
serde(
default = "HashMap::<String, OverrideField>::new",
skip_serializing_if = "HashMap::<String, OverrideField>::is_empty"
)
)]
role_permissions: HashMap<String, OverrideField>,
/// Whether this channel is marked as not safe for work
#[cfg_attr(
feature = "serde",
serde(skip_serializing_if = "crate::if_false", default)
)]
nsfw: bool,
},
}
/// Partial representation of a channel
#[derive(Default)]
pub struct PartialChannel {
#[cfg_attr(feature = "serde", serde(skip_serializing_if = "Option::is_none"))]
pub name: Option<String>,
#[cfg_attr(feature = "serde", serde(skip_serializing_if = "Option::is_none"))]
pub owner: Option<String>,
#[cfg_attr(feature = "serde", serde(skip_serializing_if = "Option::is_none"))]
pub description: Option<String>,
#[cfg_attr(feature = "serde", serde(skip_serializing_if = "Option::is_none"))]
pub icon: Option<File>,
#[cfg_attr(feature = "serde", serde(skip_serializing_if = "Option::is_none"))]
pub nsfw: Option<bool>,
#[cfg_attr(feature = "serde", serde(skip_serializing_if = "Option::is_none"))]
pub active: Option<bool>,
#[cfg_attr(feature = "serde", serde(skip_serializing_if = "Option::is_none"))]
pub permissions: Option<i64>,
#[cfg_attr(feature = "serde", serde(skip_serializing_if = "Option::is_none"))]
pub role_permissions: Option<HashMap<String, OverrideField>>,
#[cfg_attr(feature = "serde", serde(skip_serializing_if = "Option::is_none"))]
pub default_permissions: Option<OverrideField>,
#[cfg_attr(feature = "serde", serde(skip_serializing_if = "Option::is_none"))]
pub last_message_id: Option<String>,
}
/// Optional fields on channel object
pub enum FieldsChannel {
Description,
Icon,
DefaultPermissions,
}
/// New webhook information
#[cfg_attr(feature = "validator", derive(validator::Validate))]
pub struct DataEditChannel {
/// Channel name
#[cfg_attr(feature = "validator", validate(length(min = 1, max = 32)))]
pub name: Option<String>,
/// Channel description
#[cfg_attr(feature = "validator", validate(length(min = 0, max = 1024)))]
pub description: Option<String>,
/// Group owner
pub owner: Option<String>,
/// Icon
///
/// Provide an Autumn attachment Id.
#[cfg_attr(feature = "validator", validate(length(min = 1, max = 128)))]
pub icon: Option<String>,
/// Whether this channel is age-restricted
pub nsfw: Option<bool>,
/// Whether this channel is archived
pub archived: Option<bool>,
/// Fields to remove from channel
#[cfg_attr(feature = "serde", serde(default))]
pub remove: Option<Vec<FieldsChannel>>,
}
);
-39
View File
@@ -54,42 +54,3 @@ auto_derived!(
Audio,
}
);
#[cfg(feature = "from_database")]
impl From<revolt_database::File> for File {
fn from(value: revolt_database::File) -> Self {
File {
id: value.id,
tag: value.tag,
filename: value.filename,
metadata: value.metadata.into(),
content_type: value.content_type,
size: value.size,
deleted: value.deleted,
reported: value.reported,
message_id: value.message_id,
user_id: value.user_id,
server_id: value.server_id,
object_id: value.object_id,
}
}
}
#[cfg(feature = "from_database")]
impl From<revolt_database::Metadata> for Metadata {
fn from(value: revolt_database::Metadata) -> Self {
match value {
revolt_database::Metadata::File => Metadata::File,
revolt_database::Metadata::Text => Metadata::Text,
revolt_database::Metadata::Image { width, height } => Metadata::Image {
width: width as usize,
height: height as usize,
},
revolt_database::Metadata::Video { width, height } => Metadata::Video {
width: width as usize,
height: height as usize,
},
revolt_database::Metadata::Audio => Metadata::Audio,
}
}
}
+4
View File
@@ -1,9 +1,13 @@
mod account_strikes;
mod bots;
mod channel_webhooks;
mod channels;
mod files;
mod users;
pub use account_strikes::*;
pub use bots::*;
pub use channel_webhooks::*;
pub use channels::*;
pub use files::*;
pub use users::*;
+5 -106
View File
@@ -8,6 +8,11 @@ auto_derived!(
pub id: String,
/// Username
pub username: String,
/// Discriminator
pub discriminator: String,
/// Display name
#[serde(skip_serializing_if = "Option::is_none")]
pub display_name: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
/// Avatar attachment
pub avatar: Option<File>,
@@ -158,109 +163,3 @@ impl CheckRelationship for Vec<Relationship> {
RelationshipStatus::None
}
}
#[cfg(feature = "from_database")]
impl User {
pub async fn from<P>(user: revolt_database::User, perspective: P) -> Self
where
P: Into<Option<revolt_database::User>>,
{
let relationship = if let Some(perspective) = perspective.into() {
perspective
.relations
.unwrap_or_default()
.into_iter()
.find(|relationship| relationship.id == user.id)
.map(|relationship| relationship.status.into())
.unwrap_or_default()
} else {
RelationshipStatus::None
};
// do permission stuff here
// TODO: implement permissions =)
let can_see_profile = false;
Self {
username: user.username,
avatar: user.avatar.map(|file| file.into()),
relations: vec![],
badges: user.badges.unwrap_or_default() as u32,
status: None,
profile: None,
flags: user.flags.unwrap_or_default() as u32,
privileged: user.privileged,
bot: user.bot.map(|bot| bot.into()),
relationship,
online: can_see_profile && revolt_presence::is_online(&user.id).await,
id: user.id,
}
}
}
#[cfg(feature = "from_database")]
impl From<revolt_database::RelationshipStatus> for RelationshipStatus {
fn from(value: revolt_database::RelationshipStatus) -> Self {
match value {
revolt_database::RelationshipStatus::None => RelationshipStatus::None,
revolt_database::RelationshipStatus::User => RelationshipStatus::User,
revolt_database::RelationshipStatus::Friend => RelationshipStatus::Friend,
revolt_database::RelationshipStatus::Outgoing => RelationshipStatus::Outgoing,
revolt_database::RelationshipStatus::Incoming => RelationshipStatus::Incoming,
revolt_database::RelationshipStatus::Blocked => RelationshipStatus::Blocked,
revolt_database::RelationshipStatus::BlockedOther => RelationshipStatus::BlockedOther,
}
}
}
#[cfg(feature = "from_database")]
impl From<revolt_database::Relationship> for Relationship {
fn from(value: revolt_database::Relationship) -> Self {
Self {
user_id: value.id,
status: value.status.into(),
}
}
}
#[cfg(feature = "from_database")]
impl From<revolt_database::Presence> for Presence {
fn from(value: revolt_database::Presence) -> Self {
match value {
revolt_database::Presence::Online => Presence::Online,
revolt_database::Presence::Idle => Presence::Idle,
revolt_database::Presence::Focus => Presence::Focus,
revolt_database::Presence::Busy => Presence::Busy,
revolt_database::Presence::Invisible => Presence::Invisible,
}
}
}
#[cfg(feature = "from_database")]
impl From<revolt_database::UserStatus> for UserStatus {
fn from(value: revolt_database::UserStatus) -> Self {
UserStatus {
text: value.text,
presence: value.presence.map(|presence| presence.into()),
}
}
}
#[cfg(feature = "from_database")]
impl From<revolt_database::UserProfile> for UserProfile {
fn from(value: revolt_database::UserProfile) -> Self {
UserProfile {
content: value.content,
background: value.background.map(|file| file.into()),
}
}
}
#[cfg(feature = "from_database")]
impl From<revolt_database::BotInformation> for BotInformation {
fn from(value: revolt_database::BotInformation) -> Self {
BotInformation {
owner_id: value.owner,
}
}
}
+5 -2
View File
@@ -1,6 +1,6 @@
[package]
name = "revolt-permissions"
version = "0.0.2"
version = "0.6.3"
edition = "2021"
license = "AGPL-3.0-or-later"
authors = [ "Paul Makles <me@insrt.uk>" ]
@@ -9,10 +9,12 @@ description = "Revolt Backend: Permission Logic"
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
[features]
bson = ["dep:bson"]
serde = [ "dep:serde" ]
schemas = [ "dep:schemars" ]
try-from-primitive = [ "dep:num_enum" ]
[dev-dependencies]
# Async
async-std = { version = "1.8.0", features = ["attributes"] }
@@ -28,6 +30,7 @@ async-trait = "0.1.51"
# Serialisation
serde = { version = "1", features = ["derive"], optional = true }
bson = { version = "2.1.0", optional = true}
# Spec Generation
schemars = { version = "0.8.8", optional = true }
schemars = { version = "0.8.8", optional = true }
+45 -4
View File
@@ -1,6 +1,10 @@
#[cfg(feature = "schemas")]
use schemars::JsonSchema;
/// Representation of a single permission override
#[derive(Debug, Clone, Copy, Eq, PartialEq)]
#[derive(Debug, Clone, Eq, PartialEq)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
#[cfg_attr(feature = "schemas", derive(JsonSchema))]
pub struct Override {
/// Allow bit flags
pub allow: u64,
@@ -8,10 +12,43 @@ pub struct Override {
pub deny: u64,
}
/// Data permissions Field - contains both allow and deny
#[derive(Debug, Clone, Eq, PartialEq)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
#[cfg_attr(feature = "schemas", derive(JsonSchema))]
pub struct DataPermissionsField {
pub permissions: Override,
}
/// Data permissions Value - contains allow
#[derive(Debug, Clone, Copy, Eq, PartialEq)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
#[cfg_attr(feature = "schemas", derive(JsonSchema))]
pub struct DataPermissionsValue {
pub permissions: u64,
}
/// Data permissions Poly - can contain either Value or Field
#[derive(Debug, Clone, Eq, PartialEq)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
#[cfg_attr(feature = "schemas", derive(JsonSchema))]
#[cfg_attr(feature = "serde", serde(untagged))]
pub enum DataPermissionPoly {
Value {
/// Permission values to set for members in a `Group`
permissions: u64,
},
Field {
/// Allow / deny values to set for members in this `TextChannel` or `VoiceChannel`
permissions: Override,
},
}
/// Representation of a single permission override
/// as it appears on models and in the database
#[derive(/*JsonSchema, */ Debug, Clone, Copy, Default, Eq, PartialEq)]
#[derive(Debug, Clone, Copy, Default, Eq, PartialEq)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
#[cfg_attr(feature = "schemas", derive(JsonSchema))]
pub struct OverrideField {
/// Allow bit flags
a: i64,
@@ -49,8 +86,12 @@ impl From<OverrideField> for Override {
}
}
/*impl From<OverrideField> for Bson {
#[cfg(feature = "bson")]
use bson::Bson;
#[cfg(feature = "bson")]
impl From<OverrideField> for Bson {
fn from(v: OverrideField) -> Self {
Self::Document(bson::to_document(&v).unwrap())
}
}*/
}
+1 -1
View File
@@ -1,6 +1,6 @@
[package]
name = "revolt-presence"
version = "0.0.2"
version = "0.6.3"
edition = "2021"
license = "AGPL-3.0-or-later"
authors = [ "Paul Makles <me@insrt.uk>" ]
+9 -1
View File
@@ -1,6 +1,6 @@
[package]
name = "revolt-result"
version = "0.0.2"
version = "0.6.3"
edition = "2021"
license = "AGPL-3.0-or-later"
authors = [ "Paul Makles <me@insrt.uk>" ]
@@ -11,12 +11,20 @@ description = "Revolt Backend: Result and Error types"
[features]
serde = [ "dep:serde" ]
schemas = [ "dep:schemars" ]
rocket = [ "dep:rocket", "dep:serde_json" ]
okapi = [ "dep:revolt_rocket_okapi", "dep:revolt_okapi" ]
default = [ "serde" ]
[dependencies]
# Serialisation
serde_json = { version = "1", optional = true }
serde = { version = "1", features = ["derive"], optional = true }
# Spec Generation
schemars = { version = "0.8.8", optional = true }
# Rocket
rocket = { optional = true, version = "0.5.0-rc.2", default-features = false }
revolt_rocket_okapi = { version = "0.9.1", optional = true }
revolt_okapi = { version = "0.9.1", optional = true }
+6
View File
@@ -6,6 +6,12 @@ extern crate serde;
#[macro_use]
extern crate schemars;
#[cfg(feature = "rocket")]
pub mod rocket;
#[cfg(feature = "okapi")]
pub mod okapi;
/// Result type with custom Error
pub type Result<T, E = Error> = std::result::Result<T, E>;
+49
View File
@@ -0,0 +1,49 @@
use revolt_okapi::openapi3::SchemaObject;
use revolt_rocket_okapi::revolt_okapi::openapi3;
use schemars::schema::Schema;
use crate::Error;
impl revolt_rocket_okapi::response::OpenApiResponderInner for Error {
fn responses(
gen: &mut revolt_rocket_okapi::gen::OpenApiGenerator,
) -> std::result::Result<openapi3::Responses, revolt_rocket_okapi::OpenApiError> {
let mut content = revolt_okapi::Map::new();
let settings = schemars::gen::SchemaSettings::default().with(|s| {
s.option_nullable = true;
s.option_add_null_type = false;
s.definitions_path = "#/components/schemas/".to_string();
});
let mut schema_generator = settings.into_generator();
let schema = schema_generator.root_schema_for::<Error>();
let definitions = gen.schema_generator().definitions_mut();
for (key, value) in schema.definitions {
definitions.insert(key, value);
}
definitions.insert("Error".to_string(), Schema::Object(schema.schema));
content.insert(
"application/json".to_string(),
openapi3::MediaType {
schema: Some(SchemaObject {
reference: Some("#/components/schemas/Error".to_string()),
..Default::default()
}),
..Default::default()
},
);
Ok(openapi3::Responses {
default: Some(openapi3::RefOr::Object(openapi3::Response {
content,
description: "An error occurred.".to_string(),
..Default::default()
})),
..Default::default()
})
}
}
+87
View File
@@ -0,0 +1,87 @@
use std::io::Cursor;
use rocket::{
http::{ContentType, Status},
response::{self, Responder},
Request, Response,
};
use crate::{Error, ErrorType};
/// HTTP response builder for Error enum
impl<'r> Responder<'r, 'static> for Error {
fn respond_to(self, _: &'r Request<'_>) -> response::Result<'static> {
let status = match self.error_type {
ErrorType::LabelMe => Status::InternalServerError,
ErrorType::AlreadyOnboarded => Status::Forbidden,
ErrorType::UnknownUser => Status::NotFound,
ErrorType::InvalidUsername => Status::BadRequest,
ErrorType::UsernameTaken => Status::Conflict,
ErrorType::AlreadyFriends => Status::Conflict,
ErrorType::AlreadySentRequest => Status::Conflict,
ErrorType::Blocked => Status::Conflict,
ErrorType::BlockedByOther => Status::Forbidden,
ErrorType::NotFriends => Status::Forbidden,
ErrorType::UnknownChannel => Status::NotFound,
ErrorType::UnknownMessage => Status::NotFound,
ErrorType::UnknownAttachment => Status::BadRequest,
ErrorType::CannotEditMessage => Status::Forbidden,
ErrorType::CannotJoinCall => Status::BadRequest,
ErrorType::TooManyAttachments { .. } => Status::BadRequest,
ErrorType::TooManyReplies { .. } => Status::BadRequest,
ErrorType::EmptyMessage => Status::UnprocessableEntity,
ErrorType::PayloadTooLarge => Status::UnprocessableEntity,
ErrorType::CannotRemoveYourself => Status::BadRequest,
ErrorType::GroupTooLarge { .. } => Status::Forbidden,
ErrorType::AlreadyInGroup => Status::Conflict,
ErrorType::NotInGroup => Status::NotFound,
ErrorType::UnknownServer => Status::NotFound,
ErrorType::InvalidRole => Status::NotFound,
ErrorType::Banned => Status::Forbidden,
ErrorType::TooManyServers { .. } => Status::BadRequest,
ErrorType::TooManyEmoji { .. } => Status::BadRequest,
ErrorType::TooManyChannels { .. } => Status::BadRequest,
ErrorType::TooManyRoles { .. } => Status::BadRequest,
ErrorType::ReachedMaximumBots => Status::BadRequest,
ErrorType::IsBot => Status::BadRequest,
ErrorType::BotIsPrivate => Status::Forbidden,
ErrorType::CannotReportYourself => Status::BadRequest,
ErrorType::MissingPermission { .. } => Status::Forbidden,
ErrorType::MissingUserPermission { .. } => Status::Forbidden,
ErrorType::NotElevated => Status::Forbidden,
ErrorType::NotPrivileged => Status::Forbidden,
ErrorType::CannotGiveMissingPermissions => Status::Forbidden,
ErrorType::NotOwner => Status::Forbidden,
ErrorType::DatabaseError { .. } => Status::InternalServerError,
ErrorType::InternalError => Status::InternalServerError,
ErrorType::InvalidOperation => Status::BadRequest,
ErrorType::InvalidCredentials => Status::Unauthorized,
ErrorType::InvalidProperty => Status::BadRequest,
ErrorType::InvalidSession => Status::Unauthorized,
ErrorType::DuplicateNonce => Status::Conflict,
ErrorType::VosoUnavailable => Status::BadRequest,
ErrorType::NotFound => Status::NotFound,
ErrorType::NoEffect => Status::Ok,
ErrorType::FailedValidation { .. } => Status::BadRequest,
};
// Serialize the error data structure into JSON.
let string = serde_json::to_string(&self).unwrap();
// Build and send the request.
Response::build()
.sized_body(string.len(), Cursor::new(string))
.header(ContentType::new("application", "json"))
.status(status)
.ok()
}
}
+6 -4
View File
@@ -1,6 +1,6 @@
[package]
name = "revolt-delta"
version = "0.5.20"
version = "0.6.3"
license = "AGPL-3.0-or-later"
authors = ["Paul Makles <paulmakles@gmail.com>"]
edition = "2018"
@@ -31,7 +31,7 @@ nanoid = "0.4.0"
# serde
serde_json = "1.0.57"
serde = { version = "1.0.115", features = ["derive"] }
validator = { version = "0.14", features = ["derive"] }
validator = { version = "0.16", features = ["derive"] }
# async
futures = "0.3.8"
@@ -56,8 +56,10 @@ revolt_rocket_okapi = { version = "0.9.1", features = [ "swagger" ] }
revolt-quark = { path = "../quark" }
# core
revolt-database = { path = "../core/database", features = [ "rocket-impl" ] }
revolt-models = { path = "../core/models", features = [ "schemas", "redis-is-patched" ] }
revolt-database = { path = "../core/database", features = [ "rocket-impl", "redis-is-patched" ] }
revolt-models = { path = "../core/models", features = [ "schemas", "validator" ] }
revolt-result = { path = "../core/result", features = [ "rocket", "okapi" ] }
revolt-permissions = { path = "../core/permissions", features = [ "schemas" ] }
[build-dependencies]
vergen = "7.5.0"
+8
View File
@@ -8,10 +8,13 @@ extern crate serde_json;
pub mod routes;
pub mod util;
use std::net::Ipv4Addr;
use async_std::channel::unbounded;
use revolt_quark::authifier::{Authifier, AuthifierEvent};
use revolt_quark::events::client::EventV1;
use revolt_quark::DatabaseInfo;
use rocket::data::ToByteUnit;
#[launch]
async fn rocket() -> _ {
@@ -72,4 +75,9 @@ async fn rocket() -> _ {
.manage(cors.clone())
.attach(revolt_quark::web::ratelimiter::RatelimitFairing)
.attach(cors)
.configure(rocket::Config {
limits: rocket::data::Limits::default().limit("string", 5.megabytes()),
address: Ipv4Addr::new(0, 0, 0, 0).into(),
..Default::default()
})
}
+3 -5
View File
@@ -38,14 +38,12 @@ pub async fn create_bot(db: &Db, user: User, info: Json<DataCreateBot>) -> Resul
return Err(Error::ReachedMaximumBots);
}
if db.is_username_taken(&info.name).await? {
return Err(Error::UsernameTaken);
}
let id = Ulid::new().to_string();
let username = User::validate_username(info.name)?;
let bot_user = User {
id: id.clone(),
username: info.name.trim().to_string(),
discriminator: User::find_discriminator(db, &username, None).await?,
username,
bot: Some(BotInformation {
owner: user.id.clone(),
}),
-4
View File
@@ -58,10 +58,6 @@ pub async fn edit_bot(
}
if let Some(name) = data.name {
if db.is_username_taken(&name).await? {
return Err(Error::UsernameTaken);
}
let mut user = db.fetch_user(&bot.id).await?;
user.update_username(db, name).await?;
}
+6 -5
View File
@@ -23,11 +23,12 @@ pub async fn fetch_bot(
}
Ok(Json(FetchBotResponse {
user: revolt_models::v0::User::from(
db.fetch_user(&bot.id).await.map_err(Error::from_core)?,
None,
)
.await,
user: db
.fetch_user(&bot.id)
.await
.map_err(Error::from_core)?
.into(None)
.await,
bot: bot.into(),
}))
}
+1 -1
View File
@@ -21,5 +21,5 @@ pub async fn fetch_public_bot(
}
let user = db.fetch_user(&bot.id).await.map_err(Error::from_core)?;
Ok(Json(PublicBot::from(bot, user)))
Ok(Json(bot.into_public_bot(user)))
}
@@ -44,8 +44,6 @@ pub async fn req(
.throw_permission_and_view_channel(db, Permission::SendMessage)
.await?;
Message::validate_sum(&edit.content, &edit.embeds)?;
let mut message = msg.as_message(db).await?;
if message.channel != channel.id() {
return Err(Error::NotFound);
@@ -55,6 +53,8 @@ pub async fn req(
return Err(Error::CannotEditMessage);
}
Message::validate_sum(&edit.content, edit.embeds.as_deref().unwrap_or_default())?;
message.edited = Some(Timestamp::now_utc());
let mut partial = PartialMessage {
edited: message.edited,
@@ -81,7 +81,7 @@ pub async fn req(
new_embeds.clear();
for embed in embeds {
new_embeds.push(embed.clone().into_embed(db, message.id.clone()).await?);
new_embeds.push(embed.clone().into_embed(db, &message.id).await?);
}
}
+30 -177
View File
@@ -1,51 +1,13 @@
use std::collections::HashSet;
use revolt_quark::{
models::{
message::{Interactions, Masquerade, Reply, SendableEmbed},
Message, User,
},
models::{message::DataMessageSend, Message, User},
perms,
types::push::MessageAuthor,
web::idempotency::IdempotencyKey,
Db, Error, Permission, Ref, Result, variables::delta::{MAX_ATTACHMENT_COUNT, MAX_REPLY_COUNT},
Db, Error, Permission, Ref, Result,
};
use regex::Regex;
use rocket::serde::json::Json;
use serde::{Deserialize, Serialize};
use ulid::Ulid;
use validator::Validate;
use once_cell::sync::Lazy;
#[derive(Validate, Serialize, Deserialize, JsonSchema)]
pub struct DataMessageSend {
/// Unique token to prevent duplicate message sending
///
/// **This is deprecated and replaced by `Idempotency-Key`!**
#[validate(length(min = 1, max = 64))]
nonce: Option<String>,
/// Message content to send
#[validate(length(min = 0, max = 2000))]
content: Option<String>,
/// Attachments to include in message
#[validate(length(min = 1, max = 128))]
attachments: Option<Vec<String>>,
/// Messages to reply to
replies: Option<Vec<Reply>>,
/// Embeds to include in message
///
/// Text embed content contributes to the content length cap
#[validate(length(min = 1, max = 10))]
embeds: Option<Vec<SendableEmbed>>,
/// Masquerade to apply to this message
#[validate]
masquerade: Option<Masquerade>,
/// Information about how this message should be interacted with
interactions: Option<Interactions>,
}
static RE_MENTION: Lazy<Regex> = Lazy::new(|| Regex::new(r"<@([0-9A-HJKMNP-TV-Z]{26})>").unwrap());
/// # Send Message
///
@@ -57,71 +19,22 @@ pub async fn message_send(
user: User,
target: Ref,
data: Json<DataMessageSend>,
mut idempotency: IdempotencyKey,
idempotency: IdempotencyKey,
) -> Result<Json<Message>> {
let data = data.into_inner();
data.validate()
.map_err(|error| Error::FailedValidation { error })?;
// Validate Message is within reasonable length limits
Message::validate_sum(&data.content, &data.embeds)?;
// Ensure the request is unique
idempotency.consume_nonce(data.nonce).await?;
// Ensure we have permissions to send a message
let channel = target.as_channel(db).await?;
let mut permissions = perms(&user).channel(&channel);
permissions
.throw_permission_and_view_channel(db, Permission::SendMessage)
.await?;
// Check the message is not empty
if (data.content.as_ref().map_or(true, |v| v.is_empty()))
&& (data.attachments.as_ref().map_or(true, |v| v.is_empty()))
&& (data.embeds.as_ref().map_or(true, |v| v.is_empty()))
{
return Err(Error::EmptyMessage);
}
// Ensure restrict_reactions is not specified without reactions list
if let Some(interactions) = &data.interactions {
if interactions.restrict_reactions {
let disallowed = if let Some(list) = &interactions.reactions {
list.is_empty()
} else {
true
};
if disallowed {
return Err(Error::InvalidProperty);
}
}
}
// Start constructing the message
let message_id = Ulid::new().to_string();
let mut message = Message {
id: message_id.clone(),
channel: channel.id().to_string(),
author: user.id.clone(),
masquerade: data.masquerade,
interactions: data.interactions.unwrap_or_default(),
..Default::default()
};
// 1. Parse mentions in message.
let mut mentions = HashSet::new();
if let Some(content) = &data.content {
for capture in RE_MENTION.captures_iter(content) {
if let Some(mention) = capture.get(1) {
mentions.insert(mention.as_str().to_string());
}
}
}
// 2. Verify permissions for masquerade.
if let Some(masq) = &message.masquerade {
// Verify permissions for masquerade
if let Some(masq) = &data.masquerade {
permissions
.throw_permission(db, Permission::Masquerade)
.await?;
@@ -133,97 +46,37 @@ pub async fn message_send(
}
}
// 3. Ensure interactions information is correct
message.interactions.validate(db, &mut permissions).await?;
// 4. Verify replies are valid.
let mut replies = HashSet::new();
if let Some(entries) = data.replies {
if entries.len() > *MAX_REPLY_COUNT {
return Err(Error::TooManyReplies { max: *MAX_REPLY_COUNT });
}
for Reply { id, mention } in entries {
let message = Ref::from_unchecked(id).as_message(db).await?;
replies.insert(message.id);
if mention {
mentions.insert(message.author);
}
}
// Check permissions for embeds
if data.embeds.as_ref().is_some_and(|v| !v.is_empty()) {
permissions
.throw_permission(db, Permission::SendEmbeds)
.await?;
}
if !mentions.is_empty() {
message.mentions.replace(
mentions
.into_iter()
.filter(|id| !user.has_blocked(id))
.collect::<Vec<String>>(),
);
// Check permissions for files
if data.attachments.as_ref().is_some_and(|v| !v.is_empty()) {
permissions
.throw_permission(db, Permission::UploadFiles)
.await?;
}
if !replies.is_empty() {
message
.replies
.replace(replies.into_iter().collect::<Vec<String>>());
// Ensure interactions information is correct
if let Some(interactions) = &data.interactions {
interactions.validate(db, &mut permissions).await?;
}
// 5. Process included embeds.
let mut embeds = vec![];
if let Some(sendable_embeds) = data.embeds {
for sendable_embed in sendable_embeds {
embeds.push(sendable_embed.into_embed(db, message_id.clone()).await?)
}
}
if !embeds.is_empty() {
message.embeds.replace(embeds);
}
// 6. Add attachments to message.
let mut attachments = vec![];
if let Some(ids) = &data.attachments {
if !ids.is_empty() {
// Create the message
let message = channel
.send_message(
db,
data,
MessageAuthor::User(&user),
idempotency,
permissions
.throw_permission(db, Permission::UploadFiles)
.await?;
}
// ! FIXME: move this to app config
if ids.len() > *MAX_ATTACHMENT_COUNT {
return Err(Error::TooManyAttachments { max: *MAX_ATTACHMENT_COUNT} );
}
for attachment_id in ids {
attachments.push(
db.find_and_use_attachment(attachment_id, "attachments", "message", &message_id)
.await?,
);
}
}
if !attachments.is_empty() {
message.attachments.replace(attachments);
}
// 7. Set content
message.content = data.content;
// 8. Pass-through nonce value for clients
message.nonce = Some(idempotency.into_key());
message.create(db, &channel, Some(&user)).await?;
// Queue up a task for processing embeds
if let Some(content) = &message.content {
revolt_quark::tasks::process_embeds::queue(
channel.id().to_string(),
message.id.to_string(),
content.clone(),
.has_permission(db, Permission::SendEmbeds)
.await?,
)
.await;
}
.await?;
Ok(Json(message))
}
+5 -1
View File
@@ -24,6 +24,8 @@ mod message_unreact;
mod permissions_set;
mod permissions_set_default;
mod voice_join;
mod webhook_create;
mod webhook_fetch_all;
pub fn routes() -> (Vec<Route>, OpenApi) {
openapi_get_routes_spec![
@@ -49,6 +51,8 @@ pub fn routes() -> (Vec<Route>, OpenApi) {
permissions_set_default::req,
message_react::react_message,
message_unreact::unreact_message,
message_clear_reactions::clear_reactions
message_clear_reactions::clear_reactions,
webhook_create::req,
webhook_fetch_all::req,
]
}
@@ -0,0 +1,69 @@
use revolt_database::{Database, Webhook};
use revolt_quark::{
models::{Channel, User},
perms, Db, Error, Permission, Ref, Result,
};
use rocket::{serde::json::Json, State};
use serde::{Deserialize, Serialize};
use ulid::Ulid;
use validator::Validate;
#[derive(Validate, Serialize, Deserialize, JsonSchema)]
pub struct CreateWebhookBody {
#[validate(length(min = 1, max = 32))]
name: String,
#[validate(length(min = 1, max = 128))]
avatar: Option<String>,
}
/// # Creates a webhook
///
/// Creates a webhook which 3rd party platforms can use to send messages
#[openapi(tag = "Webhooks")]
#[post("/<target>/webhooks", data = "<data>")]
pub async fn req(
db: &State<Database>,
legacy_db: &Db,
user: User,
target: Ref,
data: Json<CreateWebhookBody>,
) -> Result<Json<revolt_models::v0::Webhook>> {
let data = data.into_inner();
data.validate()
.map_err(|error| Error::FailedValidation { error })?;
let channel = target.as_channel(legacy_db).await?;
if !matches!(channel, Channel::TextChannel { .. } | Channel::Group { .. }) {
return Err(Error::InvalidOperation);
}
let mut permissions = perms(&user).channel(&channel);
permissions
.has_permission(legacy_db, Permission::ManageWebhooks)
.await?;
let webhook_id = Ulid::new().to_string();
let avatar = match &data.avatar {
Some(id) => Some(
db.find_and_use_attachment(id, "avatars", "user", &webhook_id)
.await
.map_err(Error::from_core)?,
),
None => None,
};
let webhook = Webhook {
id: webhook_id,
name: data.name,
avatar,
channel_id: channel.id().to_string(),
token: Some(nanoid::nanoid!(64)),
};
webhook.create(db).await.map_err(Error::from_core)?;
Ok(Json(webhook.into()))
}
@@ -0,0 +1,31 @@
use revolt_database::Database;
use revolt_models::v0::Webhook;
use revolt_quark::{models::User, perms, Db, Error, Permission, Ref, Result};
use rocket::{serde::json::Json, State};
/// # Gets all webhooks
///
/// Gets all webhooks inside the channel
#[openapi(tag = "Webhooks")]
#[get("/<channel_id>/webhooks")]
pub async fn req(
db: &State<Database>,
legacy_db: &Db,
user: User,
channel_id: Ref,
) -> Result<Json<Vec<Webhook>>> {
let channel = channel_id.as_channel(legacy_db).await?;
let mut permissions = perms(&user).channel(&channel);
permissions
.has_permission(legacy_db, Permission::ManageWebhooks)
.await?;
Ok(Json(
db.fetch_webhooks_for_channel(channel.id())
.await
.map_err(Error::from_core)?
.into_iter()
.map(|v| v.into())
.collect::<Vec<Webhook>>(),
))
}
+57 -21
View File
@@ -1,3 +1,4 @@
use revolt_quark::variables::delta::IS_STAGING;
use revolt_rocket_okapi::{revolt_okapi::openapi3::OpenApi, settings::OpenApiSettings};
pub use rocket::http::Status;
pub use rocket::response::Redirect;
@@ -15,29 +16,53 @@ mod safety;
mod servers;
mod sync;
mod users;
mod webhooks;
pub fn mount(mut rocket: Rocket<Build>) -> Rocket<Build> {
let settings = OpenApiSettings::default();
mount_endpoints_and_merged_docs! {
rocket, "/".to_owned(), settings,
"/" => (vec![], custom_openapi_spec()),
"" => openapi_get_routes_spec![root::root, root::ping],
"/admin" => admin::routes(),
"/users" => users::routes(),
"/bots" => bots::routes(),
"/channels" => channels::routes(),
"/servers" => servers::routes(),
"/invites" => invites::routes(),
"/custom" => customisation::routes(),
"/safety" => safety::routes(),
"/auth/account" => rocket_authifier::routes::account::routes(),
"/auth/session" => rocket_authifier::routes::session::routes(),
"/auth/mfa" => rocket_authifier::routes::mfa::routes(),
"/onboard" => onboard::routes(),
"/push" => push::routes(),
"/sync" => sync::routes(),
};
if *IS_STAGING {
mount_endpoints_and_merged_docs! {
rocket, "/".to_owned(), settings,
"/" => (vec![], custom_openapi_spec()),
"" => openapi_get_routes_spec![root::root, root::ping],
"/admin" => admin::routes(),
"/users" => users::routes(),
"/bots" => bots::routes(),
"/channels" => channels::routes(),
"/servers" => servers::routes(),
"/invites" => invites::routes(),
"/custom" => customisation::routes(),
"/safety" => safety::routes(),
"/auth/account" => rocket_authifier::routes::account::routes(),
"/auth/session" => rocket_authifier::routes::session::routes(),
"/auth/mfa" => rocket_authifier::routes::mfa::routes(),
"/onboard" => onboard::routes(),
"/push" => push::routes(),
"/sync" => sync::routes(),
"/webhooks" => webhooks::routes()
};
} else {
mount_endpoints_and_merged_docs! {
rocket, "/".to_owned(), settings,
"/" => (vec![], custom_openapi_spec()),
"" => openapi_get_routes_spec![root::root, root::ping],
"/admin" => admin::routes(),
"/users" => users::routes(),
"/bots" => bots::routes(),
"/channels" => channels::routes(),
"/servers" => servers::routes(),
"/invites" => invites::routes(),
"/custom" => customisation::routes(),
"/safety" => safety::routes(),
"/auth/account" => rocket_authifier::routes::account::routes(),
"/auth/session" => rocket_authifier::routes::session::routes(),
"/auth/mfa" => rocket_authifier::routes::mfa::routes(),
"/onboard" => onboard::routes(),
"/push" => push::routes(),
"/sync" => sync::routes()
};
}
rocket
}
@@ -86,7 +111,8 @@ fn custom_openapi_spec() -> OpenApi {
"Messaging",
"Interactions",
"Groups",
"Voice"
"Voice",
"Webhooks",
]
},
{
@@ -158,7 +184,12 @@ fn custom_openapi_spec() -> OpenApi {
servers: vec![
Server {
url: "https://api.revolt.chat".to_owned(),
description: Some("Revolt API".to_owned()),
description: Some("Revolt Production".to_owned()),
..Default::default()
},
Server {
url: "https://revolt.chat/api".to_owned(),
description: Some("Revolt Staging".to_owned()),
..Default::default()
},
Server {
@@ -288,6 +319,11 @@ fn custom_openapi_spec() -> OpenApi {
),
..Default::default()
},
Tag {
name: "Webhooks".to_owned(),
description: Some("Send messages from 3rd party services".to_owned()),
..Default::default()
},
],
..Default::default()
}
+2 -1
View File
@@ -34,9 +34,10 @@ pub async fn req(
data.validate()
.map_err(|error| Error::FailedValidation { error })?;
let username = User::validate_username(db, data.username).await?;
let username = User::validate_username(data.username)?;
let user = User {
id: session.user_id,
discriminator: User::find_discriminator(db, &username, None).await?,
username,
..Default::default()
};
@@ -0,0 +1,34 @@
use revolt_database::{AccountStrike, Database};
use revolt_models::v0::{AccountStrike as AccountStrikeModel, DataCreateStrike};
use revolt_quark::models::User;
use revolt_quark::{Error, Result};
use rocket::serde::json::Json;
use rocket::State;
/// # Create Strike
///
/// Create a new account strike
#[openapi(tag = "User Safety")]
#[post("/strikes", data = "<data>")]
pub async fn create_strike(
db: &State<Database>,
user: User,
data: Json<DataCreateStrike>,
) -> Result<Json<AccountStrikeModel>> {
// Must be privileged for this route
if !user.privileged {
return Err(Error::NotPrivileged);
}
let data = data.into_inner();
let target = db
.fetch_user(&data.user_id)
.await
.map_err(Error::from_core)?;
AccountStrike::create(db, target.id, data.reason, user.id)
.await
.map(|strike| strike.into())
.map(Json)
.map_err(Error::from_core)
}
+2
View File
@@ -8,6 +8,7 @@ mod report_content;
mod fetch_snapshots;
mod create_strike;
mod delete_strike;
mod edit_strike;
mod fetch_strikes;
@@ -22,6 +23,7 @@ pub fn routes() -> (Vec<Route>, OpenApi) {
// Snapshots
fetch_snapshots::fetch_snapshots,
// Strikes
create_strike::create_strike,
fetch_strikes::fetch_strikes,
edit_strike::edit_strike,
delete_strike::delete_strike
@@ -14,6 +14,8 @@ struct BannedUser {
pub id: String,
/// Username of the banned user
pub username: String,
/// Discriminator of the banned user
pub discriminator: String,
/// Avatar of the banned user
pub avatar: Option<File>,
}
@@ -32,6 +34,7 @@ impl From<User> for BannedUser {
BannedUser {
id: user.id,
username: user.username,
discriminator: user.discriminator,
avatar: user.avatar,
}
}
@@ -1,18 +1,9 @@
use rocket::serde::json::Json;
use serde::Deserialize;
use revolt_permissions::DataPermissionsValue;
use revolt_quark::{
models::{server::PartialServer, Server, User},
perms, Db, Permission, Ref, Result,
};
/// # Permission Value
#[derive(Deserialize, JsonSchema)]
pub struct DataSetServerDefaultPermission {
/// Default member permission value
permissions: u64,
}
use rocket::serde::json::Json;
/// # Set Default Permission
///
/// Sets permissions for the default role in this server.
@@ -22,7 +13,7 @@ pub async fn req(
db: &Db,
user: User,
target: Ref,
data: Json<DataSetServerDefaultPermission>,
data: Json<DataPermissionsValue>,
) -> Result<Json<Server>> {
let data = data.into_inner();
+8 -1
View File
@@ -8,6 +8,8 @@ use rocket::State;
use serde::{Deserialize, Serialize};
use validator::Validate;
use crate::util::regex::RE_DISPLAY_NAME;
/// # Profile Data
#[derive(Validate, Serialize, Deserialize, Debug, JsonSchema)]
pub struct UserProfileData {
@@ -24,6 +26,9 @@ pub struct UserProfileData {
/// # User Data
#[derive(Validate, Serialize, Deserialize, JsonSchema)]
pub struct DataEditUser {
/// New display name
#[validate(length(min = 2, max = 32), regex = "RE_DISPLAY_NAME")]
display_name: Option<String>,
/// Attachment Id for avatar
#[validate(length(min = 1, max = 128))]
avatar: Option<String>,
@@ -84,7 +89,8 @@ pub async fn req(
}
// Exit out early if nothing is changed
if data.status.is_none()
if data.display_name.is_none()
&& data.status.is_none()
&& data.profile.is_none()
&& data.avatar.is_none()
&& data.badges.is_none()
@@ -116,6 +122,7 @@ pub async fn req(
}
let mut partial: PartialUser = PartialUser {
display_name: data.display_name,
badges: data.badges,
flags: data.flags,
..Default::default()
@@ -8,6 +8,7 @@ use serde::{Deserialize, Serialize};
/// # User Lookup Information
#[derive(Serialize, Deserialize, JsonSchema)]
pub struct DataSendFriendRequest {
/// Username and discriminator combo separated by #
username: String,
}
@@ -21,12 +22,16 @@ pub async fn req(
user: User,
data: Json<DataSendFriendRequest>,
) -> Result<Json<User>> {
let mut target = db.fetch_user_by_username(&data.username).await?;
if let Some((username, discriminator)) = data.username.split_once('#') {
let mut target = db.fetch_user_by_username(username, discriminator).await?;
if user.bot.is_some() || target.bot.is_some() {
return Err(Error::IsBot);
if user.bot.is_some() || target.bot.is_some() {
return Err(Error::IsBot);
}
user.add_friend(db, &mut target).await?;
Ok(Json(target.with_auto_perspective(db, &user).await))
} else {
Err(Error::InvalidProperty)
}
user.add_friend(db, &mut target).await?;
Ok(Json(target.with_auto_perspective(db, &user).await))
}
+24
View File
@@ -0,0 +1,24 @@
use rocket::Route;
use revolt_rocket_okapi::revolt_okapi::openapi3::OpenApi;
mod webhook_delete;
mod webhook_delete_token;
mod webhook_edit;
mod webhook_edit_token;
mod webhook_execute;
mod webhook_fetch_token;
mod webhook_fetch;
mod webhook_execute_github;
pub fn routes() -> (Vec<Route>, OpenApi) {
openapi_get_routes_spec![
webhook_delete_token::webhook_delete_token,
webhook_delete::webhook_delete,
webhook_edit_token::webhook_edit_token,
webhook_edit::webhook_edit,
webhook_execute_github::webhook_execute_github,
webhook_execute::webhook_execute,
webhook_fetch_token::webhook_fetch_token,
webhook_fetch::webhook_fetch,
]
}
@@ -0,0 +1,30 @@
use revolt_database::{util::reference::Reference, Database};
use revolt_quark::{models::User, perms, Db, Error, Permission, Result};
use rocket::State;
use rocket_empty::EmptyResponse;
/// # Deletes a webhook
///
/// Deletes a webhook
#[openapi(tag = "Webhooks")]
#[delete("/<webhook_id>")]
pub async fn webhook_delete(
db: &State<Database>,
legacy_db: &Db,
user: User,
webhook_id: Reference,
) -> Result<EmptyResponse> {
let webhook = webhook_id.as_webhook(db).await.map_err(Error::from_core)?;
let channel = legacy_db.fetch_channel(&webhook.channel_id).await?;
perms(&user)
.channel(&channel)
.throw_permission(legacy_db, Permission::ManageWebhooks)
.await?;
webhook
.delete(db)
.await
.map(|_| EmptyResponse)
.map_err(Error::from_core)
}
@@ -0,0 +1,19 @@
use revolt_database::{util::reference::Reference, Database};
use revolt_result::Result;
use rocket::State;
use rocket_empty::EmptyResponse;
/// # Deletes a webhook
///
/// Deletes a webhook with a token
#[openapi(tag = "Webhooks")]
#[delete("/<webhook_id>/<token>")]
pub async fn webhook_delete_token(
db: &State<Database>,
webhook_id: Reference,
token: String,
) -> Result<EmptyResponse> {
let webhook = webhook_id.as_webhook(db).await?;
webhook.assert_token(&token)?;
webhook.delete(db).await.map(|_| EmptyResponse)
}
@@ -0,0 +1,61 @@
use revolt_database::{util::reference::Reference, Database, PartialWebhook};
use revolt_models::v0::{DataEditWebhook, Webhook};
use revolt_quark::{models::User, perms, Db, Error, Permission, Result};
use rocket::{serde::json::Json, State};
use validator::Validate;
/// # Edits a webhook
///
/// Edits a webhook
#[openapi(tag = "Webhooks")]
#[patch("/<webhook_id>", data = "<data>")]
pub async fn webhook_edit(
db: &State<Database>,
legacy_db: &Db,
webhook_id: Reference,
user: User,
data: Json<DataEditWebhook>,
) -> Result<Json<Webhook>> {
let data = data.into_inner();
data.validate()
.map_err(|error| Error::FailedValidation { error })?;
let mut webhook = webhook_id.as_webhook(db).await.map_err(Error::from_core)?;
let channel = legacy_db.fetch_channel(&webhook.channel_id).await?;
perms(&user)
.channel(&channel)
.throw_permission(legacy_db, Permission::ManageWebhooks)
.await?;
if data.name.is_none() && data.avatar.is_none() && data.remove.is_empty() {
return Ok(Json(webhook.into()));
};
let DataEditWebhook {
name,
avatar,
remove,
} = data;
let mut partial = PartialWebhook {
name,
..Default::default()
};
if let Some(avatar) = avatar {
let file = db
.find_and_use_attachment(&avatar, "avatars", "user", &webhook.id)
.await
.map_err(Error::from_core)?;
partial.avatar = Some(file)
}
webhook
.update(db, partial, remove.into_iter().map(|v| v.into()).collect())
.await
.map_err(Error::from_core)?;
Ok(Json(webhook.into()))
}
@@ -0,0 +1,57 @@
use revolt_database::util::reference::Reference;
use revolt_database::{Database, PartialWebhook};
use revolt_models::v0::{DataEditWebhook, Webhook};
use revolt_models::validator::Validate;
use revolt_result::{create_error, Result};
use rocket::{serde::json::Json, State};
/// # Edits a webhook
///
/// Edits a webhook with a token
#[openapi(tag = "Webhooks")]
#[patch("/<webhook_id>/<token>", data = "<data>")]
pub async fn webhook_edit_token(
db: &State<Database>,
webhook_id: Reference,
token: String,
data: Json<DataEditWebhook>,
) -> Result<Json<Webhook>> {
let data = data.into_inner();
data.validate().map_err(|error| {
create_error!(FailedValidation {
error: error.to_string()
})
})?;
let mut webhook = webhook_id.as_webhook(db).await?;
webhook.assert_token(&token)?;
if data.name.is_none() && data.avatar.is_none() && data.remove.is_empty() {
return Ok(Json(webhook.into()));
};
let DataEditWebhook {
name,
avatar,
remove,
} = data;
let mut partial = PartialWebhook {
name,
..Default::default()
};
if let Some(avatar) = avatar {
let file = db
.find_and_use_attachment(&avatar, "avatars", "user", &webhook.id)
.await?;
partial.avatar = Some(file)
}
webhook
.update(db, partial, remove.into_iter().map(|v| v.into()).collect())
.await?;
Ok(Json(webhook.into()))
}
@@ -0,0 +1,47 @@
use revolt_database::{util::reference::Reference, Database};
use revolt_quark::{
models::message::{DataMessageSend, Message},
types::push::MessageAuthor,
web::idempotency::IdempotencyKey,
Db, Error, Result,
};
use rocket::{serde::json::Json, State};
use validator::Validate;
/// # Executes a webhook
///
/// Executes a webhook and sends a message
#[openapi(tag = "Webhooks")]
#[post("/<webhook_id>/<token>", data = "<data>")]
pub async fn webhook_execute(
db: &State<Database>,
legacy_db: &Db,
webhook_id: Reference,
token: String,
data: Json<DataMessageSend>,
idempotency: IdempotencyKey,
) -> Result<Json<Message>> {
let data = data.into_inner();
data.validate()
.map_err(|error| Error::FailedValidation { error })?;
let webhook = webhook_id.as_webhook(db).await.map_err(Error::from_core)?;
webhook.assert_token(&token).map_err(Error::from_core)?;
// TODO: webhooks can currently always send masquerades, files, embeds, reactions (interactions)
// TODO: they can also mention anyone
let channel = legacy_db.fetch_channel(&webhook.channel_id).await?;
let message = channel
.send_message(
legacy_db,
data,
MessageAuthor::Webhook(&webhook.into()),
idempotency,
true,
)
.await?;
Ok(Json(message))
}
File diff suppressed because it is too large Load Diff
@@ -0,0 +1,26 @@
use revolt_database::{util::reference::Reference, Database};
use revolt_models::v0::{ResponseWebhook, Webhook};
use revolt_quark::{models::User, perms, Db, Error, Permission, Result};
use rocket::{serde::json::Json, State};
/// # Gets a webhook
///
/// Gets a webhook
#[openapi(tag = "Webhooks")]
#[get("/<webhook_id>")]
pub async fn webhook_fetch(
db: &State<Database>,
legacy_db: &Db,
webhook_id: Reference,
user: User,
) -> Result<Json<ResponseWebhook>> {
let webhook = webhook_id.as_webhook(db).await.map_err(Error::from_core)?;
let channel = legacy_db.fetch_channel(&webhook.channel_id).await?;
perms(&user)
.channel(&channel)
.throw_permission(legacy_db, Permission::ViewChannel)
.await?;
Ok(Json(std::convert::Into::<Webhook>::into(webhook).into()))
}
@@ -0,0 +1,19 @@
use revolt_database::{util::reference::Reference, Database};
use revolt_models::v0::Webhook;
use revolt_result::Result;
use rocket::{serde::json::Json, State};
/// # Gets a webhook
///
/// Gets a webhook with a token
#[openapi(tag = "Webhooks")]
#[get("/<webhook_id>/<token>")]
pub async fn webhook_fetch_token(
db: &State<Database>,
webhook_id: Reference,
token: String,
) -> Result<Json<Webhook>> {
let webhook = webhook_id.as_webhook(db).await?;
webhook.assert_token(&token)?;
Ok(Json(webhook.into()))
}
+7 -2
View File
@@ -1,12 +1,17 @@
use once_cell::sync::Lazy;
use regex::Regex;
/// Regex for valid display names
///
/// Block zero width space
/// Block newline and carriage return
pub static RE_DISPLAY_NAME: Lazy<Regex> = Lazy::new(|| Regex::new(r"^[^\u200B\n\r]+$").unwrap());
/// Regex for valid usernames
///
/// Block zero width space
/// Block lookalike characters
pub static RE_USERNAME: Lazy<Regex> =
Lazy::new(|| Regex::new(r"^[^\u200BА-Яа-яΑ-Ωα-ω@#:\n\r\[\]]+$").unwrap());
pub static RE_USERNAME: Lazy<Regex> = Lazy::new(|| Regex::new(r"^(\p{L}|[\d_.-])+$").unwrap());
/// Regex for valid emoji names
///
+5 -2
View File
@@ -1,6 +1,6 @@
[package]
name = "revolt-quark"
version = "0.5.20"
version = "0.6.3"
edition = "2021"
license = "AGPL-3.0-or-later"
@@ -28,7 +28,7 @@ default = [ "test" ]
# Serialisation
revolt_optional_struct = "0.2.0"
serde = { version = "1", features = ["derive"] }
validator = { version = "0.14", features = ["derive"] }
validator = { version = "0.16", features = ["derive"] }
iso8601-timestamp = { version = "0.1.8", features = ["schema", "bson"] }
# Formats
@@ -64,6 +64,7 @@ nanoid = "0.4.0"
linkify = "0.8.1"
dotenv = "0.15.0"
indexmap = "1.9.1"
decancer = "1.6.2"
impl_ops = "0.1.1"
num_enum = "0.5.6"
reqwest = "0.11.10"
@@ -93,3 +94,5 @@ sentry = "0.25.0"
# Core
revolt-result = { path = "../core/result", features = [ "serde", "schemas" ] }
revolt-presence = { path = "../core/presence", features = [ "redis-is-patched" ] }
revolt-database = { path = "../core/database" }
revolt-models = { path = "../core/models" }
+11
View File
@@ -71,3 +71,14 @@ impl From<Database> for authifier::Database {
}
}
}
impl From<Database> for revolt_database::Database {
fn from(val: Database) -> Self {
match val {
Database::Dummy(_) => revolt_database::Database::Reference(Default::default()),
Database::MongoDb(MongoDb(client)) => revolt_database::Database::MongoDb(
revolt_database::MongoDb(client, "revolt".to_string()),
),
}
}
}
+14
View File
@@ -1,4 +1,5 @@
use authifier::AuthifierEvent;
use revolt_models::v0::{FieldsWebhook, PartialWebhook, Webhook};
use serde::{Deserialize, Serialize};
use crate::models::channel::{FieldsChannel, PartialChannel};
@@ -214,6 +215,19 @@ pub enum EventV1 {
/// Delete emoji
EmojiDelete { id: String },
/// New webhook
WebhookCreate(Webhook),
/// Update existing webhook
WebhookUpdate {
id: String,
data: PartialWebhook,
remove: Vec<FieldsWebhook>,
},
/// Delete webhook
WebhookDelete { id: String },
/// New report
ReportCreate(Report),
@@ -1,4 +1,4 @@
use crate::models::channel::{Channel, FieldsChannel, PartialChannel};
use crate::models::{channel::{Channel, FieldsChannel, PartialChannel}};
use crate::{AbstractAttachment, AbstractChannel, Error, OverrideField, Result};
use super::super::DummyDb;
+4 -3
View File
@@ -9,11 +9,12 @@ impl AbstractUser for DummyDb {
Ok(User {
id: id.into(),
username: "username".into(),
discriminator: "0000".into(),
..Default::default()
})
}
async fn fetch_user_by_username(&self, username: &str) -> Result<User> {
async fn fetch_user_by_username(&self, username: &str, _discriminator: &str) -> Result<User> {
self.fetch_user(username).await
}
@@ -45,8 +46,8 @@ impl AbstractUser for DummyDb {
Ok(vec![self.fetch_user("id").await.unwrap()])
}
async fn is_username_taken(&self, _username: &str) -> Result<bool> {
Ok(false)
async fn fetch_discriminators_in_use(&self, _username: &str) -> Result<Vec<String>> {
Ok(vec![])
}
async fn fetch_mutual_user_ids(&self, _user_a: &str, _user_b: &str) -> Result<Vec<String>> {
@@ -1,12 +1,19 @@
use std::collections::HashSet;
use ulid::Ulid;
use crate::{
events::client::EventV1,
models::{
channel::{FieldsChannel, PartialChannel},
message::SystemMessage,
message::{DataMessageSend, Message, Reply, SystemMessage, RE_MENTION},
Channel,
},
tasks::ack::AckEvent,
Database, Error, OverrideField, Result,
tasks::{ack::AckEvent, process_embeds},
types::push::MessageAuthor,
variables::delta::{MAX_ATTACHMENT_COUNT, MAX_REPLY_COUNT, MAX_EMBED_COUNT},
web::idempotency::IdempotencyKey,
Database, Error, OverrideField, Ref, Result,
};
impl Channel {
@@ -394,4 +401,155 @@ impl Channel {
_ => Err(Error::InvalidOperation),
}
}
/// Creates a message in a channel
pub async fn send_message(
&self,
db: &Database,
data: DataMessageSend,
author: MessageAuthor<'_>,
mut idempotency: IdempotencyKey,
generate_embeds: bool,
) -> Result<Message> {
Message::validate_sum(&data.content, data.embeds.as_deref().unwrap_or_default())?;
idempotency.consume_nonce(data.nonce).await?;
// Check the message is not empty
if (data.content.as_ref().map_or(true, |v| v.is_empty()))
&& (data.attachments.as_ref().map_or(true, |v| v.is_empty()))
&& (data.embeds.as_ref().map_or(true, |v| v.is_empty()))
{
return Err(Error::EmptyMessage);
}
// Ensure restrict_reactions is not specified without reactions list
if let Some(interactions) = &data.interactions {
if interactions.restrict_reactions {
let disallowed = if let Some(list) = &interactions.reactions {
list.is_empty()
} else {
true
};
if disallowed {
return Err(Error::InvalidProperty);
}
}
}
let (author_id, webhook) = match &author {
MessageAuthor::User(user) => (user.id.clone(), None),
MessageAuthor::Webhook(webhook) => (webhook.id.clone(), Some((*webhook).clone())),
};
// Start constructing the message
let message_id = Ulid::new().to_string();
let mut message = Message {
id: message_id.clone(),
channel: self.id().to_string(),
masquerade: data.masquerade,
interactions: data.interactions.unwrap_or_default(),
author: author_id,
webhook: webhook.map(|w| w.into()),
..Default::default()
};
// Parse mentions in message.
let mut mentions = HashSet::new();
if let Some(content) = &data.content {
for capture in RE_MENTION.captures_iter(content) {
if let Some(mention) = capture.get(1) {
mentions.insert(mention.as_str().to_string());
}
}
}
// Verify replies are valid.
let mut replies = HashSet::new();
if let Some(entries) = data.replies {
if entries.len() > *MAX_REPLY_COUNT {
return Err(Error::TooManyReplies {
max: *MAX_REPLY_COUNT,
});
}
for Reply { id, mention } in entries {
let message = Ref::from_unchecked(id).as_message(db).await?;
if mention {
mentions.insert(message.author.to_owned());
}
replies.insert(message.id);
}
}
if !mentions.is_empty() {
message.mentions.replace(mentions.into_iter().collect());
}
if !replies.is_empty() {
message
.replies
.replace(replies.into_iter().collect::<Vec<String>>());
}
// Add attachments to message.
let mut attachments = vec![];
if data.attachments.as_ref().is_some_and(|v| v.len() > *MAX_ATTACHMENT_COUNT) {
return Err(Error::TooManyAttachments {
max: *MAX_ATTACHMENT_COUNT,
});
}
if data.embeds.as_ref().is_some_and(|v| v.len() > *MAX_EMBED_COUNT) {
return Err(Error::TooManyEmbeds {
max: *MAX_EMBED_COUNT
})
}
for attachment_id in data.attachments.as_deref().unwrap_or_default() {
attachments.push(
db.find_and_use_attachment(attachment_id, "attachments", "message", &message_id)
.await?,
);
}
if !attachments.is_empty() {
message.attachments.replace(attachments);
}
// Process included embeds.
let mut embeds = vec![];
for sendable_embed in data.embeds.unwrap_or_default() {
embeds.push(sendable_embed.into_embed(db, &message_id).await?)
}
if !embeds.is_empty() {
message.embeds.replace(embeds);
}
// Set content
message.content = data.content;
// Pass-through nonce value for clients
message.nonce = Some(idempotency.into_key());
message.create(db, self, Some(author)).await?;
// Queue up a task for processing embeds
if generate_embeds {
if let Some(content) = &message.content {
process_embeds::queue(
self.id().to_string(),
message.id.to_string(),
content.clone(),
)
.await;
}
}
Ok(message)
}
}
@@ -18,7 +18,7 @@ use crate::{
tasks::ack::AckEvent,
types::{
january::{Embed, Text},
push::PushNotification,
push::{MessageAuthor, PushNotification},
},
Database, Error, Permission, Result,
};
@@ -66,7 +66,7 @@ impl Message {
&mut self,
db: &Database,
channel: &Channel,
sender: Option<&User>,
sender: Option<MessageAuthor<'_>>,
) -> Result<()> {
self.create_no_web_push(db, channel.id(), channel.is_direct_dm())
.await?;
@@ -170,20 +170,15 @@ impl Message {
}
/// Validate the sum of content of a message is under threshold
pub fn validate_sum(
content: &Option<String>,
embeds: &Option<Vec<SendableEmbed>>,
) -> Result<()> {
pub fn validate_sum(content: &Option<String>, embeds: &[SendableEmbed]) -> Result<()> {
let mut running_total = 0;
if let Some(content) = content {
running_total += content.len();
}
if let Some(embeds) = embeds {
for embed in embeds {
if let Some(desc) = &embed.description {
running_total += desc.len();
}
for embed in embeds {
if let Some(desc) = &embed.description {
running_total += desc.len();
}
}
@@ -271,6 +266,10 @@ impl Message {
// Write to database
db.clear_reaction(&self.id, emoji).await
}
pub fn is_webhook(&self) -> bool {
self.webhook.is_some()
}
}
pub trait IntoUsers {
@@ -279,7 +278,11 @@ pub trait IntoUsers {
impl IntoUsers for Message {
fn get_user_ids(&self) -> Vec<String> {
let mut ids = vec![self.author.clone()];
let mut ids = Vec::new();
if !self.is_webhook() {
ids.push(self.author.clone());
};
if let Some(msg) = &self.system {
match msg {
@@ -350,13 +353,13 @@ impl From<SystemMessage> for String {
}
impl SendableEmbed {
pub async fn into_embed(self, db: &Database, message_id: String) -> Result<Embed> {
pub async fn into_embed(self, db: &Database, message_id: &str) -> Result<Embed> {
self.validate()
.map_err(|error| Error::FailedValidation { error })?;
let media = if let Some(id) = self.media {
Some(
db.find_and_use_attachment(&id, "attachments", "message", &message_id)
db.find_and_use_attachment(&id, "attachments", "message", message_id)
.await?,
)
} else {
+109 -21
View File
@@ -8,8 +8,13 @@ use crate::{perms, Database, Error, Result};
use futures::try_join;
use impl_ops::impl_op_ex_commutative;
use once_cell::sync::Lazy;
use rand::seq::SliceRandom;
use revolt_database::RatelimitEventType;
use revolt_presence::filter_online;
use std::collections::HashSet;
use std::ops;
use std::time::Duration;
impl_op_ex_commutative!(+ |a: &i32, b: &Badges| -> i32 { *a | *b as i32 });
@@ -65,6 +70,7 @@ impl User {
x.background = None;
}
}
FieldsUser::DisplayName => self.display_name = None,
}
}
@@ -169,18 +175,15 @@ impl User {
}
/// Sanitise and validate a username can be used
pub async fn validate_username(db: &Database, username: String) -> Result<String> {
// Trim surrounding spaces
let username = username.trim().to_string();
// Make sure username is still at least 3 characters
if username.len() < 2 {
return Err(Error::InvalidUsername);
}
pub fn validate_username(username: String) -> Result<String> {
// Copy the username for validation
let username_lowercase = username.to_lowercase();
// Block homoglyphs
if decancer::cure(&username_lowercase).into_str() != username_lowercase {
return Err(Error::InvalidUsername);
}
// Ensure the username itself isn't blocked
const BLOCKED_USERNAMES: &[&str] = &["admin", "revolt"];
@@ -199,25 +202,96 @@ impl User {
}
}
// Make sure the username isn't taken
if db.is_username_taken(&username).await? {
Ok(username)
}
// Find a free discriminator for a given username
pub async fn find_discriminator(
db: &Database,
username: &str,
preferred: Option<(String, String)>,
) -> Result<String> {
let search_space: &HashSet<String> = &DISCRIMINATOR_SEARCH_SPACE_QUARK;
let used_discriminators: HashSet<String> = db
.fetch_discriminators_in_use(username)
.await?
.into_iter()
.collect();
let available_discriminators: Vec<&String> =
search_space.difference(&used_discriminators).collect();
if available_discriminators.is_empty() {
return Err(Error::UsernameTaken);
}
Ok(username)
if let Some((preferred, target_id)) = preferred {
if available_discriminators.contains(&&preferred) {
return Ok(preferred);
} else {
let rvdb: revolt_database::Database = db.clone().into();
if rvdb
.has_ratelimited(
&target_id,
RatelimitEventType::DiscriminatorChange,
Duration::from_secs(60 * 60 * 24),
1,
)
.await
.map_err(Error::from_core)?
{
return Err(Error::DiscriminatorChangeRatelimited);
}
rvdb.insert_ratelimit_event(&revolt_database::RatelimitEvent {
id: ulid::Ulid::new().to_string(),
target_id,
event_type: RatelimitEventType::DiscriminatorChange,
})
.await
.map_err(Error::from_core)?;
}
}
let mut rng = rand::thread_rng();
Ok(available_discriminators
.choose(&mut rng)
.expect("we can assert this has an element")
.to_string())
}
/// Update a user's username
pub async fn update_username(&mut self, db: &Database, username: String) -> Result<()> {
self.update(
db,
PartialUser {
username: Some(User::validate_username(db, username).await?),
..Default::default()
},
vec![],
)
.await
let username = User::validate_username(username)?;
if self.username.to_lowercase() == username.to_lowercase() {
self.update(
db,
PartialUser {
username: Some(username),
..Default::default()
},
vec![],
)
.await
} else {
self.update(
db,
PartialUser {
discriminator: Some(
User::find_discriminator(
db,
&username,
Some((self.discriminator.to_string(), self.id.clone())),
)
.await?,
),
username: Some(username),
..Default::default()
},
vec![],
)
.await
}
}
/// Apply a certain relationship between two users
@@ -407,3 +481,17 @@ impl User {
}
}
}
pub static DISCRIMINATOR_SEARCH_SPACE_QUARK: Lazy<HashSet<String>> = Lazy::new(|| {
let mut set = (2..9999)
.map(|v| format!("{:0>4}", v))
.collect::<HashSet<String>>();
for discrim in [
123, 1234, 1111, 2222, 3333, 4444, 5555, 6666, 7777, 8888, 9999,
] {
set.remove(&format!("{:0>4}", discrim));
}
set.into_iter().collect()
});
@@ -37,9 +37,24 @@ impl MongoDb {
operation: "delete_many",
with: "channel_unreads",
})
.map(|_| ())
.map(|_| ())?;
// update many attachments with parent id
// Delete all webhooks on this channel.
self.col::<Document>("webhooks")
.delete_many(
doc! {
"channel": &id
},
None,
)
.await
.map_err(|_| Error::DatabaseError {
operation: "delete_many",
with: "webhooks",
})
.map(|_| ())
}
}
+42 -17
View File
@@ -9,14 +9,16 @@ use crate::{AbstractUser, Error, Result};
use super::super::MongoDb;
static FIND_USERNAME_OPTIONS: Lazy<FindOneOptions> = Lazy::new(|| FindOneOptions::builder()
.collation(
Collation::builder()
.locale("en")
.strength(CollationStrength::Secondary)
.build()
)
.build());
static FIND_USERNAME_OPTIONS: Lazy<FindOneOptions> = Lazy::new(|| {
FindOneOptions::builder()
.collation(
Collation::builder()
.locale("en")
.strength(CollationStrength::Secondary)
.build(),
)
.build()
});
static COL: &str = "users";
@@ -26,11 +28,12 @@ impl AbstractUser for MongoDb {
self.find_one_by_id(COL, id).await
}
async fn fetch_user_by_username(&self, username: &str) -> Result<User> {
async fn fetch_user_by_username(&self, username: &str, discriminator: &str) -> Result<User> {
self.find_one_with_options(
COL,
doc! {
"username": username
"username": username,
"discriminator": discriminator
},
FIND_USERNAME_OPTIONS.clone(),
)
@@ -106,13 +109,34 @@ impl AbstractUser for MongoDb {
Ok(users)
}
async fn is_username_taken(&self, username: &str) -> Result<bool> {
// ! FIXME: move this up to generic
match self.fetch_user_by_username(username).await {
Ok(_) => Ok(true),
Err(Error::NotFound) => Ok(false),
Err(error) => Err(error),
}
async fn fetch_discriminators_in_use(&self, username: &str) -> Result<Vec<String>> {
Ok(self
.col::<Document>(COL)
.find(
doc! {
"username": username
},
FindOptions::builder()
.collation(
Collation::builder()
.locale("en")
.strength(CollationStrength::Secondary)
.build(),
)
.projection(doc! { "_id": 0, "discriminator": 1 })
.build(),
)
.await
.map_err(|_| Error::DatabaseError {
operation: "find",
with: "users",
})?
.filter_map(|s| async { s.ok() })
.collect::<Vec<Document>>()
.await
.into_iter()
.filter_map(|x| x.get_str("discriminator").ok().map(|x| x.to_string()))
.collect::<Vec<String>>())
}
async fn fetch_mutual_user_ids(&self, user_a: &str, user_b: &str) -> Result<Vec<String>> {
@@ -313,6 +337,7 @@ impl IntoDocumentPath for FieldsUser {
FieldsUser::ProfileContent => "profile.content",
FieldsUser::StatusPresence => "status.presence",
FieldsUser::StatusText => "status.text",
FieldsUser::DisplayName => "display_name",
})
}
}
+40 -3
View File
@@ -2,6 +2,9 @@ use crate::util::regex::RE_COLOUR;
use indexmap::{IndexMap, IndexSet};
use iso8601_timestamp::Timestamp;
use once_cell::sync::Lazy;
use regex::Regex;
use revolt_models::v0::MessageWebhook;
use serde::{Deserialize, Serialize};
use validator::Validate;
@@ -18,6 +21,9 @@ pub fn if_false(t: &bool) -> bool {
!t
}
pub static RE_MENTION: Lazy<Regex> =
Lazy::new(|| Regex::new(r"<@([0-9A-HJKMNP-TV-Z]{26})>").unwrap());
/// # Reply
///
/// Representation of a message reply before it is sent.
@@ -30,10 +36,11 @@ pub struct Reply {
}
/// Representation of a text embed before it is sent.
#[derive(Validate, Serialize, Deserialize, JsonSchema, Clone, Debug)]
#[derive(Validate, Serialize, Deserialize, JsonSchema, Clone, Debug, Default)]
pub struct SendableEmbed {
#[validate(length(min = 1, max = 128))]
pub icon_url: Option<String>,
#[validate(length(min = 1, max = 256))]
pub url: Option<String>,
#[validate(length(min = 1, max = 100))]
pub title: Option<String>,
@@ -119,9 +126,11 @@ pub struct Message {
pub nonce: Option<String>,
/// Id of the channel this message was sent in
pub channel: String,
/// Id of the user that sent this message
/// Id of the user or webhook that sent this message
pub author: String,
/// The webhook that sent this message
#[serde(skip_serializing_if = "Option::is_none")]
pub webhook: Option<MessageWebhook>,
/// Message content
#[serde(skip_serializing_if = "Option::is_none")]
pub content: Option<String>,
@@ -247,3 +256,31 @@ pub struct AppendMessage {
#[serde(skip_serializing_if = "Option::is_none")]
pub embeds: Option<Vec<Embed>>,
}
#[derive(Validate, Serialize, Deserialize, JsonSchema)]
pub struct DataMessageSend {
/// Unique token to prevent duplicate message sending
///
/// **This is deprecated and replaced by `Idempotency-Key`!**
#[validate(length(min = 1, max = 64))]
pub nonce: Option<String>,
/// Message content to send
#[validate(length(min = 0, max = 2000))]
pub content: Option<String>,
/// Attachments to include in message
pub attachments: Option<Vec<String>>,
/// Messages to reply to
pub replies: Option<Vec<Reply>>,
/// Embeds to include in message
///
/// Text embed content contributes to the content length cap
#[validate]
pub embeds: Option<Vec<SendableEmbed>>,
/// Masquerade to apply to this message
#[validate]
pub masquerade: Option<Masquerade>,
/// Information about how this message should be interacted with
pub interactions: Option<Interactions>,
}
+6
View File
@@ -128,6 +128,11 @@ pub struct User {
pub id: String,
/// Username
pub username: String,
/// Discriminator
pub discriminator: String,
/// Display name
#[serde(skip_serializing_if = "Option::is_none")]
pub display_name: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
/// Avatar attachment
pub avatar: Option<File>,
@@ -172,6 +177,7 @@ pub enum FieldsUser {
StatusPresence,
ProfileContent,
ProfileBackground,
DisplayName,
}
/// Enumeration providing a hint to the type of user we are handling
+1 -1
View File
@@ -1,4 +1,4 @@
use crate::models::channel::{Channel, FieldsChannel, PartialChannel};
use crate::models::{channel::{Channel, FieldsChannel, PartialChannel}};
use crate::{OverrideField, Result};
#[async_trait]
+3 -3
View File
@@ -7,7 +7,7 @@ pub trait AbstractUser: Sync + Send {
async fn fetch_user(&self, id: &str) -> Result<User>;
/// Fetch a user from the database by their username
async fn fetch_user_by_username(&self, username: &str) -> Result<User>;
async fn fetch_user_by_username(&self, username: &str, discriminator: &str) -> Result<User>;
/// Fetch a user from the database by their session token
async fn fetch_user_by_token(&self, token: &str) -> Result<User>;
@@ -29,8 +29,8 @@ pub trait AbstractUser: Sync + Send {
/// Fetch multiple users by their ids
async fn fetch_users<'a>(&self, ids: &'a [String]) -> Result<Vec<User>>;
/// Check whether a username is already in use by another user
async fn is_username_taken(&self, username: &str) -> Result<bool>;
/// Fetch all discriminators in use for a username
async fn fetch_discriminators_in_use(&self, username: &str) -> Result<Vec<String>>;
/// Fetch ids of users that both users are friends with
async fn fetch_mutual_user_ids(&self, user_a: &str, user_b: &str) -> Result<Vec<String>>;
+35 -6
View File
@@ -1,5 +1,6 @@
use std::time::SystemTime;
use revolt_models::v0::Webhook;
use serde::{Deserialize, Serialize};
use crate::models::{Message, User};
@@ -25,14 +26,42 @@ pub struct PushNotification {
pub url: String,
}
pub enum MessageAuthor<'a> {
User(&'a User),
Webhook(&'a Webhook),
}
impl<'a> MessageAuthor<'a> {
pub fn id(&self) -> &str {
match self {
MessageAuthor::User(user) => &user.id,
MessageAuthor::Webhook(webhook) => &webhook.id,
}
}
pub fn avatar(&self) -> Option<&str> {
match self {
MessageAuthor::User(user) => user.avatar.as_ref().map(|file| file.id.as_str()),
MessageAuthor::Webhook(webhook) => webhook.avatar.as_ref().map(|file| file.id.as_str()),
}
}
pub fn username(&self) -> &str {
match self {
MessageAuthor::User(user) => &user.username,
MessageAuthor::Webhook(webhook) => &webhook.name,
}
}
}
impl PushNotification {
/// Create a new notification from a given message, author and channel ID
pub fn new(msg: Message, author: Option<&User>, channel_id: &str) -> Self {
let icon = if let Some(author) = author {
if let Some(avatar) = &author.avatar {
format!("{}/avatars/{}", &*AUTUMN_URL, avatar.id)
pub fn new(msg: Message, author: Option<MessageAuthor<'_>>, channel_id: &str) -> Self {
let icon = if let Some(author) = &author {
if let Some(avatar) = author.avatar() {
format!("{}/avatars/{}", &*AUTUMN_URL, avatar)
} else {
format!("{}/users/{}/default_avatar", &*PUBLIC_URL, msg.author)
format!("{}/users/{}/default_avatar", &*PUBLIC_URL, author.id())
}
} else {
format!("{}/assets/logo.png", &*APP_URL)
@@ -59,7 +88,7 @@ impl PushNotification {
Self {
author: author
.map(|x| x.username.to_string())
.map(|x| x.username().to_string())
.unwrap_or_else(|| "Revolt".to_string()),
icon,
image,
+1 -1
View File
@@ -8,6 +8,6 @@ pub fn prefix_keys<T: Serialize>(t: &T, prefix: &str) -> HashMap<String, serde_j
let v: HashMap<String, serde_json::Value> = serde_json::from_str(&v).unwrap();
v.into_iter()
.filter(|(_k, v)| !v.is_null())
.map(|(k, v)| (prefix.to_owned() + &k, v))
.map(|(k, v)| (format!("{}{}", prefix.to_owned(), k), v))
.collect()
}
+6
View File
@@ -31,6 +31,7 @@ pub enum Error {
// ? User related errors
UsernameTaken,
InvalidUsername,
DiscriminatorChangeRatelimited,
UnknownUser,
AlreadyFriends,
AlreadySentRequest,
@@ -53,6 +54,9 @@ pub enum Error {
TooManyChannels {
max: usize,
},
TooManyEmbeds {
max: usize,
},
EmptyMessage,
PayloadTooLarge,
CannotRemoveYourself,
@@ -162,6 +166,7 @@ impl<'r> Responder<'r, 'static> for Error {
Error::UnknownUser => Status::NotFound,
Error::InvalidUsername => Status::BadRequest,
Error::DiscriminatorChangeRatelimited => Status::TooManyRequests,
Error::UsernameTaken => Status::Conflict,
Error::AlreadyFriends => Status::Conflict,
Error::AlreadySentRequest => Status::Conflict,
@@ -191,6 +196,7 @@ impl<'r> Responder<'r, 'static> for Error {
Error::TooManyEmoji { .. } => Status::BadRequest,
Error::TooManyChannels { .. } => Status::BadRequest,
Error::TooManyRoles { .. } => Status::BadRequest,
Error::TooManyEmbeds { .. } => Status::BadRequest,
Error::ReachedMaximumBots => Status::BadRequest,
Error::IsBot => Status::BadRequest,
+127 -38
View File
@@ -1,56 +1,141 @@
use std::env;
use once_cell::sync::Lazy;
use std::env;
// Application Settings
pub static PUBLIC_URL: Lazy<String> = Lazy::new(|| env::var("REVOLT_PUBLIC_URL").expect("Missing REVOLT_PUBLIC_URL environment variable."));
pub static APP_URL: Lazy<String> = Lazy::new(|| env::var("REVOLT_APP_URL").expect("Missing REVOLT_APP_URL environment variable."));
pub static EXTERNAL_WS_URL: Lazy<String> = Lazy::new(|| env::var("REVOLT_EXTERNAL_WS_URL").expect("Missing REVOLT_EXTERNAL_WS_URL environment variable."));
pub static PUBLIC_URL: Lazy<String> = Lazy::new(|| {
env::var("REVOLT_PUBLIC_URL").expect("Missing REVOLT_PUBLIC_URL environment variable.")
});
pub static APP_URL: Lazy<String> =
Lazy::new(|| env::var("REVOLT_APP_URL").expect("Missing REVOLT_APP_URL environment variable."));
pub static EXTERNAL_WS_URL: Lazy<String> = Lazy::new(|| {
env::var("REVOLT_EXTERNAL_WS_URL")
.expect("Missing REVOLT_EXTERNAL_WS_URL environment variable.")
});
pub static AUTUMN_URL: Lazy<String> = Lazy::new(|| env::var("AUTUMN_PUBLIC_URL").unwrap_or_else(|_| "https://example.com".to_string()));
pub static JANUARY_URL: Lazy<String> = Lazy::new(|| env::var("JANUARY_PUBLIC_URL").unwrap_or_else(|_| "https://example.com".to_string()));
pub static JANUARY_CONCURRENT_CONNECTIONS: Lazy<usize> = Lazy::new(|| env::var("JANUARY_CONCURRENT_CONNECTIONS").map_or(50, |v| v.parse().unwrap()));
pub static VOSO_URL: Lazy<String> = Lazy::new(|| env::var("VOSO_PUBLIC_URL").unwrap_or_else(|_| "https://example.com".to_string()));
pub static VOSO_WS_HOST: Lazy<String> = Lazy::new(|| env::var("VOSO_WS_HOST").unwrap_or_else(|_| "wss://example.com".to_string()));
pub static VOSO_MANAGE_TOKEN: Lazy<String> = Lazy::new(|| env::var("VOSO_MANAGE_TOKEN").unwrap_or_else(|_| "0".to_string()));
pub static AUTUMN_URL: Lazy<String> = Lazy::new(|| {
env::var("AUTUMN_PUBLIC_URL").unwrap_or_else(|_| "https://example.com".to_string())
});
pub static JANUARY_URL: Lazy<String> = Lazy::new(|| {
env::var("JANUARY_PUBLIC_URL").unwrap_or_else(|_| "https://example.com".to_string())
});
pub static JANUARY_CONCURRENT_CONNECTIONS: Lazy<usize> =
Lazy::new(|| env::var("JANUARY_CONCURRENT_CONNECTIONS").map_or(50, |v| v.parse().unwrap()));
pub static VOSO_URL: Lazy<String> =
Lazy::new(|| env::var("VOSO_PUBLIC_URL").unwrap_or_else(|_| "https://example.com".to_string()));
pub static VOSO_WS_HOST: Lazy<String> =
Lazy::new(|| env::var("VOSO_WS_HOST").unwrap_or_else(|_| "wss://example.com".to_string()));
pub static VOSO_MANAGE_TOKEN: Lazy<String> =
Lazy::new(|| env::var("VOSO_MANAGE_TOKEN").unwrap_or_else(|_| "0".to_string()));
pub static HCAPTCHA_KEY: Lazy<String> = Lazy::new(|| env::var("REVOLT_HCAPTCHA_KEY").unwrap_or_else(|_| "0x0000000000000000000000000000000000000000".to_string()));
pub static HCAPTCHA_SITEKEY: Lazy<String> = Lazy::new(|| env::var("REVOLT_HCAPTCHA_SITEKEY").unwrap_or_else(|_| "10000000-ffff-ffff-ffff-000000000001".to_string()));
pub static VAPID_PRIVATE_KEY: Lazy<String> = Lazy::new(|| env::var("REVOLT_VAPID_PRIVATE_KEY").expect("Missing REVOLT_VAPID_PRIVATE_KEY environment variable."));
pub static VAPID_PUBLIC_KEY: Lazy<String> = Lazy::new(|| env::var("REVOLT_VAPID_PUBLIC_KEY").expect("Missing REVOLT_VAPID_PUBLIC_KEY environment variable."));
pub static AUTHIFIER_SHIELD_KEY: Lazy<Option<String>> = Lazy::new(|| env::var("REVOLT_AUTHIFIER_SHIELD_KEY").ok());
pub static HCAPTCHA_KEY: Lazy<String> = Lazy::new(|| {
env::var("REVOLT_HCAPTCHA_KEY")
.unwrap_or_else(|_| "0x0000000000000000000000000000000000000000".to_string())
});
pub static HCAPTCHA_SITEKEY: Lazy<String> = Lazy::new(|| {
env::var("REVOLT_HCAPTCHA_SITEKEY")
.unwrap_or_else(|_| "10000000-ffff-ffff-ffff-000000000001".to_string())
});
pub static VAPID_PRIVATE_KEY: Lazy<String> = Lazy::new(|| {
env::var("REVOLT_VAPID_PRIVATE_KEY")
.expect("Missing REVOLT_VAPID_PRIVATE_KEY environment variable.")
});
pub static VAPID_PUBLIC_KEY: Lazy<String> = Lazy::new(|| {
env::var("REVOLT_VAPID_PUBLIC_KEY")
.expect("Missing REVOLT_VAPID_PUBLIC_KEY environment variable.")
});
pub static AUTHIFIER_SHIELD_KEY: Lazy<Option<String>> =
Lazy::new(|| env::var("REVOLT_AUTHIFIER_SHIELD_KEY").ok());
// Application Flags
pub static INVITE_ONLY: Lazy<bool> = Lazy::new(|| env::var("REVOLT_INVITE_ONLY").map_or(false, |v| v == "1"));
pub static USE_EMAIL: Lazy<bool> = Lazy::new(|| env::var("REVOLT_USE_EMAIL_VERIFICATION").map_or(
env::var("REVOLT_SMTP_HOST").is_ok()
&& env::var("REVOLT_SMTP_USERNAME").is_ok()
&& env::var("REVOLT_SMTP_PASSWORD").is_ok()
&& env::var("REVOLT_SMTP_FROM").is_ok(),
|v| v == *"1"
));
pub static INVITE_ONLY: Lazy<bool> =
Lazy::new(|| env::var("REVOLT_INVITE_ONLY").map_or(false, |v| v == "1"));
pub static USE_EMAIL: Lazy<bool> = Lazy::new(|| {
env::var("REVOLT_USE_EMAIL_VERIFICATION").map_or(
env::var("REVOLT_SMTP_HOST").is_ok()
&& env::var("REVOLT_SMTP_USERNAME").is_ok()
&& env::var("REVOLT_SMTP_PASSWORD").is_ok()
&& env::var("REVOLT_SMTP_FROM").is_ok(),
|v| v == *"1",
)
});
pub static USE_HCAPTCHA: Lazy<bool> = Lazy::new(|| env::var("REVOLT_HCAPTCHA_KEY").is_ok());
pub static USE_AUTUMN: Lazy<bool> = Lazy::new(|| env::var("AUTUMN_PUBLIC_URL").is_ok());
pub static USE_JANUARY: Lazy<bool> = Lazy::new(|| env::var("JANUARY_PUBLIC_URL").is_ok());
pub static USE_VOSO: Lazy<bool> = Lazy::new(|| env::var("VOSO_PUBLIC_URL").is_ok() && env::var("VOSO_MANAGE_TOKEN").is_ok());
pub static USE_VOSO: Lazy<bool> =
Lazy::new(|| env::var("VOSO_PUBLIC_URL").is_ok() && env::var("VOSO_MANAGE_TOKEN").is_ok());
// SMTP Settings
pub static SMTP_HOST: Lazy<String> = Lazy::new(|| env::var("REVOLT_SMTP_HOST").unwrap_or_else(|_| "".to_string()));
pub static SMTP_USERNAME: Lazy<String> = Lazy::new(|| env::var("REVOLT_SMTP_USERNAME").unwrap_or_else(|_| "".to_string()));
pub static SMTP_PASSWORD: Lazy<String> = Lazy::new(|| env::var("REVOLT_SMTP_PASSWORD").unwrap_or_else(|_| "".to_string()));
pub static SMTP_FROM: Lazy<String> = Lazy::new(|| env::var("REVOLT_SMTP_FROM").unwrap_or_else(|_| "".to_string()));
pub static SMTP_HOST: Lazy<String> =
Lazy::new(|| env::var("REVOLT_SMTP_HOST").unwrap_or_else(|_| "".to_string()));
pub static SMTP_USERNAME: Lazy<String> =
Lazy::new(|| env::var("REVOLT_SMTP_USERNAME").unwrap_or_else(|_| "".to_string()));
pub static SMTP_PASSWORD: Lazy<String> =
Lazy::new(|| env::var("REVOLT_SMTP_PASSWORD").unwrap_or_else(|_| "".to_string()));
pub static SMTP_FROM: Lazy<String> =
Lazy::new(|| env::var("REVOLT_SMTP_FROM").unwrap_or_else(|_| "".to_string()));
// Application Logic Settings
pub static MAX_GROUP_SIZE: Lazy<usize> = Lazy::new(|| env::var("REVOLT_MAX_GROUP_SIZE").unwrap_or_else(|_| "50".to_string()).parse().unwrap());
pub static MAX_BOT_COUNT: Lazy<usize> = Lazy::new(|| env::var("REVOLT_MAX_BOT_COUNT").unwrap_or_else(|_| "10".to_string()).parse().unwrap());
pub static MAX_EMBED_COUNT: Lazy<usize> = Lazy::new(|| env::var("REVOLT_MAX_EMBED_COUNT").unwrap_or_else(|_| "5".to_string()).parse().unwrap());
pub static MAX_SERVER_COUNT: Lazy<usize> = Lazy::new(|| env::var("REVOLT_MAX_SERVER_COUNT").unwrap_or_else(|_| "100".to_string()).parse().unwrap());
pub static MAX_CHANNEL_COUNT: Lazy<usize> = Lazy::new(|| env::var("REVOLT_MAX_CHANNEL_COUNT").unwrap_or_else(|_| "200".to_string()).parse().unwrap());
pub static MAX_ROLE_COUNT: Lazy<usize> = Lazy::new(|| env::var("REVOLT_MAX_ROLE_COUNT").unwrap_or_else(|_| "200".to_string()).parse().unwrap());
pub static MAX_EMOJI_COUNT: Lazy<usize> = Lazy::new(|| env::var("REVOLT_MAX_EMOJI_COUNT").unwrap_or_else(|_| "100".to_string()).parse().unwrap());
pub static MAX_ATTACHMENT_COUNT: Lazy<usize> = Lazy::new(|| env::var("REVOLT_MAX_ATTACHMENT_COUNT").unwrap_or_else(|_| "5".to_string()).parse().unwrap());
pub static MAX_REPLY_COUNT: Lazy<usize> = Lazy::new(|| env::var("REVOLT_MAX_REPLY_COUNT").unwrap_or_else(|_| "5".to_string()).parse().unwrap());
pub static MAX_GROUP_SIZE: Lazy<usize> = Lazy::new(|| {
env::var("REVOLT_MAX_GROUP_SIZE")
.unwrap_or_else(|_| "50".to_string())
.parse()
.unwrap()
});
pub static MAX_BOT_COUNT: Lazy<usize> = Lazy::new(|| {
env::var("REVOLT_MAX_BOT_COUNT")
.unwrap_or_else(|_| "10".to_string())
.parse()
.unwrap()
});
pub static MAX_EMBED_COUNT: Lazy<usize> = Lazy::new(|| {
env::var("REVOLT_MAX_EMBED_COUNT")
.unwrap_or_else(|_| "5".to_string())
.parse()
.unwrap()
});
pub static MAX_SERVER_COUNT: Lazy<usize> = Lazy::new(|| {
env::var("REVOLT_MAX_SERVER_COUNT")
.unwrap_or_else(|_| "100".to_string())
.parse()
.unwrap()
});
pub static MAX_CHANNEL_COUNT: Lazy<usize> = Lazy::new(|| {
env::var("REVOLT_MAX_CHANNEL_COUNT")
.unwrap_or_else(|_| "200".to_string())
.parse()
.unwrap()
});
pub static MAX_ROLE_COUNT: Lazy<usize> = Lazy::new(|| {
env::var("REVOLT_MAX_ROLE_COUNT")
.unwrap_or_else(|_| "200".to_string())
.parse()
.unwrap()
});
pub static MAX_EMOJI_COUNT: Lazy<usize> = Lazy::new(|| {
env::var("REVOLT_MAX_EMOJI_COUNT")
.unwrap_or_else(|_| "100".to_string())
.parse()
.unwrap()
});
pub static MAX_ATTACHMENT_COUNT: Lazy<usize> = Lazy::new(|| {
env::var("REVOLT_MAX_ATTACHMENT_COUNT")
.unwrap_or_else(|_| "5".to_string())
.parse()
.unwrap()
});
pub static MAX_REPLY_COUNT: Lazy<usize> = Lazy::new(|| {
env::var("REVOLT_MAX_REPLY_COUNT")
.unwrap_or_else(|_| "5".to_string())
.parse()
.unwrap()
});
pub static EARLY_ADOPTER_BADGE: Lazy<i64> = Lazy::new(|| env::var("REVOLT_EARLY_ADOPTER_BADGE").unwrap_or_else(|_| "0".to_string()).parse().unwrap());
pub static EARLY_ADOPTER_BADGE: Lazy<i64> = Lazy::new(|| {
env::var("REVOLT_EARLY_ADOPTER_BADGE")
.unwrap_or_else(|_| "0".to_string())
.parse()
.unwrap()
});
pub fn preflight_checks() {
format!("url = {}", *APP_URL);
@@ -80,3 +165,7 @@ pub fn preflight_checks() {
warn!("No Captcha key specified! Remember to add hCaptcha key.");
}
}
// Production / staging configuration
pub static IS_STAGING: Lazy<bool> =
Lazy::new(|| env::var("REVOLT_IS_STAGING").map_or(false, |v| v == "1"));
+13 -9
View File
@@ -101,16 +101,19 @@ pub struct Ratelimiter {
fn resolve_bucket<'r>(request: &'r rocket::Request<'_>) -> (&'r str, Option<&'r str>) {
if let Some(segment) = request.routed_segment(0) {
let resource = request.routed_segment(1);
match (segment, resource) {
("users", _) => {
let method = request.method();
match (segment, resource, method) {
("users", target, Method::Patch) => ("user_edit", target),
("users", _, _) => {
if let Some("default_avatar") = request.routed_segment(2) {
return ("default_avatar", None);
}
("users", None)
}
("bots", _) => ("bots", None),
("channels", Some(id)) => {
("bots", _, _) => ("bots", None),
("channels", Some(id), _) => {
if request.method() == Method::Post {
if let Some("messages") = request.routed_segment(2) {
return ("messaging", Some(id));
@@ -119,17 +122,17 @@ fn resolve_bucket<'r>(request: &'r rocket::Request<'_>) -> (&'r str, Option<&'r
("channels", Some(id))
}
("servers", Some(id)) => ("servers", Some(id)),
("auth", _) => {
("servers", Some(id), _) => ("servers", Some(id)),
("auth", _, _) => {
if request.method() == Method::Delete {
("auth_delete", None)
} else {
("auth", None)
}
}
("swagger", _) => ("swagger", None),
("safety", Some("report")) => ("safety_report", Some("report")),
("safety", _) => ("safety", None),
("swagger", _, _) => ("swagger", None),
("safety", Some("report"), _) => ("safety_report", Some("report")),
("safety", _, _) => ("safety", None),
_ => ("any", None),
}
} else {
@@ -140,6 +143,7 @@ fn resolve_bucket<'r>(request: &'r rocket::Request<'_>) -> (&'r str, Option<&'r
/// Resolve per-bucket limits
fn resolve_bucket_limit(bucket: &str) -> u8 {
match bucket {
"user_edit" => 2,
"users" => 20,
"bots" => 10,
"messaging" => 10,
+2 -2
View File
@@ -1,6 +1,6 @@
publish:
cargo publish --package revolt-result
cargo publish --package revolt-permissions
cargo publish --package revolt-database
cargo publish --package revolt-presence
cargo publish --package revolt-models
cargo publish --package revolt-presence
cargo publish --package revolt-database