refactor(delta): port routes to core webhook models

This commit is contained in:
Paul Makles
2023-06-03 13:01:43 +01:00
parent f9f5a30e2c
commit 23188032ca
14 changed files with 647 additions and 471 deletions

View File

@@ -1,5 +1,9 @@
use revolt_quark::{models::{User, Webhook, File, Channel}, perms, Db, Error, Permission, Ref, Result};
use rocket::serde::json::Json;
use revolt_database::{Database, Webhook};
use revolt_quark::{
models::{Channel, User},
perms, Db, Error, Permission, Ref, Result,
};
use rocket::{serde::json::Json, State};
use serde::{Deserialize, Serialize};
use ulid::Ulid;
use validator::Validate;
@@ -10,46 +14,56 @@ pub struct CreateWebhookBody {
name: String,
#[validate(length(min = 1, max = 128))]
avatar: Option<String>
avatar: Option<String>,
}
/// # 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
#[openapi(tag = "Webhooks")]
#[post("/<target>/webhooks", data = "<data>")]
pub async fn req(db: &Db, user: User, target: Ref, data: Json<CreateWebhookBody>) -> Result<Json<Webhook>> {
pub async fn req(
db: &State<Database>,
legacy_db: &Db,
user: User,
target: Ref,
data: Json<CreateWebhookBody>,
) -> Result<Json<revolt_models::v0::Webhook>> {
let data = data.into_inner();
data.validate()
.map_err(|error| Error::FailedValidation { error })?;
let channel = target.as_channel(db).await?;
let channel = target.as_channel(legacy_db).await?;
if !matches!(channel, Channel::TextChannel { .. } | Channel::Group { .. }) {
return Err(Error::InvalidOperation)
return Err(Error::InvalidOperation);
}
let mut permissions = perms(&user).channel(&channel);
permissions
.has_permission(db, Permission::ManageWebhooks)
.has_permission(legacy_db, Permission::ManageWebhooks)
.await?;
let webhook_id = Ulid::new().to_string();
let avatar = match &data.avatar {
Some(id) => Some(File::use_avatar(db, id, &webhook_id).await?),
None => None
Some(id) => Some(
db.find_and_use_attachment(id, "avatars", "user", &webhook_id)
.await
.map_err(Error::from_core)?,
),
None => None,
};
let webhook = Webhook {
id: webhook_id,
name: data.name,
avatar,
channel: channel.id().to_string(),
token: Some(nanoid::nanoid!(64))
channel_id: channel.id().to_string(),
token: Some(nanoid::nanoid!(64)),
};
webhook.create(db).await?;
webhook.create(db).await.map_err(Error::from_core)?;
Ok(Json(webhook))
Ok(Json(webhook.into()))
}