Compare commits
36
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
1a60aecdb3 | ||
|
|
789dedd9f1 | ||
|
|
d7cf809424 | ||
|
|
249a4818fc | ||
|
|
46e127ccd2 | ||
|
|
cf4fe859bf | ||
|
|
3d6f39a0eb | ||
|
|
ed22b3a5ce | ||
|
|
65fbd36624 | ||
|
|
050ba16d4a | ||
|
|
65bc6c8fc6 | ||
|
|
6ad3da5f35 | ||
|
|
947eb15771 | ||
|
|
f4ee35fb09 | ||
|
|
6048587d34 | ||
|
|
80cf8fc4e8 | ||
|
|
4f54227495 | ||
|
|
aab1734615 | ||
|
|
40a41ffd64 | ||
|
|
d30ceea373 | ||
|
|
3e8a401077 | ||
|
|
99f400bc7b | ||
|
|
73b576a75f | ||
|
|
4e4e598daf | ||
|
|
77daf82b94 | ||
|
|
e00603f276 | ||
|
|
1b2c7b2fa1 | ||
|
|
c526095d4f | ||
|
|
8cc4bbea4d | ||
|
|
911ffc767e | ||
|
|
1690df998d | ||
|
|
519d3c08a8 | ||
|
|
9846d8aac2 | ||
|
|
c74b6255dd | ||
|
|
df91b8c990 | ||
|
|
c4728c696d |
No files matched your search
Generated
+1499
-1055
File diff suppressed because it is too large.
Load diff
@@ -11,6 +11,8 @@ members = [
|
|||||||
|
|
||||||
[patch.crates-io]
|
[patch.crates-io]
|
||||||
redis23 = { package = "redis", version = "0.23.3", git = "https://github.com/revoltchat/redis-rs", rev = "523b2937367e17bd0073722bf6e23d06042cb4e4" }
|
redis23 = { package = "redis", version = "0.23.3", git = "https://github.com/revoltchat/redis-rs", rev = "523b2937367e17bd0073722bf6e23d06042cb4e4" }
|
||||||
|
#authifier = { package = "authifier", version = "1.0.10", path = "../authifier/crates/authifier" }
|
||||||
|
#rocket_authifier = { package = "rocket_authifier", version = "1.0.10", path = "../authifier/crates/rocket_authifier" }
|
||||||
|
|
||||||
# I'm 99% sure this is overloading the GitHub worker
|
# I'm 99% sure this is overloading the GitHub worker
|
||||||
# hence builds have been failing since, let's just
|
# hence builds have been failing since, let's just
|
||||||
|
|||||||
@@ -114,7 +114,8 @@ If you'd like to change anything, create a `Revolt.overrides.toml` file and spec
|
|||||||
> And corresponding Revolt configuration:
|
> And corresponding Revolt configuration:
|
||||||
>
|
>
|
||||||
> ```toml
|
> ```toml
|
||||||
> # Revolt.overrides.toml
|
> # Revolt.overrides.toml
|
||||||
|
> # and Revolt.test-overrides.toml
|
||||||
> [database]
|
> [database]
|
||||||
> mongodb = "mongodb://127.0.0.1:14017"
|
> mongodb = "mongodb://127.0.0.1:14017"
|
||||||
> redis = "redis://127.0.0.1:14079/"
|
> redis = "redis://127.0.0.1:14079/"
|
||||||
|
|||||||
@@ -26,3 +26,7 @@ disallowed-methods = [
|
|||||||
# Prefer to use Object::delete(&self)
|
# Prefer to use Object::delete(&self)
|
||||||
"revolt_database::models::bots::ops::AbstractBots::delete_bot",
|
"revolt_database::models::bots::ops::AbstractBots::delete_bot",
|
||||||
]
|
]
|
||||||
|
|
||||||
|
disallowed-types = [
|
||||||
|
"rocket::serde::json::Json",
|
||||||
|
]
|
||||||
+1
-1
@@ -34,7 +34,7 @@ services:
|
|||||||
- minio
|
- minio
|
||||||
entrypoint: >
|
entrypoint: >
|
||||||
/bin/sh -c "while ! /usr/bin/mc ready minio; do
|
/bin/sh -c "while ! /usr/bin/mc ready minio; do
|
||||||
/usr/bin/mc config host add minio http://minio:9000 minioautumn minioautumn;
|
/usr/bin/mc alias set minio http://minio:9000 minioautumn minioautumn;
|
||||||
echo 'Waiting minio...' && sleep 1;
|
echo 'Waiting minio...' && sleep 1;
|
||||||
done; /usr/bin/mc mb minio/revolt-uploads; exit 0;"
|
done; /usr/bin/mc mb minio/revolt-uploads; exit 0;"
|
||||||
|
|
||||||
|
|||||||
@@ -1,6 +1,6 @@
|
|||||||
[package]
|
[package]
|
||||||
name = "revolt-bonfire"
|
name = "revolt-bonfire"
|
||||||
version = "0.8.6"
|
version = "0.8.8"
|
||||||
license = "AGPL-3.0-or-later"
|
license = "AGPL-3.0-or-later"
|
||||||
edition = "2021"
|
edition = "2021"
|
||||||
|
|
||||||
@@ -37,11 +37,11 @@ async-std = { version = "1.8.0", features = [
|
|||||||
|
|
||||||
# core
|
# core
|
||||||
authifier = { version = "1.0.15" }
|
authifier = { version = "1.0.15" }
|
||||||
revolt-result = { path = "../core/result" }
|
revolt-result = { path = "../core/result", features = ["sentry"] }
|
||||||
revolt-models = { path = "../core/models" }
|
revolt-models = { path = "../core/models" }
|
||||||
revolt-config = { path = "../core/config" }
|
revolt-config = { path = "../core/config" }
|
||||||
revolt-database = { path = "../core/database" }
|
revolt-database = { path = "../core/database" }
|
||||||
revolt-permissions = { version = "0.8.6", path = "../core/permissions" }
|
revolt-permissions = { version = "0.8.8", path = "../core/permissions" }
|
||||||
revolt-presence = { path = "../core/presence", features = ["redis-is-patched"] }
|
revolt-presence = { path = "../core/presence", features = ["redis-is-patched"] }
|
||||||
|
|
||||||
# redis
|
# redis
|
||||||
|
|||||||
@@ -1,7 +1,7 @@
|
|||||||
use async_tungstenite::tungstenite::{handshake, Message};
|
use async_tungstenite::tungstenite::{handshake, Message};
|
||||||
use futures::channel::oneshot::Sender;
|
use futures::channel::oneshot::Sender;
|
||||||
use revolt_database::events::client::ReadyPayloadFields;
|
use revolt_database::events::client::ReadyPayloadFields;
|
||||||
use revolt_result::{create_error, Result};
|
use revolt_result::{create_error, Result, ToRevoltError};
|
||||||
use serde::{Deserialize, Serialize};
|
use serde::{Deserialize, Serialize};
|
||||||
|
|
||||||
/// Enumeration of supported protocol formats
|
/// Enumeration of supported protocol formats
|
||||||
@@ -38,16 +38,22 @@ impl ProtocolConfiguration {
|
|||||||
match self.format {
|
match self.format {
|
||||||
ProtocolFormat::Json => {
|
ProtocolFormat::Json => {
|
||||||
if let Message::Text(text) = msg {
|
if let Message::Text(text) = msg {
|
||||||
serde_json::from_str(text).map_err(|_| create_error!(InternalError))
|
// Log the error in-case we make a breaking change to the payload
|
||||||
|
|
||||||
|
serde_json::from_str(text)
|
||||||
|
.capture_error()
|
||||||
|
.map_err(|_| create_error!(UnprocessableEntity))
|
||||||
} else {
|
} else {
|
||||||
Err(create_error!(InternalError))
|
Err(create_error!(UnprocessableEntity))
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
ProtocolFormat::Msgpack => {
|
ProtocolFormat::Msgpack => {
|
||||||
if let Message::Binary(buf) = msg {
|
if let Message::Binary(buf) = msg {
|
||||||
rmp_serde::from_slice(buf).map_err(|_| create_error!(InternalError))
|
rmp_serde::from_slice(buf)
|
||||||
|
.capture_error()
|
||||||
|
.map_err(|_| create_error!(UnprocessableEntity))
|
||||||
} else {
|
} else {
|
||||||
Err(create_error!(InternalError))
|
Err(create_error!(UnprocessableEntity))
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -100,6 +100,18 @@ impl State {
|
|||||||
let user = self.clone_user();
|
let user = self.clone_user();
|
||||||
self.cache.is_bot = user.bot.is_some();
|
self.cache.is_bot = user.bot.is_some();
|
||||||
|
|
||||||
|
// Fetch pending policy changes.
|
||||||
|
let policy_changes = if user.bot.is_some() {
|
||||||
|
vec![]
|
||||||
|
} else {
|
||||||
|
db.fetch_policy_changes()
|
||||||
|
.await?
|
||||||
|
.into_iter()
|
||||||
|
.filter(|policy| policy.created_time > user.last_acknowledged_policy_change)
|
||||||
|
.map(Into::into)
|
||||||
|
.collect()
|
||||||
|
};
|
||||||
|
|
||||||
// Find all relationships to the user.
|
// Find all relationships to the user.
|
||||||
let mut user_ids: HashSet<String> = user
|
let mut user_ids: HashSet<String> = user
|
||||||
.relations
|
.relations
|
||||||
@@ -227,6 +239,7 @@ impl State {
|
|||||||
for channel in &channels {
|
for channel in &channels {
|
||||||
self.insert_subscription(channel.id().to_string()).await;
|
self.insert_subscription(channel.id().to_string()).await;
|
||||||
}
|
}
|
||||||
|
|
||||||
Ok(EventV1::Ready {
|
Ok(EventV1::Ready {
|
||||||
users: if fields.contains(&ReadyPayloadFields::Users) {
|
users: if fields.contains(&ReadyPayloadFields::Users) {
|
||||||
Some(users)
|
Some(users)
|
||||||
@@ -252,6 +265,8 @@ impl State {
|
|||||||
|
|
||||||
user_settings,
|
user_settings,
|
||||||
channel_unreads: channel_unreads.map(|vec| vec.into_iter().map(Into::into).collect()),
|
channel_unreads: channel_unreads.map(|vec| vec.into_iter().map(Into::into).collect()),
|
||||||
|
|
||||||
|
policy_changes,
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -14,9 +14,9 @@ use futures::{
|
|||||||
FutureExt, SinkExt, StreamExt, TryStreamExt,
|
FutureExt, SinkExt, StreamExt, TryStreamExt,
|
||||||
};
|
};
|
||||||
use redis_kiss::{PayloadType, REDIS_PAYLOAD_TYPE, REDIS_URI};
|
use redis_kiss::{PayloadType, REDIS_PAYLOAD_TYPE, REDIS_URI};
|
||||||
use revolt_config::report_internal_error;
|
|
||||||
use revolt_database::{
|
use revolt_database::{
|
||||||
events::{client::EventV1, server::ClientMessage},
|
events::{client::EventV1, server::ClientMessage},
|
||||||
|
iso8601_timestamp::Timestamp,
|
||||||
Database, User, UserHint,
|
Database, User, UserHint,
|
||||||
};
|
};
|
||||||
use revolt_presence::{create_session, delete_session};
|
use revolt_presence::{create_session, delete_session};
|
||||||
@@ -26,7 +26,7 @@ use async_std::{
|
|||||||
sync::{Mutex, RwLock},
|
sync::{Mutex, RwLock},
|
||||||
task::spawn,
|
task::spawn,
|
||||||
};
|
};
|
||||||
use revolt_result::create_error;
|
use revolt_result::{create_error, ToRevoltError};
|
||||||
use sentry::Level;
|
use sentry::Level;
|
||||||
|
|
||||||
use crate::config::{ProtocolConfiguration, WebsocketHandshakeCallback};
|
use crate::config::{ProtocolConfiguration, WebsocketHandshakeCallback};
|
||||||
@@ -100,26 +100,30 @@ pub async fn client(db: &'static Database, stream: TcpStream, addr: SocketAddr)
|
|||||||
|
|
||||||
info!("User {addr:?} authenticated as @{}", user.username);
|
info!("User {addr:?} authenticated as @{}", user.username);
|
||||||
|
|
||||||
|
db.update_session_last_seen(&session_id, Timestamp::now_utc())
|
||||||
|
.await
|
||||||
|
.ok();
|
||||||
|
|
||||||
// Create local state.
|
// Create local state.
|
||||||
let mut state = State::from(user, session_id);
|
let mut state = State::from(user, session_id);
|
||||||
let user_id = state.cache.user_id.clone();
|
let user_id = state.cache.user_id.clone();
|
||||||
|
|
||||||
// Notify socket we have authenticated.
|
// Notify socket we have authenticated.
|
||||||
if report_internal_error!(write.send(config.encode(&EventV1::Authenticated)).await).is_err() {
|
if write.send(config.encode(&EventV1::Authenticated)).await.to_internal_error().is_err() {
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
// Download required data to local cache and send Ready payload.
|
// Download required data to local cache and send Ready payload.
|
||||||
let ready_payload = match report_internal_error!(
|
let ready_payload = match state
|
||||||
state
|
|
||||||
.generate_ready_payload(db, config.get_ready_payload_fields())
|
.generate_ready_payload(db, config.get_ready_payload_fields())
|
||||||
.await
|
.await
|
||||||
) {
|
.to_internal_error()
|
||||||
|
{
|
||||||
Ok(ready_payload) => ready_payload,
|
Ok(ready_payload) => ready_payload,
|
||||||
Err(_) => return,
|
Err(_) => return,
|
||||||
};
|
};
|
||||||
|
|
||||||
if report_internal_error!(write.send(config.encode(&ready_payload)).await).is_err() {
|
if write.send(config.encode(&ready_payload)).await.to_internal_error().is_err() {
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -214,14 +218,15 @@ async fn listener(
|
|||||||
write: &Mutex<WsWriter>,
|
write: &Mutex<WsWriter>,
|
||||||
) {
|
) {
|
||||||
let redis_config = RedisConfig::from_url(&REDIS_URI).unwrap();
|
let redis_config = RedisConfig::from_url(&REDIS_URI).unwrap();
|
||||||
let subscriber = match report_internal_error!(
|
let subscriber = match fred::types::Builder::from_config(redis_config)
|
||||||
fred::types::Builder::from_config(redis_config).build_subscriber_client()
|
.build_subscriber_client()
|
||||||
) {
|
.to_internal_error()
|
||||||
|
{
|
||||||
Ok(subscriber) => subscriber,
|
Ok(subscriber) => subscriber,
|
||||||
Err(_) => return,
|
Err(_) => return,
|
||||||
};
|
};
|
||||||
|
|
||||||
if report_internal_error!(subscriber.init().await).is_err() {
|
if subscriber.init().await.to_internal_error().is_err() {
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -244,13 +249,13 @@ async fn listener(
|
|||||||
// Check for state changes for subscriptions.
|
// Check for state changes for subscriptions.
|
||||||
match state.apply_state().await {
|
match state.apply_state().await {
|
||||||
SubscriptionStateChange::Reset => {
|
SubscriptionStateChange::Reset => {
|
||||||
if report_internal_error!(subscriber.unsubscribe_all().await).is_err() {
|
if subscriber.unsubscribe_all().await.to_internal_error().is_err() {
|
||||||
break 'out;
|
break 'out;
|
||||||
}
|
}
|
||||||
|
|
||||||
let subscribed = state.subscribed.read().await;
|
let subscribed = state.subscribed.read().await;
|
||||||
for id in subscribed.iter() {
|
for id in subscribed.iter() {
|
||||||
if report_internal_error!(subscriber.subscribe(id).await).is_err() {
|
if subscriber.subscribe(id).await.to_internal_error().is_err() {
|
||||||
break 'out;
|
break 'out;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -263,7 +268,7 @@ async fn listener(
|
|||||||
#[cfg(debug_assertions)]
|
#[cfg(debug_assertions)]
|
||||||
info!("{addr:?} unsubscribing from {id}");
|
info!("{addr:?} unsubscribing from {id}");
|
||||||
|
|
||||||
if report_internal_error!(subscriber.unsubscribe(id).await).is_err() {
|
if subscriber.unsubscribe(id).await.to_internal_error().is_err() {
|
||||||
break 'out;
|
break 'out;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -272,7 +277,7 @@ async fn listener(
|
|||||||
#[cfg(debug_assertions)]
|
#[cfg(debug_assertions)]
|
||||||
info!("{addr:?} subscribing to {id}");
|
info!("{addr:?} subscribing to {id}");
|
||||||
|
|
||||||
if report_internal_error!(subscriber.subscribe(id).await).is_err() {
|
if subscriber.subscribe(id).await.to_internal_error().is_err() {
|
||||||
break 'out;
|
break 'out;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -297,7 +302,7 @@ async fn listener(
|
|||||||
_ = t2 => {},
|
_ = t2 => {},
|
||||||
message = t1 => {
|
message = t1 => {
|
||||||
// Handle incoming events.
|
// Handle incoming events.
|
||||||
let message = match report_internal_error!(message) {
|
let message = match message.to_internal_error() {
|
||||||
Ok(message) => message,
|
Ok(message) => message,
|
||||||
Err(_) => break 'out
|
Err(_) => break 'out
|
||||||
};
|
};
|
||||||
@@ -306,15 +311,15 @@ async fn listener(
|
|||||||
PayloadType::Json => message
|
PayloadType::Json => message
|
||||||
.value
|
.value
|
||||||
.as_str()
|
.as_str()
|
||||||
.and_then(|s| report_internal_error!(serde_json::from_str::<EventV1>(s.as_ref())).ok()),
|
.and_then(|s| serde_json::from_str::<EventV1>(s.as_ref()).to_internal_error().ok()),
|
||||||
PayloadType::Msgpack => message
|
PayloadType::Msgpack => message
|
||||||
.value
|
.value
|
||||||
.as_bytes()
|
.as_bytes()
|
||||||
.and_then(|b| report_internal_error!(rmp_serde::from_slice::<EventV1>(b)).ok()),
|
.and_then(|b| rmp_serde::from_slice::<EventV1>(b).to_internal_error().ok()),
|
||||||
PayloadType::Bincode => message
|
PayloadType::Bincode => message
|
||||||
.value
|
.value
|
||||||
.as_bytes()
|
.as_bytes()
|
||||||
.and_then(|b| report_internal_error!(bincode::deserialize::<EventV1>(b)).ok()),
|
.and_then(|b| bincode::deserialize::<EventV1>(b).to_internal_error().ok()),
|
||||||
};
|
};
|
||||||
|
|
||||||
let Some(mut event) = event else {
|
let Some(mut event) = event else {
|
||||||
@@ -374,7 +379,7 @@ async fn listener(
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
report_internal_error!(subscriber.quit().await).ok();
|
subscriber.quit().await.to_internal_error().ok();
|
||||||
}
|
}
|
||||||
|
|
||||||
#[allow(clippy::too_many_arguments)]
|
#[allow(clippy::too_many_arguments)]
|
||||||
|
|||||||
@@ -1,6 +1,6 @@
|
|||||||
[package]
|
[package]
|
||||||
name = "revolt-config"
|
name = "revolt-config"
|
||||||
version = "0.8.6"
|
version = "0.8.8"
|
||||||
edition = "2021"
|
edition = "2021"
|
||||||
license = "MIT"
|
license = "MIT"
|
||||||
authors = ["Paul Makles <me@insrt.uk>"]
|
authors = ["Paul Makles <me@insrt.uk>"]
|
||||||
@@ -11,8 +11,9 @@ description = "Revolt Backend: Configuration"
|
|||||||
[features]
|
[features]
|
||||||
anyhow = ["dep:sentry-anyhow"]
|
anyhow = ["dep:sentry-anyhow"]
|
||||||
report-macros = ["revolt-result"]
|
report-macros = ["revolt-result"]
|
||||||
|
sentry = ["dep:sentry"]
|
||||||
test = ["async-std"]
|
test = ["async-std"]
|
||||||
default = ["test", "anyhow"]
|
default = ["test", "sentry"]
|
||||||
|
|
||||||
[dependencies]
|
[dependencies]
|
||||||
# Utility
|
# Utility
|
||||||
@@ -32,8 +33,8 @@ log = "0.4.14"
|
|||||||
pretty_env_logger = "0.4.0"
|
pretty_env_logger = "0.4.0"
|
||||||
|
|
||||||
# Sentry
|
# Sentry
|
||||||
sentry = "0.31.5"
|
sentry = { version = "0.31.5", optional = true }
|
||||||
sentry-anyhow = { version = "0.38.1", optional = true }
|
sentry-anyhow = { version = "0.38.1", optional = true }
|
||||||
|
|
||||||
# Core
|
# Core
|
||||||
revolt-result = { version = "0.8.6", path = "../result", optional = true }
|
revolt-result = { version = "0.8.8", path = "../result", optional = true }
|
||||||
@@ -6,10 +6,12 @@ use futures_locks::RwLock;
|
|||||||
use once_cell::sync::Lazy;
|
use once_cell::sync::Lazy;
|
||||||
use serde::Deserialize;
|
use serde::Deserialize;
|
||||||
|
|
||||||
|
#[cfg(feature = "sentry")]
|
||||||
pub use sentry::{capture_error, capture_message, Level};
|
pub use sentry::{capture_error, capture_message, Level};
|
||||||
|
#[cfg(feature = "anyhow")]
|
||||||
pub use sentry_anyhow::capture_anyhow;
|
pub use sentry_anyhow::capture_anyhow;
|
||||||
|
|
||||||
#[cfg(feature = "report-macros")]
|
#[cfg(all(feature = "report-macros", feature = "sentry"))]
|
||||||
#[macro_export]
|
#[macro_export]
|
||||||
macro_rules! report_error {
|
macro_rules! report_error {
|
||||||
( $expr: expr, $error: ident $( $tt:tt )? ) => {
|
( $expr: expr, $error: ident $( $tt:tt )? ) => {
|
||||||
@@ -24,7 +26,7 @@ macro_rules! report_error {
|
|||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
#[cfg(feature = "report-macros")]
|
#[cfg(all(feature = "report-macros", feature = "sentry"))]
|
||||||
#[macro_export]
|
#[macro_export]
|
||||||
macro_rules! capture_internal_error {
|
macro_rules! capture_internal_error {
|
||||||
( $expr: expr ) => {
|
( $expr: expr ) => {
|
||||||
@@ -35,7 +37,7 @@ macro_rules! capture_internal_error {
|
|||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
#[cfg(feature = "report-macros")]
|
#[cfg(all(feature = "report-macros", feature = "sentry"))]
|
||||||
#[macro_export]
|
#[macro_export]
|
||||||
macro_rules! report_internal_error {
|
macro_rules! report_internal_error {
|
||||||
( $expr: expr ) => {
|
( $expr: expr ) => {
|
||||||
@@ -60,6 +62,9 @@ static CONFIG_SEARCH_PATHS: [&str; 3] = [
|
|||||||
"/Revolt.toml",
|
"/Revolt.toml",
|
||||||
];
|
];
|
||||||
|
|
||||||
|
/// Path to search for test overrides
|
||||||
|
static TEST_OVERRIDE_PATH: &str = "Revolt.test-overrides.toml";
|
||||||
|
|
||||||
/// Configuration builder
|
/// Configuration builder
|
||||||
static CONFIG_BUILDER: Lazy<RwLock<Config>> = Lazy::new(|| {
|
static CONFIG_BUILDER: Lazy<RwLock<Config>> = Lazy::new(|| {
|
||||||
RwLock::new({
|
RwLock::new({
|
||||||
@@ -73,6 +78,20 @@ static CONFIG_BUILDER: Lazy<RwLock<Config>> = Lazy::new(|| {
|
|||||||
include_str!("../Revolt.test.toml"),
|
include_str!("../Revolt.test.toml"),
|
||||||
FileFormat::Toml,
|
FileFormat::Toml,
|
||||||
));
|
));
|
||||||
|
|
||||||
|
// recursively search upwards for an overrides file (if there is one)
|
||||||
|
if let Ok(cwd) = std::env::current_dir() {
|
||||||
|
let mut path = Some(cwd.as_path());
|
||||||
|
while let Some(current_path) = path {
|
||||||
|
let target_path = current_path.join(TEST_OVERRIDE_PATH);
|
||||||
|
if target_path.exists() {
|
||||||
|
builder = builder
|
||||||
|
.add_source(File::new(target_path.to_str().unwrap(), FileFormat::Toml));
|
||||||
|
}
|
||||||
|
|
||||||
|
path = current_path.parent();
|
||||||
|
}
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
for path in CONFIG_SEARCH_PATHS {
|
for path in CONFIG_SEARCH_PATHS {
|
||||||
@@ -388,6 +407,11 @@ pub async fn read() -> Config {
|
|||||||
pub async fn config() -> Settings {
|
pub async fn config() -> Settings {
|
||||||
let mut config = read().await.try_deserialize::<Settings>().unwrap();
|
let mut config = read().await.try_deserialize::<Settings>().unwrap();
|
||||||
|
|
||||||
|
// inject REDIS_URI for redis-kiss library
|
||||||
|
if std::env::var("REDIS_URL").is_err() {
|
||||||
|
std::env::set_var("REDIS_URI", config.database.redis.clone());
|
||||||
|
}
|
||||||
|
|
||||||
// auto-detect production nodes
|
// auto-detect production nodes
|
||||||
if config.hosts.api.contains("https") && config.hosts.api.contains("revolt.chat") {
|
if config.hosts.api.contains("https") && config.hosts.api.contains("revolt.chat") {
|
||||||
config.production = true;
|
config.production = true;
|
||||||
@@ -397,6 +421,7 @@ pub async fn config() -> Settings {
|
|||||||
}
|
}
|
||||||
|
|
||||||
/// Configure logging and common Rust variables
|
/// Configure logging and common Rust variables
|
||||||
|
#[cfg(feature = "sentry")]
|
||||||
pub async fn setup_logging(release: &'static str, dsn: String) -> Option<sentry::ClientInitGuard> {
|
pub async fn setup_logging(release: &'static str, dsn: String) -> Option<sentry::ClientInitGuard> {
|
||||||
if std::env::var("RUST_LOG").is_err() {
|
if std::env::var("RUST_LOG").is_err() {
|
||||||
std::env::set_var("RUST_LOG", "info");
|
std::env::set_var("RUST_LOG", "info");
|
||||||
@@ -406,12 +431,6 @@ pub async fn setup_logging(release: &'static str, dsn: String) -> Option<sentry:
|
|||||||
std::env::set_var("ROCKET_ADDRESS", "0.0.0.0");
|
std::env::set_var("ROCKET_ADDRESS", "0.0.0.0");
|
||||||
}
|
}
|
||||||
|
|
||||||
if std::env::var("REDIS_URL").is_err() {
|
|
||||||
// Configure redis-kiss library
|
|
||||||
let config = config().await;
|
|
||||||
std::env::set_var("REDIS_URI", config.database.redis);
|
|
||||||
}
|
|
||||||
|
|
||||||
pretty_env_logger::init();
|
pretty_env_logger::init();
|
||||||
log::info!("Starting {release}");
|
log::info!("Starting {release}");
|
||||||
|
|
||||||
@@ -428,6 +447,7 @@ pub async fn setup_logging(release: &'static str, dsn: String) -> Option<sentry:
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[cfg(feature = "sentry")]
|
||||||
#[macro_export]
|
#[macro_export]
|
||||||
macro_rules! configure {
|
macro_rules! configure {
|
||||||
($application: ident) => {
|
($application: ident) => {
|
||||||
|
|||||||
@@ -1,6 +1,6 @@
|
|||||||
[package]
|
[package]
|
||||||
name = "revolt-database"
|
name = "revolt-database"
|
||||||
version = "0.8.6"
|
version = "0.8.8"
|
||||||
edition = "2021"
|
edition = "2021"
|
||||||
license = "AGPL-3.0-or-later"
|
license = "AGPL-3.0-or-later"
|
||||||
authors = ["Paul Makles <me@insrt.uk>"]
|
authors = ["Paul Makles <me@insrt.uk>"]
|
||||||
@@ -10,12 +10,12 @@ description = "Revolt Backend: Database Implementation"
|
|||||||
|
|
||||||
[features]
|
[features]
|
||||||
# Databases
|
# Databases
|
||||||
mongodb = ["dep:mongodb", "bson"]
|
mongodb = ["dep:mongodb", "bson", "authifier/database-mongodb"]
|
||||||
|
|
||||||
# ... Other
|
# ... Other
|
||||||
tasks = ["isahc", "linkify", "url-escape"]
|
tasks = ["isahc", "linkify", "url-escape"]
|
||||||
async-std-runtime = ["async-std"]
|
async-std-runtime = ["async-std", "authifier/async-std-runtime"]
|
||||||
rocket-impl = ["rocket", "schemars", "revolt_okapi", "revolt_rocket_okapi"]
|
rocket-impl = ["rocket", "schemars", "revolt_okapi", "revolt_rocket_okapi", "authifier/rocket_impl"]
|
||||||
axum-impl = ["axum"]
|
axum-impl = ["axum"]
|
||||||
redis-is-patched = ["revolt-presence/redis-is-patched"]
|
redis-is-patched = ["revolt-presence/redis-is-patched"]
|
||||||
|
|
||||||
@@ -24,19 +24,19 @@ default = ["mongodb", "async-std-runtime", "tasks"]
|
|||||||
|
|
||||||
[dependencies]
|
[dependencies]
|
||||||
# Core
|
# Core
|
||||||
revolt-config = { version = "0.8.6", path = "../config", features = [
|
revolt-config = { version = "0.8.8", path = "../config", features = [
|
||||||
"report-macros",
|
"report-macros",
|
||||||
] }
|
] }
|
||||||
revolt-result = { version = "0.8.6", path = "../result" }
|
revolt-result = { version = "0.8.8", path = "../result" }
|
||||||
revolt-models = { version = "0.8.6", path = "../models", features = [
|
revolt-models = { version = "0.8.8", path = "../models", features = [
|
||||||
"validator",
|
"validator",
|
||||||
] }
|
] }
|
||||||
revolt-presence = { version = "0.8.6", path = "../presence" }
|
revolt-presence = { version = "0.8.8", path = "../presence" }
|
||||||
revolt-permissions = { version = "0.8.6", path = "../permissions", features = [
|
revolt-permissions = { version = "0.8.8", path = "../permissions", features = [
|
||||||
"serde",
|
"serde",
|
||||||
"bson",
|
"bson",
|
||||||
] }
|
] }
|
||||||
revolt-parser = { version = "0.8.6", path = "../parser" }
|
revolt-parser = { version = "0.8.8", path = "../parser" }
|
||||||
|
|
||||||
# Utility
|
# Utility
|
||||||
log = "0.4"
|
log = "0.4"
|
||||||
@@ -91,13 +91,8 @@ rocket = { version = "0.5.1", default-features = false, features = [
|
|||||||
revolt_okapi = { version = "0.9.1", optional = true }
|
revolt_okapi = { version = "0.9.1", optional = true }
|
||||||
revolt_rocket_okapi = { version = "0.10.0", optional = true }
|
revolt_rocket_okapi = { version = "0.10.0", optional = true }
|
||||||
|
|
||||||
# Notifications
|
|
||||||
fcm_v1 = "0.3.0"
|
|
||||||
web-push = "0.10.0"
|
|
||||||
revolt_a2 = { version = "0.10", default-features = false, features = ["ring"] }
|
|
||||||
|
|
||||||
# Authifier
|
# Authifier
|
||||||
authifier = { version = "1.0.15", features = ["rocket_impl"] }
|
authifier = { version = "1.0.15" }
|
||||||
|
|
||||||
# RabbitMQ
|
# RabbitMQ
|
||||||
amqprs = { version = "1.7.0" }
|
amqprs = { version = "1.7.0" }
|
||||||
@@ -3,18 +3,21 @@
|
|||||||
"_object_type": "User",
|
"_object_type": "User",
|
||||||
"_id": "__ID:0__",
|
"_id": "__ID:0__",
|
||||||
"username": "Owner",
|
"username": "Owner",
|
||||||
|
"last_acknowledged_policy_change": "2025-06-07T04:04:48+0000",
|
||||||
"discriminator": "0001"
|
"discriminator": "0001"
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
"_object_type": "User",
|
"_object_type": "User",
|
||||||
"_id": "__ID:1__",
|
"_id": "__ID:1__",
|
||||||
"username": "Member",
|
"username": "Member",
|
||||||
|
"last_acknowledged_policy_change": "2025-06-07T04:04:48+0000",
|
||||||
"discriminator": "0001"
|
"discriminator": "0001"
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
"_object_type": "User",
|
"_object_type": "User",
|
||||||
"_id": "__ID:2__",
|
"_id": "__ID:2__",
|
||||||
"username": "Member",
|
"username": "Member",
|
||||||
|
"last_acknowledged_policy_change": "2025-06-07T04:04:48+0000",
|
||||||
"discriminator": "0002"
|
"discriminator": "0002"
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
@@ -23,6 +26,9 @@
|
|||||||
"channel_type": "Group",
|
"channel_type": "Group",
|
||||||
"name": "My Group",
|
"name": "My Group",
|
||||||
"owner": "__ID:0__",
|
"owner": "__ID:0__",
|
||||||
"recipients": ["__ID:0__", "__ID:1__"]
|
"recipients": [
|
||||||
|
"__ID:0__",
|
||||||
|
"__ID:1__"
|
||||||
|
]
|
||||||
}
|
}
|
||||||
]
|
]
|
||||||
@@ -3,18 +3,21 @@
|
|||||||
"_object_type": "User",
|
"_object_type": "User",
|
||||||
"_id": "__ID:0__",
|
"_id": "__ID:0__",
|
||||||
"username": "Owner",
|
"username": "Owner",
|
||||||
|
"last_acknowledged_policy_change": "2025-06-07T04:04:48+0000",
|
||||||
"discriminator": "0001"
|
"discriminator": "0001"
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
"_object_type": "User",
|
"_object_type": "User",
|
||||||
"_id": "__ID:1__",
|
"_id": "__ID:1__",
|
||||||
"username": "Moderator",
|
"username": "Moderator",
|
||||||
|
"last_acknowledged_policy_change": "2025-06-07T04:04:48+0000",
|
||||||
"discriminator": "0001"
|
"discriminator": "0001"
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
"_object_type": "User",
|
"_object_type": "User",
|
||||||
"_id": "__ID:2__",
|
"_id": "__ID:2__",
|
||||||
"username": "User",
|
"username": "User",
|
||||||
|
"last_acknowledged_policy_change": "2025-06-07T04:04:48+0000",
|
||||||
"discriminator": "0001"
|
"discriminator": "0001"
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
@@ -39,7 +42,9 @@
|
|||||||
"_id": "__ID:4__",
|
"_id": "__ID:4__",
|
||||||
"owner": "__ID:0__",
|
"owner": "__ID:0__",
|
||||||
"name": "Server",
|
"name": "Server",
|
||||||
"channels": ["__ID:3__"],
|
"channels": [
|
||||||
|
"__ID:3__"
|
||||||
|
],
|
||||||
"roles": {
|
"roles": {
|
||||||
"__ID:5__": {
|
"__ID:5__": {
|
||||||
"name": "Moderator",
|
"name": "Moderator",
|
||||||
@@ -47,7 +52,7 @@
|
|||||||
"a": 545270208,
|
"a": 545270208,
|
||||||
"d": 0
|
"d": 0
|
||||||
},
|
},
|
||||||
"rank": 3
|
"rank": 1
|
||||||
},
|
},
|
||||||
"__ID:6__": {
|
"__ID:6__": {
|
||||||
"name": "Owner",
|
"name": "Owner",
|
||||||
@@ -66,7 +71,9 @@
|
|||||||
"user": "__ID:0__",
|
"user": "__ID:0__",
|
||||||
"server": "__ID:4__"
|
"server": "__ID:4__"
|
||||||
},
|
},
|
||||||
"roles": ["__ID:6__"],
|
"roles": [
|
||||||
|
"__ID:6__"
|
||||||
|
],
|
||||||
"joined_at": 1698318340195
|
"joined_at": 1698318340195
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
@@ -75,7 +82,9 @@
|
|||||||
"user": "__ID:1__",
|
"user": "__ID:1__",
|
||||||
"server": "__ID:4__"
|
"server": "__ID:4__"
|
||||||
},
|
},
|
||||||
"roles": ["__ID:5__"],
|
"roles": [
|
||||||
|
"__ID:5__"
|
||||||
|
],
|
||||||
"joined_at": 1698318340195
|
"joined_at": 1698318340195
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
@@ -86,4 +95,4 @@
|
|||||||
},
|
},
|
||||||
"joined_at": 1698318340195
|
"joined_at": 1698318340195
|
||||||
}
|
}
|
||||||
]
|
]
|
||||||
@@ -1,3 +1,4 @@
|
|||||||
|
#[cfg(feature = "mongodb")]
|
||||||
mod mongodb;
|
mod mongodb;
|
||||||
mod reference;
|
mod reference;
|
||||||
|
|
||||||
@@ -13,6 +14,7 @@ use authifier::Authifier;
|
|||||||
use rand::Rng;
|
use rand::Rng;
|
||||||
use revolt_config::config;
|
use revolt_config::config;
|
||||||
|
|
||||||
|
#[cfg(feature = "mongodb")]
|
||||||
pub use self::mongodb::*;
|
pub use self::mongodb::*;
|
||||||
pub use self::reference::*;
|
pub use self::reference::*;
|
||||||
|
|
||||||
@@ -25,8 +27,10 @@ pub enum DatabaseInfo {
|
|||||||
/// Use the mock database
|
/// Use the mock database
|
||||||
Reference,
|
Reference,
|
||||||
/// Connect to MongoDB
|
/// Connect to MongoDB
|
||||||
|
#[cfg(feature = "mongodb")]
|
||||||
MongoDb { uri: String, database_name: String },
|
MongoDb { uri: String, database_name: String },
|
||||||
/// Use existing MongoDB connection
|
/// Use existing MongoDB connection
|
||||||
|
#[cfg(feature = "mongodb")]
|
||||||
MongoDbFromClient(::mongodb::Client, String),
|
MongoDbFromClient(::mongodb::Client, String),
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -36,6 +40,7 @@ pub enum Database {
|
|||||||
/// Mock database
|
/// Mock database
|
||||||
Reference(ReferenceDb),
|
Reference(ReferenceDb),
|
||||||
/// MongoDB database
|
/// MongoDB database
|
||||||
|
#[cfg(feature = "mongodb")]
|
||||||
MongoDb(MongoDb),
|
MongoDb(MongoDb),
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -45,7 +50,7 @@ impl DatabaseInfo {
|
|||||||
pub async fn connect(self) -> Result<Database, String> {
|
pub async fn connect(self) -> Result<Database, String> {
|
||||||
let config = config().await;
|
let config = config().await;
|
||||||
|
|
||||||
Ok(match self {
|
match self {
|
||||||
DatabaseInfo::Auto => {
|
DatabaseInfo::Auto => {
|
||||||
if std::env::var("TEST_DB").is_ok() {
|
if std::env::var("TEST_DB").is_ok() {
|
||||||
DatabaseInfo::Test(format!(
|
DatabaseInfo::Test(format!(
|
||||||
@@ -53,16 +58,20 @@ impl DatabaseInfo {
|
|||||||
rand::thread_rng().gen_range(1_000_000..10_000_000)
|
rand::thread_rng().gen_range(1_000_000..10_000_000)
|
||||||
))
|
))
|
||||||
.connect()
|
.connect()
|
||||||
.await?
|
.await
|
||||||
} else if !config.database.mongodb.is_empty() {
|
} else if !config.database.mongodb.is_empty() {
|
||||||
DatabaseInfo::MongoDb {
|
#[cfg(feature = "mongodb")]
|
||||||
|
return DatabaseInfo::MongoDb {
|
||||||
uri: config.database.mongodb,
|
uri: config.database.mongodb,
|
||||||
database_name: "revolt".to_string(),
|
database_name: "revolt".to_string(),
|
||||||
}
|
}
|
||||||
.connect()
|
.connect()
|
||||||
.await?
|
.await;
|
||||||
|
|
||||||
|
#[cfg(not(feature = "mongodb"))]
|
||||||
|
return Err("MongoDB not enabled.".to_string())
|
||||||
} else {
|
} else {
|
||||||
DatabaseInfo::Reference.connect().await?
|
DatabaseInfo::Reference.connect().await
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
DatabaseInfo::Test(database_name) => {
|
DatabaseInfo::Test(database_name) => {
|
||||||
@@ -70,30 +79,36 @@ impl DatabaseInfo {
|
|||||||
.expect("`TEST_DB` environment variable should be set to REFERENCE or MONGODB")
|
.expect("`TEST_DB` environment variable should be set to REFERENCE or MONGODB")
|
||||||
.as_str()
|
.as_str()
|
||||||
{
|
{
|
||||||
"REFERENCE" => DatabaseInfo::Reference.connect().await?,
|
"REFERENCE" => DatabaseInfo::Reference.connect().await,
|
||||||
"MONGODB" => {
|
"MONGODB" => {
|
||||||
DatabaseInfo::MongoDb {
|
#[cfg(feature = "mongodb")]
|
||||||
|
return DatabaseInfo::MongoDb {
|
||||||
uri: config.database.mongodb,
|
uri: config.database.mongodb,
|
||||||
database_name,
|
database_name,
|
||||||
}
|
}
|
||||||
.connect()
|
.connect()
|
||||||
.await?
|
.await;
|
||||||
|
|
||||||
|
#[cfg(not(feature = "mongodb"))]
|
||||||
|
return Err("MongoDB not enabled.".to_string())
|
||||||
}
|
}
|
||||||
_ => unreachable!("must specify REFERENCE or MONGODB"),
|
_ => unreachable!("must specify REFERENCE or MONGODB"),
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
DatabaseInfo::Reference => Database::Reference(Default::default()),
|
DatabaseInfo::Reference => Ok(Database::Reference(Default::default())),
|
||||||
|
#[cfg(feature = "mongodb")]
|
||||||
DatabaseInfo::MongoDb { uri, database_name } => {
|
DatabaseInfo::MongoDb { uri, database_name } => {
|
||||||
let client = ::mongodb::Client::with_uri_str(uri)
|
let client = ::mongodb::Client::with_uri_str(uri)
|
||||||
.await
|
.await
|
||||||
.map_err(|_| "Failed to init db connection.".to_string())?;
|
.map_err(|_| "Failed to init db connection.".to_string())?;
|
||||||
|
|
||||||
Database::MongoDb(MongoDb(client, database_name))
|
Ok(Database::MongoDb(MongoDb(client, database_name)))
|
||||||
}
|
}
|
||||||
|
#[cfg(feature = "mongodb")]
|
||||||
DatabaseInfo::MongoDbFromClient(client, database_name) => {
|
DatabaseInfo::MongoDbFromClient(client, database_name) => {
|
||||||
Database::MongoDb(MongoDb(client, database_name))
|
Ok(Database::MongoDb(MongoDb(client, database_name)))
|
||||||
}
|
}
|
||||||
})
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -219,12 +234,16 @@ impl Database {
|
|||||||
Authifier {
|
Authifier {
|
||||||
database: match self {
|
database: match self {
|
||||||
Database::Reference(_) => Default::default(),
|
Database::Reference(_) => Default::default(),
|
||||||
|
#[cfg(feature = "mongodb")]
|
||||||
Database::MongoDb(MongoDb(client, _)) => authifier::Database::MongoDb(
|
Database::MongoDb(MongoDb(client, _)) => authifier::Database::MongoDb(
|
||||||
authifier::database::MongoDb(client.database("revolt")),
|
authifier::database::MongoDb(client.database("revolt")),
|
||||||
),
|
),
|
||||||
},
|
},
|
||||||
config: auth_config,
|
config: auth_config,
|
||||||
|
#[cfg(feature = "tasks")]
|
||||||
event_channel: Some(crate::tasks::authifier_relay::sender()),
|
event_channel: Some(crate::tasks::authifier_relay::sender()),
|
||||||
|
#[cfg(not(feature = "tasks"))]
|
||||||
|
event_channel: None,
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -10,7 +10,6 @@ use serde::de::DeserializeOwned;
|
|||||||
use serde::Serialize;
|
use serde::Serialize;
|
||||||
|
|
||||||
database_derived!(
|
database_derived!(
|
||||||
#[cfg(feature = "mongodb")]
|
|
||||||
/// MongoDB implementation
|
/// MongoDB implementation
|
||||||
pub struct MongoDb(pub ::mongodb::Client, pub String);
|
pub struct MongoDb(pub ::mongodb::Client, pub String);
|
||||||
);
|
);
|
||||||
|
|||||||
@@ -4,8 +4,8 @@ use futures::lock::Mutex;
|
|||||||
|
|
||||||
use crate::{
|
use crate::{
|
||||||
Bot, Channel, ChannelCompositeKey, ChannelUnread, Emoji, File, FileHash, Invite, Member,
|
Bot, Channel, ChannelCompositeKey, ChannelUnread, Emoji, File, FileHash, Invite, Member,
|
||||||
MemberCompositeKey, Message, RatelimitEvent, Report, Server, ServerBan, Snapshot, User,
|
MemberCompositeKey, Message, PolicyChange, RatelimitEvent, Report, Server, ServerBan, Snapshot,
|
||||||
UserSettings, Webhook,
|
User, UserSettings, Webhook,
|
||||||
};
|
};
|
||||||
|
|
||||||
database_derived!(
|
database_derived!(
|
||||||
@@ -21,6 +21,7 @@ database_derived!(
|
|||||||
pub file_hashes: Arc<Mutex<HashMap<String, FileHash>>>,
|
pub file_hashes: Arc<Mutex<HashMap<String, FileHash>>>,
|
||||||
pub files: Arc<Mutex<HashMap<String, File>>>,
|
pub files: Arc<Mutex<HashMap<String, File>>>,
|
||||||
pub messages: Arc<Mutex<HashMap<String, Message>>>,
|
pub messages: Arc<Mutex<HashMap<String, Message>>>,
|
||||||
|
pub policy_changes: Arc<Mutex<HashMap<String, PolicyChange>>>,
|
||||||
pub ratelimit_events: Arc<Mutex<HashMap<String, RatelimitEvent>>>,
|
pub ratelimit_events: Arc<Mutex<HashMap<String, RatelimitEvent>>>,
|
||||||
pub user_settings: Arc<Mutex<HashMap<String, UserSettings>>>,
|
pub user_settings: Arc<Mutex<HashMap<String, UserSettings>>>,
|
||||||
pub users: Arc<Mutex<HashMap<String, User>>>,
|
pub users: Arc<Mutex<HashMap<String, User>>>,
|
||||||
|
|||||||
@@ -6,7 +6,7 @@ use revolt_models::v0::{
|
|||||||
AppendMessage, Channel, ChannelUnread, Emoji, FieldsChannel, FieldsMember, FieldsMessage,
|
AppendMessage, Channel, ChannelUnread, Emoji, FieldsChannel, FieldsMember, FieldsMessage,
|
||||||
FieldsRole, FieldsServer, FieldsUser, FieldsWebhook, Member, MemberCompositeKey, Message,
|
FieldsRole, FieldsServer, FieldsUser, FieldsWebhook, Member, MemberCompositeKey, Message,
|
||||||
PartialChannel, PartialMember, PartialMessage, PartialRole, PartialServer, PartialUser,
|
PartialChannel, PartialMember, PartialMessage, PartialRole, PartialServer, PartialUser,
|
||||||
PartialWebhook, RemovalIntention, Report, Server, User, UserSettings, Webhook,
|
PartialWebhook, PolicyChange, RemovalIntention, Report, Server, User, UserSettings, Webhook,
|
||||||
};
|
};
|
||||||
|
|
||||||
use crate::Database;
|
use crate::Database;
|
||||||
@@ -62,6 +62,8 @@ pub enum EventV1 {
|
|||||||
user_settings: Option<UserSettings>,
|
user_settings: Option<UserSettings>,
|
||||||
#[serde(skip_serializing_if = "Option::is_none")]
|
#[serde(skip_serializing_if = "Option::is_none")]
|
||||||
channel_unreads: Option<Vec<ChannelUnread>>,
|
channel_unreads: Option<Vec<ChannelUnread>>,
|
||||||
|
|
||||||
|
policy_changes: Vec<PolicyChange>,
|
||||||
},
|
},
|
||||||
|
|
||||||
/// Ping response
|
/// Ping response
|
||||||
@@ -163,6 +165,9 @@ pub enum EventV1 {
|
|||||||
/// Server role deleted
|
/// Server role deleted
|
||||||
ServerRoleDelete { id: String, role_id: String },
|
ServerRoleDelete { id: String, role_id: String },
|
||||||
|
|
||||||
|
/// Server roles ranks updated
|
||||||
|
ServerRoleRanksUpdate { id: String, ranks: Vec<String> },
|
||||||
|
|
||||||
/// Update existing user
|
/// Update existing user
|
||||||
UserUpdate {
|
UserUpdate {
|
||||||
id: String,
|
id: String,
|
||||||
|
|||||||
@@ -25,6 +25,9 @@ pub use mongodb;
|
|||||||
#[macro_use]
|
#[macro_use]
|
||||||
extern crate bson;
|
extern crate bson;
|
||||||
|
|
||||||
|
#[cfg(not(feature = "async-std-runtime"))]
|
||||||
|
compile_error!("async-std-runtime feature must be enabled.");
|
||||||
|
|
||||||
#[macro_export]
|
#[macro_export]
|
||||||
#[cfg(debug_assertions)]
|
#[cfg(debug_assertions)]
|
||||||
macro_rules! query {
|
macro_rules! query {
|
||||||
@@ -103,6 +106,7 @@ pub mod util;
|
|||||||
pub use models::*;
|
pub use models::*;
|
||||||
|
|
||||||
pub mod events;
|
pub mod events;
|
||||||
|
#[cfg(feature = "tasks")]
|
||||||
pub mod tasks;
|
pub mod tasks;
|
||||||
|
|
||||||
mod amqp;
|
mod amqp;
|
||||||
|
|||||||
@@ -1,3 +1,4 @@
|
|||||||
|
#[cfg(feature = "mongodb")]
|
||||||
mod mongodb;
|
mod mongodb;
|
||||||
mod reference;
|
mod reference;
|
||||||
|
|
||||||
|
|||||||
@@ -64,6 +64,10 @@ pub async fn create_database(db: &MongoDb) {
|
|||||||
.await
|
.await
|
||||||
.expect("Failed to create user_settings collection.");
|
.expect("Failed to create user_settings collection.");
|
||||||
|
|
||||||
|
db.create_collection("policy_changes")
|
||||||
|
.await
|
||||||
|
.expect("Failed to create policy_changes collection.");
|
||||||
|
|
||||||
db.create_collection("safety_reports")
|
db.create_collection("safety_reports")
|
||||||
.await
|
.await
|
||||||
.expect("Failed to create safety_reports collection.");
|
.expect("Failed to create safety_reports collection.");
|
||||||
|
|||||||
@@ -1,14 +1,19 @@
|
|||||||
use std::{collections::HashSet, ops::BitXor, time::Duration};
|
use std::{
|
||||||
|
collections::{HashMap, HashSet},
|
||||||
|
ops::BitXor,
|
||||||
|
time::Duration,
|
||||||
|
};
|
||||||
|
|
||||||
use crate::{
|
use crate::{
|
||||||
mongodb::{
|
mongodb::{
|
||||||
bson::{doc, from_bson, from_document, to_document, Bson, DateTime, Document},
|
bson::{doc, from_bson, from_document, to_document, Bson, DateTime, Document},
|
||||||
options::FindOptions,
|
options::FindOptions,
|
||||||
},
|
},
|
||||||
AbstractChannels, AbstractServers, Channel, Invite, MongoDb, DISCRIMINATOR_SEARCH_SPACE,
|
AbstractChannels, AbstractServers, Channel, Invite, MongoDb, User, DISCRIMINATOR_SEARCH_SPACE,
|
||||||
};
|
};
|
||||||
use bson::oid::ObjectId;
|
use bson::{oid::ObjectId, to_bson};
|
||||||
use futures::StreamExt;
|
use futures::StreamExt;
|
||||||
|
use iso8601_timestamp::Timestamp;
|
||||||
use rand::seq::SliceRandom;
|
use rand::seq::SliceRandom;
|
||||||
use revolt_permissions::DEFAULT_WEBHOOK_PERMISSIONS;
|
use revolt_permissions::DEFAULT_WEBHOOK_PERMISSIONS;
|
||||||
use revolt_result::{Error, ErrorType};
|
use revolt_result::{Error, ErrorType};
|
||||||
@@ -21,7 +26,7 @@ struct MigrationInfo {
|
|||||||
revision: i32,
|
revision: i32,
|
||||||
}
|
}
|
||||||
|
|
||||||
pub const LATEST_REVISION: i32 = 33; // MUST BE +1 to last migration
|
pub const LATEST_REVISION: i32 = 42; // MUST BE +1 to last migration
|
||||||
|
|
||||||
pub async fn migrate_database(db: &MongoDb) {
|
pub async fn migrate_database(db: &MongoDb) {
|
||||||
let migrations = db.col::<Document>("migrations");
|
let migrations = db.col::<Document>("migrations");
|
||||||
@@ -1139,6 +1144,88 @@ pub async fn run_migrations(db: &MongoDb, revision: i32) -> i32 {
|
|||||||
.unwrap();
|
.unwrap();
|
||||||
}
|
}
|
||||||
|
|
||||||
|
if revision <= 40 {
|
||||||
|
info!(
|
||||||
|
"Running migration [revision |> 40 / 30-05-2025]: Set last policy acknowlegement date to now and create policy changes collection."
|
||||||
|
);
|
||||||
|
|
||||||
|
db.db()
|
||||||
|
.create_collection("policy_changes")
|
||||||
|
.await
|
||||||
|
.expect("Failed to create policy_changes collection.");
|
||||||
|
|
||||||
|
db.db()
|
||||||
|
.collection::<User>("users")
|
||||||
|
.update_many(
|
||||||
|
doc! {},
|
||||||
|
doc! {
|
||||||
|
"$set": {
|
||||||
|
"last_acknowledged_policy_change": to_bson(&Timestamp::now_utc())
|
||||||
|
.expect("failed to serialise timestamp")
|
||||||
|
}
|
||||||
|
},
|
||||||
|
)
|
||||||
|
.await
|
||||||
|
.expect("failed to update users");
|
||||||
|
}
|
||||||
|
|
||||||
|
if revision <= 41 {
|
||||||
|
info!(
|
||||||
|
"Running migration [revision 41 / 05-06-2025]: convert role ranks to uniform numbers."
|
||||||
|
);
|
||||||
|
|
||||||
|
#[derive(Serialize, Deserialize, Clone)]
|
||||||
|
struct Role {
|
||||||
|
pub rank: i64,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Serialize, Deserialize, Clone)]
|
||||||
|
struct Server {
|
||||||
|
#[serde(rename = "_id")]
|
||||||
|
pub id: String,
|
||||||
|
#[serde(default = "HashMap::<String, Role>::new")]
|
||||||
|
pub roles: HashMap<String, Role>,
|
||||||
|
}
|
||||||
|
|
||||||
|
let mut servers = db
|
||||||
|
.db()
|
||||||
|
.collection::<Server>("servers")
|
||||||
|
.find(doc! {
|
||||||
|
"roles": {
|
||||||
|
"$exists": true,
|
||||||
|
"$ne": []
|
||||||
|
}
|
||||||
|
})
|
||||||
|
.await
|
||||||
|
.unwrap()
|
||||||
|
.filter_map(|s| async { s.ok() })
|
||||||
|
.boxed();
|
||||||
|
|
||||||
|
while let Some(server) = servers.next().await {
|
||||||
|
let mut ordered_roles = server.roles.clone().into_iter().collect::<Vec<_>>();
|
||||||
|
ordered_roles.sort_by(|(_, role_a), (_, role_b)| role_a.rank.cmp(&role_b.rank));
|
||||||
|
let ordered_roles = ordered_roles
|
||||||
|
.into_iter()
|
||||||
|
.map(|(id, _)| id)
|
||||||
|
.collect::<Vec<_>>();
|
||||||
|
|
||||||
|
let mut doc = doc! {};
|
||||||
|
|
||||||
|
for id in server.roles.keys() {
|
||||||
|
doc.insert(
|
||||||
|
format!("roles.{id}.rank"),
|
||||||
|
ordered_roles.iter().position(|x| id == x).unwrap() as i64,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
db.db()
|
||||||
|
.collection::<Server>("servers")
|
||||||
|
.update_one(doc! { "_id": &server.id }, doc! { "$set": doc })
|
||||||
|
.await
|
||||||
|
.unwrap();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
// Reminder to update LATEST_REVISION when adding new migrations.
|
// Reminder to update LATEST_REVISION when adding new migrations.
|
||||||
LATEST_REVISION.max(revision)
|
LATEST_REVISION.max(revision)
|
||||||
}
|
}
|
||||||
@@ -2,6 +2,7 @@ use revolt_result::Result;
|
|||||||
|
|
||||||
use crate::{Bot, FieldsBot, PartialBot};
|
use crate::{Bot, FieldsBot, PartialBot};
|
||||||
|
|
||||||
|
#[cfg(feature = "mongodb")]
|
||||||
mod mongodb;
|
mod mongodb;
|
||||||
mod reference;
|
mod reference;
|
||||||
|
|
||||||
|
|||||||
@@ -2,6 +2,7 @@ use revolt_result::Result;
|
|||||||
|
|
||||||
use crate::Invite;
|
use crate::Invite;
|
||||||
|
|
||||||
|
#[cfg(feature = "mongodb")]
|
||||||
mod mongodb;
|
mod mongodb;
|
||||||
mod reference;
|
mod reference;
|
||||||
|
|
||||||
|
|||||||
@@ -2,6 +2,7 @@ use revolt_result::Result;
|
|||||||
|
|
||||||
use crate::ChannelUnread;
|
use crate::ChannelUnread;
|
||||||
|
|
||||||
|
#[cfg(feature = "mongodb")]
|
||||||
mod mongodb;
|
mod mongodb;
|
||||||
mod reference;
|
mod reference;
|
||||||
|
|
||||||
|
|||||||
@@ -2,6 +2,7 @@ use revolt_result::Result;
|
|||||||
|
|
||||||
use crate::{FieldsWebhook, PartialWebhook, Webhook};
|
use crate::{FieldsWebhook, PartialWebhook, Webhook};
|
||||||
|
|
||||||
|
#[cfg(feature = "mongodb")]
|
||||||
mod mongodb;
|
mod mongodb;
|
||||||
mod reference;
|
mod reference;
|
||||||
|
|
||||||
|
|||||||
@@ -8,10 +8,13 @@ use serde::{Deserialize, Serialize};
|
|||||||
use ulid::Ulid;
|
use ulid::Ulid;
|
||||||
|
|
||||||
use crate::{
|
use crate::{
|
||||||
events::client::EventV1, tasks::ack::AckEvent, Database, File, IntoDocumentPath, PartialServer,
|
events::client::EventV1, Database, File, PartialServer,
|
||||||
Server, SystemMessage, User, AMQP,
|
Server, SystemMessage, User, AMQP,
|
||||||
};
|
};
|
||||||
|
|
||||||
|
#[cfg(feature = "mongodb")]
|
||||||
|
use crate::IntoDocumentPath;
|
||||||
|
|
||||||
auto_derived!(
|
auto_derived!(
|
||||||
#[serde(tag = "channel_type")]
|
#[serde(tag = "channel_type")]
|
||||||
pub enum Channel {
|
pub enum Channel {
|
||||||
@@ -646,10 +649,11 @@ impl Channel {
|
|||||||
.private(user.to_string())
|
.private(user.to_string())
|
||||||
.await;
|
.await;
|
||||||
|
|
||||||
|
#[cfg(feature = "tasks")]
|
||||||
crate::tasks::ack::queue_ack(
|
crate::tasks::ack::queue_ack(
|
||||||
self.id().to_string(),
|
self.id().to_string(),
|
||||||
user.to_string(),
|
user.to_string(),
|
||||||
AckEvent::AckMessage {
|
crate::tasks::ack::AckEvent::AckMessage {
|
||||||
id: message.to_string(),
|
id: message.to_string(),
|
||||||
},
|
},
|
||||||
)
|
)
|
||||||
@@ -766,6 +770,7 @@ impl Channel {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[cfg(feature = "mongodb")]
|
||||||
impl IntoDocumentPath for FieldsChannel {
|
impl IntoDocumentPath for FieldsChannel {
|
||||||
fn as_path(&self) -> Option<&'static str> {
|
fn as_path(&self) -> Option<&'static str> {
|
||||||
Some(match self {
|
Some(match self {
|
||||||
|
|||||||
@@ -1,5 +1,7 @@
|
|||||||
use crate::{revolt_result::Result, Channel, FieldsChannel, PartialChannel};
|
use crate::{revolt_result::Result, Channel, FieldsChannel, PartialChannel};
|
||||||
use revolt_permissions::OverrideField;
|
use revolt_permissions::OverrideField;
|
||||||
|
|
||||||
|
#[cfg(feature = "mongodb")]
|
||||||
mod mongodb;
|
mod mongodb;
|
||||||
mod reference;
|
mod reference;
|
||||||
|
|
||||||
|
|||||||
@@ -2,6 +2,7 @@ use revolt_result::Result;
|
|||||||
|
|
||||||
use crate::Emoji;
|
use crate::Emoji;
|
||||||
|
|
||||||
|
#[cfg(feature = "mongodb")]
|
||||||
mod mongodb;
|
mod mongodb;
|
||||||
mod reference;
|
mod reference;
|
||||||
|
|
||||||
|
|||||||
@@ -2,6 +2,7 @@ use revolt_result::Result;
|
|||||||
|
|
||||||
use crate::FileHash;
|
use crate::FileHash;
|
||||||
|
|
||||||
|
#[cfg(feature = "mongodb")]
|
||||||
mod mongodb;
|
mod mongodb;
|
||||||
mod reference;
|
mod reference;
|
||||||
|
|
||||||
|
|||||||
@@ -4,6 +4,7 @@ use crate::File;
|
|||||||
|
|
||||||
use super::FileUsedFor;
|
use super::FileUsedFor;
|
||||||
|
|
||||||
|
#[cfg(feature = "mongodb")]
|
||||||
mod mongodb;
|
mod mongodb;
|
||||||
mod reference;
|
mod reference;
|
||||||
|
|
||||||
|
|||||||
@@ -1,7 +1,7 @@
|
|||||||
use bson::to_document;
|
use bson::to_document;
|
||||||
use bson::Document;
|
use bson::Document;
|
||||||
use revolt_config::report_internal_error;
|
|
||||||
use revolt_result::Result;
|
use revolt_result::Result;
|
||||||
|
use revolt_result::ToRevoltError;
|
||||||
|
|
||||||
use crate::File;
|
use crate::File;
|
||||||
use crate::FileUsedFor;
|
use crate::FileUsedFor;
|
||||||
@@ -106,7 +106,7 @@ impl AbstractAttachments for MongoDb {
|
|||||||
},
|
},
|
||||||
doc! {
|
doc! {
|
||||||
"$set": {
|
"$set": {
|
||||||
"used_for": report_internal_error!(to_document(&used_for))?,
|
"used_for": to_document(&used_for).to_internal_error()?,
|
||||||
"uploader_id": uploader_id
|
"uploader_id": uploader_id
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
|
|||||||
@@ -10,11 +10,9 @@ use revolt_models::v0::{
|
|||||||
use revolt_permissions::{calculate_channel_permissions, ChannelPermission, PermissionValue};
|
use revolt_permissions::{calculate_channel_permissions, ChannelPermission, PermissionValue};
|
||||||
use revolt_result::{ErrorType, Result};
|
use revolt_result::{ErrorType, Result};
|
||||||
use ulid::Ulid;
|
use ulid::Ulid;
|
||||||
use validator::Validate;
|
|
||||||
|
|
||||||
use crate::{
|
use crate::{
|
||||||
events::client::EventV1,
|
events::client::EventV1,
|
||||||
tasks::{self, ack::AckEvent},
|
|
||||||
util::{
|
util::{
|
||||||
bulk_permissions::BulkDatabasePermissionQuery, idempotency::IdempotencyKey,
|
bulk_permissions::BulkDatabasePermissionQuery, idempotency::IdempotencyKey,
|
||||||
permissions::DatabasePermissionQuery,
|
permissions::DatabasePermissionQuery,
|
||||||
@@ -22,6 +20,9 @@ use crate::{
|
|||||||
Channel, Database, Emoji, File, User, AMQP,
|
Channel, Database, Emoji, File, User, AMQP,
|
||||||
};
|
};
|
||||||
|
|
||||||
|
#[cfg(feature = "tasks")]
|
||||||
|
use crate::tasks::{self, ack::AckEvent};
|
||||||
|
|
||||||
auto_derived_partial!(
|
auto_derived_partial!(
|
||||||
/// Message
|
/// Message
|
||||||
pub struct Message {
|
pub struct Message {
|
||||||
@@ -487,31 +488,28 @@ impl Message {
|
|||||||
| Channel::VoiceChannel { ref server, .. } => {
|
| Channel::VoiceChannel { ref server, .. } => {
|
||||||
let mentions_vec = Vec::from_iter(user_mentions.iter().cloned());
|
let mentions_vec = Vec::from_iter(user_mentions.iter().cloned());
|
||||||
|
|
||||||
let valid_members = db.fetch_members(server.as_str(), &mentions_vec[..]).await;
|
let valid_members = db.fetch_members(server.as_str(), &mentions_vec[..]).await?;
|
||||||
if let Ok(valid_members) = valid_members {
|
|
||||||
let valid_mentions = HashSet::<&String, RandomState>::from_iter(
|
|
||||||
valid_members.iter().map(|m| &m.id.user),
|
|
||||||
);
|
|
||||||
|
|
||||||
user_mentions.retain(|m| valid_mentions.contains(m)); // quick pass, validate mentions are in the server
|
let valid_mentions = HashSet::<&String, RandomState>::from_iter(
|
||||||
|
valid_members.iter().map(|m| &m.id.user),
|
||||||
|
);
|
||||||
|
|
||||||
if !user_mentions.is_empty() {
|
user_mentions.retain(|m| valid_mentions.contains(m)); // quick pass, validate mentions are in the server
|
||||||
// if there are still mentions, drill down to a channel-level
|
|
||||||
let member_channel_view_perms =
|
|
||||||
BulkDatabasePermissionQuery::from_server_id(db, server)
|
|
||||||
.await
|
|
||||||
.channel(&channel)
|
|
||||||
.members(&valid_members)
|
|
||||||
.members_can_see_channel()
|
|
||||||
.await;
|
|
||||||
|
|
||||||
user_mentions
|
if !user_mentions.is_empty() {
|
||||||
.retain(|m| *member_channel_view_perms.get(m).unwrap_or(&false));
|
// if there are still mentions, drill down to a channel-level
|
||||||
}
|
let member_channel_view_perms =
|
||||||
} else {
|
BulkDatabasePermissionQuery::from_server_id(db, server)
|
||||||
revolt_config::capture_error(&valid_members.unwrap_err());
|
.await
|
||||||
return Err(create_error!(InternalError));
|
.channel(&channel)
|
||||||
|
.members(&valid_members)
|
||||||
|
.members_can_see_channel()
|
||||||
|
.await;
|
||||||
|
|
||||||
|
user_mentions
|
||||||
|
.retain(|m| *member_channel_view_perms.get(m).unwrap_or(&false));
|
||||||
}
|
}
|
||||||
|
|
||||||
}
|
}
|
||||||
Channel::SavedMessages { .. } => {
|
Channel::SavedMessages { .. } => {
|
||||||
user_mentions.clear();
|
user_mentions.clear();
|
||||||
@@ -616,9 +614,11 @@ impl Message {
|
|||||||
.await;
|
.await;
|
||||||
|
|
||||||
// Update last_message_id
|
// Update last_message_id
|
||||||
|
#[cfg(feature = "tasks")]
|
||||||
tasks::last_message_id::queue(self.channel.to_string(), self.id.to_string(), is_dm).await;
|
tasks::last_message_id::queue(self.channel.to_string(), self.id.to_string(), is_dm).await;
|
||||||
|
|
||||||
// Add mentions for affected users
|
// Add mentions for affected users
|
||||||
|
#[cfg(feature = "tasks")]
|
||||||
if !mentions_elsewhere {
|
if !mentions_elsewhere {
|
||||||
if let Some(mentions) = &self.mentions {
|
if let Some(mentions) = &self.mentions {
|
||||||
tasks::ack::queue_message(
|
tasks::ack::queue_message(
|
||||||
@@ -637,6 +637,7 @@ impl Message {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// Generate embeds
|
// Generate embeds
|
||||||
|
#[cfg(feature = "tasks")]
|
||||||
if generate_embeds {
|
if generate_embeds {
|
||||||
if let Some(content) = &self.content {
|
if let Some(content) = &self.content {
|
||||||
tasks::process_embeds::queue(
|
tasks::process_embeds::queue(
|
||||||
@@ -673,10 +674,12 @@ impl Message {
|
|||||||
)
|
)
|
||||||
.await?;
|
.await?;
|
||||||
|
|
||||||
|
|
||||||
if !self.has_suppressed_notifications()
|
if !self.has_suppressed_notifications()
|
||||||
&& (self.mentions.is_some() || self.contains_mass_push_mention())
|
&& (self.mentions.is_some() || self.contains_mass_push_mention())
|
||||||
{
|
{
|
||||||
// send Push notifications
|
// send Push notifications
|
||||||
|
#[cfg(feature = "tasks")]
|
||||||
tasks::ack::queue_message(
|
tasks::ack::queue_message(
|
||||||
self.channel.to_string(),
|
self.channel.to_string(),
|
||||||
AckEvent::ProcessMessage {
|
AckEvent::ProcessMessage {
|
||||||
@@ -710,12 +713,6 @@ impl Message {
|
|||||||
|
|
||||||
/// Create text embed from sendable embed
|
/// Create text embed from sendable embed
|
||||||
pub async fn create_embed(&self, db: &Database, embed: SendableEmbed) -> Result<Embed> {
|
pub async fn create_embed(&self, db: &Database, embed: SendableEmbed) -> Result<Embed> {
|
||||||
embed.validate().map_err(|error| {
|
|
||||||
create_error!(FailedValidation {
|
|
||||||
error: error.to_string()
|
|
||||||
})
|
|
||||||
})?;
|
|
||||||
|
|
||||||
let media = if let Some(id) = embed.media {
|
let media = if let Some(id) = embed.media {
|
||||||
Some(File::use_attachment(db, &id, &self.id, &self.author).await?)
|
Some(File::use_attachment(db, &id, &self.id, &self.author).await?)
|
||||||
} else {
|
} else {
|
||||||
|
|||||||
@@ -2,6 +2,7 @@ use revolt_result::Result;
|
|||||||
|
|
||||||
use crate::{AppendMessage, FieldsMessage, Message, MessageQuery, PartialMessage};
|
use crate::{AppendMessage, FieldsMessage, Message, MessageQuery, PartialMessage};
|
||||||
|
|
||||||
|
#[cfg(feature = "mongodb")]
|
||||||
mod mongodb;
|
mod mongodb;
|
||||||
mod reference;
|
mod reference;
|
||||||
|
|
||||||
|
|||||||
@@ -8,6 +8,7 @@ mod emojis;
|
|||||||
mod file_hashes;
|
mod file_hashes;
|
||||||
mod files;
|
mod files;
|
||||||
mod messages;
|
mod messages;
|
||||||
|
mod policy_changes;
|
||||||
mod ratelimit_events;
|
mod ratelimit_events;
|
||||||
mod safety_reports;
|
mod safety_reports;
|
||||||
mod safety_snapshots;
|
mod safety_snapshots;
|
||||||
@@ -27,6 +28,7 @@ pub use emojis::*;
|
|||||||
pub use file_hashes::*;
|
pub use file_hashes::*;
|
||||||
pub use files::*;
|
pub use files::*;
|
||||||
pub use messages::*;
|
pub use messages::*;
|
||||||
|
pub use policy_changes::*;
|
||||||
pub use ratelimit_events::*;
|
pub use ratelimit_events::*;
|
||||||
pub use safety_reports::*;
|
pub use safety_reports::*;
|
||||||
pub use safety_snapshots::*;
|
pub use safety_snapshots::*;
|
||||||
@@ -36,7 +38,10 @@ pub use servers::*;
|
|||||||
pub use user_settings::*;
|
pub use user_settings::*;
|
||||||
pub use users::*;
|
pub use users::*;
|
||||||
|
|
||||||
use crate::{Database, MongoDb, ReferenceDb};
|
use crate::{Database, ReferenceDb};
|
||||||
|
|
||||||
|
#[cfg(feature = "mongodb")]
|
||||||
|
use crate::MongoDb;
|
||||||
|
|
||||||
pub trait AbstractDatabase:
|
pub trait AbstractDatabase:
|
||||||
Sync
|
Sync
|
||||||
@@ -51,6 +56,7 @@ pub trait AbstractDatabase:
|
|||||||
+ file_hashes::AbstractAttachmentHashes
|
+ file_hashes::AbstractAttachmentHashes
|
||||||
+ files::AbstractAttachments
|
+ files::AbstractAttachments
|
||||||
+ messages::AbstractMessages
|
+ messages::AbstractMessages
|
||||||
|
+ policy_changes::AbstractPolicyChange
|
||||||
+ ratelimit_events::AbstractRatelimitEvents
|
+ ratelimit_events::AbstractRatelimitEvents
|
||||||
+ safety_reports::AbstractReport
|
+ safety_reports::AbstractReport
|
||||||
+ safety_snapshots::AbstractSnapshot
|
+ safety_snapshots::AbstractSnapshot
|
||||||
@@ -63,6 +69,8 @@ pub trait AbstractDatabase:
|
|||||||
}
|
}
|
||||||
|
|
||||||
impl AbstractDatabase for ReferenceDb {}
|
impl AbstractDatabase for ReferenceDb {}
|
||||||
|
|
||||||
|
#[cfg(feature = "mongodb")]
|
||||||
impl AbstractDatabase for MongoDb {}
|
impl AbstractDatabase for MongoDb {}
|
||||||
|
|
||||||
impl std::ops::Deref for Database {
|
impl std::ops::Deref for Database {
|
||||||
@@ -71,6 +79,7 @@ impl std::ops::Deref for Database {
|
|||||||
fn deref(&self) -> &Self::Target {
|
fn deref(&self) -> &Self::Target {
|
||||||
match &self {
|
match &self {
|
||||||
Database::Reference(dummy) => dummy,
|
Database::Reference(dummy) => dummy,
|
||||||
|
#[cfg(feature = "mongodb")]
|
||||||
Database::MongoDb(mongo) => mongo,
|
Database::MongoDb(mongo) => mongo,
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -0,0 +1,5 @@
|
|||||||
|
mod model;
|
||||||
|
mod ops;
|
||||||
|
|
||||||
|
pub use model::*;
|
||||||
|
pub use ops::*;
|
||||||
@@ -0,0 +1,20 @@
|
|||||||
|
use iso8601_timestamp::Timestamp;
|
||||||
|
|
||||||
|
auto_derived!(
|
||||||
|
/// Platform policy change
|
||||||
|
pub struct PolicyChange {
|
||||||
|
/// Unique Id
|
||||||
|
#[serde(rename = "_id")]
|
||||||
|
pub id: String,
|
||||||
|
|
||||||
|
/// Time at which this policy was created
|
||||||
|
pub created_time: Timestamp,
|
||||||
|
/// Time at which this policy is effective
|
||||||
|
pub effective_time: Timestamp,
|
||||||
|
|
||||||
|
/// Message shown to users
|
||||||
|
pub description: String,
|
||||||
|
/// URL with details about changes
|
||||||
|
pub url: String,
|
||||||
|
}
|
||||||
|
);
|
||||||
@@ -0,0 +1,16 @@
|
|||||||
|
use revolt_result::Result;
|
||||||
|
|
||||||
|
use crate::PolicyChange;
|
||||||
|
|
||||||
|
#[cfg(feature = "mongodb")]
|
||||||
|
mod mongodb;
|
||||||
|
mod reference;
|
||||||
|
|
||||||
|
#[async_trait]
|
||||||
|
pub trait AbstractPolicyChange: Sync + Send {
|
||||||
|
/// Fetch all policy changes
|
||||||
|
async fn fetch_policy_changes(&self) -> Result<Vec<PolicyChange>>;
|
||||||
|
|
||||||
|
/// Acknowledge policy changes
|
||||||
|
async fn acknowledge_policy_changes(&self, user_id: &str) -> Result<()>;
|
||||||
|
}
|
||||||
@@ -0,0 +1,46 @@
|
|||||||
|
use bson::to_bson;
|
||||||
|
use iso8601_timestamp::Timestamp;
|
||||||
|
use revolt_result::Result;
|
||||||
|
|
||||||
|
use crate::MongoDb;
|
||||||
|
use crate::PolicyChange;
|
||||||
|
use crate::User;
|
||||||
|
|
||||||
|
use super::AbstractPolicyChange;
|
||||||
|
|
||||||
|
static COL: &str = "policy_changes";
|
||||||
|
|
||||||
|
#[async_trait]
|
||||||
|
impl AbstractPolicyChange for MongoDb {
|
||||||
|
/// Fetch all policy changes
|
||||||
|
async fn fetch_policy_changes(&self) -> Result<Vec<PolicyChange>> {
|
||||||
|
query!(self, find, COL, doc! {})
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Acknowledge policy changes
|
||||||
|
async fn acknowledge_policy_changes(&self, user_id: &str) -> Result<()> {
|
||||||
|
let latest_policy = self
|
||||||
|
.fetch_policy_changes()
|
||||||
|
.await?
|
||||||
|
.into_iter()
|
||||||
|
.map(|policy| policy.created_time)
|
||||||
|
.max()
|
||||||
|
.unwrap_or(Timestamp::UNIX_EPOCH);
|
||||||
|
|
||||||
|
self.col::<User>("users")
|
||||||
|
.update_one(
|
||||||
|
doc! {
|
||||||
|
"_id": user_id
|
||||||
|
},
|
||||||
|
doc! {
|
||||||
|
"$set": {
|
||||||
|
"last_acknowledged_policy_change": to_bson(&latest_policy)
|
||||||
|
.map_err(|_| create_database_error!("to_bson", "timestamp"))?
|
||||||
|
}
|
||||||
|
},
|
||||||
|
)
|
||||||
|
.await
|
||||||
|
.map(|_| ())
|
||||||
|
.map_err(|_| create_database_error!("update_one", COL))
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,31 @@
|
|||||||
|
use iso8601_timestamp::Timestamp;
|
||||||
|
use revolt_result::Result;
|
||||||
|
|
||||||
|
use crate::PolicyChange;
|
||||||
|
use crate::ReferenceDb;
|
||||||
|
|
||||||
|
use super::AbstractPolicyChange;
|
||||||
|
|
||||||
|
#[async_trait]
|
||||||
|
impl AbstractPolicyChange for ReferenceDb {
|
||||||
|
/// Fetch all policy changes
|
||||||
|
async fn fetch_policy_changes(&self) -> Result<Vec<PolicyChange>> {
|
||||||
|
let policy_changes = self.policy_changes.lock().await;
|
||||||
|
Ok(policy_changes.values().cloned().collect())
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Acknowledge policy changes
|
||||||
|
async fn acknowledge_policy_changes(&self, user_id: &str) -> Result<()> {
|
||||||
|
let mut users = self.users.lock().await;
|
||||||
|
let user = users.get_mut(user_id).expect("user doesn't exist");
|
||||||
|
user.last_acknowledged_policy_change = self
|
||||||
|
.fetch_policy_changes()
|
||||||
|
.await?
|
||||||
|
.into_iter()
|
||||||
|
.map(|policy| policy.created_time)
|
||||||
|
.max()
|
||||||
|
.unwrap_or(Timestamp::UNIX_EPOCH);
|
||||||
|
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -1,6 +1,8 @@
|
|||||||
use std::time::Duration;
|
use std::time::Duration;
|
||||||
|
|
||||||
use crate::{revolt_result::Result, RatelimitEvent, RatelimitEventType};
|
use crate::{revolt_result::Result, RatelimitEvent, RatelimitEventType};
|
||||||
|
|
||||||
|
#[cfg(feature = "mongodb")]
|
||||||
mod mongodb;
|
mod mongodb;
|
||||||
mod reference;
|
mod reference;
|
||||||
|
|
||||||
|
|||||||
@@ -2,6 +2,7 @@ use revolt_result::Result;
|
|||||||
|
|
||||||
use crate::Report;
|
use crate::Report;
|
||||||
|
|
||||||
|
#[cfg(feature = "mongodb")]
|
||||||
mod mongodb;
|
mod mongodb;
|
||||||
mod reference;
|
mod reference;
|
||||||
|
|
||||||
|
|||||||
@@ -2,6 +2,7 @@ use revolt_result::Result;
|
|||||||
|
|
||||||
use crate::Snapshot;
|
use crate::Snapshot;
|
||||||
|
|
||||||
|
#[cfg(feature = "mongodb")]
|
||||||
mod mongodb;
|
mod mongodb;
|
||||||
mod reference;
|
mod reference;
|
||||||
|
|
||||||
|
|||||||
@@ -2,6 +2,7 @@ use revolt_result::Result;
|
|||||||
|
|
||||||
use crate::{MemberCompositeKey, ServerBan};
|
use crate::{MemberCompositeKey, ServerBan};
|
||||||
|
|
||||||
|
#[cfg(feature = "mongodb")]
|
||||||
mod mongodb;
|
mod mongodb;
|
||||||
mod reference;
|
mod reference;
|
||||||
|
|
||||||
|
|||||||
@@ -1,16 +1,20 @@
|
|||||||
use ::mongodb::SessionCursor;
|
#[cfg(feature = "mongodb")]
|
||||||
|
use ::mongodb::{ClientSession, SessionCursor};
|
||||||
|
|
||||||
use revolt_result::Result;
|
use revolt_result::Result;
|
||||||
|
|
||||||
use crate::{FieldsMember, Member, MemberCompositeKey, PartialMember};
|
use crate::{FieldsMember, Member, MemberCompositeKey, PartialMember};
|
||||||
|
|
||||||
|
#[cfg(feature = "mongodb")]
|
||||||
mod mongodb;
|
mod mongodb;
|
||||||
mod reference;
|
mod reference;
|
||||||
|
|
||||||
#[derive(Debug)]
|
#[derive(Debug)]
|
||||||
|
#[allow(clippy::large_enum_variant)]
|
||||||
pub enum ChunkedServerMembersGenerator {
|
pub enum ChunkedServerMembersGenerator {
|
||||||
#[cfg(feature = "mongodb")]
|
#[cfg(feature = "mongodb")]
|
||||||
MongoDb {
|
MongoDb {
|
||||||
session: ::mongodb::ClientSession,
|
session: ClientSession,
|
||||||
cursor: Option<SessionCursor<Member>>,
|
cursor: Option<SessionCursor<Member>>,
|
||||||
},
|
},
|
||||||
|
|
||||||
@@ -22,7 +26,7 @@ pub enum ChunkedServerMembersGenerator {
|
|||||||
|
|
||||||
impl ChunkedServerMembersGenerator {
|
impl ChunkedServerMembersGenerator {
|
||||||
#[cfg(feature = "mongodb")]
|
#[cfg(feature = "mongodb")]
|
||||||
pub fn new_mongo(session: ::mongodb::ClientSession, cursor: SessionCursor<Member>) -> Self {
|
pub fn new_mongo(session: ClientSession, cursor: SessionCursor<Member>) -> Self {
|
||||||
ChunkedServerMembersGenerator::MongoDb {
|
ChunkedServerMembersGenerator::MongoDb {
|
||||||
session,
|
session,
|
||||||
cursor: Some(cursor),
|
cursor: Some(cursor),
|
||||||
|
|||||||
@@ -181,7 +181,7 @@ impl Server {
|
|||||||
}
|
}
|
||||||
|
|
||||||
/// Update server data
|
/// Update server data
|
||||||
pub async fn update<'a>(
|
pub async fn update(
|
||||||
&mut self,
|
&mut self,
|
||||||
db: &Database,
|
db: &Database,
|
||||||
partial: PartialServer,
|
partial: PartialServer,
|
||||||
@@ -228,6 +228,13 @@ impl Server {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// Ordered roles list
|
||||||
|
pub fn ordered_roles(&self) -> Vec<(String, Role)> {
|
||||||
|
let mut ordered_roles = self.roles.clone().into_iter().collect::<Vec<_>>();
|
||||||
|
ordered_roles.sort_by(|(_, role_a), (_, role_b)| role_a.rank.cmp(&role_b.rank));
|
||||||
|
ordered_roles
|
||||||
|
}
|
||||||
|
|
||||||
/// Set role permission on a server
|
/// Set role permission on a server
|
||||||
pub async fn set_role_permission(
|
pub async fn set_role_permission(
|
||||||
&mut self,
|
&mut self,
|
||||||
@@ -253,6 +260,37 @@ impl Server {
|
|||||||
Err(create_error!(NotFound))
|
Err(create_error!(NotFound))
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// Reorders the server's roles rankings
|
||||||
|
pub async fn set_role_ordering(&mut self, db: &Database, new_order: Vec<String>) -> Result<()> {
|
||||||
|
// New order must always contain every role
|
||||||
|
debug_assert_eq!(self.roles.len(), new_order.len());
|
||||||
|
|
||||||
|
// Set the role's ranks to the positions in the vec
|
||||||
|
for (rank, id) in new_order.iter().enumerate() {
|
||||||
|
self.roles.get_mut(id).unwrap().rank = rank as i64;
|
||||||
|
}
|
||||||
|
|
||||||
|
db.update_server(
|
||||||
|
&self.id,
|
||||||
|
&PartialServer {
|
||||||
|
roles: Some(self.roles.clone()),
|
||||||
|
..Default::default()
|
||||||
|
},
|
||||||
|
Vec::new(),
|
||||||
|
)
|
||||||
|
.await?;
|
||||||
|
|
||||||
|
// Publish bulk update event
|
||||||
|
EventV1::ServerRoleRanksUpdate {
|
||||||
|
id: self.id.clone(),
|
||||||
|
ranks: new_order,
|
||||||
|
}
|
||||||
|
.p(self.id.clone())
|
||||||
|
.await;
|
||||||
|
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
impl Role {
|
impl Role {
|
||||||
|
|||||||
@@ -2,6 +2,7 @@ use revolt_result::Result;
|
|||||||
|
|
||||||
use crate::{FieldsRole, FieldsServer, PartialRole, PartialServer, Role, Server};
|
use crate::{FieldsRole, FieldsServer, PartialRole, PartialServer, Role, Server};
|
||||||
|
|
||||||
|
#[cfg(feature = "mongodb")]
|
||||||
mod mongodb;
|
mod mongodb;
|
||||||
mod reference;
|
mod reference;
|
||||||
|
|
||||||
|
|||||||
@@ -2,6 +2,7 @@ use revolt_result::Result;
|
|||||||
|
|
||||||
use crate::UserSettings;
|
use crate::UserSettings;
|
||||||
|
|
||||||
|
#[cfg(feature = "mongodb")]
|
||||||
mod mongodb;
|
mod mongodb;
|
||||||
mod reference;
|
mod reference;
|
||||||
|
|
||||||
|
|||||||
@@ -7,11 +7,5 @@ mod rocket;
|
|||||||
#[cfg(feature = "rocket-impl")]
|
#[cfg(feature = "rocket-impl")]
|
||||||
mod schema;
|
mod schema;
|
||||||
|
|
||||||
#[cfg(feature = "axum-impl")]
|
|
||||||
pub use self::axum::*;
|
|
||||||
#[cfg(feature = "rocket-impl")]
|
|
||||||
pub use self::rocket::*;
|
|
||||||
#[cfg(feature = "rocket-impl")]
|
|
||||||
pub use self::schema::*;
|
|
||||||
pub use model::*;
|
pub use model::*;
|
||||||
pub use ops::*;
|
pub use ops::*;
|
||||||
@@ -57,6 +57,8 @@ auto_derived_partial!(
|
|||||||
/// Time until user is unsuspended
|
/// Time until user is unsuspended
|
||||||
#[serde(skip_serializing_if = "Option::is_none")]
|
#[serde(skip_serializing_if = "Option::is_none")]
|
||||||
pub suspended_until: Option<Timestamp>,
|
pub suspended_until: Option<Timestamp>,
|
||||||
|
/// Last acknowledged policy change
|
||||||
|
pub last_acknowledged_policy_change: Timestamp,
|
||||||
},
|
},
|
||||||
"PartialUser"
|
"PartialUser"
|
||||||
);
|
);
|
||||||
@@ -178,6 +180,7 @@ impl Default for User {
|
|||||||
privileged: Default::default(),
|
privileged: Default::default(),
|
||||||
bot: Default::default(),
|
bot: Default::default(),
|
||||||
suspended_until: Default::default(),
|
suspended_until: Default::default(),
|
||||||
|
last_acknowledged_policy_change: Timestamp::UNIX_EPOCH,
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -200,6 +203,7 @@ impl User {
|
|||||||
id: account_id.into().unwrap_or_else(|| Ulid::new().to_string()),
|
id: account_id.into().unwrap_or_else(|| Ulid::new().to_string()),
|
||||||
discriminator: User::find_discriminator(db, &username, None).await?,
|
discriminator: User::find_discriminator(db, &username, None).await?,
|
||||||
username,
|
username,
|
||||||
|
last_acknowledged_policy_change: Timestamp::now_utc(),
|
||||||
..Default::default()
|
..Default::default()
|
||||||
};
|
};
|
||||||
|
|
||||||
@@ -701,6 +705,8 @@ impl User {
|
|||||||
duration_days: Option<usize>,
|
duration_days: Option<usize>,
|
||||||
reason: Option<Vec<String>>,
|
reason: Option<Vec<String>>,
|
||||||
) -> Result<()> {
|
) -> Result<()> {
|
||||||
|
// TODO: authifier Error should implement Error
|
||||||
|
|
||||||
let authifier = db.clone().to_authifier().await;
|
let authifier = db.clone().to_authifier().await;
|
||||||
let mut account = authifier
|
let mut account = authifier
|
||||||
.database
|
.database
|
||||||
|
|||||||
@@ -1,8 +1,10 @@
|
|||||||
use authifier::models::Session;
|
use authifier::models::Session;
|
||||||
|
use iso8601_timestamp::Timestamp;
|
||||||
use revolt_result::Result;
|
use revolt_result::Result;
|
||||||
|
|
||||||
use crate::{FieldsUser, PartialUser, RelationshipStatus, User};
|
use crate::{FieldsUser, PartialUser, RelationshipStatus, User};
|
||||||
|
|
||||||
|
#[cfg(feature = "mongodb")]
|
||||||
mod mongodb;
|
mod mongodb;
|
||||||
mod reference;
|
mod reference;
|
||||||
|
|
||||||
@@ -61,4 +63,6 @@ pub trait AbstractUsers: Sync + Send {
|
|||||||
|
|
||||||
/// Remove push subscription for a session by session id (TODO: remove)
|
/// Remove push subscription for a session by session id (TODO: remove)
|
||||||
async fn remove_push_subscription_by_session_id(&self, session_id: &str) -> Result<()>;
|
async fn remove_push_subscription_by_session_id(&self, session_id: &str) -> Result<()>;
|
||||||
|
|
||||||
|
async fn update_session_last_seen(&self, session_id: &str, when: Timestamp) -> Result<()>;
|
||||||
}
|
}
|
||||||
@@ -1,6 +1,7 @@
|
|||||||
use ::mongodb::options::{Collation, CollationStrength, FindOneOptions, FindOptions};
|
use ::mongodb::options::{Collation, CollationStrength, FindOneOptions, FindOptions};
|
||||||
use authifier::models::Session;
|
use authifier::models::Session;
|
||||||
use futures::StreamExt;
|
use futures::StreamExt;
|
||||||
|
use iso8601_timestamp::Timestamp;
|
||||||
use revolt_result::Result;
|
use revolt_result::Result;
|
||||||
|
|
||||||
use crate::DocumentId;
|
use crate::DocumentId;
|
||||||
@@ -211,16 +212,34 @@ impl AbstractUsers for MongoDb {
|
|||||||
partial: &PartialUser,
|
partial: &PartialUser,
|
||||||
remove: Vec<FieldsUser>,
|
remove: Vec<FieldsUser>,
|
||||||
) -> Result<()> {
|
) -> Result<()> {
|
||||||
query!(
|
if remove.contains(&FieldsUser::StatusText) && partial.status.is_some() {
|
||||||
self,
|
// stupid-ass workaround to fix mongo conflicting the same item
|
||||||
update_one_by_id,
|
let _: Result<()> = query!(
|
||||||
COL,
|
self,
|
||||||
id,
|
update_one_by_id,
|
||||||
partial,
|
COL,
|
||||||
remove.iter().map(|x| x as &dyn IntoDocumentPath).collect(),
|
id,
|
||||||
None
|
PartialUser {
|
||||||
)
|
..Default::default()
|
||||||
.map(|_| ())
|
},
|
||||||
|
remove.iter().map(|x| x as &dyn IntoDocumentPath).collect(),
|
||||||
|
None
|
||||||
|
)
|
||||||
|
.map(|_| ());
|
||||||
|
|
||||||
|
query!(self, update_one_by_id, COL, id, partial, vec![], None).map(|_| ())
|
||||||
|
} else {
|
||||||
|
query!(
|
||||||
|
self,
|
||||||
|
update_one_by_id,
|
||||||
|
COL,
|
||||||
|
id,
|
||||||
|
partial,
|
||||||
|
remove.iter().map(|x| x as &dyn IntoDocumentPath).collect(),
|
||||||
|
None
|
||||||
|
)
|
||||||
|
.map(|_| ())
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Set relationship with another user
|
/// Set relationship with another user
|
||||||
@@ -317,7 +336,26 @@ impl AbstractUsers for MongoDb {
|
|||||||
)
|
)
|
||||||
.await
|
.await
|
||||||
.map(|_| ())
|
.map(|_| ())
|
||||||
.map_err(|_| create_database_error!("update_one", COL))
|
.map_err(|_| create_database_error!("update_one", "sessions"))
|
||||||
|
}
|
||||||
|
|
||||||
|
async fn update_session_last_seen(&self, session_id: &str, when: Timestamp) -> Result<()> {
|
||||||
|
let formatted: &str = &when.format();
|
||||||
|
|
||||||
|
self.col::<Session>("sessions")
|
||||||
|
.update_one(
|
||||||
|
doc! {
|
||||||
|
"_id": session_id
|
||||||
|
},
|
||||||
|
doc! {
|
||||||
|
"$set": {
|
||||||
|
"last_seen": formatted
|
||||||
|
}
|
||||||
|
},
|
||||||
|
)
|
||||||
|
.await
|
||||||
|
.map(|_| ())
|
||||||
|
.map_err(|_| create_database_error!("update_one", "sessions"))
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -1,4 +1,5 @@
|
|||||||
use authifier::models::Session;
|
use authifier::models::Session;
|
||||||
|
use iso8601_timestamp::Timestamp;
|
||||||
use revolt_result::Result;
|
use revolt_result::Result;
|
||||||
|
|
||||||
use crate::{FieldsUser, PartialUser, RelationshipStatus, User};
|
use crate::{FieldsUser, PartialUser, RelationshipStatus, User};
|
||||||
@@ -168,4 +169,8 @@ impl AbstractUsers for ReferenceDb {
|
|||||||
async fn remove_push_subscription_by_session_id(&self, _session_id: &str) -> Result<()> {
|
async fn remove_push_subscription_by_session_id(&self, _session_id: &str) -> Result<()> {
|
||||||
todo!()
|
todo!()
|
||||||
}
|
}
|
||||||
|
|
||||||
|
async fn update_session_last_seen(&self, _session_id: &str, _when: Timestamp) -> Result<()> {
|
||||||
|
todo!()
|
||||||
|
}
|
||||||
}
|
}
|
||||||
@@ -38,6 +38,7 @@ impl<'r> FromRequest<'r> for User {
|
|||||||
if let Some(user) = user {
|
if let Some(user) = user {
|
||||||
Outcome::Success(user.clone())
|
Outcome::Success(user.clone())
|
||||||
} else {
|
} else {
|
||||||
|
request.local_cache(|| Some(create_error!(InvalidSession)));
|
||||||
Outcome::Error((Status::Unauthorized, authifier::Error::InvalidSession))
|
Outcome::Error((Status::Unauthorized, authifier::Error::InvalidSession))
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -4,7 +4,7 @@ use once_cell::sync::Lazy;
|
|||||||
|
|
||||||
use crate::events::client::EventV1;
|
use crate::events::client::EventV1;
|
||||||
|
|
||||||
static Q: Lazy<(Sender<AuthifierEvent>, Receiver<AuthifierEvent>)> = Lazy::new(|| unbounded());
|
static Q: Lazy<(Sender<AuthifierEvent>, Receiver<AuthifierEvent>)> = Lazy::new(unbounded);
|
||||||
|
|
||||||
/// Get sender
|
/// Get sender
|
||||||
pub fn sender() -> Sender<AuthifierEvent> {
|
pub fn sender() -> Sender<AuthifierEvent> {
|
||||||
|
|||||||
@@ -1,3 +1,4 @@
|
|||||||
|
use iso8601_timestamp::Timestamp;
|
||||||
use revolt_models::v0::*;
|
use revolt_models::v0::*;
|
||||||
use revolt_permissions::{calculate_user_permissions, UserPermission};
|
use revolt_permissions::{calculate_user_permissions, UserPermission};
|
||||||
|
|
||||||
@@ -14,8 +15,7 @@ impl crate::Bot {
|
|||||||
avatar: user.avatar.map(|x| x.id).unwrap_or_default(),
|
avatar: user.avatar.map(|x| x.id).unwrap_or_default(),
|
||||||
description: user
|
description: user
|
||||||
.profile
|
.profile
|
||||||
.map(|profile| profile.content)
|
.and_then(|profile| profile.content)
|
||||||
.flatten()
|
|
||||||
.unwrap_or_default(),
|
.unwrap_or_default(),
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -597,6 +597,17 @@ impl From<Masquerade> for crate::Masquerade {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
impl From<crate::PolicyChange> for PolicyChange {
|
||||||
|
fn from(value: crate::PolicyChange) -> Self {
|
||||||
|
PolicyChange {
|
||||||
|
created_time: value.created_time,
|
||||||
|
effective_time: value.effective_time,
|
||||||
|
description: value.description,
|
||||||
|
url: value.url,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
impl From<crate::Report> for Report {
|
impl From<crate::Report> for Report {
|
||||||
fn from(value: crate::Report) -> Self {
|
fn from(value: crate::Report) -> Self {
|
||||||
Report {
|
Report {
|
||||||
@@ -1102,7 +1113,7 @@ impl crate::User {
|
|||||||
}
|
}
|
||||||
|
|
||||||
/// Convert user object into user model without presence information
|
/// Convert user object into user model without presence information
|
||||||
pub async fn into_known_static<'a>(self, is_online: bool) -> User {
|
pub async fn into_known_static(self, is_online: bool) -> User {
|
||||||
let badges = self.get_badges().await;
|
let badges = self.get_badges().await;
|
||||||
|
|
||||||
User {
|
User {
|
||||||
@@ -1188,6 +1199,7 @@ impl From<User> for crate::User {
|
|||||||
privileged: value.privileged,
|
privileged: value.privileged,
|
||||||
bot: value.bot.map(Into::into),
|
bot: value.bot.map(Into::into),
|
||||||
suspended_until: None,
|
suspended_until: None,
|
||||||
|
last_acknowledged_policy_change: Timestamp::UNIX_EPOCH,
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -54,7 +54,7 @@ use revolt_rocket_okapi::{
|
|||||||
use schemars::schema::{InstanceType, SchemaObject, SingleOrVec};
|
use schemars::schema::{InstanceType, SchemaObject, SingleOrVec};
|
||||||
|
|
||||||
#[cfg(feature = "rocket-impl")]
|
#[cfg(feature = "rocket-impl")]
|
||||||
impl<'r> OpenApiFromRequest<'r> for IdempotencyKey {
|
impl OpenApiFromRequest<'_> for IdempotencyKey {
|
||||||
fn from_request_input(
|
fn from_request_input(
|
||||||
_gen: &mut OpenApiGenerator,
|
_gen: &mut OpenApiGenerator,
|
||||||
_name: String,
|
_name: String,
|
||||||
@@ -113,6 +113,8 @@ impl<'r> FromRequest<'r> for IdempotencyKey {
|
|||||||
let idempotency = IdempotencyKey { key };
|
let idempotency = IdempotencyKey { key };
|
||||||
let mut cache = TOKEN_CACHE.lock().await;
|
let mut cache = TOKEN_CACHE.lock().await;
|
||||||
if cache.get(&idempotency.key).is_some() {
|
if cache.get(&idempotency.key).is_some() {
|
||||||
|
request.local_cache(|| Some(create_error!(DuplicateNonce)));
|
||||||
|
|
||||||
return Outcome::Error((Status::Conflict, create_error!(DuplicateNonce)));
|
return Outcome::Error((Status::Conflict, create_error!(DuplicateNonce)));
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -104,7 +104,7 @@ impl PermissionQuery for DatabasePermissionQuery<'_> {
|
|||||||
.unwrap_or_default();
|
.unwrap_or_default();
|
||||||
|
|
||||||
self.cached_mutual_connection = Some(value);
|
self.cached_mutual_connection = Some(value);
|
||||||
matches!(value, true)
|
value
|
||||||
} else {
|
} else {
|
||||||
false
|
false
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -14,41 +14,40 @@ use crate::{
|
|||||||
};
|
};
|
||||||
|
|
||||||
/// Reference to some object in the database
|
/// Reference to some object in the database
|
||||||
#[derive(Serialize, Deserialize)]
|
pub struct Reference<'a> {
|
||||||
pub struct Reference {
|
|
||||||
/// Id of object
|
/// Id of object
|
||||||
pub id: String,
|
pub id: &'a str,
|
||||||
}
|
}
|
||||||
|
|
||||||
impl Reference {
|
impl<'a> Reference<'a> {
|
||||||
/// Create a Ref from an unchecked string
|
/// Create a Ref from an unchecked string
|
||||||
pub fn from_unchecked(id: String) -> Reference {
|
pub fn from_unchecked(id: &'a str) -> Reference<'a> {
|
||||||
Reference { id }
|
Reference { id }
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Fetch ban from Ref
|
/// Fetch ban from Ref
|
||||||
pub async fn as_ban(&self, db: &Database, server: &str) -> Result<ServerBan> {
|
pub async fn as_ban(&self, db: &Database, server: &str) -> Result<ServerBan> {
|
||||||
db.fetch_ban(server, &self.id).await
|
db.fetch_ban(server, self.id).await
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Fetch bot from Ref
|
/// Fetch bot from Ref
|
||||||
pub async fn as_bot(&self, db: &Database) -> Result<Bot> {
|
pub async fn as_bot(&self, db: &Database) -> Result<Bot> {
|
||||||
db.fetch_bot(&self.id).await
|
db.fetch_bot(self.id).await
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Fetch emoji from Ref
|
/// Fetch emoji from Ref
|
||||||
pub async fn as_emoji(&self, db: &Database) -> Result<Emoji> {
|
pub async fn as_emoji(&self, db: &Database) -> Result<Emoji> {
|
||||||
db.fetch_emoji(&self.id).await
|
db.fetch_emoji(self.id).await
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Fetch channel from Ref
|
/// Fetch channel from Ref
|
||||||
pub async fn as_channel(&self, db: &Database) -> Result<Channel> {
|
pub async fn as_channel(&self, db: &Database) -> Result<Channel> {
|
||||||
db.fetch_channel(&self.id).await
|
db.fetch_channel(self.id).await
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Fetch invite from Ref or create invite to server if discoverable
|
/// Fetch invite from Ref or create invite to server if discoverable
|
||||||
pub async fn as_invite(&self, db: &Database) -> Result<Invite> {
|
pub async fn as_invite(&self, db: &Database) -> Result<Invite> {
|
||||||
if ulid::Ulid::from_str(&self.id).is_ok() {
|
if ulid::Ulid::from_str(self.id).is_ok() {
|
||||||
let server = self.as_server(db).await?;
|
let server = self.as_server(db).await?;
|
||||||
if !server.discoverable {
|
if !server.discoverable {
|
||||||
return Err(create_error!(NotFound));
|
return Err(create_error!(NotFound));
|
||||||
@@ -65,18 +64,18 @@ impl Reference {
|
|||||||
.ok_or(create_error!(NotFound))?,
|
.ok_or(create_error!(NotFound))?,
|
||||||
})
|
})
|
||||||
} else {
|
} else {
|
||||||
db.fetch_invite(&self.id).await
|
db.fetch_invite(self.id).await
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Fetch message from Ref
|
/// Fetch message from Ref
|
||||||
pub async fn as_message(&self, db: &Database) -> Result<Message> {
|
pub async fn as_message(&self, db: &Database) -> Result<Message> {
|
||||||
db.fetch_message(&self.id).await
|
db.fetch_message(self.id).await
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Fetch message from Ref and validate channel
|
/// Fetch message from Ref and validate channel
|
||||||
pub async fn as_message_in_channel(&self, db: &Database, channel: &str) -> Result<Message> {
|
pub async fn as_message_in_channel(&self, db: &Database, channel: &str) -> Result<Message> {
|
||||||
let msg = db.fetch_message(&self.id).await?;
|
let msg = db.fetch_message(self.id).await?;
|
||||||
if msg.channel != channel {
|
if msg.channel != channel {
|
||||||
return Err(create_error!(NotFound));
|
return Err(create_error!(NotFound));
|
||||||
}
|
}
|
||||||
@@ -86,36 +85,36 @@ impl Reference {
|
|||||||
|
|
||||||
/// Fetch member from Ref
|
/// Fetch member from Ref
|
||||||
pub async fn as_member(&self, db: &Database, server: &str) -> Result<Member> {
|
pub async fn as_member(&self, db: &Database, server: &str) -> Result<Member> {
|
||||||
db.fetch_member(server, &self.id).await
|
db.fetch_member(server, self.id).await
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Fetch server from Ref
|
/// Fetch server from Ref
|
||||||
pub async fn as_server(&self, db: &Database) -> Result<Server> {
|
pub async fn as_server(&self, db: &Database) -> Result<Server> {
|
||||||
db.fetch_server(&self.id).await
|
db.fetch_server(self.id).await
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Fetch user from Ref
|
/// Fetch user from Ref
|
||||||
pub async fn as_user(&self, db: &Database) -> Result<User> {
|
pub async fn as_user(&self, db: &Database) -> Result<User> {
|
||||||
db.fetch_user(&self.id).await
|
db.fetch_user(self.id).await
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Fetch webhook from Ref
|
/// Fetch webhook from Ref
|
||||||
pub async fn as_webhook(&self, db: &Database) -> Result<Webhook> {
|
pub async fn as_webhook(&self, db: &Database) -> Result<Webhook> {
|
||||||
db.fetch_webhook(&self.id).await
|
db.fetch_webhook(self.id).await
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
#[cfg(feature = "rocket-impl")]
|
#[cfg(feature = "rocket-impl")]
|
||||||
impl<'r> FromParam<'r> for Reference {
|
impl<'r> FromParam<'r> for Reference<'r> {
|
||||||
type Error = &'r str;
|
type Error = &'r str;
|
||||||
|
|
||||||
fn from_param(param: &'r str) -> Result<Self, Self::Error> {
|
fn from_param(param: &'r str) -> Result<Self, Self::Error> {
|
||||||
Ok(Reference::from_unchecked(param.into()))
|
Ok(Reference::from_unchecked(param))
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
#[cfg(feature = "rocket-impl")]
|
#[cfg(feature = "rocket-impl")]
|
||||||
impl JsonSchema for Reference {
|
impl<'a> JsonSchema for Reference<'a> {
|
||||||
fn schema_name() -> String {
|
fn schema_name() -> String {
|
||||||
"Id".to_string()
|
"Id".to_string()
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,6 +1,6 @@
|
|||||||
[package]
|
[package]
|
||||||
name = "revolt-files"
|
name = "revolt-files"
|
||||||
version = "0.8.6"
|
version = "0.8.8"
|
||||||
edition = "2021"
|
edition = "2021"
|
||||||
license = "AGPL-3.0-or-later"
|
license = "AGPL-3.0-or-later"
|
||||||
authors = ["Paul Makles <me@insrt.uk>"]
|
authors = ["Paul Makles <me@insrt.uk>"]
|
||||||
@@ -14,16 +14,16 @@ imagesize = "0.13.0"
|
|||||||
tempfile = "3.12.0"
|
tempfile = "3.12.0"
|
||||||
|
|
||||||
base64 = "0.22.1"
|
base64 = "0.22.1"
|
||||||
aes-gcm = "0.10.3"
|
aes-gcm = { version = "0.10.3", features = ["std"] }
|
||||||
typenum = "1.17.0"
|
typenum = "1.17.0"
|
||||||
|
|
||||||
aws-config = "1.5.5"
|
aws-config = "1.5.5"
|
||||||
aws-sdk-s3 = { version = "1.46.0", features = ["behavior-version-latest"] }
|
aws-sdk-s3 = { version = "1.46.0", features = ["behavior-version-latest"] }
|
||||||
|
|
||||||
revolt-config = { version = "0.8.6", path = "../config", features = [
|
revolt-config = { version = "0.8.8", path = "../config", features = [
|
||||||
"report-macros",
|
"report-macros",
|
||||||
] }
|
] }
|
||||||
revolt-result = { version = "0.8.6", path = "../result" }
|
revolt-result = { version = "0.8.8", path = "../result", features = ["sentry"] }
|
||||||
|
|
||||||
# image processing
|
# image processing
|
||||||
jxl-oxide = "0.8.1"
|
jxl-oxide = "0.8.1"
|
||||||
|
|||||||
@@ -6,7 +6,7 @@ use aes_gcm::{
|
|||||||
};
|
};
|
||||||
use image::{DynamicImage, ImageBuffer};
|
use image::{DynamicImage, ImageBuffer};
|
||||||
use revolt_config::{config, report_internal_error, FilesS3};
|
use revolt_config::{config, report_internal_error, FilesS3};
|
||||||
use revolt_result::{create_error, Result};
|
use revolt_result::{create_error, Result, ToRevoltError};
|
||||||
|
|
||||||
use aws_sdk_s3::{
|
use aws_sdk_s3::{
|
||||||
config::{Credentials, Region},
|
config::{Credentials, Region},
|
||||||
@@ -55,13 +55,12 @@ pub async fn fetch_from_s3(bucket_id: &str, path: &str, nonce: &str) -> Result<V
|
|||||||
|
|
||||||
// Send a request for the file
|
// Send a request for the file
|
||||||
let mut obj =
|
let mut obj =
|
||||||
report_internal_error!(client.get_object().bucket(bucket_id).key(path).send().await)?;
|
client.get_object().bucket(bucket_id).key(path).send().await.to_internal_error()?;
|
||||||
|
|
||||||
// Read the file from remote
|
// Read the file from remote
|
||||||
let mut buf = vec![];
|
let mut buf = vec![];
|
||||||
while let Some(bytes) = obj.body.next().await {
|
while let Some(bytes) = obj.body.next().await {
|
||||||
let data = report_internal_error!(bytes)?;
|
buf.write_all(&bytes.to_internal_error()?).to_internal_error()?;
|
||||||
report_internal_error!(buf.write_all(&data))?;
|
|
||||||
// is there a more efficient way to do this?
|
// is there a more efficient way to do this?
|
||||||
// we just want the Vec<u8>
|
// we just want the Vec<u8>
|
||||||
}
|
}
|
||||||
@@ -78,7 +77,7 @@ pub async fn fetch_from_s3(bucket_id: &str, path: &str, nonce: &str) -> Result<V
|
|||||||
// Decrypt the file
|
// Decrypt the file
|
||||||
create_cipher(&config.files.encryption_key)
|
create_cipher(&config.files.encryption_key)
|
||||||
.decrypt_in_place(nonce, b"", &mut buf)
|
.decrypt_in_place(nonce, b"", &mut buf)
|
||||||
.map_err(|_| create_error!(InternalError))?;
|
.to_internal_error()?;
|
||||||
|
|
||||||
Ok(buf)
|
Ok(buf)
|
||||||
}
|
}
|
||||||
@@ -97,18 +96,17 @@ pub async fn upload_to_s3(bucket_id: &str, path: &str, buf: &[u8]) -> Result<Str
|
|||||||
// Encrypt the file in place
|
// Encrypt the file in place
|
||||||
create_cipher(&config.files.encryption_key)
|
create_cipher(&config.files.encryption_key)
|
||||||
.encrypt_in_place(&nonce, b"", &mut buf)
|
.encrypt_in_place(&nonce, b"", &mut buf)
|
||||||
.map_err(|_| create_error!(InternalError))?;
|
.to_internal_error()?;
|
||||||
|
|
||||||
// Upload the file to remote
|
// Upload the file to remote
|
||||||
report_internal_error!(
|
client
|
||||||
client
|
.put_object()
|
||||||
.put_object()
|
.bucket(bucket_id)
|
||||||
.bucket(bucket_id)
|
.key(path)
|
||||||
.key(path)
|
.body(buf.into())
|
||||||
.body(buf.into())
|
.send()
|
||||||
.send()
|
.await
|
||||||
.await
|
.to_internal_error()?;
|
||||||
)?;
|
|
||||||
|
|
||||||
Ok(BASE64_STANDARD.encode(nonce))
|
Ok(BASE64_STANDARD.encode(nonce))
|
||||||
}
|
}
|
||||||
@@ -118,14 +116,13 @@ pub async fn delete_from_s3(bucket_id: &str, path: &str) -> Result<()> {
|
|||||||
let config = config().await;
|
let config = config().await;
|
||||||
let client = create_client(config.files.s3);
|
let client = create_client(config.files.s3);
|
||||||
|
|
||||||
report_internal_error!(
|
client
|
||||||
client
|
.delete_object()
|
||||||
.delete_object()
|
.bucket(bucket_id)
|
||||||
.bucket(bucket_id)
|
.key(path)
|
||||||
.key(path)
|
.send()
|
||||||
.send()
|
.await
|
||||||
.await
|
.to_internal_error()?;
|
||||||
)?;
|
|
||||||
|
|
||||||
Ok(())
|
Ok(())
|
||||||
}
|
}
|
||||||
@@ -145,8 +142,7 @@ pub fn image_size(f: &NamedTempFile) -> Option<(usize, usize)> {
|
|||||||
pub fn image_size_vec(v: &[u8], mime: &str) -> Option<(usize, usize)> {
|
pub fn image_size_vec(v: &[u8], mime: &str) -> Option<(usize, usize)> {
|
||||||
match mime {
|
match mime {
|
||||||
"image/svg+xml" => {
|
"image/svg+xml" => {
|
||||||
let tree =
|
let tree = usvg::Tree::from_data(v, &Default::default()).to_internal_error().ok()?;
|
||||||
report_internal_error!(usvg::Tree::from_data(v, &Default::default())).ok()?;
|
|
||||||
|
|
||||||
let size = tree.size();
|
let size = tree.size();
|
||||||
Some((size.width() as usize, size.height() as usize))
|
Some((size.width() as usize, size.height() as usize))
|
||||||
@@ -221,9 +217,9 @@ pub fn decode_image<R: Read + BufRead + Seek>(reader: &mut R, mime: &str) -> Res
|
|||||||
"image/svg+xml" => {
|
"image/svg+xml" => {
|
||||||
// usvg doesn't support Read trait so copy to buffer
|
// usvg doesn't support Read trait so copy to buffer
|
||||||
let mut buf = Vec::new();
|
let mut buf = Vec::new();
|
||||||
report_internal_error!(reader.read_to_end(&mut buf))?;
|
reader.read_to_end(&mut buf).to_internal_error()?;
|
||||||
|
|
||||||
let tree = report_internal_error!(usvg::Tree::from_data(&buf, &Default::default()))?;
|
let tree = usvg::Tree::from_data(&buf, &Default::default()).to_internal_error()?;
|
||||||
let size = tree.size();
|
let size = tree.size();
|
||||||
let mut pixmap = Pixmap::new(size.width() as u32, size.height() as u32)
|
let mut pixmap = Pixmap::new(size.width() as u32, size.height() as u32)
|
||||||
.ok_or_else(|| create_error!(ImageProcessingFailed))?;
|
.ok_or_else(|| create_error!(ImageProcessingFailed))?;
|
||||||
@@ -241,10 +237,11 @@ pub fn decode_image<R: Read + BufRead + Seek>(reader: &mut R, mime: &str) -> Res
|
|||||||
))
|
))
|
||||||
}
|
}
|
||||||
// Check if we can read using image-rs crate
|
// Check if we can read using image-rs crate
|
||||||
_ => report_internal_error!(report_internal_error!(
|
_ => image::ImageReader::new(reader)
|
||||||
image::ImageReader::new(reader).with_guessed_format()
|
.with_guessed_format()
|
||||||
)?
|
.to_internal_error()?
|
||||||
.decode()),
|
.decode()
|
||||||
|
.to_internal_error()
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -1,6 +1,6 @@
|
|||||||
[package]
|
[package]
|
||||||
name = "revolt-models"
|
name = "revolt-models"
|
||||||
version = "0.8.6"
|
version = "0.8.8"
|
||||||
edition = "2021"
|
edition = "2021"
|
||||||
license = "MIT"
|
license = "MIT"
|
||||||
authors = ["Paul Makles <me@insrt.uk>"]
|
authors = ["Paul Makles <me@insrt.uk>"]
|
||||||
@@ -20,8 +20,8 @@ default = ["serde", "partials", "rocket"]
|
|||||||
|
|
||||||
[dependencies]
|
[dependencies]
|
||||||
# Core
|
# Core
|
||||||
revolt-config = { version = "0.8.6", path = "../config" }
|
revolt-config = { version = "0.8.8", path = "../config" }
|
||||||
revolt-permissions = { version = "0.8.6", path = "../permissions" }
|
revolt-permissions = { version = "0.8.8", path = "../permissions" }
|
||||||
|
|
||||||
# Utility
|
# Utility
|
||||||
regex = "1.11"
|
regex = "1.11"
|
||||||
|
|||||||
@@ -132,8 +132,8 @@ auto_derived!(
|
|||||||
#[cfg_attr(feature = "validator", validate(length(min = 1, max = 2048)))]
|
#[cfg_attr(feature = "validator", validate(length(min = 1, max = 2048)))]
|
||||||
pub interactions_url: Option<String>,
|
pub interactions_url: Option<String>,
|
||||||
/// Fields to remove from bot object
|
/// Fields to remove from bot object
|
||||||
#[cfg_attr(feature = "validator", validate(length(min = 1)))]
|
#[cfg_attr(feature = "serde", serde(default))]
|
||||||
pub remove: Option<Vec<FieldsBot>>,
|
pub remove: Vec<FieldsBot>,
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Where we are inviting a bot to
|
/// Where we are inviting a bot to
|
||||||
|
|||||||
@@ -207,7 +207,7 @@ auto_derived!(
|
|||||||
|
|
||||||
/// Fields to remove from channel
|
/// Fields to remove from channel
|
||||||
#[cfg_attr(feature = "serde", serde(default))]
|
#[cfg_attr(feature = "serde", serde(default))]
|
||||||
pub remove: Option<Vec<FieldsChannel>>,
|
pub remove: Vec<FieldsChannel>,
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Create new group
|
/// Create new group
|
||||||
@@ -310,14 +310,14 @@ impl Channel {
|
|||||||
/// This returns a Result because the recipient name can't be determined here without a db call,
|
/// This returns a Result because the recipient name can't be determined here without a db call,
|
||||||
/// which can't be done since this is models, which can't reference the database crate.
|
/// which can't be done since this is models, which can't reference the database crate.
|
||||||
///
|
///
|
||||||
/// If it returns Err, you need to fetch the name from the db.
|
/// If it returns None, you need to fetch the name from the db.
|
||||||
pub fn name(&self) -> Result<&str, ()> {
|
pub fn name(&self) -> Option<&str> {
|
||||||
match self {
|
match self {
|
||||||
Channel::DirectMessage { .. } => Err(()),
|
Channel::DirectMessage { .. } => None,
|
||||||
Channel::SavedMessages { .. } => Ok("Saved Messages"),
|
Channel::SavedMessages { .. } => Some("Saved Messages"),
|
||||||
Channel::TextChannel { name, .. }
|
Channel::TextChannel { name, .. }
|
||||||
| Channel::Group { name, .. }
|
| Channel::Group { name, .. }
|
||||||
| Channel::VoiceChannel { name, .. } => Ok(name),
|
| Channel::VoiceChannel { name, .. } => Some(name),
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -215,7 +215,7 @@ auto_derived!(
|
|||||||
#[derive(Default)]
|
#[derive(Default)]
|
||||||
#[cfg_attr(feature = "validator", derive(Validate))]
|
#[cfg_attr(feature = "validator", derive(Validate))]
|
||||||
pub struct SendableEmbed {
|
pub struct SendableEmbed {
|
||||||
#[cfg_attr(feature = "validator", validate(length(min = 1, max = 128)))]
|
#[cfg_attr(feature = "validator", validate(length(min = 1, max = 256)))]
|
||||||
pub icon_url: Option<String>,
|
pub icon_url: Option<String>,
|
||||||
#[cfg_attr(feature = "validator", validate(length(min = 1, max = 256)))]
|
#[cfg_attr(feature = "validator", validate(length(min = 1, max = 256)))]
|
||||||
pub url: Option<String>,
|
pub url: Option<String>,
|
||||||
|
|||||||
@@ -7,6 +7,8 @@ mod embeds;
|
|||||||
mod emojis;
|
mod emojis;
|
||||||
mod files;
|
mod files;
|
||||||
mod messages;
|
mod messages;
|
||||||
|
mod onboard;
|
||||||
|
mod policy_changes;
|
||||||
mod safety_reports;
|
mod safety_reports;
|
||||||
mod server_bans;
|
mod server_bans;
|
||||||
mod server_members;
|
mod server_members;
|
||||||
@@ -23,6 +25,8 @@ pub use embeds::*;
|
|||||||
pub use emojis::*;
|
pub use emojis::*;
|
||||||
pub use files::*;
|
pub use files::*;
|
||||||
pub use messages::*;
|
pub use messages::*;
|
||||||
|
pub use onboard::*;
|
||||||
|
pub use policy_changes::*;
|
||||||
pub use safety_reports::*;
|
pub use safety_reports::*;
|
||||||
pub use server_bans::*;
|
pub use server_bans::*;
|
||||||
pub use server_members::*;
|
pub use server_members::*;
|
||||||
|
|||||||
@@ -0,0 +1,15 @@
|
|||||||
|
auto_derived!(
|
||||||
|
/// # New User Data
|
||||||
|
#[derive(validator::Validate)]
|
||||||
|
pub struct DataOnboard {
|
||||||
|
/// New username which will be used to identify the user on the platform
|
||||||
|
#[validate(length(min = 2, max = 32), regex = "super::RE_USERNAME")]
|
||||||
|
pub username: String,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// # Onboarding Status
|
||||||
|
pub struct DataHello {
|
||||||
|
/// Whether onboarding is required
|
||||||
|
pub onboarding: bool,
|
||||||
|
}
|
||||||
|
);
|
||||||
@@ -0,0 +1,16 @@
|
|||||||
|
use iso8601_timestamp::Timestamp;
|
||||||
|
|
||||||
|
auto_derived!(
|
||||||
|
/// Platform policy change
|
||||||
|
pub struct PolicyChange {
|
||||||
|
/// Time at which this policy was created
|
||||||
|
pub created_time: Timestamp,
|
||||||
|
/// Time at which this policy is effective
|
||||||
|
pub effective_time: Timestamp,
|
||||||
|
|
||||||
|
/// Message shown to users
|
||||||
|
pub description: String,
|
||||||
|
/// URL with details about changes
|
||||||
|
pub url: String,
|
||||||
|
}
|
||||||
|
);
|
||||||
@@ -1,6 +1,17 @@
|
|||||||
use iso8601_timestamp::Timestamp;
|
use iso8601_timestamp::Timestamp;
|
||||||
|
|
||||||
auto_derived!(
|
auto_derived!(
|
||||||
|
/// # Report Data
|
||||||
|
#[derive(validator::Validate)]
|
||||||
|
pub struct DataReportContent {
|
||||||
|
/// Content being reported
|
||||||
|
pub content: ReportedContent,
|
||||||
|
/// Additional report description
|
||||||
|
#[validate(length(min = 0, max = 1000))]
|
||||||
|
#[serde(default)]
|
||||||
|
pub additional_context: String,
|
||||||
|
}
|
||||||
|
|
||||||
/// User-generated platform moderation report
|
/// User-generated platform moderation report
|
||||||
pub struct Report {
|
pub struct Report {
|
||||||
/// Unique Id
|
/// Unique Id
|
||||||
|
|||||||
@@ -124,7 +124,7 @@ auto_derived!(
|
|||||||
/// Timestamp this member is timed out until
|
/// Timestamp this member is timed out until
|
||||||
pub timeout: Option<Timestamp>,
|
pub timeout: Option<Timestamp>,
|
||||||
/// Fields to remove from channel object
|
/// Fields to remove from channel object
|
||||||
#[cfg_attr(feature = "validator", validate(length(min = 1)))]
|
#[cfg_attr(feature = "serde", serde(default))]
|
||||||
pub remove: Option<Vec<FieldsMember>>,
|
pub remove: Vec<FieldsMember>,
|
||||||
}
|
}
|
||||||
);
|
);
|
||||||
@@ -1,4 +1,4 @@
|
|||||||
use super::{Channel, File, RE_COLOUR};
|
use super::{Channel, File, Member, User, RE_COLOUR};
|
||||||
|
|
||||||
use revolt_permissions::{Override, OverrideField};
|
use revolt_permissions::{Override, OverrideField};
|
||||||
use std::collections::HashMap;
|
use std::collections::HashMap;
|
||||||
@@ -175,6 +175,8 @@ auto_derived!(
|
|||||||
/// Ranking position
|
/// Ranking position
|
||||||
///
|
///
|
||||||
/// Smaller values take priority.
|
/// Smaller values take priority.
|
||||||
|
///
|
||||||
|
/// **Removed** - no effect, use the edit server role positions route
|
||||||
pub rank: Option<i64>,
|
pub rank: Option<i64>,
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -247,8 +249,8 @@ auto_derived!(
|
|||||||
pub analytics: Option<bool>,
|
pub analytics: Option<bool>,
|
||||||
|
|
||||||
/// Fields to remove from server object
|
/// Fields to remove from server object
|
||||||
#[cfg_attr(feature = "validator", validate(length(min = 1)))]
|
#[cfg_attr(feature = "serde", serde(default))]
|
||||||
pub remove: Option<Vec<FieldsServer>>,
|
pub remove: Vec<FieldsServer>,
|
||||||
}
|
}
|
||||||
|
|
||||||
/// New role information
|
/// New role information
|
||||||
@@ -267,11 +269,11 @@ auto_derived!(
|
|||||||
pub hoist: Option<bool>,
|
pub hoist: Option<bool>,
|
||||||
/// Ranking position
|
/// Ranking position
|
||||||
///
|
///
|
||||||
/// Smaller values take priority.
|
/// **Removed** - no effect, use the edit server role positions route
|
||||||
pub rank: Option<i64>,
|
pub rank: Option<i64>,
|
||||||
/// Fields to remove from role object
|
/// Fields to remove from role object
|
||||||
#[cfg_attr(feature = "validator", validate(length(min = 1)))]
|
#[cfg_attr(feature = "serde", serde(default))]
|
||||||
pub remove: Option<Vec<FieldsRole>>,
|
pub remove: Vec<FieldsRole>,
|
||||||
}
|
}
|
||||||
|
|
||||||
/// New role permissions
|
/// New role permissions
|
||||||
@@ -286,4 +288,27 @@ auto_derived!(
|
|||||||
/// Whether to not send a leave message
|
/// Whether to not send a leave message
|
||||||
pub leave_silently: Option<bool>,
|
pub leave_silently: Option<bool>,
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// New role positions
|
||||||
|
pub struct DataEditRoleRanks {
|
||||||
|
pub ranks: Vec<String>,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// # Query Parameters
|
||||||
|
#[derive(FromForm)]
|
||||||
|
pub struct OptionsQueryMembers {
|
||||||
|
/// String to search for
|
||||||
|
pub query: String,
|
||||||
|
|
||||||
|
/// Discourage use of this API
|
||||||
|
pub experimental_api: bool,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// # Query members by name
|
||||||
|
pub struct MemberQueryResponse {
|
||||||
|
/// List of members
|
||||||
|
pub members: Vec<Member>,
|
||||||
|
/// List of users
|
||||||
|
pub users: Vec<User>,
|
||||||
|
}
|
||||||
);
|
);
|
||||||
@@ -245,8 +245,8 @@ auto_derived!(
|
|||||||
pub flags: Option<i32>,
|
pub flags: Option<i32>,
|
||||||
|
|
||||||
/// Fields to remove from user object
|
/// Fields to remove from user object
|
||||||
#[cfg_attr(feature = "validator", validate(length(min = 1)))]
|
#[cfg_attr(feature = "serde", serde(default))]
|
||||||
pub remove: Option<Vec<FieldsUser>>,
|
pub remove: Vec<FieldsUser>,
|
||||||
}
|
}
|
||||||
|
|
||||||
/// User flag reponse
|
/// User flag reponse
|
||||||
@@ -275,6 +275,17 @@ auto_derived!(
|
|||||||
/// Username and discriminator combo separated by #
|
/// Username and discriminator combo separated by #
|
||||||
pub username: String,
|
pub username: String,
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// # Username Information
|
||||||
|
#[derive(Validate)]
|
||||||
|
pub struct DataChangeUsername {
|
||||||
|
/// New username
|
||||||
|
#[validate(length(min = 2, max = 32), regex = "super::RE_USERNAME")]
|
||||||
|
pub username: String,
|
||||||
|
/// Current account password
|
||||||
|
#[validate(length(min = 8, max = 1024))]
|
||||||
|
pub password: String,
|
||||||
|
}
|
||||||
);
|
);
|
||||||
|
|
||||||
pub trait CheckRelationship {
|
pub trait CheckRelationship {
|
||||||
|
|||||||
@@ -1,6 +1,6 @@
|
|||||||
[package]
|
[package]
|
||||||
name = "revolt-parser"
|
name = "revolt-parser"
|
||||||
version = "0.8.6"
|
version = "0.8.8"
|
||||||
edition = "2021"
|
edition = "2021"
|
||||||
license = "AGPL-3.0-or-later"
|
license = "AGPL-3.0-or-later"
|
||||||
description = "Revolt Backend: Message Parser"
|
description = "Revolt Backend: Message Parser"
|
||||||
|
|||||||
@@ -1,6 +1,6 @@
|
|||||||
[package]
|
[package]
|
||||||
name = "revolt-permissions"
|
name = "revolt-permissions"
|
||||||
version = "0.8.6"
|
version = "0.8.8"
|
||||||
edition = "2021"
|
edition = "2021"
|
||||||
license = "MIT"
|
license = "MIT"
|
||||||
authors = ["Paul Makles <me@insrt.uk>"]
|
authors = ["Paul Makles <me@insrt.uk>"]
|
||||||
@@ -21,7 +21,7 @@ async-std = { version = "1.8.0", features = ["attributes"] }
|
|||||||
|
|
||||||
[dependencies]
|
[dependencies]
|
||||||
# Core
|
# Core
|
||||||
revolt-result = { version = "0.8.6", path = "../result" }
|
revolt-result = { version = "0.8.8", path = "../result" }
|
||||||
|
|
||||||
# Utility
|
# Utility
|
||||||
auto_ops = "0.3.0"
|
auto_ops = "0.3.0"
|
||||||
|
|||||||
@@ -1,6 +1,6 @@
|
|||||||
[package]
|
[package]
|
||||||
name = "revolt-presence"
|
name = "revolt-presence"
|
||||||
version = "0.8.6"
|
version = "0.8.8"
|
||||||
edition = "2021"
|
edition = "2021"
|
||||||
license = "AGPL-3.0-or-later"
|
license = "AGPL-3.0-or-later"
|
||||||
authors = ["Paul Makles <me@insrt.uk>"]
|
authors = ["Paul Makles <me@insrt.uk>"]
|
||||||
@@ -15,6 +15,9 @@ redis-is-patched = []
|
|||||||
# Async
|
# Async
|
||||||
async-std = { version = "1.8.0", features = ["attributes"] }
|
async-std = { version = "1.8.0", features = ["attributes"] }
|
||||||
|
|
||||||
|
# Config for loading Redis URI
|
||||||
|
revolt-config = { version = "0.8.8", path = "../config" }
|
||||||
|
|
||||||
[dependencies]
|
[dependencies]
|
||||||
# Utility
|
# Utility
|
||||||
log = "0.4.17"
|
log = "0.4.17"
|
||||||
|
|||||||
@@ -197,6 +197,8 @@ mod tests {
|
|||||||
|
|
||||||
#[async_std::test]
|
#[async_std::test]
|
||||||
async fn it_works() {
|
async fn it_works() {
|
||||||
|
revolt_config::config().await;
|
||||||
|
|
||||||
// Clear the region before we start the tests:
|
// Clear the region before we start the tests:
|
||||||
clear_region(None).await;
|
clear_region(None).await;
|
||||||
|
|
||||||
|
|||||||
@@ -1,6 +1,6 @@
|
|||||||
[package]
|
[package]
|
||||||
name = "revolt-result"
|
name = "revolt-result"
|
||||||
version = "0.8.6"
|
version = "0.8.8"
|
||||||
edition = "2021"
|
edition = "2021"
|
||||||
license = "MIT"
|
license = "MIT"
|
||||||
authors = ["Paul Makles <me@insrt.uk>"]
|
authors = ["Paul Makles <me@insrt.uk>"]
|
||||||
@@ -15,6 +15,7 @@ utoipa = ["dep:utoipa"]
|
|||||||
rocket = ["dep:rocket", "dep:serde_json"]
|
rocket = ["dep:rocket", "dep:serde_json"]
|
||||||
axum = ["dep:axum", "dep:serde_json"]
|
axum = ["dep:axum", "dep:serde_json"]
|
||||||
okapi = ["dep:revolt_rocket_okapi", "dep:revolt_okapi", "schemas"]
|
okapi = ["dep:revolt_rocket_okapi", "dep:revolt_okapi", "schemas"]
|
||||||
|
sentry = ["dep:sentry"]
|
||||||
|
|
||||||
default = ["serde"]
|
default = ["serde"]
|
||||||
|
|
||||||
@@ -34,3 +35,6 @@ revolt_okapi = { version = "0.9.1", optional = true }
|
|||||||
|
|
||||||
# Axum
|
# Axum
|
||||||
axum = { version = "0.7.5", optional = true }
|
axum = { version = "0.7.5", optional = true }
|
||||||
|
|
||||||
|
# Sentry
|
||||||
|
sentry = { version = "0.31.5", optional = true }
|
||||||
@@ -2,10 +2,9 @@ use axum::{http::StatusCode, response::IntoResponse, Json};
|
|||||||
|
|
||||||
use crate::{Error, ErrorType};
|
use crate::{Error, ErrorType};
|
||||||
|
|
||||||
/// HTTP response builder for Error enum
|
impl Error {
|
||||||
impl IntoResponse for Error {
|
pub fn axum_status(&self) -> StatusCode {
|
||||||
fn into_response(self) -> axum::response::Response {
|
match self.error_type {
|
||||||
let status = match self.error_type {
|
|
||||||
ErrorType::LabelMe => StatusCode::INTERNAL_SERVER_ERROR,
|
ErrorType::LabelMe => StatusCode::INTERNAL_SERVER_ERROR,
|
||||||
|
|
||||||
ErrorType::AlreadyOnboarded => StatusCode::FORBIDDEN,
|
ErrorType::AlreadyOnboarded => StatusCode::FORBIDDEN,
|
||||||
@@ -70,11 +69,15 @@ impl IntoResponse for Error {
|
|||||||
ErrorType::InvalidProperty => StatusCode::BAD_REQUEST,
|
ErrorType::InvalidProperty => StatusCode::BAD_REQUEST,
|
||||||
ErrorType::InvalidSession => StatusCode::UNAUTHORIZED,
|
ErrorType::InvalidSession => StatusCode::UNAUTHORIZED,
|
||||||
ErrorType::NotAuthenticated => StatusCode::UNAUTHORIZED,
|
ErrorType::NotAuthenticated => StatusCode::UNAUTHORIZED,
|
||||||
|
ErrorType::Conflict => StatusCode::CONFLICT,
|
||||||
ErrorType::DuplicateNonce => StatusCode::CONFLICT,
|
ErrorType::DuplicateNonce => StatusCode::CONFLICT,
|
||||||
ErrorType::VosoUnavailable => StatusCode::BAD_REQUEST,
|
ErrorType::VosoUnavailable => StatusCode::BAD_REQUEST,
|
||||||
ErrorType::NotFound => StatusCode::NOT_FOUND,
|
ErrorType::NotFound => StatusCode::NOT_FOUND,
|
||||||
ErrorType::NoEffect => StatusCode::OK,
|
ErrorType::NoEffect => StatusCode::OK,
|
||||||
ErrorType::FailedValidation { .. } => StatusCode::BAD_REQUEST,
|
ErrorType::IOError => StatusCode::BAD_REQUEST,
|
||||||
|
ErrorType::UnprocessableEntity => StatusCode::UNPROCESSABLE_ENTITY,
|
||||||
|
ErrorType::DeserializationError { .. } => StatusCode::UNPROCESSABLE_ENTITY,
|
||||||
|
ErrorType::FailedValidation { .. } => StatusCode::UNPROCESSABLE_ENTITY,
|
||||||
ErrorType::InvalidFlagValue => StatusCode::BAD_REQUEST,
|
ErrorType::InvalidFlagValue => StatusCode::BAD_REQUEST,
|
||||||
ErrorType::FeatureDisabled { .. } => StatusCode::BAD_REQUEST,
|
ErrorType::FeatureDisabled { .. } => StatusCode::BAD_REQUEST,
|
||||||
|
|
||||||
@@ -84,8 +87,13 @@ impl IntoResponse for Error {
|
|||||||
ErrorType::FileTypeNotAllowed => StatusCode::BAD_REQUEST,
|
ErrorType::FileTypeNotAllowed => StatusCode::BAD_REQUEST,
|
||||||
ErrorType::ImageProcessingFailed => StatusCode::INTERNAL_SERVER_ERROR,
|
ErrorType::ImageProcessingFailed => StatusCode::INTERNAL_SERVER_ERROR,
|
||||||
ErrorType::NoEmbedData => StatusCode::BAD_REQUEST,
|
ErrorType::NoEmbedData => StatusCode::BAD_REQUEST,
|
||||||
};
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
(status, Json(&self)).into_response()
|
/// HTTP response builder for Error enum
|
||||||
|
impl IntoResponse for Error {
|
||||||
|
fn into_response(self) -> axum::response::Response {
|
||||||
|
(self.axum_status(), Json(&self)).into_response()
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -1,3 +1,4 @@
|
|||||||
|
use std::panic::Location;
|
||||||
use std::fmt::Display;
|
use std::fmt::Display;
|
||||||
|
|
||||||
#[cfg(feature = "serde")]
|
#[cfg(feature = "serde")]
|
||||||
@@ -151,9 +152,15 @@ pub enum ErrorType {
|
|||||||
InvalidSession,
|
InvalidSession,
|
||||||
InvalidFlagValue,
|
InvalidFlagValue,
|
||||||
NotAuthenticated,
|
NotAuthenticated,
|
||||||
|
Conflict,
|
||||||
DuplicateNonce,
|
DuplicateNonce,
|
||||||
NotFound,
|
NotFound,
|
||||||
NoEffect,
|
NoEffect,
|
||||||
|
IOError,
|
||||||
|
UnprocessableEntity,
|
||||||
|
DeserializationError {
|
||||||
|
error: String,
|
||||||
|
},
|
||||||
FailedValidation {
|
FailedValidation {
|
||||||
error: String,
|
error: String,
|
||||||
},
|
},
|
||||||
@@ -174,7 +181,7 @@ pub enum ErrorType {
|
|||||||
// ? Feature flag disabled in the config
|
// ? Feature flag disabled in the config
|
||||||
FeatureDisabled {
|
FeatureDisabled {
|
||||||
feature: String,
|
feature: String,
|
||||||
},
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
#[macro_export]
|
#[macro_export]
|
||||||
@@ -197,6 +204,62 @@ macro_rules! create_database_error {
|
|||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
|
pub trait ToRevoltError<T>: Sized {
|
||||||
|
fn capture_error(self) -> Self;
|
||||||
|
|
||||||
|
#[track_caller]
|
||||||
|
fn to_internal_error(self) -> Result<T, Error>;
|
||||||
|
}
|
||||||
|
|
||||||
|
impl<T, E: std::error::Error> ToRevoltError<T> for Result<T, E> {
|
||||||
|
fn capture_error(self) -> Self {
|
||||||
|
|
||||||
|
#[allow(unused_variables)]
|
||||||
|
self.inspect_err(|e| {
|
||||||
|
#[cfg(feature = "sentry")]
|
||||||
|
sentry::capture_error(e);
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
#[track_caller]
|
||||||
|
fn to_internal_error(self) -> Result<T, Error> {
|
||||||
|
let loc = Location::caller();
|
||||||
|
|
||||||
|
self
|
||||||
|
.capture_error()
|
||||||
|
.map_err(|_| {
|
||||||
|
Error {
|
||||||
|
error_type: ErrorType::InternalError,
|
||||||
|
location: format!("{}:{}:{}", loc.file(), loc.line(), loc.column())
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl<T: std::error::Error> ToRevoltError<T> for Option<T> {
|
||||||
|
fn capture_error(self) -> Self {
|
||||||
|
#[allow(unused_variables)]
|
||||||
|
self.inspect(|e| {
|
||||||
|
#[cfg(feature = "sentry")]
|
||||||
|
sentry::capture_error(e);
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
#[track_caller]
|
||||||
|
fn to_internal_error(self) -> Result<T, Error> {
|
||||||
|
let loc = Location::caller();
|
||||||
|
|
||||||
|
self
|
||||||
|
.capture_error()
|
||||||
|
.ok_or_else(|| {
|
||||||
|
Error {
|
||||||
|
error_type: ErrorType::InternalError,
|
||||||
|
location: format!("{}:{}:{}", loc.file(), loc.line(), loc.column())
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
#[cfg(test)]
|
#[cfg(test)]
|
||||||
mod tests {
|
mod tests {
|
||||||
use crate::ErrorType;
|
use crate::ErrorType;
|
||||||
|
|||||||
@@ -8,10 +8,9 @@ use rocket::{
|
|||||||
|
|
||||||
use crate::{Error, ErrorType};
|
use crate::{Error, ErrorType};
|
||||||
|
|
||||||
/// HTTP response builder for Error enum
|
impl Error {
|
||||||
impl<'r> Responder<'r, 'static> for Error {
|
pub fn rocket_status(&self) -> Status {
|
||||||
fn respond_to(self, _: &'r Request<'_>) -> response::Result<'static> {
|
match self.error_type {
|
||||||
let status = match self.error_type {
|
|
||||||
ErrorType::LabelMe => Status::InternalServerError,
|
ErrorType::LabelMe => Status::InternalServerError,
|
||||||
|
|
||||||
ErrorType::AlreadyOnboarded => Status::Forbidden,
|
ErrorType::AlreadyOnboarded => Status::Forbidden,
|
||||||
@@ -77,11 +76,15 @@ impl<'r> Responder<'r, 'static> for Error {
|
|||||||
ErrorType::InvalidProperty => Status::BadRequest,
|
ErrorType::InvalidProperty => Status::BadRequest,
|
||||||
ErrorType::InvalidSession => Status::Unauthorized,
|
ErrorType::InvalidSession => Status::Unauthorized,
|
||||||
ErrorType::NotAuthenticated => Status::Unauthorized,
|
ErrorType::NotAuthenticated => Status::Unauthorized,
|
||||||
|
ErrorType::Conflict => Status::Conflict,
|
||||||
ErrorType::DuplicateNonce => Status::Conflict,
|
ErrorType::DuplicateNonce => Status::Conflict,
|
||||||
ErrorType::VosoUnavailable => Status::BadRequest,
|
ErrorType::VosoUnavailable => Status::BadRequest,
|
||||||
ErrorType::NotFound => Status::NotFound,
|
ErrorType::NotFound => Status::NotFound,
|
||||||
ErrorType::NoEffect => Status::Ok,
|
ErrorType::NoEffect => Status::Ok,
|
||||||
ErrorType::FailedValidation { .. } => Status::BadRequest,
|
ErrorType::IOError => Status::BadRequest,
|
||||||
|
ErrorType::UnprocessableEntity => Status::UnprocessableEntity,
|
||||||
|
ErrorType::DeserializationError { .. } => Status::UnprocessableEntity,
|
||||||
|
ErrorType::FailedValidation { .. } => Status::UnprocessableEntity,
|
||||||
ErrorType::FeatureDisabled { .. } => Status::BadRequest,
|
ErrorType::FeatureDisabled { .. } => Status::BadRequest,
|
||||||
|
|
||||||
ErrorType::ProxyError => Status::BadRequest,
|
ErrorType::ProxyError => Status::BadRequest,
|
||||||
@@ -90,8 +93,13 @@ impl<'r> Responder<'r, 'static> for Error {
|
|||||||
ErrorType::FileTypeNotAllowed => Status::BadRequest,
|
ErrorType::FileTypeNotAllowed => Status::BadRequest,
|
||||||
ErrorType::ImageProcessingFailed => Status::InternalServerError,
|
ErrorType::ImageProcessingFailed => Status::InternalServerError,
|
||||||
ErrorType::NoEmbedData => Status::BadRequest,
|
ErrorType::NoEmbedData => Status::BadRequest,
|
||||||
};
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// HTTP response builder for Error enum
|
||||||
|
impl<'r> Responder<'r, 'static> for Error {
|
||||||
|
fn respond_to(self, _: &'r Request<'_>) -> response::Result<'static> {
|
||||||
// Serialize the error data structure into JSON.
|
// Serialize the error data structure into JSON.
|
||||||
let string = serde_json::to_string(&self).unwrap();
|
let string = serde_json::to_string(&self).unwrap();
|
||||||
|
|
||||||
@@ -99,7 +107,7 @@ impl<'r> Responder<'r, 'static> for Error {
|
|||||||
Response::build()
|
Response::build()
|
||||||
.sized_body(string.len(), Cursor::new(string))
|
.sized_body(string.len(), Cursor::new(string))
|
||||||
.header(ContentType::new("application", "json"))
|
.header(ContentType::new("application", "json"))
|
||||||
.status(status)
|
.status(self.rocket_status())
|
||||||
.ok()
|
.ok()
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -1,6 +1,6 @@
|
|||||||
[package]
|
[package]
|
||||||
name = "revolt-crond"
|
name = "revolt-crond"
|
||||||
version = "0.8.6"
|
version = "0.8.8"
|
||||||
license = "AGPL-3.0-or-later"
|
license = "AGPL-3.0-or-later"
|
||||||
authors = ["Paul Makles <me@insrt.uk>"]
|
authors = ["Paul Makles <me@insrt.uk>"]
|
||||||
edition = "2021"
|
edition = "2021"
|
||||||
@@ -16,7 +16,7 @@ log = "0.4"
|
|||||||
tokio = { version = "1" }
|
tokio = { version = "1" }
|
||||||
|
|
||||||
# Core
|
# Core
|
||||||
revolt-database = { version = "0.8.6", path = "../../core/database" }
|
revolt-database = { version = "0.8.8", path = "../../core/database" }
|
||||||
revolt-result = { version = "0.8.6", path = "../../core/result" }
|
revolt-result = { version = "0.8.8", path = "../../core/result" }
|
||||||
revolt-config = { version = "0.8.6", path = "../../core/config" }
|
revolt-config = { version = "0.8.8", path = "../../core/config" }
|
||||||
revolt-files = { version = "0.8.6", path = "../../core/files" }
|
revolt-files = { version = "0.8.8", path = "../../core/files" }
|
||||||
@@ -1,19 +1,32 @@
|
|||||||
use revolt_config::configure;
|
use std::{future::Future, time::Duration};
|
||||||
use revolt_database::DatabaseInfo;
|
|
||||||
|
use revolt_config::{configure, capture_error};
|
||||||
|
use revolt_database::{Database, DatabaseInfo};
|
||||||
use revolt_result::Result;
|
use revolt_result::Result;
|
||||||
use tasks::{file_deletion, prune_dangling_files};
|
use tasks::{file_deletion, prune_dangling_files};
|
||||||
use tokio::try_join;
|
use tokio::{join, time::sleep};
|
||||||
|
|
||||||
pub mod tasks;
|
pub mod tasks;
|
||||||
|
|
||||||
|
pub async fn cron_task_wrapper<Fut: Future<Output = Result<()>>>(func: fn(Database) -> Fut, db: Database) {
|
||||||
|
loop {
|
||||||
|
if let Err(error) = func(db.clone()).await {
|
||||||
|
log::error!("cron task failed unexpectidly: {error:?}\nRetrying after 60s");
|
||||||
|
capture_error(&error);
|
||||||
|
}
|
||||||
|
|
||||||
|
sleep(Duration::from_secs(60)).await;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
#[tokio::main]
|
#[tokio::main]
|
||||||
async fn main() -> Result<()> {
|
async fn main() {
|
||||||
configure!(crond);
|
configure!(crond);
|
||||||
|
|
||||||
let db = DatabaseInfo::Auto.connect().await.expect("database");
|
let db = DatabaseInfo::Auto.connect().await.expect("database");
|
||||||
try_join!(
|
|
||||||
file_deletion::task(db.clone()),
|
join!(
|
||||||
prune_dangling_files::task(db)
|
cron_task_wrapper(file_deletion::task, db.clone()),
|
||||||
)
|
cron_task_wrapper(prune_dangling_files::task, db.clone()),
|
||||||
.map(|_| ())
|
);
|
||||||
}
|
}
|
||||||
@@ -1,19 +1,20 @@
|
|||||||
[package]
|
[package]
|
||||||
name = "revolt-pushd"
|
name = "revolt-pushd"
|
||||||
version = "0.8.6"
|
version = "0.8.8"
|
||||||
edition = "2021"
|
edition = "2021"
|
||||||
license = "AGPL-3.0-or-later"
|
license = "AGPL-3.0-or-later"
|
||||||
|
|
||||||
[dependencies]
|
[dependencies]
|
||||||
revolt-result = { version = "0.8.6", path = "../../core/result" }
|
revolt-result = { version = "0.8.8", path = "../../core/result" }
|
||||||
revolt-config = { version = "0.8.6", path = "../../core/config", features = [
|
revolt-config = { version = "0.8.8", path = "../../core/config", features = [
|
||||||
"report-macros",
|
"report-macros",
|
||||||
|
"anyhow"
|
||||||
] }
|
] }
|
||||||
revolt-database = { version = "0.8.6", path = "../../core/database" }
|
revolt-database = { version = "0.8.8", path = "../../core/database" }
|
||||||
revolt-models = { version = "0.8.6", path = "../../core/models", features = [
|
revolt-models = { version = "0.8.8", path = "../../core/models", features = [
|
||||||
"validator",
|
"validator",
|
||||||
] }
|
] }
|
||||||
revolt-presence = { version = "0.8.6", path = "../../core/presence", features = [
|
revolt-presence = { version = "0.8.8", path = "../../core/presence", features = [
|
||||||
"redis-is-patched",
|
"redis-is-patched",
|
||||||
] }
|
] }
|
||||||
|
|
||||||
|
|||||||
@@ -123,24 +123,26 @@ impl AsyncConsumer for AckConsumer {
|
|||||||
token: session.subscription.as_ref().unwrap().auth.clone(),
|
token: session.subscription.as_ref().unwrap().auth.clone(),
|
||||||
extras: Default::default(),
|
extras: Default::default(),
|
||||||
};
|
};
|
||||||
let raw_service_payload = serde_json::to_string(&service_payload);
|
|
||||||
|
|
||||||
if let Ok(p) = raw_service_payload {
|
match serde_json::to_string(&service_payload) {
|
||||||
let args = BasicPublishArguments::new(
|
Ok(p) => {
|
||||||
config.pushd.exchange.as_str(),
|
let args = BasicPublishArguments::new(
|
||||||
config.pushd.apn.queue.as_str(),
|
config.pushd.exchange.as_str(),
|
||||||
)
|
config.pushd.apn.queue.as_str(),
|
||||||
.finish();
|
)
|
||||||
|
.finish();
|
||||||
|
|
||||||
log::debug!(
|
log::debug!(
|
||||||
"Publishing ack to apn session {}",
|
"Publishing ack to apn session {}",
|
||||||
session.subscription.as_ref().unwrap().auth
|
session.subscription.as_ref().unwrap().auth
|
||||||
);
|
);
|
||||||
|
|
||||||
publish_message(self, p.into(), args).await;
|
publish_message(self, p.into(), args).await;
|
||||||
} else {
|
},
|
||||||
log::warn!("Failed to serialize ack badge update payload!");
|
Err(e) => {
|
||||||
revolt_config::capture_error(&raw_service_payload.unwrap_err());
|
log::warn!("Failed to serialize ack badge update payload!");
|
||||||
|
revolt_config::capture_error(&e);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,6 +1,6 @@
|
|||||||
[package]
|
[package]
|
||||||
name = "revolt-delta"
|
name = "revolt-delta"
|
||||||
version = "0.8.6"
|
version = "0.8.8"
|
||||||
license = "AGPL-3.0-or-later"
|
license = "AGPL-3.0-or-later"
|
||||||
authors = ["Paul Makles <paulmakles@gmail.com>"]
|
authors = ["Paul Makles <paulmakles@gmail.com>"]
|
||||||
edition = "2018"
|
edition = "2018"
|
||||||
@@ -79,7 +79,7 @@ revolt-models = { path = "../core/models", features = [
|
|||||||
"rocket",
|
"rocket",
|
||||||
] }
|
] }
|
||||||
revolt-presence = { path = "../core/presence" }
|
revolt-presence = { path = "../core/presence" }
|
||||||
revolt-result = { path = "../core/result", features = ["rocket", "okapi"] }
|
revolt-result = { path = "../core/result", features = ["rocket", "okapi", "sentry"] }
|
||||||
revolt-permissions = { path = "../core/permissions", features = ["schemas"] }
|
revolt-permissions = { path = "../core/permissions", features = ["schemas"] }
|
||||||
|
|
||||||
[build-dependencies]
|
[build-dependencies]
|
||||||
|
|||||||
@@ -0,0 +1,114 @@
|
|||||||
|
[
|
||||||
|
{
|
||||||
|
"_object_type": "User",
|
||||||
|
"_id": "__ID:0__",
|
||||||
|
"username": "Owner",
|
||||||
|
"last_acknowledged_policy_change": "2025-06-07T04:04:48+0000",
|
||||||
|
"discriminator": "0001"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"_object_type": "User",
|
||||||
|
"_id": "__ID:1__",
|
||||||
|
"username": "Moderator",
|
||||||
|
"last_acknowledged_policy_change": "2025-06-07T04:04:48+0000",
|
||||||
|
"discriminator": "0001"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"_object_type": "User",
|
||||||
|
"_id": "__ID:2__",
|
||||||
|
"username": "User",
|
||||||
|
"last_acknowledged_policy_change": "2025-06-07T04:04:48+0000",
|
||||||
|
"discriminator": "0001"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"_object_type": "Channel",
|
||||||
|
"_id": "__ID:3__",
|
||||||
|
"channel_type": "TextChannel",
|
||||||
|
"name": "General",
|
||||||
|
"server": "__ID:4__",
|
||||||
|
"default_permissions": {
|
||||||
|
"a": 0,
|
||||||
|
"d": 1048576
|
||||||
|
},
|
||||||
|
"role_permissions": {
|
||||||
|
"__ID:5__": {
|
||||||
|
"a": 1048576,
|
||||||
|
"d": 0
|
||||||
|
}
|
||||||
|
}
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"_object_type": "Server",
|
||||||
|
"_id": "__ID:4__",
|
||||||
|
"owner": "__ID:0__",
|
||||||
|
"name": "Server",
|
||||||
|
"channels": [
|
||||||
|
"__ID:3__"
|
||||||
|
],
|
||||||
|
"roles": {
|
||||||
|
"__ID:5__": {
|
||||||
|
"name": "Moderator",
|
||||||
|
"permissions": {
|
||||||
|
"a": 545270216,
|
||||||
|
"d": 0
|
||||||
|
},
|
||||||
|
"rank": 1
|
||||||
|
},
|
||||||
|
"__ID:6__": {
|
||||||
|
"name": "Owner",
|
||||||
|
"permissions": {
|
||||||
|
"a": 0,
|
||||||
|
"d": 0
|
||||||
|
},
|
||||||
|
"rank": 0
|
||||||
|
},
|
||||||
|
"__ID:7__": {
|
||||||
|
"name": "Lower Rank 1",
|
||||||
|
"permissions": {
|
||||||
|
"a": 0,
|
||||||
|
"d": 0
|
||||||
|
},
|
||||||
|
"rank": 2
|
||||||
|
},
|
||||||
|
"__ID:8__": {
|
||||||
|
"name": "Lower Rank 2",
|
||||||
|
"permissions": {
|
||||||
|
"a": 0,
|
||||||
|
"d": 0
|
||||||
|
},
|
||||||
|
"rank": 2
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"default_permissions": 4000322560
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"_object_type": "ServerMember",
|
||||||
|
"_id": {
|
||||||
|
"user": "__ID:0__",
|
||||||
|
"server": "__ID:4__"
|
||||||
|
},
|
||||||
|
"roles": [
|
||||||
|
"__ID:6__"
|
||||||
|
],
|
||||||
|
"joined_at": 1698318340195
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"_object_type": "ServerMember",
|
||||||
|
"_id": {
|
||||||
|
"user": "__ID:1__",
|
||||||
|
"server": "__ID:4__"
|
||||||
|
},
|
||||||
|
"roles": [
|
||||||
|
"__ID:5__"
|
||||||
|
],
|
||||||
|
"joined_at": 1698318340195
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"_object_type": "ServerMember",
|
||||||
|
"_id": {
|
||||||
|
"user": "__ID:2__",
|
||||||
|
"server": "__ID:4__"
|
||||||
|
},
|
||||||
|
"joined_at": 1698318340195
|
||||||
|
}
|
||||||
|
]
|
||||||
@@ -135,6 +135,7 @@ pub async fn web() -> Rocket<Build> {
|
|||||||
.manage(cors.clone())
|
.manage(cors.clone())
|
||||||
.attach(util::ratelimiter::RatelimitFairing)
|
.attach(util::ratelimiter::RatelimitFairing)
|
||||||
.attach(cors)
|
.attach(cors)
|
||||||
|
.register("/", util::catchers::all_catchers())
|
||||||
.configure(rocket::Config {
|
.configure(rocket::Config {
|
||||||
limits: rocket::data::Limits::default().limit("string", 5.megabytes()),
|
limits: rocket::data::Limits::default().limit("string", 5.megabytes()),
|
||||||
address: Ipv4Addr::new(0, 0, 0, 0).into(),
|
address: Ipv4Addr::new(0, 0, 0, 0).into(),
|
||||||
|
|||||||
@@ -1,9 +1,8 @@
|
|||||||
|
use crate::util::json::{Json, Validate};
|
||||||
use revolt_database::{Bot, Database, User};
|
use revolt_database::{Bot, Database, User};
|
||||||
use revolt_models::v0;
|
use revolt_models::v0;
|
||||||
use revolt_result::{create_error, Result};
|
use revolt_result::Result;
|
||||||
use rocket::serde::json::Json;
|
|
||||||
use rocket::State;
|
use rocket::State;
|
||||||
use validator::Validate;
|
|
||||||
|
|
||||||
/// # Create Bot
|
/// # Create Bot
|
||||||
///
|
///
|
||||||
@@ -13,14 +12,9 @@ use validator::Validate;
|
|||||||
pub async fn create_bot(
|
pub async fn create_bot(
|
||||||
db: &State<Database>,
|
db: &State<Database>,
|
||||||
user: User,
|
user: User,
|
||||||
info: Json<v0::DataCreateBot>,
|
info: Validate<Json<v0::DataCreateBot>>,
|
||||||
) -> Result<Json<v0::BotWithUserResponse>> {
|
) -> Result<Json<v0::BotWithUserResponse>> {
|
||||||
let info = info.into_inner();
|
let info = info.into_inner().into_inner();
|
||||||
info.validate().map_err(|error| {
|
|
||||||
create_error!(FailedValidation {
|
|
||||||
error: error.to_string()
|
|
||||||
})
|
|
||||||
})?;
|
|
||||||
|
|
||||||
let (bot, user) = Bot::create(db, info.name, &user, None).await?;
|
let (bot, user) = Bot::create(db, info.name, &user, None).await?;
|
||||||
Ok(Json(v0::BotWithUserResponse {
|
Ok(Json(v0::BotWithUserResponse {
|
||||||
|
|||||||
@@ -11,7 +11,7 @@ use rocket_empty::EmptyResponse;
|
|||||||
pub async fn delete_bot(
|
pub async fn delete_bot(
|
||||||
db: &State<Database>,
|
db: &State<Database>,
|
||||||
user: User,
|
user: User,
|
||||||
target: Reference,
|
target: Reference<'_>,
|
||||||
) -> Result<EmptyResponse> {
|
) -> Result<EmptyResponse> {
|
||||||
let bot = target.as_bot(db).await?;
|
let bot = target.as_bot(db).await?;
|
||||||
if bot.owner != user.id {
|
if bot.owner != user.id {
|
||||||
|
|||||||
@@ -3,8 +3,7 @@ use revolt_models::v0::{self, DataEditBot};
|
|||||||
use revolt_result::{create_error, Result};
|
use revolt_result::{create_error, Result};
|
||||||
use rocket::State;
|
use rocket::State;
|
||||||
|
|
||||||
use rocket::serde::json::Json;
|
use crate::util::json::{Json, Validate};
|
||||||
use validator::Validate;
|
|
||||||
|
|
||||||
/// # Edit Bot
|
/// # Edit Bot
|
||||||
///
|
///
|
||||||
@@ -14,15 +13,10 @@ use validator::Validate;
|
|||||||
pub async fn edit_bot(
|
pub async fn edit_bot(
|
||||||
db: &State<Database>,
|
db: &State<Database>,
|
||||||
user: User,
|
user: User,
|
||||||
target: Reference,
|
target: Reference<'_>,
|
||||||
data: Json<DataEditBot>,
|
data: Validate<Json<DataEditBot>>,
|
||||||
) -> Result<Json<v0::BotWithUserResponse>> {
|
) -> Result<Json<v0::BotWithUserResponse>> {
|
||||||
let data = data.into_inner();
|
let data = data.into_inner().into_inner();
|
||||||
data.validate().map_err(|error| {
|
|
||||||
create_error!(FailedValidation {
|
|
||||||
error: error.to_string()
|
|
||||||
})
|
|
||||||
})?;
|
|
||||||
|
|
||||||
let mut bot = target.as_bot(db).await?;
|
let mut bot = target.as_bot(db).await?;
|
||||||
if bot.owner != user.id {
|
if bot.owner != user.id {
|
||||||
@@ -37,7 +31,7 @@ pub async fn edit_bot(
|
|||||||
if data.public.is_none()
|
if data.public.is_none()
|
||||||
&& data.analytics.is_none()
|
&& data.analytics.is_none()
|
||||||
&& data.interactions_url.is_none()
|
&& data.interactions_url.is_none()
|
||||||
&& data.remove.is_none()
|
&& data.remove.is_empty()
|
||||||
{
|
{
|
||||||
return Ok(Json(v0::BotWithUserResponse {
|
return Ok(Json(v0::BotWithUserResponse {
|
||||||
bot: bot.into(),
|
bot: bot.into(),
|
||||||
@@ -64,7 +58,6 @@ pub async fn edit_bot(
|
|||||||
db,
|
db,
|
||||||
partial,
|
partial,
|
||||||
remove
|
remove
|
||||||
.unwrap_or_default()
|
|
||||||
.into_iter()
|
.into_iter()
|
||||||
.map(|v| v.into())
|
.map(|v| v.into())
|
||||||
.collect(),
|
.collect(),
|
||||||
@@ -100,7 +93,7 @@ mod test {
|
|||||||
.body(
|
.body(
|
||||||
json!(v0::DataEditBot {
|
json!(v0::DataEditBot {
|
||||||
public: Some(true),
|
public: Some(true),
|
||||||
remove: Some(vec![FieldsBot::Token]),
|
remove: vec![FieldsBot::Token],
|
||||||
..Default::default()
|
..Default::default()
|
||||||
})
|
})
|
||||||
.to_string(),
|
.to_string(),
|
||||||
|
|||||||
@@ -1,7 +1,8 @@
|
|||||||
use revolt_database::{util::reference::Reference, Database, User};
|
use revolt_database::{util::reference::Reference, Database, User};
|
||||||
use revolt_models::v0::FetchBotResponse;
|
use revolt_models::v0::FetchBotResponse;
|
||||||
use revolt_result::{create_error, Result};
|
use revolt_result::{create_error, Result};
|
||||||
use rocket::{serde::json::Json, State};
|
use rocket::State;
|
||||||
|
use crate::util::json::Json;
|
||||||
|
|
||||||
/// # Fetch Bot
|
/// # Fetch Bot
|
||||||
///
|
///
|
||||||
@@ -11,7 +12,7 @@ use rocket::{serde::json::Json, State};
|
|||||||
pub async fn fetch_bot(
|
pub async fn fetch_bot(
|
||||||
db: &State<Database>,
|
db: &State<Database>,
|
||||||
user: User,
|
user: User,
|
||||||
bot: Reference,
|
bot: Reference<'_>,
|
||||||
) -> Result<Json<FetchBotResponse>> {
|
) -> Result<Json<FetchBotResponse>> {
|
||||||
if user.bot.is_some() {
|
if user.bot.is_some() {
|
||||||
return Err(create_error!(IsBot));
|
return Err(create_error!(IsBot));
|
||||||
|
|||||||
@@ -2,7 +2,7 @@ use futures::future::join_all;
|
|||||||
use revolt_database::{Database, User};
|
use revolt_database::{Database, User};
|
||||||
use revolt_models::v0::OwnedBotsResponse;
|
use revolt_models::v0::OwnedBotsResponse;
|
||||||
use revolt_result::Result;
|
use revolt_result::Result;
|
||||||
use rocket::serde::json::Json;
|
use crate::util::json::Json;
|
||||||
use rocket::State;
|
use rocket::State;
|
||||||
|
|
||||||
/// # Fetch Owned Bots
|
/// # Fetch Owned Bots
|
||||||
|
|||||||
@@ -2,7 +2,7 @@ use revolt_database::{util::reference::Reference, Database, User};
|
|||||||
use revolt_models::v0::PublicBot;
|
use revolt_models::v0::PublicBot;
|
||||||
use revolt_result::{create_error, Result};
|
use revolt_result::{create_error, Result};
|
||||||
|
|
||||||
use rocket::serde::json::Json;
|
use crate::util::json::Json;
|
||||||
use rocket::State;
|
use rocket::State;
|
||||||
|
|
||||||
/// # Fetch Public Bot
|
/// # Fetch Public Bot
|
||||||
@@ -13,10 +13,10 @@ use rocket::State;
|
|||||||
pub async fn fetch_public_bot(
|
pub async fn fetch_public_bot(
|
||||||
db: &State<Database>,
|
db: &State<Database>,
|
||||||
user: Option<User>,
|
user: Option<User>,
|
||||||
target: Reference,
|
target: Reference<'_>,
|
||||||
) -> Result<Json<PublicBot>> {
|
) -> Result<Json<PublicBot>> {
|
||||||
let bot = db.fetch_bot(&target.id).await?;
|
let bot = db.fetch_bot(target.id).await?;
|
||||||
if !bot.public && user.map_or(true, |x| x.id != bot.owner) {
|
if !bot.public && user.is_none_or(|x| x.id != bot.owner) {
|
||||||
return Err(create_error!(NotFound));
|
return Err(create_error!(NotFound));
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -8,7 +8,7 @@ use revolt_permissions::{
|
|||||||
use revolt_result::{create_error, Result};
|
use revolt_result::{create_error, Result};
|
||||||
use rocket::State;
|
use rocket::State;
|
||||||
|
|
||||||
use rocket::serde::json::Json;
|
use crate::util::json::Json;
|
||||||
use rocket_empty::EmptyResponse;
|
use rocket_empty::EmptyResponse;
|
||||||
|
|
||||||
/// # Invite Bot
|
/// # Invite Bot
|
||||||
@@ -20,7 +20,7 @@ pub async fn invite_bot(
|
|||||||
db: &State<Database>,
|
db: &State<Database>,
|
||||||
amqp: &State<AMQP>,
|
amqp: &State<AMQP>,
|
||||||
user: User,
|
user: User,
|
||||||
target: Reference,
|
target: Reference<'_>,
|
||||||
dest: Json<v0::InviteBotDestination>,
|
dest: Json<v0::InviteBotDestination>,
|
||||||
) -> Result<EmptyResponse> {
|
) -> Result<EmptyResponse> {
|
||||||
if user.bot.is_some() {
|
if user.bot.is_some() {
|
||||||
|
|||||||
@@ -15,8 +15,8 @@ use rocket_empty::EmptyResponse;
|
|||||||
pub async fn ack(
|
pub async fn ack(
|
||||||
db: &State<Database>,
|
db: &State<Database>,
|
||||||
user: User,
|
user: User,
|
||||||
target: Reference,
|
target: Reference<'_>,
|
||||||
message: Reference,
|
message: Reference<'_>,
|
||||||
) -> Result<EmptyResponse> {
|
) -> Result<EmptyResponse> {
|
||||||
if user.bot.is_some() {
|
if user.bot.is_some() {
|
||||||
return Err(create_error!(IsBot));
|
return Err(create_error!(IsBot));
|
||||||
@@ -29,7 +29,7 @@ pub async fn ack(
|
|||||||
.throw_if_lacking_channel_permission(ChannelPermission::ViewChannel)?;
|
.throw_if_lacking_channel_permission(ChannelPermission::ViewChannel)?;
|
||||||
|
|
||||||
channel
|
channel
|
||||||
.ack(&user.id, &message.id)
|
.ack(&user.id, message.id)
|
||||||
.await
|
.await
|
||||||
.map(|_| EmptyResponse)
|
.map(|_| EmptyResponse)
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -17,7 +17,7 @@ pub async fn delete(
|
|||||||
db: &State<Database>,
|
db: &State<Database>,
|
||||||
amqp: &State<AMQP>,
|
amqp: &State<AMQP>,
|
||||||
user: User,
|
user: User,
|
||||||
target: Reference,
|
target: Reference<'_>,
|
||||||
options: v0::OptionsChannelDelete,
|
options: v0::OptionsChannelDelete,
|
||||||
) -> Result<EmptyResponse> {
|
) -> Result<EmptyResponse> {
|
||||||
let mut channel = target.as_channel(db).await?;
|
let mut channel = target.as_channel(db).await?;
|
||||||
|
|||||||
@@ -5,8 +5,8 @@ use revolt_database::{
|
|||||||
use revolt_models::v0;
|
use revolt_models::v0;
|
||||||
use revolt_permissions::{calculate_channel_permissions, ChannelPermission};
|
use revolt_permissions::{calculate_channel_permissions, ChannelPermission};
|
||||||
use revolt_result::{create_error, Result};
|
use revolt_result::{create_error, Result};
|
||||||
use rocket::{serde::json::Json, State};
|
use rocket::State;
|
||||||
use validator::Validate;
|
use crate::util::json::{Json, Validate};
|
||||||
|
|
||||||
/// # Edit Channel
|
/// # Edit Channel
|
||||||
///
|
///
|
||||||
@@ -17,15 +17,10 @@ pub async fn edit(
|
|||||||
db: &State<Database>,
|
db: &State<Database>,
|
||||||
amqp: &State<AMQP>,
|
amqp: &State<AMQP>,
|
||||||
user: User,
|
user: User,
|
||||||
target: Reference,
|
target: Reference<'_>,
|
||||||
data: Json<v0::DataEditChannel>,
|
data: Validate<Json<v0::DataEditChannel>>,
|
||||||
) -> Result<Json<v0::Channel>> {
|
) -> Result<Json<v0::Channel>> {
|
||||||
let data = data.into_inner();
|
let data = data.into_inner().into_inner();
|
||||||
data.validate().map_err(|error| {
|
|
||||||
create_error!(FailedValidation {
|
|
||||||
error: error.to_string()
|
|
||||||
})
|
|
||||||
})?;
|
|
||||||
|
|
||||||
let mut channel = target.as_channel(db).await?;
|
let mut channel = target.as_channel(db).await?;
|
||||||
let mut query = DatabasePermissionQuery::new(db, &user).channel(&channel);
|
let mut query = DatabasePermissionQuery::new(db, &user).channel(&channel);
|
||||||
@@ -38,7 +33,7 @@ pub async fn edit(
|
|||||||
&& data.icon.is_none()
|
&& data.icon.is_none()
|
||||||
&& data.nsfw.is_none()
|
&& data.nsfw.is_none()
|
||||||
&& data.owner.is_none()
|
&& data.owner.is_none()
|
||||||
&& data.remove.is_none()
|
&& data.remove.is_empty()
|
||||||
{
|
{
|
||||||
return Ok(Json(channel.into()));
|
return Ok(Json(channel.into()));
|
||||||
}
|
}
|
||||||
@@ -112,23 +107,21 @@ pub async fn edit(
|
|||||||
nsfw,
|
nsfw,
|
||||||
..
|
..
|
||||||
} => {
|
} => {
|
||||||
if let Some(fields) = &data.remove {
|
if data.remove.contains(&v0::FieldsChannel::Icon) {
|
||||||
if fields.contains(&v0::FieldsChannel::Icon) {
|
if let Some(icon) = &icon {
|
||||||
if let Some(icon) = &icon {
|
db.mark_attachment_as_deleted(&icon.id).await?;
|
||||||
db.mark_attachment_as_deleted(&icon.id).await?;
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
}
|
||||||
|
|
||||||
for field in fields {
|
for field in &data.remove {
|
||||||
match field {
|
match field {
|
||||||
v0::FieldsChannel::Description => {
|
v0::FieldsChannel::Description => {
|
||||||
description.take();
|
description.take();
|
||||||
}
|
|
||||||
v0::FieldsChannel::Icon => {
|
|
||||||
icon.take();
|
|
||||||
}
|
|
||||||
_ => {}
|
|
||||||
}
|
}
|
||||||
|
v0::FieldsChannel::Icon => {
|
||||||
|
icon.take();
|
||||||
|
}
|
||||||
|
_ => {}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -214,11 +207,7 @@ pub async fn edit(
|
|||||||
.update(
|
.update(
|
||||||
db,
|
db,
|
||||||
partial,
|
partial,
|
||||||
data.remove
|
data.remove.into_iter().map(|f| f.into()).collect(),
|
||||||
.unwrap_or_default()
|
|
||||||
.into_iter()
|
|
||||||
.map(|f| f.into())
|
|
||||||
.collect(),
|
|
||||||
)
|
)
|
||||||
.await?;
|
.await?;
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -6,7 +6,8 @@ use revolt_database::{
|
|||||||
use revolt_models::v0;
|
use revolt_models::v0;
|
||||||
use revolt_permissions::{calculate_channel_permissions, ChannelPermission};
|
use revolt_permissions::{calculate_channel_permissions, ChannelPermission};
|
||||||
use revolt_result::Result;
|
use revolt_result::Result;
|
||||||
use rocket::{serde::json::Json, State};
|
use rocket::State;
|
||||||
|
use crate::util::json::Json;
|
||||||
|
|
||||||
/// # Fetch Channel
|
/// # Fetch Channel
|
||||||
///
|
///
|
||||||
@@ -16,7 +17,7 @@ use rocket::{serde::json::Json, State};
|
|||||||
pub async fn fetch(
|
pub async fn fetch(
|
||||||
db: &State<Database>,
|
db: &State<Database>,
|
||||||
user: User,
|
user: User,
|
||||||
target: Reference,
|
target: Reference<'_>,
|
||||||
) -> Result<Json<v0::Channel>> {
|
) -> Result<Json<v0::Channel>> {
|
||||||
let channel = target.as_channel(db).await?;
|
let channel = target.as_channel(db).await?;
|
||||||
|
|
||||||
|
|||||||
@@ -17,8 +17,8 @@ pub async fn add_member(
|
|||||||
db: &State<Database>,
|
db: &State<Database>,
|
||||||
amqp: &State<AMQP>,
|
amqp: &State<AMQP>,
|
||||||
user: User,
|
user: User,
|
||||||
group_id: Reference,
|
group_id: Reference<'_>,
|
||||||
member_id: Reference,
|
member_id: Reference<'_>,
|
||||||
) -> Result<EmptyResponse> {
|
) -> Result<EmptyResponse> {
|
||||||
if user.bot.is_some() {
|
if user.bot.is_some() {
|
||||||
return Err(create_error!(IsBot));
|
return Err(create_error!(IsBot));
|
||||||
|
|||||||
@@ -2,9 +2,8 @@ use revolt_database::{Channel, Database, RelationshipStatus, User};
|
|||||||
use revolt_models::v0;
|
use revolt_models::v0;
|
||||||
use revolt_result::{create_error, Result};
|
use revolt_result::{create_error, Result};
|
||||||
|
|
||||||
use rocket::serde::json::Json;
|
use crate::util::json::{Json, Validate};
|
||||||
use rocket::State;
|
use rocket::State;
|
||||||
use validator::Validate;
|
|
||||||
|
|
||||||
/// # Create Group
|
/// # Create Group
|
||||||
///
|
///
|
||||||
@@ -14,18 +13,13 @@ use validator::Validate;
|
|||||||
pub async fn create_group(
|
pub async fn create_group(
|
||||||
db: &State<Database>,
|
db: &State<Database>,
|
||||||
user: User,
|
user: User,
|
||||||
data: Json<v0::DataCreateGroup>,
|
data: Validate<Json<v0::DataCreateGroup>>,
|
||||||
) -> Result<Json<v0::Channel>> {
|
) -> Result<Json<v0::Channel>> {
|
||||||
if user.bot.is_some() {
|
if user.bot.is_some() {
|
||||||
return Err(create_error!(IsBot));
|
return Err(create_error!(IsBot));
|
||||||
}
|
}
|
||||||
|
|
||||||
let data = data.into_inner();
|
let data = data.into_inner().into_inner();
|
||||||
data.validate().map_err(|error| {
|
|
||||||
create_error!(FailedValidation {
|
|
||||||
error: error.to_string()
|
|
||||||
})
|
|
||||||
})?;
|
|
||||||
|
|
||||||
for target in &data.users {
|
for target in &data.users {
|
||||||
match user.relationship_with(target) {
|
match user.relationship_with(target) {
|
||||||
|
|||||||
Loaded 100 of 203 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user