forked from jmug/stoatchat
Compare commits
14
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
9789909061 | ||
|
|
895de86f1e | ||
|
|
98b8c5403b | ||
|
|
aa7c75c60e | ||
|
|
4270f0c5d4 | ||
|
|
eb1f45d208 | ||
|
|
9929f7499a | ||
|
|
279d9ef1b5 | ||
|
|
5a9bb9e68d | ||
|
|
a8fc9e928a | ||
|
|
da231ae390 | ||
|
|
7a31da4189 | ||
|
|
7d0b5392b5 | ||
|
|
1e1d44c0e4 |
No files matched your search
@@ -1,4 +1,6 @@
|
|||||||
Rocket.toml
|
Rocket.toml
|
||||||
|
Revolt.toml
|
||||||
|
|
||||||
target
|
target
|
||||||
.data
|
.data
|
||||||
.env
|
.env
|
||||||
|
|||||||
Generated
+10
-9
@@ -3494,7 +3494,7 @@ dependencies = [
|
|||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "revolt-bonfire"
|
name = "revolt-bonfire"
|
||||||
version = "0.6.7"
|
version = "0.6.8"
|
||||||
dependencies = [
|
dependencies = [
|
||||||
"async-std",
|
"async-std",
|
||||||
"async-tungstenite",
|
"async-tungstenite",
|
||||||
@@ -3512,7 +3512,7 @@ dependencies = [
|
|||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "revolt-config"
|
name = "revolt-config"
|
||||||
version = "0.6.7"
|
version = "0.6.8"
|
||||||
dependencies = [
|
dependencies = [
|
||||||
"async-std",
|
"async-std",
|
||||||
"cached",
|
"cached",
|
||||||
@@ -3524,7 +3524,7 @@ dependencies = [
|
|||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "revolt-database"
|
name = "revolt-database"
|
||||||
version = "0.6.7"
|
version = "0.6.8"
|
||||||
dependencies = [
|
dependencies = [
|
||||||
"async-lock",
|
"async-lock",
|
||||||
"async-recursion",
|
"async-recursion",
|
||||||
@@ -3569,7 +3569,7 @@ dependencies = [
|
|||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "revolt-delta"
|
name = "revolt-delta"
|
||||||
version = "0.6.7"
|
version = "0.6.8"
|
||||||
dependencies = [
|
dependencies = [
|
||||||
"async-channel",
|
"async-channel",
|
||||||
"async-std",
|
"async-std",
|
||||||
@@ -3591,6 +3591,7 @@ dependencies = [
|
|||||||
"redis-kiss",
|
"redis-kiss",
|
||||||
"regex",
|
"regex",
|
||||||
"reqwest",
|
"reqwest",
|
||||||
|
"revolt-config",
|
||||||
"revolt-database",
|
"revolt-database",
|
||||||
"revolt-models",
|
"revolt-models",
|
||||||
"revolt-permissions",
|
"revolt-permissions",
|
||||||
@@ -3613,7 +3614,7 @@ dependencies = [
|
|||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "revolt-models"
|
name = "revolt-models"
|
||||||
version = "0.6.7"
|
version = "0.6.8"
|
||||||
dependencies = [
|
dependencies = [
|
||||||
"indexmap",
|
"indexmap",
|
||||||
"iso8601-timestamp 0.2.11",
|
"iso8601-timestamp 0.2.11",
|
||||||
@@ -3629,7 +3630,7 @@ dependencies = [
|
|||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "revolt-permissions"
|
name = "revolt-permissions"
|
||||||
version = "0.6.7"
|
version = "0.6.8"
|
||||||
dependencies = [
|
dependencies = [
|
||||||
"async-std",
|
"async-std",
|
||||||
"async-trait",
|
"async-trait",
|
||||||
@@ -3644,7 +3645,7 @@ dependencies = [
|
|||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "revolt-presence"
|
name = "revolt-presence"
|
||||||
version = "0.6.7"
|
version = "0.6.8"
|
||||||
dependencies = [
|
dependencies = [
|
||||||
"async-std",
|
"async-std",
|
||||||
"log",
|
"log",
|
||||||
@@ -3655,7 +3656,7 @@ dependencies = [
|
|||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "revolt-quark"
|
name = "revolt-quark"
|
||||||
version = "0.6.7"
|
version = "0.6.8"
|
||||||
dependencies = [
|
dependencies = [
|
||||||
"async-lock",
|
"async-lock",
|
||||||
"async-recursion",
|
"async-recursion",
|
||||||
@@ -3708,7 +3709,7 @@ dependencies = [
|
|||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "revolt-result"
|
name = "revolt-result"
|
||||||
version = "0.6.7"
|
version = "0.6.8"
|
||||||
dependencies = [
|
dependencies = [
|
||||||
"revolt_okapi",
|
"revolt_okapi",
|
||||||
"revolt_rocket_okapi",
|
"revolt_rocket_okapi",
|
||||||
|
|||||||
@@ -20,6 +20,7 @@ COPY Cargo.toml Cargo.lock ./
|
|||||||
COPY crates/bonfire/Cargo.toml ./crates/bonfire/
|
COPY crates/bonfire/Cargo.toml ./crates/bonfire/
|
||||||
COPY crates/delta/Cargo.toml ./crates/delta/
|
COPY crates/delta/Cargo.toml ./crates/delta/
|
||||||
COPY crates/quark/Cargo.toml ./crates/quark/
|
COPY crates/quark/Cargo.toml ./crates/quark/
|
||||||
|
COPY crates/core/config/Cargo.toml ./crates/core/config/
|
||||||
COPY crates/core/database/Cargo.toml ./crates/core/database/
|
COPY crates/core/database/Cargo.toml ./crates/core/database/
|
||||||
COPY crates/core/models/Cargo.toml ./crates/core/models/
|
COPY crates/core/models/Cargo.toml ./crates/core/models/
|
||||||
COPY crates/core/permissions/Cargo.toml ./crates/core/permissions/
|
COPY crates/core/permissions/Cargo.toml ./crates/core/permissions/
|
||||||
|
|||||||
@@ -16,6 +16,7 @@ COPY Cargo.toml Cargo.lock ./
|
|||||||
COPY crates/bonfire/Cargo.toml ./crates/bonfire/
|
COPY crates/bonfire/Cargo.toml ./crates/bonfire/
|
||||||
COPY crates/delta/Cargo.toml ./crates/delta/
|
COPY crates/delta/Cargo.toml ./crates/delta/
|
||||||
COPY crates/quark/Cargo.toml ./crates/quark/
|
COPY crates/quark/Cargo.toml ./crates/quark/
|
||||||
|
COPY crates/core/config/Cargo.toml ./crates/core/config/
|
||||||
COPY crates/core/database/Cargo.toml ./crates/core/database/
|
COPY crates/core/database/Cargo.toml ./crates/core/database/
|
||||||
COPY crates/core/models/Cargo.toml ./crates/core/models/
|
COPY crates/core/models/Cargo.toml ./crates/core/models/
|
||||||
COPY crates/core/permissions/Cargo.toml ./crates/core/permissions/
|
COPY crates/core/permissions/Cargo.toml ./crates/core/permissions/
|
||||||
|
|||||||
@@ -1,6 +1,7 @@
|
|||||||
disallowed-methods = [
|
disallowed-methods = [
|
||||||
# Shouldn't need to access these directly
|
# Shouldn't need to access these directly
|
||||||
"revolt_database::models::bots::model::Bot::remove_field",
|
"revolt_database::models::bots::model::Bot::remove_field",
|
||||||
|
"revolt_database::models::messages::model::Message::attach_sendable_embed",
|
||||||
|
|
||||||
# Prefer to use Object::create()
|
# Prefer to use Object::create()
|
||||||
"revolt_database::models::bots::ops::AbstractBots::insert_bot",
|
"revolt_database::models::bots::ops::AbstractBots::insert_bot",
|
||||||
|
|||||||
@@ -1,6 +1,6 @@
|
|||||||
[package]
|
[package]
|
||||||
name = "revolt-bonfire"
|
name = "revolt-bonfire"
|
||||||
version = "0.6.7"
|
version = "0.6.8"
|
||||||
license = "AGPL-3.0-or-later"
|
license = "AGPL-3.0-or-later"
|
||||||
edition = "2021"
|
edition = "2021"
|
||||||
|
|
||||||
|
|||||||
@@ -1,6 +1,6 @@
|
|||||||
[package]
|
[package]
|
||||||
name = "revolt-config"
|
name = "revolt-config"
|
||||||
version = "0.6.7"
|
version = "0.6.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>"]
|
||||||
|
|||||||
@@ -48,9 +48,11 @@ max_concurrent_connections = 50
|
|||||||
[features.limits.default]
|
[features.limits.default]
|
||||||
group_size = 100
|
group_size = 100
|
||||||
bots = 5
|
bots = 5
|
||||||
|
message_length = 2000
|
||||||
|
message_embeds = 5
|
||||||
message_replies = 5
|
message_replies = 5
|
||||||
message_attachments = 5
|
message_attachments = 5
|
||||||
message_embeds = 5
|
message_reactions = 20
|
||||||
servers = 100
|
servers = 100
|
||||||
server_emoji = 100
|
server_emoji = 100
|
||||||
server_roles = 200
|
server_roles = 200
|
||||||
|
|||||||
@@ -13,8 +13,8 @@ static CONFIG_BUILDER: Lazy<RwLock<Config>> = Lazy::new(|| {
|
|||||||
FileFormat::Toml,
|
FileFormat::Toml,
|
||||||
));
|
));
|
||||||
|
|
||||||
if std::path::Path::new("revolt.toml").exists() {
|
if std::path::Path::new("Revolt.toml").exists() {
|
||||||
builder = builder.add_source(File::new("revolt.toml", FileFormat::Toml));
|
builder = builder.add_source(File::new("Revolt.toml", FileFormat::Toml));
|
||||||
}
|
}
|
||||||
|
|
||||||
builder.build().unwrap()
|
builder.build().unwrap()
|
||||||
@@ -97,9 +97,11 @@ pub struct Api {
|
|||||||
pub struct FeaturesLimits {
|
pub struct FeaturesLimits {
|
||||||
pub group_size: usize,
|
pub group_size: usize,
|
||||||
pub bots: usize,
|
pub bots: usize,
|
||||||
|
pub message_length: usize,
|
||||||
pub message_replies: usize,
|
pub message_replies: usize,
|
||||||
pub message_attachments: usize,
|
pub message_attachments: usize,
|
||||||
pub message_embeds: usize,
|
pub message_embeds: usize,
|
||||||
|
pub message_reactions: usize,
|
||||||
pub servers: usize,
|
pub servers: usize,
|
||||||
pub server_emoji: usize,
|
pub server_emoji: usize,
|
||||||
pub server_roles: usize,
|
pub server_roles: usize,
|
||||||
|
|||||||
@@ -1,6 +1,6 @@
|
|||||||
[package]
|
[package]
|
||||||
name = "revolt-database"
|
name = "revolt-database"
|
||||||
version = "0.6.7"
|
version = "0.6.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>"]
|
||||||
@@ -23,11 +23,11 @@ default = ["mongodb", "async-std-runtime", "tasks"]
|
|||||||
|
|
||||||
[dependencies]
|
[dependencies]
|
||||||
# Core
|
# Core
|
||||||
revolt-config = { version = "0.6.7", path = "../config" }
|
revolt-config = { version = "0.6.8", path = "../config" }
|
||||||
revolt-result = { version = "0.6.7", path = "../result" }
|
revolt-result = { version = "0.6.8", path = "../result" }
|
||||||
revolt-models = { version = "0.6.7", path = "../models" }
|
revolt-models = { version = "0.6.8", path = "../models" }
|
||||||
revolt-presence = { version = "0.6.7", path = "../presence" }
|
revolt-presence = { version = "0.6.8", path = "../presence" }
|
||||||
revolt-permissions = { version = "0.6.7", path = "../permissions", features = [
|
revolt-permissions = { version = "0.6.8", path = "../permissions", features = [
|
||||||
"serde",
|
"serde",
|
||||||
"bson",
|
"bson",
|
||||||
] }
|
] }
|
||||||
|
|||||||
@@ -1,6 +1,6 @@
|
|||||||
use std::collections::HashMap;
|
use std::collections::HashMap;
|
||||||
|
|
||||||
use revolt_models::v0::MessageAuthor;
|
use revolt_models::v0::{self, MessageAuthor};
|
||||||
use revolt_permissions::OverrideField;
|
use revolt_permissions::OverrideField;
|
||||||
use revolt_result::Result;
|
use revolt_result::Result;
|
||||||
use serde::{Deserialize, Serialize};
|
use serde::{Deserialize, Serialize};
|
||||||
@@ -168,7 +168,7 @@ auto_derived!(
|
|||||||
|
|
||||||
#[allow(clippy::disallowed_methods)]
|
#[allow(clippy::disallowed_methods)]
|
||||||
impl Channel {
|
impl Channel {
|
||||||
/// Create a channel
|
/* /// Create a channel
|
||||||
pub async fn create(&self, db: &Database) -> Result<()> {
|
pub async fn create(&self, db: &Database) -> Result<()> {
|
||||||
db.insert_channel(self).await?;
|
db.insert_channel(self).await?;
|
||||||
|
|
||||||
@@ -186,6 +186,39 @@ impl Channel {
|
|||||||
}
|
}
|
||||||
|
|
||||||
Ok(())
|
Ok(())
|
||||||
|
}*/
|
||||||
|
|
||||||
|
/// Create a group
|
||||||
|
pub async fn create_group(
|
||||||
|
db: &Database,
|
||||||
|
data: v0::DataCreateGroup,
|
||||||
|
owner_id: String,
|
||||||
|
) -> Result<Channel> {
|
||||||
|
let recipients = data.users.into_iter().collect::<Vec<String>>();
|
||||||
|
let channel = Channel::Group {
|
||||||
|
id: ulid::Ulid::new().to_string(),
|
||||||
|
|
||||||
|
name: data.name,
|
||||||
|
owner: owner_id,
|
||||||
|
description: data.description,
|
||||||
|
recipients: recipients.clone(),
|
||||||
|
|
||||||
|
icon: None,
|
||||||
|
last_message_id: None,
|
||||||
|
|
||||||
|
permissions: None,
|
||||||
|
|
||||||
|
nsfw: data.nsfw.unwrap_or(false),
|
||||||
|
};
|
||||||
|
|
||||||
|
db.insert_channel(&channel).await?;
|
||||||
|
|
||||||
|
let event = EventV1::ChannelCreate(channel.clone().into());
|
||||||
|
for recipient in recipients {
|
||||||
|
event.clone().private(recipient).await;
|
||||||
|
}
|
||||||
|
|
||||||
|
Ok(channel)
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Add user to a group
|
/// Add user to a group
|
||||||
|
|||||||
@@ -6,7 +6,7 @@ use crate::MongoDb;
|
|||||||
|
|
||||||
use super::AbstractAttachments;
|
use super::AbstractAttachments;
|
||||||
|
|
||||||
static COL: &str = "bots";
|
static COL: &str = "attachments";
|
||||||
|
|
||||||
#[async_trait]
|
#[async_trait]
|
||||||
impl AbstractAttachments for MongoDb {
|
impl AbstractAttachments for MongoDb {
|
||||||
|
|||||||
@@ -1,13 +1,21 @@
|
|||||||
|
use std::collections::HashSet;
|
||||||
|
|
||||||
use indexmap::{IndexMap, IndexSet};
|
use indexmap::{IndexMap, IndexSet};
|
||||||
use iso8601_timestamp::Timestamp;
|
use iso8601_timestamp::Timestamp;
|
||||||
use revolt_models::v0::{Embed, MessageAuthor, MessageSort, MessageWebhook, PushNotification};
|
use revolt_config::config;
|
||||||
|
use revolt_models::v0::{
|
||||||
|
self, DataMessageSend, Embed, MessageAuthor, MessageSort, MessageWebhook, PushNotification,
|
||||||
|
ReplyIntent, SendableEmbed, RE_MENTION,
|
||||||
|
};
|
||||||
|
use revolt_permissions::{ChannelPermission, PermissionValue};
|
||||||
use revolt_result::Result;
|
use revolt_result::Result;
|
||||||
use ulid::Ulid;
|
use ulid::Ulid;
|
||||||
|
|
||||||
use crate::{
|
use crate::{
|
||||||
events::client::EventV1,
|
events::client::EventV1,
|
||||||
tasks::{self, ack::AckEvent},
|
tasks::{self, ack::AckEvent},
|
||||||
Channel, Database, File,
|
util::idempotency::IdempotencyKey,
|
||||||
|
Channel, Database, Emoji, File,
|
||||||
};
|
};
|
||||||
|
|
||||||
auto_derived_partial!(
|
auto_derived_partial!(
|
||||||
@@ -196,6 +204,162 @@ impl Default for Message {
|
|||||||
|
|
||||||
#[allow(clippy::disallowed_methods)]
|
#[allow(clippy::disallowed_methods)]
|
||||||
impl Message {
|
impl Message {
|
||||||
|
/// Create message from API data
|
||||||
|
pub async fn create_from_api(
|
||||||
|
db: &Database,
|
||||||
|
channel: Channel,
|
||||||
|
data: DataMessageSend,
|
||||||
|
author: MessageAuthor<'_>,
|
||||||
|
mut idempotency: IdempotencyKey,
|
||||||
|
generate_embeds: bool,
|
||||||
|
) -> Result<Message> {
|
||||||
|
let config = config().await;
|
||||||
|
|
||||||
|
Message::validate_sum(
|
||||||
|
&data.content,
|
||||||
|
data.embeds.as_deref().unwrap_or_default(),
|
||||||
|
config.features.limits.default.message_length,
|
||||||
|
)?;
|
||||||
|
|
||||||
|
idempotency
|
||||||
|
.consume_nonce(data.nonce)
|
||||||
|
.await
|
||||||
|
.map_err(|_| create_error!(InvalidOperation))?;
|
||||||
|
|
||||||
|
// Check the message is not empty
|
||||||
|
if (data.content.as_ref().map_or(true, |v| v.is_empty()))
|
||||||
|
&& (data.attachments.as_ref().map_or(true, |v| v.is_empty()))
|
||||||
|
&& (data.embeds.as_ref().map_or(true, |v| v.is_empty()))
|
||||||
|
{
|
||||||
|
return Err(create_error!(EmptyMessage));
|
||||||
|
}
|
||||||
|
|
||||||
|
// Ensure restrict_reactions is not specified without reactions list
|
||||||
|
if let Some(interactions) = &data.interactions {
|
||||||
|
if interactions.restrict_reactions {
|
||||||
|
let disallowed = if let Some(list) = &interactions.reactions {
|
||||||
|
list.is_empty()
|
||||||
|
} else {
|
||||||
|
true
|
||||||
|
};
|
||||||
|
|
||||||
|
if disallowed {
|
||||||
|
return Err(create_error!(InvalidProperty));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
let (author_id, webhook) = match &author {
|
||||||
|
MessageAuthor::User(user) => (user.id.clone(), None),
|
||||||
|
MessageAuthor::Webhook(webhook) => (webhook.id.clone(), Some((*webhook).clone())),
|
||||||
|
MessageAuthor::System { .. } => ("00000000000000000000000000".to_string(), None),
|
||||||
|
};
|
||||||
|
|
||||||
|
// Start constructing the message
|
||||||
|
let message_id = Ulid::new().to_string();
|
||||||
|
let mut message = Message {
|
||||||
|
id: message_id.clone(),
|
||||||
|
channel: channel.id(),
|
||||||
|
masquerade: data.masquerade.map(|masquerade| masquerade.into()),
|
||||||
|
interactions: data
|
||||||
|
.interactions
|
||||||
|
.map(|interactions| interactions.into())
|
||||||
|
.unwrap_or_default(),
|
||||||
|
author: author_id,
|
||||||
|
webhook: webhook.map(|w| w.into()),
|
||||||
|
..Default::default()
|
||||||
|
};
|
||||||
|
|
||||||
|
// Parse mentions in message.
|
||||||
|
let mut mentions = HashSet::new();
|
||||||
|
if let Some(content) = &data.content {
|
||||||
|
for capture in RE_MENTION.captures_iter(content) {
|
||||||
|
if let Some(mention) = capture.get(1) {
|
||||||
|
mentions.insert(mention.as_str().to_string());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Verify replies are valid.
|
||||||
|
let mut replies = HashSet::new();
|
||||||
|
if let Some(entries) = data.replies {
|
||||||
|
if entries.len() > config.features.limits.default.message_replies {
|
||||||
|
return Err(create_error!(TooManyReplies {
|
||||||
|
max: config.features.limits.default.message_replies,
|
||||||
|
}));
|
||||||
|
}
|
||||||
|
|
||||||
|
for ReplyIntent { id, mention } in entries {
|
||||||
|
let message = db.fetch_message(&id).await?;
|
||||||
|
|
||||||
|
if mention {
|
||||||
|
mentions.insert(message.author.to_owned());
|
||||||
|
}
|
||||||
|
|
||||||
|
replies.insert(message.id);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if !mentions.is_empty() {
|
||||||
|
message.mentions.replace(mentions.into_iter().collect());
|
||||||
|
}
|
||||||
|
|
||||||
|
if !replies.is_empty() {
|
||||||
|
message
|
||||||
|
.replies
|
||||||
|
.replace(replies.into_iter().collect::<Vec<String>>());
|
||||||
|
}
|
||||||
|
|
||||||
|
// Add attachments to message.
|
||||||
|
let mut attachments = vec![];
|
||||||
|
if data
|
||||||
|
.attachments
|
||||||
|
.as_ref()
|
||||||
|
.is_some_and(|v| v.len() > config.features.limits.default.message_attachments)
|
||||||
|
{
|
||||||
|
return Err(create_error!(TooManyAttachments {
|
||||||
|
max: config.features.limits.default.message_attachments,
|
||||||
|
}));
|
||||||
|
}
|
||||||
|
|
||||||
|
if data
|
||||||
|
.embeds
|
||||||
|
.as_ref()
|
||||||
|
.is_some_and(|v| v.len() > config.features.limits.default.message_embeds)
|
||||||
|
{
|
||||||
|
return Err(create_error!(TooManyEmbeds {
|
||||||
|
max: config.features.limits.default.message_embeds,
|
||||||
|
}));
|
||||||
|
}
|
||||||
|
|
||||||
|
for attachment_id in data.attachments.as_deref().unwrap_or_default() {
|
||||||
|
attachments.push(
|
||||||
|
db.find_and_use_attachment(attachment_id, "attachments", "message", &message_id)
|
||||||
|
.await?,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
if !attachments.is_empty() {
|
||||||
|
message.attachments.replace(attachments);
|
||||||
|
}
|
||||||
|
|
||||||
|
// Process included embeds.
|
||||||
|
for sendable_embed in data.embeds.unwrap_or_default() {
|
||||||
|
message.attach_sendable_embed(db, sendable_embed).await?;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Set content
|
||||||
|
message.content = data.content;
|
||||||
|
|
||||||
|
// Pass-through nonce value for clients
|
||||||
|
message.nonce = Some(idempotency.into_key());
|
||||||
|
|
||||||
|
// Send the message
|
||||||
|
message.send(db, author, &channel, generate_embeds).await?;
|
||||||
|
|
||||||
|
Ok(message)
|
||||||
|
}
|
||||||
|
|
||||||
/// Send a message without any notifications
|
/// Send a message without any notifications
|
||||||
pub async fn send_without_notifications(
|
pub async fn send_without_notifications(
|
||||||
&mut self,
|
&mut self,
|
||||||
@@ -293,6 +457,64 @@ impl Message {
|
|||||||
|
|
||||||
Ok(())
|
Ok(())
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// Convert sendable embed to text embed and attach to message
|
||||||
|
pub async fn attach_sendable_embed(
|
||||||
|
&mut self,
|
||||||
|
db: &Database,
|
||||||
|
embed: v0::SendableEmbed,
|
||||||
|
) -> Result<()> {
|
||||||
|
let media: Option<v0::File> = if let Some(id) = embed.media {
|
||||||
|
Some(
|
||||||
|
db.find_and_use_attachment(&id, "attachments", "message", &self.id)
|
||||||
|
.await?
|
||||||
|
.into(),
|
||||||
|
)
|
||||||
|
} else {
|
||||||
|
None
|
||||||
|
};
|
||||||
|
|
||||||
|
let embed = v0::Embed::Text(v0::Text {
|
||||||
|
icon_url: embed.icon_url,
|
||||||
|
url: embed.url,
|
||||||
|
title: embed.title,
|
||||||
|
description: embed.description,
|
||||||
|
media,
|
||||||
|
colour: embed.colour,
|
||||||
|
});
|
||||||
|
|
||||||
|
if let Some(embeds) = &mut self.embeds {
|
||||||
|
embeds.push(embed);
|
||||||
|
} else {
|
||||||
|
self.embeds = Some(vec![embed]);
|
||||||
|
}
|
||||||
|
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Validate the sum of content of a message is under threshold
|
||||||
|
pub fn validate_sum(
|
||||||
|
content: &Option<String>,
|
||||||
|
embeds: &[SendableEmbed],
|
||||||
|
max_length: usize,
|
||||||
|
) -> Result<()> {
|
||||||
|
let mut running_total = 0;
|
||||||
|
if let Some(content) = content {
|
||||||
|
running_total += content.len();
|
||||||
|
}
|
||||||
|
|
||||||
|
for embed in embeds {
|
||||||
|
if let Some(desc) = &embed.description {
|
||||||
|
running_total += desc.len();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if running_total <= max_length {
|
||||||
|
Ok(())
|
||||||
|
} else {
|
||||||
|
Err(create_error!(PayloadTooLarge))
|
||||||
|
}
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
impl SystemMessage {
|
impl SystemMessage {
|
||||||
@@ -309,6 +531,27 @@ impl SystemMessage {
|
|||||||
}
|
}
|
||||||
|
|
||||||
impl Interactions {
|
impl Interactions {
|
||||||
|
/// Validate interactions info is correct
|
||||||
|
pub async fn validate(&self, db: &Database, permissions: &PermissionValue) -> Result<()> {
|
||||||
|
let config = config().await;
|
||||||
|
|
||||||
|
if let Some(reactions) = &self.reactions {
|
||||||
|
permissions.throw_if_lacking_channel_permission(ChannelPermission::React)?;
|
||||||
|
|
||||||
|
if reactions.len() > config.features.limits.default.message_reactions {
|
||||||
|
return Err(create_error!(InvalidOperation));
|
||||||
|
}
|
||||||
|
|
||||||
|
for reaction in reactions {
|
||||||
|
if !Emoji::can_use(db, reaction).await? {
|
||||||
|
return Err(create_error!(InvalidOperation));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
/// Check if we can use a given emoji to react
|
/// Check if we can use a given emoji to react
|
||||||
pub fn can_use(&self, emoji: &str) -> bool {
|
pub fn can_use(&self, emoji: &str) -> bool {
|
||||||
if self.restrict_reactions {
|
if self.restrict_reactions {
|
||||||
|
|||||||
@@ -182,6 +182,21 @@ impl User {
|
|||||||
Ok(user)
|
Ok(user)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// Get the relationship with another user
|
||||||
|
pub fn relationship_with(&self, user_b: &str) -> RelationshipStatus {
|
||||||
|
if self.id == user_b {
|
||||||
|
return RelationshipStatus::User;
|
||||||
|
}
|
||||||
|
|
||||||
|
if let Some(relations) = &self.relations {
|
||||||
|
if let Some(relationship) = relations.iter().find(|x| x.id == user_b) {
|
||||||
|
return relationship.status.clone();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
RelationshipStatus::None
|
||||||
|
}
|
||||||
|
|
||||||
/// Check whether two users have a mutual connection
|
/// Check whether two users have a mutual connection
|
||||||
///
|
///
|
||||||
/// This will check if user and user_b share a server or a group.
|
/// This will check if user and user_b share a server or a group.
|
||||||
|
|||||||
@@ -275,6 +275,15 @@ impl From<crate::EmojiParent> for EmojiParent {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
impl From<EmojiParent> for crate::EmojiParent {
|
||||||
|
fn from(value: EmojiParent) -> Self {
|
||||||
|
match value {
|
||||||
|
EmojiParent::Detached => crate::EmojiParent::Detached,
|
||||||
|
EmojiParent::Server { id } => crate::EmojiParent::Server { id },
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
impl From<crate::File> for File {
|
impl From<crate::File> for File {
|
||||||
fn from(value: crate::File) -> Self {
|
fn from(value: crate::File) -> Self {
|
||||||
File {
|
File {
|
||||||
@@ -329,7 +338,11 @@ impl From<crate::Message> for Message {
|
|||||||
embeds: value.embeds,
|
embeds: value.embeds,
|
||||||
mentions: value.mentions,
|
mentions: value.mentions,
|
||||||
replies: value.replies,
|
replies: value.replies,
|
||||||
reactions: value.reactions,
|
reactions: value
|
||||||
|
.reactions
|
||||||
|
.into_iter()
|
||||||
|
.map(|(k, v)| (k, v.into_iter().collect()))
|
||||||
|
.collect(),
|
||||||
interactions: value.interactions.into(),
|
interactions: value.interactions.into(),
|
||||||
masquerade: value.masquerade.map(|masq| masq.into()),
|
masquerade: value.masquerade.map(|masq| masq.into()),
|
||||||
}
|
}
|
||||||
@@ -353,7 +366,12 @@ impl From<crate::PartialMessage> for PartialMessage {
|
|||||||
embeds: value.embeds,
|
embeds: value.embeds,
|
||||||
mentions: value.mentions,
|
mentions: value.mentions,
|
||||||
replies: value.replies,
|
replies: value.replies,
|
||||||
reactions: value.reactions,
|
reactions: value.reactions.map(|reactions| {
|
||||||
|
reactions
|
||||||
|
.into_iter()
|
||||||
|
.map(|(k, v)| (k, v.into_iter().collect()))
|
||||||
|
.collect()
|
||||||
|
}),
|
||||||
interactions: value.interactions.map(|interactions| interactions.into()),
|
interactions: value.interactions.map(|interactions| interactions.into()),
|
||||||
masquerade: value.masquerade.map(|masq| masq.into()),
|
masquerade: value.masquerade.map(|masq| masq.into()),
|
||||||
}
|
}
|
||||||
@@ -385,7 +403,20 @@ impl From<crate::SystemMessage> for SystemMessage {
|
|||||||
impl From<crate::Interactions> for Interactions {
|
impl From<crate::Interactions> for Interactions {
|
||||||
fn from(value: crate::Interactions) -> Self {
|
fn from(value: crate::Interactions) -> Self {
|
||||||
Interactions {
|
Interactions {
|
||||||
reactions: value.reactions,
|
reactions: value
|
||||||
|
.reactions
|
||||||
|
.map(|reactions| reactions.into_iter().collect()),
|
||||||
|
restrict_reactions: value.restrict_reactions,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl From<Interactions> for crate::Interactions {
|
||||||
|
fn from(value: Interactions) -> Self {
|
||||||
|
crate::Interactions {
|
||||||
|
reactions: value
|
||||||
|
.reactions
|
||||||
|
.map(|reactions| reactions.into_iter().collect()),
|
||||||
restrict_reactions: value.restrict_reactions,
|
restrict_reactions: value.restrict_reactions,
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -409,6 +440,16 @@ impl From<crate::Masquerade> for Masquerade {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
impl From<Masquerade> for crate::Masquerade {
|
||||||
|
fn from(value: Masquerade) -> Self {
|
||||||
|
crate::Masquerade {
|
||||||
|
name: value.name,
|
||||||
|
avatar: value.avatar,
|
||||||
|
colour: value.colour,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
impl From<crate::ServerBan> for ServerBan {
|
impl From<crate::ServerBan> for ServerBan {
|
||||||
fn from(value: crate::ServerBan) -> Self {
|
fn from(value: crate::ServerBan) -> Self {
|
||||||
ServerBan {
|
ServerBan {
|
||||||
@@ -594,18 +635,26 @@ impl From<crate::FieldsRole> for FieldsRole {
|
|||||||
}
|
}
|
||||||
|
|
||||||
impl crate::User {
|
impl crate::User {
|
||||||
pub async fn into<P>(self, perspective: P) -> User
|
pub async fn into<'a, P>(self, perspective: P) -> User
|
||||||
where
|
where
|
||||||
P: Into<Option<crate::User>>,
|
P: Into<Option<&'a crate::User>>,
|
||||||
{
|
{
|
||||||
let relationship = if let Some(perspective) = perspective.into() {
|
let relationship = if let Some(perspective) = perspective.into() {
|
||||||
perspective
|
if perspective.id == self.id {
|
||||||
.relations
|
RelationshipStatus::User
|
||||||
.unwrap_or_default()
|
} else {
|
||||||
.into_iter()
|
perspective
|
||||||
.find(|relationship| relationship.id == self.id)
|
.relations
|
||||||
.map(|relationship| relationship.status.into())
|
.as_ref()
|
||||||
.unwrap_or_default()
|
.map(|relations| {
|
||||||
|
relations
|
||||||
|
.iter()
|
||||||
|
.find(|relationship| relationship.id == self.id)
|
||||||
|
.map(|relationship| relationship.status.clone().into())
|
||||||
|
.unwrap_or_default()
|
||||||
|
})
|
||||||
|
.unwrap_or_default()
|
||||||
|
}
|
||||||
} else {
|
} else {
|
||||||
RelationshipStatus::None
|
RelationshipStatus::None
|
||||||
};
|
};
|
||||||
|
|||||||
@@ -4,12 +4,6 @@ use revolt_result::{create_error, Error, Result};
|
|||||||
|
|
||||||
use async_std::sync::Mutex;
|
use async_std::sync::Mutex;
|
||||||
use once_cell::sync::Lazy;
|
use once_cell::sync::Lazy;
|
||||||
use revolt_rocket_okapi::gen::OpenApiGenerator;
|
|
||||||
use revolt_rocket_okapi::request::{OpenApiFromRequest, RequestHeaderInput};
|
|
||||||
use revolt_rocket_okapi::revolt_okapi::openapi3::{Parameter, ParameterValue};
|
|
||||||
use rocket::http::Status;
|
|
||||||
use rocket::request::{FromRequest, Outcome};
|
|
||||||
use schemars::schema::{InstanceType, SchemaObject, SingleOrVec};
|
|
||||||
use serde::{Deserialize, Serialize};
|
use serde::{Deserialize, Serialize};
|
||||||
|
|
||||||
#[derive(Serialize, Deserialize)]
|
#[derive(Serialize, Deserialize)]
|
||||||
@@ -42,6 +36,17 @@ impl IdempotencyKey {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[cfg(feature = "rocket-impl")]
|
||||||
|
use revolt_rocket_okapi::{
|
||||||
|
gen::OpenApiGenerator,
|
||||||
|
request::{OpenApiFromRequest, RequestHeaderInput},
|
||||||
|
revolt_okapi::openapi3::{Parameter, ParameterValue},
|
||||||
|
};
|
||||||
|
|
||||||
|
#[cfg(feature = "rocket-impl")]
|
||||||
|
use schemars::schema::{InstanceType, SchemaObject, SingleOrVec};
|
||||||
|
|
||||||
|
#[cfg(feature = "rocket-impl")]
|
||||||
impl<'r> OpenApiFromRequest<'r> for IdempotencyKey {
|
impl<'r> OpenApiFromRequest<'r> for IdempotencyKey {
|
||||||
fn from_request_input(
|
fn from_request_input(
|
||||||
_gen: &mut OpenApiGenerator,
|
_gen: &mut OpenApiGenerator,
|
||||||
@@ -71,6 +76,13 @@ impl<'r> OpenApiFromRequest<'r> for IdempotencyKey {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[cfg(feature = "rocket-impl")]
|
||||||
|
use rocket::{
|
||||||
|
http::Status,
|
||||||
|
request::{FromRequest, Outcome},
|
||||||
|
};
|
||||||
|
|
||||||
|
#[cfg(feature = "rocket-impl")]
|
||||||
#[async_trait]
|
#[async_trait]
|
||||||
impl<'r> FromRequest<'r> for IdempotencyKey {
|
impl<'r> FromRequest<'r> for IdempotencyKey {
|
||||||
type Error = Error;
|
type Error = Error;
|
||||||
|
|||||||
@@ -7,7 +7,7 @@ use schemars::{
|
|||||||
JsonSchema,
|
JsonSchema,
|
||||||
};
|
};
|
||||||
|
|
||||||
use crate::{Bot, Database, Webhook};
|
use crate::{Bot, Channel, Database, Emoji, Message, Webhook};
|
||||||
|
|
||||||
/// Reference to some object in the database
|
/// Reference to some object in the database
|
||||||
#[derive(Serialize, Deserialize)]
|
#[derive(Serialize, Deserialize)]
|
||||||
@@ -27,6 +27,21 @@ impl Reference {
|
|||||||
db.fetch_bot(&self.id).await
|
db.fetch_bot(&self.id).await
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// Fetch emoji from Ref
|
||||||
|
pub async fn as_emoji(&self, db: &Database) -> Result<Emoji> {
|
||||||
|
db.fetch_emoji(&self.id).await
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Fetch channel from Ref
|
||||||
|
pub async fn as_channel(&self, db: &Database) -> Result<Channel> {
|
||||||
|
db.fetch_channel(&self.id).await
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Fetch message from Ref
|
||||||
|
pub async fn as_message(&self, db: &Database) -> Result<Message> {
|
||||||
|
db.fetch_message(&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
|
||||||
|
|||||||
@@ -1,6 +1,6 @@
|
|||||||
[package]
|
[package]
|
||||||
name = "revolt-models"
|
name = "revolt-models"
|
||||||
version = "0.6.7"
|
version = "0.6.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>"]
|
||||||
@@ -9,7 +9,7 @@ description = "Revolt Backend: API Models"
|
|||||||
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
|
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
|
||||||
|
|
||||||
[features]
|
[features]
|
||||||
serde = ["dep:serde", "revolt-permissions/serde"]
|
serde = ["dep:serde", "revolt-permissions/serde", "indexmap/serde"]
|
||||||
schemas = ["dep:schemars", "revolt-permissions/schemas"]
|
schemas = ["dep:schemars", "revolt-permissions/schemas"]
|
||||||
validator = ["dep:validator"]
|
validator = ["dep:validator"]
|
||||||
partials = ["dep:revolt_optional_struct", "serde", "schemas"]
|
partials = ["dep:revolt_optional_struct", "serde", "schemas"]
|
||||||
@@ -18,8 +18,8 @@ default = ["serde", "partials"]
|
|||||||
|
|
||||||
[dependencies]
|
[dependencies]
|
||||||
# Core
|
# Core
|
||||||
revolt-config = { version = "0.6.7", path = "../config" }
|
revolt-config = { version = "0.6.8", path = "../config" }
|
||||||
revolt-permissions = { version = "0.6.7", path = "../permissions" }
|
revolt-permissions = { version = "0.6.8", path = "../permissions" }
|
||||||
|
|
||||||
# Utility
|
# Utility
|
||||||
regex = "1"
|
regex = "1"
|
||||||
|
|||||||
@@ -1,7 +1,5 @@
|
|||||||
use super::User;
|
use super::User;
|
||||||
|
|
||||||
use validator::Validate;
|
|
||||||
|
|
||||||
auto_derived!(
|
auto_derived!(
|
||||||
/// Bot
|
/// Bot
|
||||||
#[derive(Default)]
|
#[derive(Default)]
|
||||||
@@ -103,7 +101,7 @@ auto_derived!(
|
|||||||
|
|
||||||
/// Bot Details
|
/// Bot Details
|
||||||
#[derive(Default)]
|
#[derive(Default)]
|
||||||
#[cfg_attr(feature = "validator", derive(Validate))]
|
#[cfg_attr(feature = "validator", derive(validator::Validate))]
|
||||||
pub struct DataCreateBot {
|
pub struct DataCreateBot {
|
||||||
/// Bot username
|
/// Bot username
|
||||||
#[cfg_attr(
|
#[cfg_attr(
|
||||||
@@ -115,7 +113,7 @@ auto_derived!(
|
|||||||
|
|
||||||
/// New Bot Details
|
/// New Bot Details
|
||||||
#[derive(Default)]
|
#[derive(Default)]
|
||||||
#[cfg_attr(feature = "validator", derive(Validate))]
|
#[cfg_attr(feature = "validator", derive(validator::Validate))]
|
||||||
pub struct DataEditBot {
|
pub struct DataEditBot {
|
||||||
/// Bot username
|
/// Bot username
|
||||||
#[cfg_attr(
|
#[cfg_attr(
|
||||||
|
|||||||
@@ -1,3 +1,5 @@
|
|||||||
|
use validator::Validate;
|
||||||
|
|
||||||
use super::File;
|
use super::File;
|
||||||
|
|
||||||
auto_derived_partial!(
|
auto_derived_partial!(
|
||||||
@@ -69,13 +71,23 @@ auto_derived!(
|
|||||||
pub channel_id: String,
|
pub channel_id: String,
|
||||||
|
|
||||||
/// The permissions for the webhook
|
/// The permissions for the webhook
|
||||||
pub permissions: u64
|
pub permissions: u64,
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Optional fields on webhook object
|
/// Optional fields on webhook object
|
||||||
pub enum FieldsWebhook {
|
pub enum FieldsWebhook {
|
||||||
Avatar,
|
Avatar,
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// Information for the webhook
|
||||||
|
#[derive(Validate)]
|
||||||
|
pub struct CreateWebhookBody {
|
||||||
|
#[validate(length(min = 1, max = 32))]
|
||||||
|
pub name: String,
|
||||||
|
|
||||||
|
#[validate(length(min = 1, max = 128))]
|
||||||
|
pub avatar: Option<String>,
|
||||||
|
}
|
||||||
);
|
);
|
||||||
|
|
||||||
impl From<Webhook> for MessageWebhook {
|
impl From<Webhook> for MessageWebhook {
|
||||||
@@ -94,7 +106,7 @@ impl From<Webhook> for ResponseWebhook {
|
|||||||
name: value.name,
|
name: value.name,
|
||||||
avatar: value.avatar.map(|file| file.id),
|
avatar: value.avatar.map(|file| file.id),
|
||||||
channel_id: value.channel_id,
|
channel_id: value.channel_id,
|
||||||
permissions: value.permissions
|
permissions: value.permissions,
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -1,10 +1,11 @@
|
|||||||
use super::File;
|
use super::File;
|
||||||
|
|
||||||
use revolt_permissions::OverrideField;
|
use revolt_permissions::OverrideField;
|
||||||
use std::collections::HashMap;
|
use std::collections::{HashMap, HashSet};
|
||||||
|
|
||||||
auto_derived!(
|
auto_derived!(
|
||||||
/// Channel
|
/// Channel
|
||||||
|
#[serde(tag = "channel_type")]
|
||||||
pub enum Channel {
|
pub enum Channel {
|
||||||
/// Personal "Saved Notes" channel which allows users to save messages
|
/// Personal "Saved Notes" channel which allows users to save messages
|
||||||
SavedMessages {
|
SavedMessages {
|
||||||
@@ -205,4 +206,28 @@ auto_derived!(
|
|||||||
#[cfg_attr(feature = "serde", serde(default))]
|
#[cfg_attr(feature = "serde", serde(default))]
|
||||||
pub remove: Option<Vec<FieldsChannel>>,
|
pub remove: Option<Vec<FieldsChannel>>,
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// Create new group
|
||||||
|
#[derive(Default)]
|
||||||
|
#[cfg_attr(feature = "validator", derive(validator::Validate))]
|
||||||
|
pub struct DataCreateGroup {
|
||||||
|
/// Group name
|
||||||
|
#[validate(length(min = 1, max = 32))]
|
||||||
|
pub name: String,
|
||||||
|
/// Group description
|
||||||
|
#[validate(length(min = 0, max = 1024))]
|
||||||
|
pub description: Option<String>,
|
||||||
|
/// Group icon
|
||||||
|
#[validate(length(min = 1, max = 128))]
|
||||||
|
pub icon: Option<String>,
|
||||||
|
/// Array of user IDs to add to the group
|
||||||
|
///
|
||||||
|
/// Must be friends with these users.
|
||||||
|
#[validate(length(min = 0, max = 49))]
|
||||||
|
#[serde(default)]
|
||||||
|
pub users: HashSet<String>,
|
||||||
|
/// Whether this group is age-restricted
|
||||||
|
#[serde(skip_serializing_if = "Option::is_none")]
|
||||||
|
pub nsfw: Option<bool>,
|
||||||
|
}
|
||||||
);
|
);
|
||||||
@@ -1,3 +1,12 @@
|
|||||||
|
use once_cell::sync::Lazy;
|
||||||
|
use regex::Regex;
|
||||||
|
use validator::Validate;
|
||||||
|
|
||||||
|
/// Regex for valid emoji names
|
||||||
|
///
|
||||||
|
/// Alphanumeric and underscores
|
||||||
|
pub static RE_EMOJI: Lazy<Regex> = Lazy::new(|| Regex::new(r"^[a-z0-9_]+$").unwrap());
|
||||||
|
|
||||||
auto_derived!(
|
auto_derived!(
|
||||||
/// Emoji
|
/// Emoji
|
||||||
pub struct Emoji {
|
pub struct Emoji {
|
||||||
@@ -30,4 +39,17 @@ auto_derived!(
|
|||||||
Server { id: String },
|
Server { id: String },
|
||||||
Detached,
|
Detached,
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// Create a new emoji
|
||||||
|
#[derive(Validate)]
|
||||||
|
pub struct DataCreateEmoji {
|
||||||
|
/// Server name
|
||||||
|
#[validate(length(min = 1, max = 32), regex = "RE_EMOJI")]
|
||||||
|
pub name: String,
|
||||||
|
/// Parent information
|
||||||
|
pub parent: EmojiParent,
|
||||||
|
/// Whether the emoji is mature
|
||||||
|
#[serde(default)]
|
||||||
|
pub nsfw: bool,
|
||||||
|
}
|
||||||
);
|
);
|
||||||
@@ -1,11 +1,19 @@
|
|||||||
use std::time::SystemTime;
|
use std::{
|
||||||
|
collections::{HashMap, HashSet},
|
||||||
|
time::SystemTime,
|
||||||
|
};
|
||||||
|
|
||||||
|
use once_cell::sync::Lazy;
|
||||||
|
use regex::Regex;
|
||||||
use revolt_config::config;
|
use revolt_config::config;
|
||||||
|
use validator::Validate;
|
||||||
|
|
||||||
use indexmap::{IndexMap, IndexSet};
|
|
||||||
use iso8601_timestamp::Timestamp;
|
use iso8601_timestamp::Timestamp;
|
||||||
|
|
||||||
use super::{Embed, File, MessageWebhook, User, Webhook};
|
use super::{Embed, File, MessageWebhook, User, Webhook, RE_COLOUR};
|
||||||
|
|
||||||
|
pub static RE_MENTION: Lazy<Regex> =
|
||||||
|
Lazy::new(|| Regex::new(r"<@([0-9A-HJKMNP-TV-Z]{26})>").unwrap());
|
||||||
|
|
||||||
auto_derived_partial!(
|
auto_derived_partial!(
|
||||||
/// Message
|
/// Message
|
||||||
@@ -45,8 +53,8 @@ auto_derived_partial!(
|
|||||||
#[serde(skip_serializing_if = "Option::is_none")]
|
#[serde(skip_serializing_if = "Option::is_none")]
|
||||||
pub replies: Option<Vec<String>>,
|
pub replies: Option<Vec<String>>,
|
||||||
/// Hashmap of emoji IDs to array of user IDs
|
/// Hashmap of emoji IDs to array of user IDs
|
||||||
#[serde(skip_serializing_if = "IndexMap::is_empty", default)]
|
#[serde(skip_serializing_if = "HashMap::is_empty", default)]
|
||||||
pub reactions: IndexMap<String, IndexSet<String>>,
|
pub reactions: HashMap<String, HashSet<String>>,
|
||||||
/// Information about how this message should be interacted with
|
/// Information about how this message should be interacted with
|
||||||
#[serde(skip_serializing_if = "Interactions::is_default", default)]
|
#[serde(skip_serializing_if = "Interactions::is_default", default)]
|
||||||
pub interactions: Interactions,
|
pub interactions: Interactions,
|
||||||
@@ -86,7 +94,9 @@ auto_derived!(
|
|||||||
}
|
}
|
||||||
|
|
||||||
/// Name and / or avatar override information
|
/// Name and / or avatar override information
|
||||||
|
#[derive(Validate)]
|
||||||
pub struct Masquerade {
|
pub struct Masquerade {
|
||||||
|
// FIXME: missing validation
|
||||||
/// Replace the display name shown on this message
|
/// Replace the display name shown on this message
|
||||||
#[serde(skip_serializing_if = "Option::is_none")]
|
#[serde(skip_serializing_if = "Option::is_none")]
|
||||||
pub name: Option<String>,
|
pub name: Option<String>,
|
||||||
@@ -105,7 +115,7 @@ auto_derived!(
|
|||||||
pub struct Interactions {
|
pub struct Interactions {
|
||||||
/// Reactions which should always appear and be distinct
|
/// Reactions which should always appear and be distinct
|
||||||
#[serde(skip_serializing_if = "Option::is_none", default)]
|
#[serde(skip_serializing_if = "Option::is_none", default)]
|
||||||
pub reactions: Option<IndexSet<String>>,
|
pub reactions: Option<HashSet<String>>,
|
||||||
/// Whether reactions should be restricted to the given list
|
/// Whether reactions should be restricted to the given list
|
||||||
///
|
///
|
||||||
/// Can only be set to true if reactions list is of at least length 1
|
/// Can only be set to true if reactions list is of at least length 1
|
||||||
@@ -152,6 +162,58 @@ auto_derived!(
|
|||||||
/// URL to open when clicking notification
|
/// URL to open when clicking notification
|
||||||
pub url: String,
|
pub url: String,
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// Representation of a text embed before it is sent.
|
||||||
|
#[derive(Default, Validate)]
|
||||||
|
pub struct SendableEmbed {
|
||||||
|
#[validate(length(min = 1, max = 128))]
|
||||||
|
pub icon_url: Option<String>,
|
||||||
|
#[validate(length(min = 1, max = 256))]
|
||||||
|
pub url: Option<String>,
|
||||||
|
#[validate(length(min = 1, max = 100))]
|
||||||
|
pub title: Option<String>,
|
||||||
|
#[validate(length(min = 1, max = 2000))]
|
||||||
|
pub description: Option<String>,
|
||||||
|
pub media: Option<String>,
|
||||||
|
#[validate(length(min = 1, max = 128), regex = "RE_COLOUR")]
|
||||||
|
pub colour: Option<String>,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// What this message should reply to and how
|
||||||
|
pub struct ReplyIntent {
|
||||||
|
/// Message Id
|
||||||
|
pub id: String,
|
||||||
|
/// Whether this reply should mention the message's author
|
||||||
|
pub mention: bool,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Message to send
|
||||||
|
#[derive(Validate)]
|
||||||
|
pub struct DataMessageSend {
|
||||||
|
/// Unique token to prevent duplicate message sending
|
||||||
|
///
|
||||||
|
/// **This is deprecated and replaced by `Idempotency-Key`!**
|
||||||
|
#[validate(length(min = 1, max = 64))]
|
||||||
|
pub nonce: Option<String>,
|
||||||
|
|
||||||
|
/// Message content to send
|
||||||
|
#[validate(length(min = 0, max = 2000))]
|
||||||
|
pub content: Option<String>,
|
||||||
|
/// Attachments to include in message
|
||||||
|
pub attachments: Option<Vec<String>>,
|
||||||
|
/// Messages to reply to
|
||||||
|
pub replies: Option<Vec<ReplyIntent>>,
|
||||||
|
/// Embeds to include in message
|
||||||
|
///
|
||||||
|
/// Text embed content contributes to the content length cap
|
||||||
|
#[validate]
|
||||||
|
pub embeds: Option<Vec<SendableEmbed>>,
|
||||||
|
/// Masquerade to apply to this message
|
||||||
|
#[validate]
|
||||||
|
pub masquerade: Option<Masquerade>,
|
||||||
|
/// Information about how this message should be interacted with
|
||||||
|
pub interactions: Option<Interactions>,
|
||||||
|
}
|
||||||
);
|
);
|
||||||
|
|
||||||
/// Message Author Abstraction
|
/// Message Author Abstraction
|
||||||
|
|||||||
@@ -1,6 +1,27 @@
|
|||||||
use super::File;
|
use super::File;
|
||||||
|
|
||||||
use iso8601_timestamp::Timestamp;
|
use iso8601_timestamp::Timestamp;
|
||||||
|
use once_cell::sync::Lazy;
|
||||||
|
use regex::Regex;
|
||||||
|
|
||||||
|
/// Regex for valid role colours
|
||||||
|
///
|
||||||
|
/// Allows the use of named colours, rgb(a), variables and all gradients.
|
||||||
|
///
|
||||||
|
/// Flags:
|
||||||
|
/// - Case-insensitive (`i`)
|
||||||
|
///
|
||||||
|
/// Source:
|
||||||
|
/// ```regex
|
||||||
|
/// VALUE = [a-z ]+|var\(--[a-z\d-]+\)|rgba?\([\d, ]+\)|#[a-f0-9]+
|
||||||
|
/// ADDITIONAL_VALUE = \d+deg
|
||||||
|
/// STOP = ([ ]+(\d{1,3}%|0))?
|
||||||
|
///
|
||||||
|
/// ^(?:VALUE|(repeating-)?(linear|conic|radial)-gradient\((VALUE|ADDITIONAL_VALUE)STOP(,[ ]*(VALUE)STOP)+\))$
|
||||||
|
/// ```
|
||||||
|
pub static RE_COLOUR: Lazy<Regex> = Lazy::new(|| {
|
||||||
|
Regex::new(r"(?i)^(?:[a-z ]+|var\(--[a-z\d-]+\)|rgba?\([\d, ]+\)|#[a-f0-9]+|(repeating-)?(linear|conic|radial)-gradient\(([a-z ]+|var\(--[a-z\d-]+\)|rgba?\([\d, ]+\)|#[a-f0-9]+|\d+deg)([ ]+(\d{1,3}%|0))?(,[ ]*([a-z ]+|var\(--[a-z\d-]+\)|rgba?\([\d, ]+\)|#[a-f0-9]+)([ ]+(\d{1,3}%|0))?)+\))$").unwrap()
|
||||||
|
});
|
||||||
|
|
||||||
auto_derived_partial!(
|
auto_derived_partial!(
|
||||||
/// Server Member
|
/// Server Member
|
||||||
|
|||||||
@@ -1,6 +1,6 @@
|
|||||||
[package]
|
[package]
|
||||||
name = "revolt-permissions"
|
name = "revolt-permissions"
|
||||||
version = "0.6.7"
|
version = "0.6.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>"]
|
||||||
|
|||||||
@@ -39,20 +39,17 @@ impl PermissionValue {
|
|||||||
}
|
}
|
||||||
|
|
||||||
/// Check whether certain a permission has been granted
|
/// Check whether certain a permission has been granted
|
||||||
pub fn has(&mut self, v: u64) -> bool {
|
pub fn has(&self, v: u64) -> bool {
|
||||||
(self.0 & v) == v
|
(self.0 & v) == v
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Check whether certain a channel permission has been granted
|
/// Check whether certain a channel permission has been granted
|
||||||
pub fn has_channel_permission(&mut self, permission: ChannelPermission) -> bool {
|
pub fn has_channel_permission(&self, permission: ChannelPermission) -> bool {
|
||||||
self.has(permission as u64)
|
self.has(permission as u64)
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Throw if missing channel permission
|
/// Throw if missing channel permission
|
||||||
pub fn throw_if_lacking_channel_permission(
|
pub fn throw_if_lacking_channel_permission(&self, permission: ChannelPermission) -> Result<()> {
|
||||||
&mut self,
|
|
||||||
permission: ChannelPermission,
|
|
||||||
) -> Result<()> {
|
|
||||||
if self.has_channel_permission(permission) {
|
if self.has_channel_permission(permission) {
|
||||||
Ok(())
|
Ok(())
|
||||||
} else {
|
} else {
|
||||||
|
|||||||
@@ -1,6 +1,6 @@
|
|||||||
[package]
|
[package]
|
||||||
name = "revolt-presence"
|
name = "revolt-presence"
|
||||||
version = "0.6.7"
|
version = "0.6.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>"]
|
||||||
|
|||||||
@@ -1,6 +1,6 @@
|
|||||||
[package]
|
[package]
|
||||||
name = "revolt-result"
|
name = "revolt-result"
|
||||||
version = "0.6.7"
|
version = "0.6.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>"]
|
||||||
|
|||||||
@@ -60,6 +60,9 @@ pub enum ErrorType {
|
|||||||
TooManyAttachments {
|
TooManyAttachments {
|
||||||
max: usize,
|
max: usize,
|
||||||
},
|
},
|
||||||
|
TooManyEmbeds {
|
||||||
|
max: usize,
|
||||||
|
},
|
||||||
TooManyReplies {
|
TooManyReplies {
|
||||||
max: usize,
|
max: usize,
|
||||||
},
|
},
|
||||||
|
|||||||
@@ -46,6 +46,7 @@ impl<'r> Responder<'r, 'static> for Error {
|
|||||||
ErrorType::AlreadyInServer => Status::Conflict,
|
ErrorType::AlreadyInServer => Status::Conflict,
|
||||||
|
|
||||||
ErrorType::TooManyServers { .. } => Status::BadRequest,
|
ErrorType::TooManyServers { .. } => Status::BadRequest,
|
||||||
|
ErrorType::TooManyEmbeds { .. } => Status::BadRequest,
|
||||||
ErrorType::TooManyEmoji { .. } => Status::BadRequest,
|
ErrorType::TooManyEmoji { .. } => Status::BadRequest,
|
||||||
ErrorType::TooManyChannels { .. } => Status::BadRequest,
|
ErrorType::TooManyChannels { .. } => Status::BadRequest,
|
||||||
ErrorType::TooManyRoles { .. } => Status::BadRequest,
|
ErrorType::TooManyRoles { .. } => Status::BadRequest,
|
||||||
|
|||||||
@@ -1,6 +1,6 @@
|
|||||||
[package]
|
[package]
|
||||||
name = "revolt-delta"
|
name = "revolt-delta"
|
||||||
version = "0.6.7"
|
version = "0.6.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"
|
||||||
@@ -68,6 +68,7 @@ revolt_rocket_okapi = { version = "0.9.1", features = ["swagger"] }
|
|||||||
revolt-quark = { path = "../quark" }
|
revolt-quark = { path = "../quark" }
|
||||||
|
|
||||||
# core
|
# core
|
||||||
|
revolt-config = { path = "../core/config" }
|
||||||
revolt-database = { path = "../core/database", features = [
|
revolt-database = { path = "../core/database", features = [
|
||||||
"rocket-impl",
|
"rocket-impl",
|
||||||
"redis-is-patched",
|
"redis-is-patched",
|
||||||
|
|||||||
@@ -78,20 +78,16 @@ mod test {
|
|||||||
.await
|
.await
|
||||||
.expect("`Bot`");
|
.expect("`Bot`");
|
||||||
|
|
||||||
// FIXME: Channel::create_group
|
let group = Channel::create_group(
|
||||||
let group = Channel::Group {
|
&harness.db,
|
||||||
id: ulid::Ulid::new().to_string(),
|
v0::DataCreateGroup {
|
||||||
name: TestHarness::rand_string(),
|
name: TestHarness::rand_string(),
|
||||||
owner: user.id.to_string(),
|
..Default::default()
|
||||||
description: None,
|
},
|
||||||
last_message_id: None,
|
user.id.to_string(),
|
||||||
icon: None,
|
)
|
||||||
nsfw: false,
|
.await
|
||||||
permissions: None,
|
.unwrap();
|
||||||
recipients: vec![user.id.to_string()],
|
|
||||||
};
|
|
||||||
|
|
||||||
group.create(&harness.db).await.unwrap();
|
|
||||||
|
|
||||||
let response = harness
|
let response = harness
|
||||||
.client
|
.client
|
||||||
|
|||||||
@@ -1,8 +1,11 @@
|
|||||||
use revolt_quark::{
|
use revolt_database::{
|
||||||
models::{Channel, User},
|
util::{permissions::DatabasePermissionQuery, reference::Reference},
|
||||||
perms, Database, Permission, Ref, Result,
|
Database, User,
|
||||||
};
|
};
|
||||||
|
|
||||||
|
use revolt_models::v0;
|
||||||
|
use revolt_permissions::{calculate_channel_permissions, ChannelPermission};
|
||||||
|
use revolt_result::Result;
|
||||||
use rocket::{serde::json::Json, State};
|
use rocket::{serde::json::Json, State};
|
||||||
|
|
||||||
/// # Fetch Channel
|
/// # Fetch Channel
|
||||||
@@ -10,12 +13,54 @@ use rocket::{serde::json::Json, State};
|
|||||||
/// Fetch channel by its id.
|
/// Fetch channel by its id.
|
||||||
#[openapi(tag = "Channel Information")]
|
#[openapi(tag = "Channel Information")]
|
||||||
#[get("/<target>")]
|
#[get("/<target>")]
|
||||||
pub async fn req(db: &State<Database>, user: User, target: Ref) -> Result<Json<Channel>> {
|
pub async fn fetch_channel(
|
||||||
|
db: &State<Database>,
|
||||||
|
user: User,
|
||||||
|
target: Reference,
|
||||||
|
) -> Result<Json<v0::Channel>> {
|
||||||
let channel = target.as_channel(db).await?;
|
let channel = target.as_channel(db).await?;
|
||||||
perms(&user)
|
|
||||||
.channel(&channel)
|
|
||||||
.throw_permission(db, Permission::ViewChannel)
|
|
||||||
.await?;
|
|
||||||
|
|
||||||
Ok(Json(channel))
|
let mut query = DatabasePermissionQuery::new(db, &user).channel(&channel);
|
||||||
|
calculate_channel_permissions(&mut query)
|
||||||
|
.await
|
||||||
|
.throw_if_lacking_channel_permission(ChannelPermission::ViewChannel)?;
|
||||||
|
|
||||||
|
Ok(Json(channel.into()))
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(test)]
|
||||||
|
mod test {
|
||||||
|
use crate::{rocket, util::test::TestHarness};
|
||||||
|
use revolt_database::Channel;
|
||||||
|
use revolt_models::v0;
|
||||||
|
use rocket::http::{Header, Status};
|
||||||
|
|
||||||
|
#[rocket::async_test]
|
||||||
|
async fn fetch_channel() {
|
||||||
|
let harness = TestHarness::new().await;
|
||||||
|
let (_, session, user) = harness.new_user().await;
|
||||||
|
|
||||||
|
let group = Channel::create_group(
|
||||||
|
&harness.db,
|
||||||
|
v0::DataCreateGroup {
|
||||||
|
name: TestHarness::rand_string(),
|
||||||
|
..Default::default()
|
||||||
|
},
|
||||||
|
user.id.to_string(),
|
||||||
|
)
|
||||||
|
.await
|
||||||
|
.unwrap();
|
||||||
|
|
||||||
|
let response = harness
|
||||||
|
.client
|
||||||
|
.get(format!("/channels/{}", group.id()))
|
||||||
|
.header(Header::new("x-session-token", session.token.to_string()))
|
||||||
|
.dispatch()
|
||||||
|
.await;
|
||||||
|
|
||||||
|
assert_eq!(response.status(), Status::Ok);
|
||||||
|
|
||||||
|
let channel: v0::Channel = response.into_json().await.expect("`Channel`");
|
||||||
|
assert_eq!(channel, group.into());
|
||||||
|
}
|
||||||
}
|
}
|
||||||
@@ -1,84 +1,96 @@
|
|||||||
use std::{collections::HashSet, iter::FromIterator};
|
use revolt_config::config;
|
||||||
|
use revolt_database::{Channel, Database, RelationshipStatus, User};
|
||||||
use revolt_quark::{
|
use revolt_models::v0;
|
||||||
get_relationship,
|
use revolt_result::{create_error, Result};
|
||||||
models::{user::RelationshipStatus, Channel, User},
|
|
||||||
variables::delta::MAX_GROUP_SIZE,
|
|
||||||
Db, Error, Result,
|
|
||||||
};
|
|
||||||
|
|
||||||
use rocket::serde::json::Json;
|
use rocket::serde::json::Json;
|
||||||
use serde::{Deserialize, Serialize};
|
use rocket::State;
|
||||||
use ulid::Ulid;
|
|
||||||
use validator::Validate;
|
use validator::Validate;
|
||||||
|
|
||||||
/// # Group Data
|
|
||||||
#[derive(Validate, Serialize, Deserialize, JsonSchema)]
|
|
||||||
pub struct DataCreateGroup {
|
|
||||||
/// Group name
|
|
||||||
#[validate(length(min = 1, max = 32))]
|
|
||||||
name: String,
|
|
||||||
/// Group description
|
|
||||||
#[validate(length(min = 0, max = 1024))]
|
|
||||||
description: Option<String>,
|
|
||||||
/// Array of user IDs to add to the group
|
|
||||||
///
|
|
||||||
/// Must be friends with these users.
|
|
||||||
#[validate(length(min = 0, max = 49))]
|
|
||||||
users: Vec<String>,
|
|
||||||
/// Whether this group is age-restricted
|
|
||||||
#[serde(skip_serializing_if = "Option::is_none")]
|
|
||||||
nsfw: Option<bool>,
|
|
||||||
}
|
|
||||||
|
|
||||||
/// # Create Group
|
/// # Create Group
|
||||||
///
|
///
|
||||||
/// Create a new group channel.
|
/// Create a new group channel.
|
||||||
#[openapi(tag = "Groups")]
|
#[openapi(tag = "Groups")]
|
||||||
#[post("/create", data = "<info>")]
|
#[post("/create", data = "<data>")]
|
||||||
pub async fn req(db: &Db, user: User, info: Json<DataCreateGroup>) -> Result<Json<Channel>> {
|
pub async fn create_group(
|
||||||
|
db: &State<Database>,
|
||||||
|
user: User,
|
||||||
|
data: Json<v0::DataCreateGroup>,
|
||||||
|
) -> Result<Json<v0::Channel>> {
|
||||||
|
let config = config().await;
|
||||||
if user.bot.is_some() {
|
if user.bot.is_some() {
|
||||||
return Err(Error::IsBot);
|
return Err(create_error!(IsBot));
|
||||||
}
|
}
|
||||||
|
|
||||||
let info = info.into_inner();
|
let mut data = data.into_inner();
|
||||||
info.validate()
|
data.validate().map_err(|error| {
|
||||||
.map_err(|error| Error::FailedValidation { error })?;
|
create_error!(FailedValidation {
|
||||||
|
error: error.to_string()
|
||||||
|
})
|
||||||
|
})?;
|
||||||
|
|
||||||
let mut set: HashSet<String> = HashSet::from_iter(info.users.into_iter());
|
data.users.insert(user.id.to_string());
|
||||||
set.insert(user.id.clone());
|
|
||||||
|
|
||||||
if set.len() > *MAX_GROUP_SIZE {
|
if data.users.len() > config.features.limits.default.group_size {
|
||||||
return Err(Error::GroupTooLarge {
|
return Err(create_error!(GroupTooLarge {
|
||||||
max: *MAX_GROUP_SIZE,
|
max: config.features.limits.default.group_size,
|
||||||
});
|
}));
|
||||||
}
|
}
|
||||||
|
|
||||||
for target in &set {
|
for target in &data.users {
|
||||||
match get_relationship(&user, target) {
|
match user.relationship_with(target) {
|
||||||
RelationshipStatus::Friend | RelationshipStatus::User => {}
|
RelationshipStatus::Friend | RelationshipStatus::User => {}
|
||||||
_ => {
|
_ => {
|
||||||
return Err(Error::NotFriends);
|
return Err(create_error!(NotFriends));
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
let group = Channel::Group {
|
Ok(Json(Channel::create_group(db, data, user.id).await?.into()))
|
||||||
id: Ulid::new().to_string(),
|
}
|
||||||
|
|
||||||
name: info.name,
|
#[cfg(test)]
|
||||||
owner: user.id,
|
mod test {
|
||||||
description: info.description,
|
use crate::{rocket, util::test::TestHarness};
|
||||||
recipients: set.into_iter().collect::<Vec<String>>(),
|
use revolt_models::v0;
|
||||||
|
use rocket::http::{ContentType, Header, Status};
|
||||||
|
|
||||||
icon: None,
|
#[rocket::async_test]
|
||||||
last_message_id: None,
|
async fn create_group() {
|
||||||
|
let harness = TestHarness::new().await;
|
||||||
|
let (_, session, user) = harness.new_user().await;
|
||||||
|
|
||||||
permissions: None,
|
let response = harness
|
||||||
|
.client
|
||||||
|
.post("/channels/create")
|
||||||
|
.header(Header::new("x-session-token", session.token.to_string()))
|
||||||
|
.header(ContentType::JSON)
|
||||||
|
.body(
|
||||||
|
json!(v0::DataCreateBot {
|
||||||
|
name: TestHarness::rand_string(),
|
||||||
|
})
|
||||||
|
.to_string(),
|
||||||
|
)
|
||||||
|
.dispatch()
|
||||||
|
.await;
|
||||||
|
|
||||||
nsfw: info.nsfw.unwrap_or(false),
|
assert_eq!(response.status(), Status::Ok);
|
||||||
};
|
|
||||||
|
|
||||||
group.create(db).await?;
|
let channel: v0::Channel = response.into_json().await.expect("`Channel`");
|
||||||
Ok(Json(group))
|
match channel {
|
||||||
|
v0::Channel::Group {
|
||||||
|
id,
|
||||||
|
owner,
|
||||||
|
recipients,
|
||||||
|
..
|
||||||
|
} => {
|
||||||
|
assert_eq!(owner, user.id);
|
||||||
|
assert_eq!(recipients.len(), 1);
|
||||||
|
assert!(harness.db.fetch_channel(&id).await.is_ok());
|
||||||
|
|
||||||
|
// TODO: does not check for events
|
||||||
|
}
|
||||||
|
_ => unreachable!(),
|
||||||
|
}
|
||||||
|
}
|
||||||
}
|
}
|
||||||
@@ -1,26 +1,34 @@
|
|||||||
use revolt_quark::{
|
use revolt_database::{
|
||||||
models::{Message, User},
|
util::{permissions::DatabasePermissionQuery, reference::Reference},
|
||||||
perms, Db, Error, Permission, Ref, Result,
|
Database, User,
|
||||||
};
|
};
|
||||||
|
use revolt_models::v0;
|
||||||
use rocket::serde::json::Json;
|
use revolt_permissions::{calculate_channel_permissions, ChannelPermission};
|
||||||
|
use revolt_result::{create_error, Result};
|
||||||
|
use rocket::{serde::json::Json, State};
|
||||||
|
|
||||||
/// # Fetch Message
|
/// # Fetch Message
|
||||||
///
|
///
|
||||||
/// Retrieves a message by its id.
|
/// Retrieves a message by its id.
|
||||||
#[openapi(tag = "Messaging")]
|
#[openapi(tag = "Messaging")]
|
||||||
#[get("/<target>/messages/<msg>")]
|
#[get("/<target>/messages/<msg>")]
|
||||||
pub async fn req(db: &Db, user: User, target: Ref, msg: Ref) -> Result<Json<Message>> {
|
pub async fn req(
|
||||||
|
db: &State<Database>,
|
||||||
|
user: User,
|
||||||
|
target: Reference,
|
||||||
|
msg: Reference,
|
||||||
|
) -> Result<Json<v0::Message>> {
|
||||||
let channel = target.as_channel(db).await?;
|
let channel = target.as_channel(db).await?;
|
||||||
perms(&user)
|
|
||||||
.channel(&channel)
|
let mut query = DatabasePermissionQuery::new(db, &user).channel(&channel);
|
||||||
.throw_permission(db, Permission::ViewChannel)
|
calculate_channel_permissions(&mut query)
|
||||||
.await?;
|
.await
|
||||||
|
.throw_if_lacking_channel_permission(ChannelPermission::ViewChannel)?;
|
||||||
|
|
||||||
let message = msg.as_message(db).await?;
|
let message = msg.as_message(db).await?;
|
||||||
if message.channel != channel.as_id() {
|
if message.channel != channel.id() {
|
||||||
return Err(Error::NotFound);
|
return Err(create_error!(NotFound));
|
||||||
}
|
}
|
||||||
|
|
||||||
Ok(Json(message))
|
Ok(Json(message.into()))
|
||||||
}
|
}
|
||||||
@@ -1,26 +0,0 @@
|
|||||||
use revolt_quark::{models::User, Ref, Result};
|
|
||||||
|
|
||||||
use rocket::serde::json::Json;
|
|
||||||
use serde::{Deserialize, Serialize};
|
|
||||||
use validator::Validate;
|
|
||||||
|
|
||||||
/// # Query Parameters
|
|
||||||
#[derive(Validate, Serialize, Deserialize, JsonSchema)]
|
|
||||||
pub struct OptionsQueryStale {
|
|
||||||
/// Array of message IDs
|
|
||||||
#[validate(length(min = 0, max = 150))]
|
|
||||||
ids: Vec<String>,
|
|
||||||
}
|
|
||||||
|
|
||||||
/// # Poll Message Changes
|
|
||||||
///
|
|
||||||
/// This route returns any changed message objects and tells you if any have been deleted.
|
|
||||||
///
|
|
||||||
/// Don't actually poll this route, instead use this to update your local database.
|
|
||||||
///
|
|
||||||
/// **DEPRECATED**
|
|
||||||
#[openapi(tag = "Messaging")]
|
|
||||||
#[post("/<_target>/messages/stale", data = "<_data>")]
|
|
||||||
pub async fn req(_user: User, _target: Ref, _data: Json<OptionsQueryStale>) -> Result<()> {
|
|
||||||
Ok(())
|
|
||||||
}
|
|
||||||
@@ -1,12 +1,13 @@
|
|||||||
use revolt_database::util::idempotency::IdempotencyKey;
|
use revolt_database::util::permissions::DatabasePermissionQuery;
|
||||||
use revolt_quark::{
|
use revolt_database::{
|
||||||
models::{message::DataMessageSend, Message, User},
|
util::idempotency::IdempotencyKey, util::reference::Reference, Database, User,
|
||||||
perms,
|
|
||||||
types::push::MessageAuthor,
|
|
||||||
Db, Error, Permission, Ref, Result,
|
|
||||||
};
|
};
|
||||||
|
use revolt_database::{Interactions, Message};
|
||||||
|
use revolt_models::v0;
|
||||||
|
use revolt_permissions::{calculate_channel_permissions, ChannelPermission};
|
||||||
|
use revolt_result::{create_error, Result};
|
||||||
use rocket::serde::json::Json;
|
use rocket::serde::json::Json;
|
||||||
|
use rocket::State;
|
||||||
use validator::Validate;
|
use validator::Validate;
|
||||||
|
|
||||||
/// # Send Message
|
/// # Send Message
|
||||||
@@ -15,68 +16,63 @@ use validator::Validate;
|
|||||||
#[openapi(tag = "Messaging")]
|
#[openapi(tag = "Messaging")]
|
||||||
#[post("/<target>/messages", data = "<data>")]
|
#[post("/<target>/messages", data = "<data>")]
|
||||||
pub async fn message_send(
|
pub async fn message_send(
|
||||||
db: &Db,
|
db: &State<Database>,
|
||||||
user: User,
|
user: User,
|
||||||
target: Ref,
|
target: Reference,
|
||||||
data: Json<DataMessageSend>,
|
data: Json<v0::DataMessageSend>,
|
||||||
idempotency: IdempotencyKey,
|
idempotency: IdempotencyKey,
|
||||||
) -> Result<Json<Message>> {
|
) -> Result<Json<v0::Message>> {
|
||||||
let data = data.into_inner();
|
let data = data.into_inner();
|
||||||
data.validate()
|
data.validate().map_err(|error| {
|
||||||
.map_err(|error| Error::FailedValidation { error })?;
|
create_error!(FailedValidation {
|
||||||
|
error: error.to_string()
|
||||||
|
})
|
||||||
|
})?;
|
||||||
|
|
||||||
// Ensure we have permissions to send a message
|
// Ensure we have permissions to send a message
|
||||||
let channel = target.as_channel(db).await?;
|
let channel = target.as_channel(db).await?;
|
||||||
|
|
||||||
let mut permissions = perms(&user).channel(&channel);
|
let mut query = DatabasePermissionQuery::new(db, &user).channel(&channel);
|
||||||
permissions
|
let permissions = calculate_channel_permissions(&mut query).await;
|
||||||
.throw_permission_and_view_channel(db, Permission::SendMessage)
|
permissions.throw_if_lacking_channel_permission(ChannelPermission::SendMessage)?;
|
||||||
.await?;
|
|
||||||
|
|
||||||
// Verify permissions for masquerade
|
// Verify permissions for masquerade
|
||||||
if let Some(masq) = &data.masquerade {
|
if let Some(masq) = &data.masquerade {
|
||||||
permissions
|
permissions.throw_if_lacking_channel_permission(ChannelPermission::Masquerade)?;
|
||||||
.throw_permission(db, Permission::Masquerade)
|
|
||||||
.await?;
|
|
||||||
|
|
||||||
if masq.colour.is_some() {
|
if masq.colour.is_some() {
|
||||||
permissions
|
permissions.throw_if_lacking_channel_permission(ChannelPermission::ManageRole)?;
|
||||||
.throw_permission(db, Permission::ManageRole)
|
|
||||||
.await?;
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// Check permissions for embeds
|
// Check permissions for embeds
|
||||||
if data.embeds.as_ref().is_some_and(|v| !v.is_empty()) {
|
if data.embeds.as_ref().is_some_and(|v| !v.is_empty()) {
|
||||||
permissions
|
permissions.throw_if_lacking_channel_permission(ChannelPermission::SendEmbeds)?;
|
||||||
.throw_permission(db, Permission::SendEmbeds)
|
|
||||||
.await?;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// Check permissions for files
|
// Check permissions for files
|
||||||
if data.attachments.as_ref().is_some_and(|v| !v.is_empty()) {
|
if data.attachments.as_ref().is_some_and(|v| !v.is_empty()) {
|
||||||
permissions
|
permissions.throw_if_lacking_channel_permission(ChannelPermission::UploadFiles)?;
|
||||||
.throw_permission(db, Permission::UploadFiles)
|
|
||||||
.await?;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// Ensure interactions information is correct
|
// Ensure interactions information is correct
|
||||||
if let Some(interactions) = &data.interactions {
|
if let Some(interactions) = &data.interactions {
|
||||||
interactions.validate(db, &mut permissions).await?;
|
let interactions: Interactions = interactions.clone().into();
|
||||||
|
interactions.validate(db, &permissions).await?;
|
||||||
}
|
}
|
||||||
|
|
||||||
// Create the message
|
// Create the message
|
||||||
let message = channel
|
let author: v0::User = user.clone().into(Some(&user)).await;
|
||||||
.send_message(
|
Ok(Json(
|
||||||
|
Message::create_from_api(
|
||||||
db,
|
db,
|
||||||
|
channel,
|
||||||
data,
|
data,
|
||||||
MessageAuthor::User(&user),
|
v0::MessageAuthor::User(&author),
|
||||||
idempotency,
|
idempotency,
|
||||||
permissions
|
true,
|
||||||
.has_permission(db, Permission::SendEmbeds)
|
|
||||||
.await?,
|
|
||||||
)
|
)
|
||||||
.await?;
|
.await?
|
||||||
|
.into(),
|
||||||
Ok(Json(message))
|
))
|
||||||
}
|
}
|
||||||
@@ -16,7 +16,6 @@ mod message_delete;
|
|||||||
mod message_edit;
|
mod message_edit;
|
||||||
mod message_fetch;
|
mod message_fetch;
|
||||||
mod message_query;
|
mod message_query;
|
||||||
mod message_query_stale;
|
|
||||||
mod message_react;
|
mod message_react;
|
||||||
mod message_search;
|
mod message_search;
|
||||||
mod message_send;
|
mod message_send;
|
||||||
@@ -30,7 +29,7 @@ mod webhook_fetch_all;
|
|||||||
pub fn routes() -> (Vec<Route>, OpenApi) {
|
pub fn routes() -> (Vec<Route>, OpenApi) {
|
||||||
openapi_get_routes_spec![
|
openapi_get_routes_spec![
|
||||||
channel_ack::req,
|
channel_ack::req,
|
||||||
channel_fetch::req,
|
channel_fetch::fetch_channel,
|
||||||
members_fetch::req,
|
members_fetch::req,
|
||||||
channel_delete::req,
|
channel_delete::req,
|
||||||
channel_edit::req,
|
channel_edit::req,
|
||||||
@@ -38,12 +37,11 @@ pub fn routes() -> (Vec<Route>, OpenApi) {
|
|||||||
message_send::message_send,
|
message_send::message_send,
|
||||||
message_query::req,
|
message_query::req,
|
||||||
message_search::req,
|
message_search::req,
|
||||||
message_query_stale::req,
|
|
||||||
message_fetch::req,
|
message_fetch::req,
|
||||||
message_edit::req,
|
message_edit::req,
|
||||||
message_bulk_delete::req,
|
message_bulk_delete::req,
|
||||||
message_delete::req,
|
message_delete::req,
|
||||||
group_create::req,
|
group_create::create_group,
|
||||||
group_add_member::req,
|
group_add_member::req,
|
||||||
group_remove_member::req,
|
group_remove_member::req,
|
||||||
voice_join::req,
|
voice_join::req,
|
||||||
|
|||||||
@@ -1,23 +1,16 @@
|
|||||||
use revolt_database::{Database, Webhook};
|
use revolt_database::{
|
||||||
use revolt_quark::{
|
util::{permissions::DatabasePermissionQuery, reference::Reference},
|
||||||
models::{Channel, User},
|
Channel, Database, User, Webhook,
|
||||||
perms, Db, Error, Permission, Ref, Result,
|
|
||||||
DEFAULT_WEBHOOK_PERMISSIONS,
|
|
||||||
};
|
};
|
||||||
|
use revolt_models::v0;
|
||||||
|
use revolt_permissions::{
|
||||||
|
calculate_channel_permissions, ChannelPermission, DEFAULT_WEBHOOK_PERMISSIONS,
|
||||||
|
};
|
||||||
|
use revolt_result::{create_error, Result};
|
||||||
use rocket::{serde::json::Json, State};
|
use rocket::{serde::json::Json, State};
|
||||||
use serde::{Deserialize, Serialize};
|
|
||||||
use ulid::Ulid;
|
use ulid::Ulid;
|
||||||
use validator::Validate;
|
use validator::Validate;
|
||||||
|
|
||||||
#[derive(Validate, Serialize, Deserialize, JsonSchema)]
|
|
||||||
pub struct CreateWebhookBody {
|
|
||||||
#[validate(length(min = 1, max = 32))]
|
|
||||||
name: String,
|
|
||||||
|
|
||||||
#[validate(length(min = 1, max = 128))]
|
|
||||||
avatar: Option<String>,
|
|
||||||
}
|
|
||||||
|
|
||||||
/// # Creates a webhook
|
/// # Creates a webhook
|
||||||
///
|
///
|
||||||
/// Creates a webhook which 3rd party platforms can use to send messages
|
/// Creates a webhook which 3rd party platforms can use to send messages
|
||||||
@@ -25,33 +18,34 @@ pub struct CreateWebhookBody {
|
|||||||
#[post("/<target>/webhooks", data = "<data>")]
|
#[post("/<target>/webhooks", data = "<data>")]
|
||||||
pub async fn req(
|
pub async fn req(
|
||||||
db: &State<Database>,
|
db: &State<Database>,
|
||||||
legacy_db: &Db,
|
|
||||||
user: User,
|
user: User,
|
||||||
target: Ref,
|
target: Reference,
|
||||||
data: Json<CreateWebhookBody>,
|
data: Json<v0::CreateWebhookBody>,
|
||||||
) -> Result<Json<revolt_models::v0::Webhook>> {
|
) -> Result<Json<v0::Webhook>> {
|
||||||
let data = data.into_inner();
|
let data = data.into_inner();
|
||||||
data.validate()
|
data.validate().map_err(|error| {
|
||||||
.map_err(|error| Error::FailedValidation { error })?;
|
create_error!(FailedValidation {
|
||||||
|
error: error.to_string()
|
||||||
|
})
|
||||||
|
})?;
|
||||||
|
|
||||||
let channel = target.as_channel(legacy_db).await?;
|
let channel = target.as_channel(db).await?;
|
||||||
|
|
||||||
if !matches!(channel, Channel::TextChannel { .. } | Channel::Group { .. }) {
|
if !matches!(channel, Channel::TextChannel { .. } | Channel::Group { .. }) {
|
||||||
return Err(Error::InvalidOperation);
|
return Err(create_error!(InvalidOperation));
|
||||||
}
|
}
|
||||||
|
|
||||||
let mut permissions = perms(&user).channel(&channel);
|
let mut query = DatabasePermissionQuery::new(db, &user).channel(&channel);
|
||||||
permissions
|
calculate_channel_permissions(&mut query)
|
||||||
.has_permission(legacy_db, Permission::ManageWebhooks)
|
.await
|
||||||
.await?;
|
.throw_if_lacking_channel_permission(ChannelPermission::ManageWebhooks)?;
|
||||||
|
|
||||||
let webhook_id = Ulid::new().to_string();
|
let webhook_id = Ulid::new().to_string();
|
||||||
|
|
||||||
let avatar = match &data.avatar {
|
let avatar = match &data.avatar {
|
||||||
Some(id) => Some(
|
Some(id) => Some(
|
||||||
db.find_and_use_attachment(id, "avatars", "user", &webhook_id)
|
db.find_and_use_attachment(id, "avatars", "user", &webhook_id)
|
||||||
.await
|
.await?,
|
||||||
.map_err(Error::from_core)?,
|
|
||||||
),
|
),
|
||||||
None => None,
|
None => None,
|
||||||
};
|
};
|
||||||
@@ -60,12 +54,12 @@ pub async fn req(
|
|||||||
id: webhook_id,
|
id: webhook_id,
|
||||||
name: data.name,
|
name: data.name,
|
||||||
avatar,
|
avatar,
|
||||||
channel_id: channel.id().to_string(),
|
channel_id: channel.id(),
|
||||||
permissions: *DEFAULT_WEBHOOK_PERMISSIONS,
|
permissions: *DEFAULT_WEBHOOK_PERMISSIONS,
|
||||||
token: Some(nanoid::nanoid!(64)),
|
token: Some(nanoid::nanoid!(64)),
|
||||||
};
|
};
|
||||||
|
|
||||||
webhook.create(db).await.map_err(Error::from_core)?;
|
webhook.create(db).await?;
|
||||||
|
|
||||||
Ok(Json(webhook.into()))
|
Ok(Json(webhook.into()))
|
||||||
}
|
}
|
||||||
@@ -1,6 +1,10 @@
|
|||||||
use revolt_database::Database;
|
use revolt_database::{
|
||||||
|
util::{permissions::DatabasePermissionQuery, reference::Reference},
|
||||||
|
Database, User,
|
||||||
|
};
|
||||||
use revolt_models::v0::Webhook;
|
use revolt_models::v0::Webhook;
|
||||||
use revolt_quark::{models::User, perms, Db, Error, Permission, Ref, Result};
|
use revolt_permissions::{calculate_channel_permissions, ChannelPermission};
|
||||||
|
use revolt_result::Result;
|
||||||
use rocket::{serde::json::Json, State};
|
use rocket::{serde::json::Json, State};
|
||||||
|
|
||||||
/// # Gets all webhooks
|
/// # Gets all webhooks
|
||||||
@@ -10,20 +14,19 @@ use rocket::{serde::json::Json, State};
|
|||||||
#[get("/<channel_id>/webhooks")]
|
#[get("/<channel_id>/webhooks")]
|
||||||
pub async fn req(
|
pub async fn req(
|
||||||
db: &State<Database>,
|
db: &State<Database>,
|
||||||
legacy_db: &Db,
|
|
||||||
user: User,
|
user: User,
|
||||||
channel_id: Ref,
|
channel_id: Reference,
|
||||||
) -> Result<Json<Vec<Webhook>>> {
|
) -> Result<Json<Vec<Webhook>>> {
|
||||||
let channel = channel_id.as_channel(legacy_db).await?;
|
let channel = channel_id.as_channel(db).await?;
|
||||||
let mut permissions = perms(&user).channel(&channel);
|
|
||||||
permissions
|
let mut query = DatabasePermissionQuery::new(db, &user).channel(&channel);
|
||||||
.has_permission(legacy_db, Permission::ManageWebhooks)
|
calculate_channel_permissions(&mut query)
|
||||||
.await?;
|
.await
|
||||||
|
.throw_if_lacking_channel_permission(ChannelPermission::ViewChannel)?;
|
||||||
|
|
||||||
Ok(Json(
|
Ok(Json(
|
||||||
db.fetch_webhooks_for_channel(channel.id())
|
db.fetch_webhooks_for_channel(&channel.id())
|
||||||
.await
|
.await?
|
||||||
.map_err(Error::from_core)?
|
|
||||||
.into_iter()
|
.into_iter()
|
||||||
.map(|v| v.into())
|
.map(|v| v.into())
|
||||||
.collect::<Vec<Webhook>>(),
|
.collect::<Vec<Webhook>>(),
|
||||||
|
|||||||
@@ -1,31 +1,11 @@
|
|||||||
use once_cell::sync::Lazy;
|
use revolt_config::config;
|
||||||
use regex::Regex;
|
use revolt_database::{util::permissions::DatabasePermissionQuery, Database, Emoji, File, User};
|
||||||
use revolt_quark::models::emoji::EmojiParent;
|
use revolt_models::v0;
|
||||||
use revolt_quark::models::{Emoji, File, User};
|
use revolt_permissions::{calculate_server_permissions, ChannelPermission};
|
||||||
use revolt_quark::variables::delta::MAX_EMOJI_COUNT;
|
use revolt_result::{create_error, Result};
|
||||||
use revolt_quark::{perms, Db, Error, Permission, Result};
|
|
||||||
use serde::Deserialize;
|
|
||||||
use validator::Validate;
|
use validator::Validate;
|
||||||
|
|
||||||
use rocket::serde::json::Json;
|
use rocket::{serde::json::Json, State};
|
||||||
|
|
||||||
/// Regex for valid emoji names
|
|
||||||
///
|
|
||||||
/// Alphanumeric and underscores
|
|
||||||
pub static RE_EMOJI: Lazy<Regex> = Lazy::new(|| Regex::new(r"^[a-z0-9_]+$").unwrap());
|
|
||||||
|
|
||||||
/// # Emoji Data
|
|
||||||
#[derive(Validate, Deserialize, JsonSchema)]
|
|
||||||
pub struct DataCreateEmoji {
|
|
||||||
/// Server name
|
|
||||||
#[validate(length(min = 1, max = 32), regex = "RE_EMOJI")]
|
|
||||||
name: String,
|
|
||||||
/// Parent information
|
|
||||||
parent: EmojiParent,
|
|
||||||
/// Whether the emoji is mature
|
|
||||||
#[serde(default)]
|
|
||||||
nsfw: bool,
|
|
||||||
}
|
|
||||||
|
|
||||||
/// # Create New Emoji
|
/// # Create New Emoji
|
||||||
///
|
///
|
||||||
@@ -33,41 +13,45 @@ pub struct DataCreateEmoji {
|
|||||||
#[openapi(tag = "Emojis")]
|
#[openapi(tag = "Emojis")]
|
||||||
#[put("/emoji/<id>", data = "<data>")]
|
#[put("/emoji/<id>", data = "<data>")]
|
||||||
pub async fn create_emoji(
|
pub async fn create_emoji(
|
||||||
db: &Db,
|
db: &State<Database>,
|
||||||
user: User,
|
user: User,
|
||||||
id: String,
|
id: String,
|
||||||
data: Json<DataCreateEmoji>,
|
data: Json<v0::DataCreateEmoji>,
|
||||||
) -> Result<Json<Emoji>> {
|
) -> Result<Json<v0::Emoji>> {
|
||||||
|
let config = config().await;
|
||||||
|
|
||||||
let data = data.into_inner();
|
let data = data.into_inner();
|
||||||
data.validate()
|
data.validate().map_err(|error| {
|
||||||
.map_err(|error| Error::FailedValidation { error })?;
|
create_error!(FailedValidation {
|
||||||
|
error: error.to_string()
|
||||||
|
})
|
||||||
|
})?;
|
||||||
|
|
||||||
// Bots cannot manage emojis
|
// Bots cannot manage emojis
|
||||||
if user.bot.is_some() {
|
if user.bot.is_some() {
|
||||||
return Err(Error::IsBot);
|
return Err(create_error!(IsBot));
|
||||||
}
|
}
|
||||||
|
|
||||||
// Validate we have permission to write into parent
|
// Validate we have permission to write into parent
|
||||||
match &data.parent {
|
match &data.parent {
|
||||||
EmojiParent::Server { id } => {
|
v0::EmojiParent::Server { id } => {
|
||||||
let server = db.fetch_server(id).await?;
|
let server = db.fetch_server(id).await?;
|
||||||
|
|
||||||
// Check for permission
|
// Check for permission
|
||||||
perms(&user)
|
let mut query = DatabasePermissionQuery::new(db, &user).server(&server);
|
||||||
.server(&server)
|
calculate_server_permissions(&mut query)
|
||||||
.throw_permission(db, Permission::ManageCustomisation)
|
.await
|
||||||
.await?;
|
.throw_if_lacking_channel_permission(ChannelPermission::ManageCustomisation)?;
|
||||||
|
|
||||||
// Check that there are no more than 100 emoji
|
// Check that we haven't hit the emoji limit
|
||||||
// ! FIXME: hardcoded upper limit
|
|
||||||
let emojis = db.fetch_emoji_by_parent_id(&server.id).await?;
|
let emojis = db.fetch_emoji_by_parent_id(&server.id).await?;
|
||||||
if emojis.len() > *MAX_EMOJI_COUNT {
|
if emojis.len() > config.features.limits.default.server_emoji {
|
||||||
return Err(Error::TooManyEmoji {
|
return Err(create_error!(TooManyEmoji {
|
||||||
max: *MAX_EMOJI_COUNT,
|
max: config.features.limits.default.server_emoji,
|
||||||
});
|
}));
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
EmojiParent::Detached => return Err(Error::InvalidOperation),
|
v0::EmojiParent::Detached => return Err(create_error!(InvalidOperation)),
|
||||||
};
|
};
|
||||||
|
|
||||||
// Find the relevant attachment
|
// Find the relevant attachment
|
||||||
@@ -76,7 +60,7 @@ pub async fn create_emoji(
|
|||||||
// Create the emoji object
|
// Create the emoji object
|
||||||
let emoji = Emoji {
|
let emoji = Emoji {
|
||||||
id,
|
id,
|
||||||
parent: data.parent,
|
parent: data.parent.into(),
|
||||||
creator_id: user.id,
|
creator_id: user.id,
|
||||||
name: data.name,
|
name: data.name,
|
||||||
animated: "image/gif" == &attachment.content_type,
|
animated: "image/gif" == &attachment.content_type,
|
||||||
@@ -85,5 +69,5 @@ pub async fn create_emoji(
|
|||||||
|
|
||||||
// Save emoji
|
// Save emoji
|
||||||
emoji.create(db).await?;
|
emoji.create(db).await?;
|
||||||
Ok(Json(emoji))
|
Ok(Json(emoji.into()))
|
||||||
}
|
}
|
||||||
@@ -1,19 +1,30 @@
|
|||||||
use revolt_quark::models::{emoji::EmojiParent, User};
|
use revolt_database::{
|
||||||
use revolt_quark::{perms, Db, EmptyResponse, Error, Permission, Ref, Result};
|
util::{permissions::DatabasePermissionQuery, reference::Reference},
|
||||||
|
Database, EmojiParent, User,
|
||||||
|
};
|
||||||
|
use revolt_permissions::{calculate_server_permissions, ChannelPermission};
|
||||||
|
use revolt_result::{create_error, Result};
|
||||||
|
|
||||||
|
use rocket::State;
|
||||||
|
use rocket_empty::EmptyResponse;
|
||||||
|
|
||||||
/// # Delete Emoji
|
/// # Delete Emoji
|
||||||
///
|
///
|
||||||
/// Delete an emoji by its id.
|
/// Delete an emoji by its id.
|
||||||
#[openapi(tag = "Emojis")]
|
#[openapi(tag = "Emojis")]
|
||||||
#[delete("/emoji/<id>")]
|
#[delete("/emoji/<emoji_id>")]
|
||||||
pub async fn delete_emoji(db: &Db, user: User, id: Ref) -> Result<EmptyResponse> {
|
pub async fn delete_emoji(
|
||||||
|
db: &State<Database>,
|
||||||
|
user: User,
|
||||||
|
emoji_id: Reference,
|
||||||
|
) -> Result<EmptyResponse> {
|
||||||
// Bots cannot manage emoji
|
// Bots cannot manage emoji
|
||||||
if user.bot.is_some() {
|
if user.bot.is_some() {
|
||||||
return Err(Error::IsBot);
|
return Err(create_error!(IsBot));
|
||||||
}
|
}
|
||||||
|
|
||||||
// Fetch the emoji
|
// Fetch the emoji
|
||||||
let emoji = id.as_emoji(db).await?;
|
let emoji = emoji_id.as_emoji(db).await?;
|
||||||
|
|
||||||
// If we uploaded the emoji, then we have permission to delete it
|
// If we uploaded the emoji, then we have permission to delete it
|
||||||
if emoji.creator_id != user.id {
|
if emoji.creator_id != user.id {
|
||||||
@@ -23,10 +34,10 @@ pub async fn delete_emoji(db: &Db, user: User, id: Ref) -> Result<EmptyResponse>
|
|||||||
let server = db.fetch_server(id).await?;
|
let server = db.fetch_server(id).await?;
|
||||||
|
|
||||||
// Check for permission
|
// Check for permission
|
||||||
perms(&user)
|
let mut query = DatabasePermissionQuery::new(db, &user).server(&server);
|
||||||
.server(&server)
|
calculate_server_permissions(&mut query)
|
||||||
.throw_permission(db, Permission::ManageCustomisation)
|
.await
|
||||||
.await?;
|
.throw_if_lacking_channel_permission(ChannelPermission::ManageCustomisation)?;
|
||||||
}
|
}
|
||||||
EmojiParent::Detached => return Ok(EmptyResponse),
|
EmojiParent::Detached => return Ok(EmptyResponse),
|
||||||
};
|
};
|
||||||
|
|||||||
@@ -1,13 +1,18 @@
|
|||||||
use revolt_quark::models::{Emoji, User};
|
use revolt_database::{util::reference::Reference, Database};
|
||||||
use revolt_quark::{Db, Ref, Result};
|
use revolt_models::v0;
|
||||||
|
use revolt_result::Result;
|
||||||
|
|
||||||
use rocket::serde::json::Json;
|
use rocket::{serde::json::Json, State};
|
||||||
|
|
||||||
/// # Fetch Emoji
|
/// # Fetch Emoji
|
||||||
///
|
///
|
||||||
/// Fetch an emoji by its id.
|
/// Fetch an emoji by its id.
|
||||||
#[openapi(tag = "Emojis")]
|
#[openapi(tag = "Emojis")]
|
||||||
#[get("/emoji/<id>")]
|
#[get("/emoji/<emoji_id>")]
|
||||||
pub async fn fetch_emoji(db: &Db, _user: User, id: Ref) -> Result<Json<Emoji>> {
|
pub async fn fetch_emoji(db: &State<Database>, emoji_id: Reference) -> Result<Json<v0::Emoji>> {
|
||||||
id.as_emoji(db).await.map(Json)
|
emoji_id
|
||||||
|
.as_emoji(db)
|
||||||
|
.await
|
||||||
|
.map(|emoji| emoji.into())
|
||||||
|
.map(Json)
|
||||||
}
|
}
|
||||||
@@ -1,5 +1,9 @@
|
|||||||
use revolt_database::{util::reference::Reference, Database};
|
use revolt_database::{
|
||||||
use revolt_quark::{models::User, perms, Db, Error, Permission, Result};
|
util::{permissions::DatabasePermissionQuery, reference::Reference},
|
||||||
|
Database, User,
|
||||||
|
};
|
||||||
|
use revolt_permissions::{calculate_channel_permissions, ChannelPermission};
|
||||||
|
use revolt_result::Result;
|
||||||
use rocket::State;
|
use rocket::State;
|
||||||
use rocket_empty::EmptyResponse;
|
use rocket_empty::EmptyResponse;
|
||||||
|
|
||||||
@@ -10,21 +14,16 @@ use rocket_empty::EmptyResponse;
|
|||||||
#[delete("/<webhook_id>")]
|
#[delete("/<webhook_id>")]
|
||||||
pub async fn webhook_delete(
|
pub async fn webhook_delete(
|
||||||
db: &State<Database>,
|
db: &State<Database>,
|
||||||
legacy_db: &Db,
|
|
||||||
user: User,
|
user: User,
|
||||||
webhook_id: Reference,
|
webhook_id: Reference,
|
||||||
) -> Result<EmptyResponse> {
|
) -> Result<EmptyResponse> {
|
||||||
let webhook = webhook_id.as_webhook(db).await.map_err(Error::from_core)?;
|
let webhook = webhook_id.as_webhook(db).await?;
|
||||||
let channel = legacy_db.fetch_channel(&webhook.channel_id).await?;
|
let channel = db.fetch_channel(&webhook.channel_id).await?;
|
||||||
|
|
||||||
perms(&user)
|
let mut query = DatabasePermissionQuery::new(db, &user).channel(&channel);
|
||||||
.channel(&channel)
|
calculate_channel_permissions(&mut query)
|
||||||
.throw_permission(legacy_db, Permission::ManageWebhooks)
|
|
||||||
.await?;
|
|
||||||
|
|
||||||
webhook
|
|
||||||
.delete(db)
|
|
||||||
.await
|
.await
|
||||||
.map(|_| EmptyResponse)
|
.throw_if_lacking_channel_permission(ChannelPermission::ManageWebhooks)?;
|
||||||
.map_err(Error::from_core)
|
|
||||||
|
webhook.delete(db).await.map(|_| EmptyResponse)
|
||||||
}
|
}
|
||||||
@@ -1,6 +1,10 @@
|
|||||||
use revolt_database::{util::reference::Reference, Database, PartialWebhook};
|
use revolt_database::{
|
||||||
|
util::{permissions::DatabasePermissionQuery, reference::Reference},
|
||||||
|
Database, PartialWebhook, User,
|
||||||
|
};
|
||||||
use revolt_models::v0::{DataEditWebhook, Webhook};
|
use revolt_models::v0::{DataEditWebhook, Webhook};
|
||||||
use revolt_quark::{models::User, perms, Db, Error, Permission, Result};
|
use revolt_permissions::{calculate_channel_permissions, ChannelPermission};
|
||||||
|
use revolt_result::{create_error, Result};
|
||||||
use rocket::{serde::json::Json, State};
|
use rocket::{serde::json::Json, State};
|
||||||
use validator::Validate;
|
use validator::Validate;
|
||||||
|
|
||||||
@@ -11,22 +15,24 @@ use validator::Validate;
|
|||||||
#[patch("/<webhook_id>", data = "<data>")]
|
#[patch("/<webhook_id>", data = "<data>")]
|
||||||
pub async fn webhook_edit(
|
pub async fn webhook_edit(
|
||||||
db: &State<Database>,
|
db: &State<Database>,
|
||||||
legacy_db: &Db,
|
|
||||||
webhook_id: Reference,
|
webhook_id: Reference,
|
||||||
user: User,
|
user: User,
|
||||||
data: Json<DataEditWebhook>,
|
data: Json<DataEditWebhook>,
|
||||||
) -> Result<Json<Webhook>> {
|
) -> Result<Json<Webhook>> {
|
||||||
let data = data.into_inner();
|
let data = data.into_inner();
|
||||||
data.validate()
|
data.validate().map_err(|error| {
|
||||||
.map_err(|error| Error::FailedValidation { error })?;
|
create_error!(FailedValidation {
|
||||||
|
error: error.to_string()
|
||||||
|
})
|
||||||
|
})?;
|
||||||
|
|
||||||
let mut webhook = webhook_id.as_webhook(db).await.map_err(Error::from_core)?;
|
let mut webhook = webhook_id.as_webhook(db).await?;
|
||||||
let channel = legacy_db.fetch_channel(&webhook.channel_id).await?;
|
let channel = db.fetch_channel(&webhook.channel_id).await?;
|
||||||
|
|
||||||
perms(&user)
|
let mut query = DatabasePermissionQuery::new(db, &user).channel(&channel);
|
||||||
.channel(&channel)
|
calculate_channel_permissions(&mut query)
|
||||||
.throw_permission(legacy_db, Permission::ManageWebhooks)
|
.await
|
||||||
.await?;
|
.throw_if_lacking_channel_permission(ChannelPermission::ManageWebhooks)?;
|
||||||
|
|
||||||
if data.name.is_none() && data.avatar.is_none() && data.remove.is_empty() {
|
if data.name.is_none() && data.avatar.is_none() && data.remove.is_empty() {
|
||||||
return Ok(Json(webhook.into()));
|
return Ok(Json(webhook.into()));
|
||||||
@@ -48,16 +54,14 @@ pub async fn webhook_edit(
|
|||||||
if let Some(avatar) = avatar {
|
if let Some(avatar) = avatar {
|
||||||
let file = db
|
let file = db
|
||||||
.find_and_use_attachment(&avatar, "avatars", "user", &webhook.id)
|
.find_and_use_attachment(&avatar, "avatars", "user", &webhook.id)
|
||||||
.await
|
.await?;
|
||||||
.map_err(Error::from_core)?;
|
|
||||||
|
|
||||||
partial.avatar = Some(file)
|
partial.avatar = Some(file)
|
||||||
}
|
}
|
||||||
|
|
||||||
webhook
|
webhook
|
||||||
.update(db, partial, remove.into_iter().map(|v| v.into()).collect())
|
.update(db, partial, remove.into_iter().map(|v| v.into()).collect())
|
||||||
.await
|
.await?;
|
||||||
.map_err(Error::from_core)?;
|
|
||||||
|
|
||||||
Ok(Json(webhook.into()))
|
Ok(Json(webhook.into()))
|
||||||
}
|
}
|
||||||
@@ -1,12 +1,10 @@
|
|||||||
use revolt_database::{
|
use revolt_database::{
|
||||||
util::{idempotency::IdempotencyKey, reference::Reference},
|
util::{idempotency::IdempotencyKey, reference::Reference},
|
||||||
Database,
|
Database, Message,
|
||||||
};
|
|
||||||
use revolt_quark::{
|
|
||||||
models::message::{DataMessageSend, Message},
|
|
||||||
types::push::MessageAuthor,
|
|
||||||
Db, Error, Result,
|
|
||||||
};
|
};
|
||||||
|
use revolt_models::v0;
|
||||||
|
use revolt_permissions::{ChannelPermission, PermissionValue};
|
||||||
|
use revolt_result::{create_error, Result};
|
||||||
use rocket::{serde::json::Json, State};
|
use rocket::{serde::json::Json, State};
|
||||||
|
|
||||||
use validator::Validate;
|
use validator::Validate;
|
||||||
@@ -18,31 +16,52 @@ use validator::Validate;
|
|||||||
#[post("/<webhook_id>/<token>", data = "<data>")]
|
#[post("/<webhook_id>/<token>", data = "<data>")]
|
||||||
pub async fn webhook_execute(
|
pub async fn webhook_execute(
|
||||||
db: &State<Database>,
|
db: &State<Database>,
|
||||||
legacy_db: &Db,
|
|
||||||
webhook_id: Reference,
|
webhook_id: Reference,
|
||||||
token: String,
|
token: String,
|
||||||
data: Json<DataMessageSend>,
|
data: Json<v0::DataMessageSend>,
|
||||||
idempotency: IdempotencyKey,
|
idempotency: IdempotencyKey,
|
||||||
) -> Result<Json<Message>> {
|
) -> Result<Json<v0::Message>> {
|
||||||
let data = data.into_inner();
|
let data = data.into_inner();
|
||||||
data.validate()
|
data.validate().map_err(|error| {
|
||||||
.map_err(|error| Error::FailedValidation { error })?;
|
create_error!(FailedValidation {
|
||||||
|
error: error.to_string()
|
||||||
|
})
|
||||||
|
})?;
|
||||||
|
|
||||||
let webhook = webhook_id.as_webhook(db).await.map_err(Error::from_core)?;
|
let webhook = webhook_id.as_webhook(db).await?;
|
||||||
webhook.assert_token(&token).map_err(Error::from_core)?;
|
webhook.assert_token(&token)?;
|
||||||
|
|
||||||
data.validate_webhook_permissions(webhook.permissions)?;
|
let permissions: PermissionValue = webhook.permissions.into();
|
||||||
|
permissions.throw_if_lacking_channel_permission(ChannelPermission::SendMessage)?;
|
||||||
|
|
||||||
let channel = legacy_db.fetch_channel(&webhook.channel_id).await?;
|
if data.attachments.as_ref().map_or(false, |v| !v.is_empty()) {
|
||||||
let message = channel
|
permissions.throw_if_lacking_channel_permission(ChannelPermission::UploadFiles)?;
|
||||||
.send_message(
|
}
|
||||||
legacy_db,
|
|
||||||
|
if data.embeds.as_ref().map_or(false, |v| !v.is_empty()) {
|
||||||
|
permissions.throw_if_lacking_channel_permission(ChannelPermission::SendEmbeds)?;
|
||||||
|
}
|
||||||
|
|
||||||
|
if data.masquerade.is_some() {
|
||||||
|
permissions.throw_if_lacking_channel_permission(ChannelPermission::Masquerade)?;
|
||||||
|
}
|
||||||
|
|
||||||
|
if data.interactions.is_some() {
|
||||||
|
permissions.throw_if_lacking_channel_permission(ChannelPermission::React)?;
|
||||||
|
}
|
||||||
|
|
||||||
|
let channel = db.fetch_channel(&webhook.channel_id).await?;
|
||||||
|
|
||||||
|
Ok(Json(
|
||||||
|
Message::create_from_api(
|
||||||
|
db,
|
||||||
|
channel,
|
||||||
data,
|
data,
|
||||||
MessageAuthor::Webhook(&webhook.into()),
|
v0::MessageAuthor::Webhook(&webhook.into()),
|
||||||
idempotency,
|
idempotency,
|
||||||
true,
|
true,
|
||||||
)
|
)
|
||||||
.await?;
|
.await?
|
||||||
|
.into(),
|
||||||
Ok(Json(message))
|
))
|
||||||
}
|
}
|
||||||
@@ -1,10 +1,6 @@
|
|||||||
use revolt_database::{util::reference::Reference, Database};
|
use revolt_database::{util::reference::Reference, Database, Message};
|
||||||
use revolt_models::v0::Webhook;
|
use revolt_models::v0::{MessageAuthor, SendableEmbed, Webhook};
|
||||||
use revolt_quark::{
|
use revolt_result::{create_error, Error, Result};
|
||||||
models::{message::SendableEmbed, Message},
|
|
||||||
types::push::MessageAuthor,
|
|
||||||
Db, Error, Result,
|
|
||||||
};
|
|
||||||
use revolt_rocket_okapi::{
|
use revolt_rocket_okapi::{
|
||||||
gen::OpenApiGenerator,
|
gen::OpenApiGenerator,
|
||||||
request::{OpenApiFromRequest, RequestHeaderInput},
|
request::{OpenApiFromRequest, RequestHeaderInput},
|
||||||
@@ -639,7 +635,7 @@ impl<'r> FromRequest<'r> for EventHeader<'r> {
|
|||||||
async fn from_request(request: &'r Request<'_>) -> rocket::request::Outcome<Self, Self::Error> {
|
async fn from_request(request: &'r Request<'_>) -> rocket::request::Outcome<Self, Self::Error> {
|
||||||
let headers = request.headers();
|
let headers = request.headers();
|
||||||
let Some(event) = headers.get_one("X-GitHub-Event") else {
|
let Some(event) = headers.get_one("X-GitHub-Event") else {
|
||||||
return rocket::request::Outcome::Failure((Status::BadRequest, Error::InvalidOperation))
|
return rocket::request::Outcome::Failure((Status::BadRequest, create_error!(InvalidOperation)))
|
||||||
};
|
};
|
||||||
|
|
||||||
rocket::request::Outcome::Success(Self(event))
|
rocket::request::Outcome::Success(Self(event))
|
||||||
@@ -702,7 +698,7 @@ fn safe_from_str<T: for<'de> Deserialize<'de>>(data: &str) -> Result<T> {
|
|||||||
Ok(output) => Ok(output),
|
Ok(output) => Ok(output),
|
||||||
Err(err) => {
|
Err(err) => {
|
||||||
log::error!("{err:?}");
|
log::error!("{err:?}");
|
||||||
Err(Error::InvalidOperation)
|
Err(create_error!(InvalidOperation))
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -727,7 +723,7 @@ fn convert_event(data: &str, event_name: &str) -> Result<Event> {
|
|||||||
"issue_comment" => BaseEvent::IssueComment(safe_from_str(data)?),
|
"issue_comment" => BaseEvent::IssueComment(safe_from_str(data)?),
|
||||||
"issues" => BaseEvent::Issues(safe_from_str(data)?),
|
"issues" => BaseEvent::Issues(safe_from_str(data)?),
|
||||||
"pull_request" => BaseEvent::PullRequest(safe_from_str(data)?),
|
"pull_request" => BaseEvent::PullRequest(safe_from_str(data)?),
|
||||||
_ => return Err(Error::InvalidOperation),
|
_ => return Err(create_error!(InvalidOperation)),
|
||||||
};
|
};
|
||||||
|
|
||||||
let _Event {
|
let _Event {
|
||||||
@@ -751,16 +747,15 @@ fn convert_event(data: &str, event_name: &str) -> Result<Event> {
|
|||||||
#[post("/<webhook_id>/<token>/github", data = "<data>")]
|
#[post("/<webhook_id>/<token>/github", data = "<data>")]
|
||||||
pub async fn webhook_execute_github(
|
pub async fn webhook_execute_github(
|
||||||
db: &State<Database>,
|
db: &State<Database>,
|
||||||
legacy_db: &Db,
|
|
||||||
webhook_id: Reference,
|
webhook_id: Reference,
|
||||||
token: String,
|
token: String,
|
||||||
event: EventHeader<'_>,
|
event: EventHeader<'_>,
|
||||||
data: String,
|
data: String,
|
||||||
) -> Result<()> {
|
) -> Result<()> {
|
||||||
let webhook = webhook_id.as_webhook(db).await.map_err(Error::from_core)?;
|
let webhook = webhook_id.as_webhook(db).await?;
|
||||||
webhook.assert_token(&token).map_err(Error::from_core)?;
|
webhook.assert_token(&token)?;
|
||||||
|
|
||||||
let channel = legacy_db.fetch_channel(&webhook.channel_id).await?;
|
let channel = db.fetch_channel(&webhook.channel_id).await?;
|
||||||
let event = convert_event(&data, &event)?;
|
let event = convert_event(&data, &event)?;
|
||||||
|
|
||||||
let sendable_embed = match event.event {
|
let sendable_embed = match event.event {
|
||||||
@@ -1058,30 +1053,25 @@ pub async fn webhook_execute_github(
|
|||||||
},
|
},
|
||||||
};
|
};
|
||||||
|
|
||||||
sendable_embed
|
sendable_embed.validate().map_err(|error| {
|
||||||
.validate()
|
create_error!(FailedValidation {
|
||||||
.map_err(|error| Error::FailedValidation { error })?;
|
error: error.to_string()
|
||||||
|
})
|
||||||
|
})?;
|
||||||
|
|
||||||
let message_id = Ulid::new().to_string();
|
let message_id = Ulid::new().to_string();
|
||||||
|
|
||||||
let embed = sendable_embed
|
|
||||||
.into_embed(legacy_db, &message_id)
|
|
||||||
.await?;
|
|
||||||
|
|
||||||
let mut message = Message {
|
let mut message = Message {
|
||||||
id: message_id,
|
id: message_id,
|
||||||
author: webhook.id.clone(),
|
author: webhook.id.clone(),
|
||||||
channel: webhook.channel_id.clone(),
|
channel: webhook.channel_id.clone(),
|
||||||
embeds: Some(vec![embed]),
|
|
||||||
webhook: Some(std::convert::Into::<Webhook>::into(webhook.clone()).into()),
|
webhook: Some(std::convert::Into::<Webhook>::into(webhook.clone()).into()),
|
||||||
..Default::default()
|
..Default::default()
|
||||||
};
|
};
|
||||||
|
|
||||||
|
#[allow(clippy::disallowed_methods)]
|
||||||
|
message.attach_sendable_embed(db, sendable_embed).await?;
|
||||||
message
|
message
|
||||||
.create(
|
.send(db, MessageAuthor::Webhook(&webhook.into()), &channel, false)
|
||||||
legacy_db,
|
|
||||||
&channel,
|
|
||||||
Some(MessageAuthor::Webhook(&webhook.into())),
|
|
||||||
)
|
|
||||||
.await
|
.await
|
||||||
}
|
}
|
||||||
@@ -1,6 +1,10 @@
|
|||||||
use revolt_database::{util::reference::Reference, Database};
|
use revolt_database::{
|
||||||
|
util::{permissions::DatabasePermissionQuery, reference::Reference},
|
||||||
|
Database, User,
|
||||||
|
};
|
||||||
use revolt_models::v0::{ResponseWebhook, Webhook};
|
use revolt_models::v0::{ResponseWebhook, Webhook};
|
||||||
use revolt_quark::{models::User, perms, Db, Error, Permission, Result};
|
use revolt_permissions::{calculate_channel_permissions, ChannelPermission};
|
||||||
|
use revolt_result::Result;
|
||||||
use rocket::{serde::json::Json, State};
|
use rocket::{serde::json::Json, State};
|
||||||
|
|
||||||
/// # Gets a webhook
|
/// # Gets a webhook
|
||||||
@@ -10,17 +14,16 @@ use rocket::{serde::json::Json, State};
|
|||||||
#[get("/<webhook_id>")]
|
#[get("/<webhook_id>")]
|
||||||
pub async fn webhook_fetch(
|
pub async fn webhook_fetch(
|
||||||
db: &State<Database>,
|
db: &State<Database>,
|
||||||
legacy_db: &Db,
|
|
||||||
webhook_id: Reference,
|
webhook_id: Reference,
|
||||||
user: User,
|
user: User,
|
||||||
) -> Result<Json<ResponseWebhook>> {
|
) -> Result<Json<ResponseWebhook>> {
|
||||||
let webhook = webhook_id.as_webhook(db).await.map_err(Error::from_core)?;
|
let webhook = webhook_id.as_webhook(db).await?;
|
||||||
let channel = legacy_db.fetch_channel(&webhook.channel_id).await?;
|
let channel = db.fetch_channel(&webhook.channel_id).await?;
|
||||||
|
|
||||||
perms(&user)
|
let mut query = DatabasePermissionQuery::new(db, &user).channel(&channel);
|
||||||
.channel(&channel)
|
calculate_channel_permissions(&mut query)
|
||||||
.throw_permission(legacy_db, Permission::ViewChannel)
|
.await
|
||||||
.await?;
|
.throw_if_lacking_channel_permission(ChannelPermission::ViewChannel)?;
|
||||||
|
|
||||||
Ok(Json(std::convert::Into::<Webhook>::into(webhook).into()))
|
Ok(Json(std::convert::Into::<Webhook>::into(webhook).into()))
|
||||||
}
|
}
|
||||||
@@ -1,6 +1,6 @@
|
|||||||
[package]
|
[package]
|
||||||
name = "revolt-quark"
|
name = "revolt-quark"
|
||||||
version = "0.6.7"
|
version = "0.6.8"
|
||||||
edition = "2021"
|
edition = "2021"
|
||||||
license = "AGPL-3.0-or-later"
|
license = "AGPL-3.0-or-later"
|
||||||
|
|
||||||
|
|||||||
@@ -1,4 +1,5 @@
|
|||||||
publish:
|
publish:
|
||||||
|
cargo publish --package revolt-config
|
||||||
cargo publish --package revolt-result
|
cargo publish --package revolt-result
|
||||||
cargo publish --package revolt-permissions
|
cargo publish --package revolt-permissions
|
||||||
cargo publish --package revolt-models
|
cargo publish --package revolt-models
|
||||||
|
|||||||
@@ -25,6 +25,7 @@ deps() {
|
|||||||
crates/bonfire/src \
|
crates/bonfire/src \
|
||||||
crates/delta/src \
|
crates/delta/src \
|
||||||
crates/quark/src \
|
crates/quark/src \
|
||||||
|
crates/core/config/src \
|
||||||
crates/core/database/src \
|
crates/core/database/src \
|
||||||
crates/core/models/src \
|
crates/core/models/src \
|
||||||
crates/core/permissions/src \
|
crates/core/permissions/src \
|
||||||
@@ -35,6 +36,7 @@ deps() {
|
|||||||
tee crates/delta/src/main.rs
|
tee crates/delta/src/main.rs
|
||||||
echo '' |
|
echo '' |
|
||||||
tee crates/quark/src/lib.rs |
|
tee crates/quark/src/lib.rs |
|
||||||
|
tee crates/core/config/src/lib.rs |
|
||||||
tee crates/core/database/src/lib.rs |
|
tee crates/core/database/src/lib.rs |
|
||||||
tee crates/core/models/src/lib.rs |
|
tee crates/core/models/src/lib.rs |
|
||||||
tee crates/core/permissions/src/lib.rs |
|
tee crates/core/permissions/src/lib.rs |
|
||||||
@@ -53,6 +55,7 @@ apps() {
|
|||||||
crates/bonfire/src/main.rs \
|
crates/bonfire/src/main.rs \
|
||||||
crates/delta/src/main.rs \
|
crates/delta/src/main.rs \
|
||||||
crates/quark/src/lib.rs \
|
crates/quark/src/lib.rs \
|
||||||
|
crates/core/config/src/lib.rs \
|
||||||
crates/core/database/src/lib.rs \
|
crates/core/database/src/lib.rs \
|
||||||
crates/core/models/src/lib.rs \
|
crates/core/models/src/lib.rs \
|
||||||
crates/core/permissions/src/lib.rs \
|
crates/core/permissions/src/lib.rs \
|
||||||
|
|||||||
Reference in new issue
Block a user