Wip commit

This commit is contained in:
jude
2024-01-06 19:48:17 +00:00
parent cce0de7c75
commit e5e621be5c
22 changed files with 485 additions and 823 deletions

View File

@ -7,7 +7,7 @@ edition = "2018"
[dependencies]
rocket = { git = "https://github.com/SergioBenitez/Rocket", branch = "master", features = ["tls", "secrets", "json"] }
rocket_dyn_templates = { git = "https://github.com/SergioBenitez/Rocket", branch = "master", features = ["tera"] }
serenity = { version = "0.11", default-features = false, features = ["builder", "cache", "client", "gateway", "http", "model", "utils", "rustls_backend"] }
serenity = { version = "0.12", default-features = false, features = ["builder", "cache", "client", "gateway", "http", "model", "utils", "rustls_backend"] }
oauth2 = "4"
log = "0.4"
reqwest = "0.11"
@ -20,3 +20,4 @@ rand = "0.8"
base64 = "0.13"
csv = "1.2"
prometheus = "0.13.3"
secrecy = "0.8.0"

View File

@ -23,14 +23,13 @@ pub const CHARACTERS: &str = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWX
use std::{collections::HashSet, env, iter::FromIterator};
use lazy_static::lazy_static;
use serenity::model::prelude::AttachmentType;
use serenity::builder::CreateAttachment;
lazy_static! {
pub static ref DEFAULT_AVATAR: AttachmentType<'static> = (
pub static ref DEFAULT_AVATAR: CreateAttachment = CreateAttachment::bytes(
include_bytes!(concat!(env!("CARGO_MANIFEST_DIR"), "/../assets/webhook.jpg")) as &[u8],
"webhook.jpg",
)
.into();
);
pub static ref SUBSCRIPTION_ROLES: HashSet<u64> = HashSet::from_iter(
env::var("PATREON_ROLE_ID")
.map(|var| var

View File

@ -169,11 +169,11 @@ pub async fn check_subscription(cache_http: impl CacheHttp, user_id: impl Into<U
offline!(true);
if let Some(subscription_guild) = *CNC_GUILD {
let guild_member = GuildId(subscription_guild).member(cache_http, user_id).await;
let guild_member = GuildId::new(subscription_guild).member(cache_http, user_id).await;
if let Ok(member) = guild_member {
for role in member.roles {
if SUBSCRIPTION_ROLES.contains(role.as_u64()) {
if SUBSCRIPTION_ROLES.contains(&role.get()) {
return true;
}
}
@ -217,9 +217,9 @@ pub async fn check_authorization(
return Ok(());
}
match GuildId(guild).to_guild_cached(ctx) {
match GuildId::new(guild).to_guild_cached(ctx) {
Some(guild) => {
let member_res = guild.member(ctx, UserId(user_id)).await;
let member_res = guild.member(ctx, UserId::new(user_id)).await;
match member_res {
Err(_) => {

View File

@ -32,7 +32,7 @@ pub async fn get_guild_channels(
}])));
check_authorization(cookies, ctx.inner(), id).await?;
match GuildId(id).to_guild_cached(ctx.inner()) {
match GuildId::new(id).to_guild_cached(ctx.inner()) {
Some(guild) => {
let mut channels = guild
.channels

View File

@ -22,16 +22,16 @@ pub async fn get_guild_info(id: u64, cookies: &CookieJar<'_>, ctx: &State<Contex
offline!(Ok(json!({ "patreon": true, "name": "Guild" })));
check_authorization(cookies, ctx.inner(), id).await?;
match GuildId(id).to_guild_cached(ctx.inner()) {
match GuildId::new(id).to_guild_cached(ctx.inner()) {
Some(guild) => {
let member_res = GuildId(env::var("PATREON_GUILD_ID").unwrap().parse().unwrap())
let member_res = GuildId::new(env::var("PATREON_GUILD_ID").unwrap().parse().unwrap())
.member(&ctx.inner(), guild.owner_id)
.await;
let patreon = member_res.map_or(false, |member| {
member
.roles
.contains(&RoleId(env::var("PATREON_ROLE_ID").unwrap().parse().unwrap()))
.contains(&RoleId::new(env::var("PATREON_ROLE_ID").unwrap().parse().unwrap()))
});
Ok(json!({ "patreon": patreon, "name": guild.name }))

View File

@ -39,7 +39,7 @@ pub async fn get_user_info(
if let Some(user_id) =
cookies.get_private("userid").map(|u| u.value().parse::<u64>().ok()).flatten()
{
let member_res = GuildId(env::var("PATREON_GUILD_ID").unwrap().parse().unwrap())
let member_res = GuildId::new(env::var("PATREON_GUILD_ID").unwrap().parse().unwrap())
.member(&ctx.inner(), user_id)
.await;
@ -58,7 +58,7 @@ pub async fn get_user_info(
patreon: member_res.map_or(false, |member| {
member
.roles
.contains(&RoleId(env::var("PATREON_ROLE_ID").unwrap().parse().unwrap()))
.contains(&RoleId::new(env::var("PATREON_ROLE_ID").unwrap().parse().unwrap()))
}),
timezone,
};

View File

@ -8,8 +8,11 @@ use rocket::{
response::Redirect,
serde::json::json,
};
use secrecy::ExposeSecret;
use serde::{de, Deserialize, Deserializer, Serialize, Serializer};
use serenity::{
all::CacheHttp,
builder::CreateWebhook,
client::Context,
http::Http,
model::id::{ChannelId, GuildId, UserId},
@ -363,12 +366,12 @@ pub(crate) async fn create_reminder(
reminder: Reminder,
) -> JsonResult {
// check guild in db
match sqlx::query!("SELECT 1 as A FROM guilds WHERE guild = ?", guild_id.0)
match sqlx::query!("SELECT 1 as A FROM guilds WHERE guild = ?", guild_id.get())
.fetch_one(transaction.executor())
.await
{
Err(sqlx::Error::RowNotFound) => {
if sqlx::query!("INSERT INTO guilds (guild) VALUES (?)", guild_id.0)
if sqlx::query!("INSERT INTO guilds (guild) VALUES (?)", guild_id.get())
.execute(transaction.executor())
.await
.is_err()
@ -380,11 +383,11 @@ pub(crate) async fn create_reminder(
}
// validate channel
let channel = ChannelId(reminder.channel).to_channel_cached(&ctx);
let channel = ChannelId::new(reminder.channel).to_channel_cached(&ctx.cache);
let channel_exists = channel.is_some();
let channel_matches_guild =
channel.map_or(false, |c| c.guild().map_or(false, |c| c.guild_id == guild_id));
channel.map_or(false, |c| c.guild(&ctx.cache).map_or(false, |c| c.id == guild_id));
if !channel_matches_guild || !channel_exists {
warn!(
@ -395,7 +398,8 @@ pub(crate) async fn create_reminder(
return Err(json!({"error": "Channel not found"}));
}
let channel = create_database_channel(&ctx, ChannelId(reminder.channel), transaction).await;
let channel =
create_database_channel(&ctx, ChannelId::new(reminder.channel), transaction).await;
if let Err(e) = channel {
warn!("`create_database_channel` returned an error code: {:?}", e);
@ -590,28 +594,34 @@ pub(crate) async fn create_reminder(
}
async fn create_database_channel(
ctx: impl AsRef<Http>,
ctx: impl CacheHttp,
channel: ChannelId,
transaction: &mut Transaction<'_>,
) -> Result<u32, crate::Error> {
let row =
sqlx::query!("SELECT webhook_token, webhook_id FROM channels WHERE channel = ?", channel.0)
.fetch_one(transaction.executor())
.await;
let row = sqlx::query!(
"SELECT webhook_token, webhook_id FROM channels WHERE channel = ?",
channel.get()
)
.fetch_one(transaction.executor())
.await;
match row {
Ok(row) => {
if row.webhook_token.is_none() || row.webhook_id.is_none() {
let webhook = channel
.create_webhook_with_avatar(&ctx, "Reminder", DEFAULT_AVATAR.clone())
.create_webhook(&ctx, CreateWebhook::new("Reminder").avatar(&*DEFAULT_AVATAR))
.await
.map_err(|e| Error::Serenity(e))?;
let token = webhook.token.unwrap();
sqlx::query!(
"UPDATE channels SET webhook_id = ?, webhook_token = ? WHERE channel = ?",
webhook.id.0,
webhook.token,
channel.0
"
UPDATE channels SET webhook_id = ?, webhook_token = ? WHERE channel = ?
",
webhook.id.get(),
token.expose_secret(),
channel.get()
)
.execute(transaction.executor())
.await
@ -624,20 +634,24 @@ async fn create_database_channel(
Err(sqlx::Error::RowNotFound) => {
// create webhook
let webhook = channel
.create_webhook_with_avatar(&ctx, "Reminder", DEFAULT_AVATAR.clone())
.create_webhook(&ctx, CreateWebhook::new("Reminder").avatar(&*DEFAULT_AVATAR))
.await
.map_err(|e| Error::Serenity(e))?;
let token = webhook.token.unwrap();
// create database entry
sqlx::query!(
"INSERT INTO channels (
"
INSERT INTO channels (
webhook_id,
webhook_token,
channel
) VALUES (?, ?, ?)",
webhook.id.0,
webhook.token,
channel.0
) VALUES (?, ?, ?)
",
webhook.id.get(),
token.expose_secret(),
channel.get()
)
.execute(transaction.executor())
.await
@ -649,7 +663,7 @@ async fn create_database_channel(
Err(e) => Err(Error::SQLx(e)),
}?;
let row = sqlx::query!("SELECT id FROM channels WHERE channel = ?", channel.0)
let row = sqlx::query!("SELECT id FROM channels WHERE channel = ?", channel.get())
.fetch_one(transaction.executor())
.await
.map_err(|e| Error::SQLx(e))?;

View File

@ -102,10 +102,9 @@ pub async fn discord_callback(
match user_res {
Ok(user) => {
let user_name = format!("{}#{}", user.name, user.discriminator);
let user_id = user.id.as_u64().to_string();
let user_id = user.id.get().to_string();
cookies.add_private(Cookie::new("username", user_name));
cookies.add_private(Cookie::new("username", user.name));
cookies.add_private(Cookie::new("userid", user_id));
Ok(Redirect::to(uri!(super::return_to_same_site("dashboard"))))