From c3c0dbbbaecec0ad72218cb35eb73c02df050950 Mon Sep 17 00:00:00 2001 From: jude Date: Wed, 21 Jun 2023 13:26:28 +0100 Subject: [PATCH] Fetch upcoming schedule and backlog count --- web/src/lib.rs | 2 +- web/src/routes/admin.rs | 53 ++++++++++++++++++++++++++++++++++++++++- 2 files changed, 53 insertions(+), 2 deletions(-) diff --git a/web/src/lib.rs b/web/src/lib.rs index 0486cb3..a0b5cf6 100644 --- a/web/src/lib.rs +++ b/web/src/lib.rs @@ -168,7 +168,7 @@ pub async fn initialize( routes::dashboard::export::import_todos, ], ) - .mount("/admin", routes![routes::admin::admin_dashboard_home]) + .mount("/admin", routes![routes::admin::admin_dashboard_home, routes::admin::bot_data]) .launch() .await?; diff --git a/web/src/routes/admin.rs b/web/src/routes/admin.rs index 473d30d..b5f3392 100644 --- a/web/src/routes/admin.rs +++ b/web/src/routes/admin.rs @@ -1,10 +1,22 @@ use std::{collections::HashMap, env}; +use chrono::{DateTime, Utc}; use rocket::{ http::{CookieJar, Status}, - serde::json::{json, Json}, + serde::json::json, + State, }; use rocket_dyn_templates::Template; +use serde::Serialize; +use sqlx::{MySql, Pool}; + +use crate::routes::JsonResult; + +fn is_admin(cookies: &CookieJar<'_>) -> bool { + cookies + .get_private("userid") + .map_or(false, |cookie| Some(cookie.value().to_string()) == env::var("ADMIN_ID").ok()) +} #[get("/")] pub async fn admin_dashboard_home(cookies: &CookieJar<'_>) -> Result { @@ -19,3 +31,42 @@ pub async fn admin_dashboard_home(cookies: &CookieJar<'_>) -> Result, + count: i64, +} + +#[get("/data")] +pub async fn bot_data(cookies: &CookieJar<'_>, pool: &State>) -> JsonResult { + if !is_admin(cookies) { + return json_err!("Not authorized"); + } + + let backlog = sqlx::query!( + "SELECT COUNT(1) AS backlog FROM reminders WHERE `utc_time` < NOW() AND enabled = 1" + ) + .fetch_one(pool.inner()) + .await + .unwrap(); + + let schedule = sqlx::query_as_unchecked!( + TimeFrame, + "SELECT + FROM_UNIXTIME(FLOOR(UNIX_TIMESTAMP(`utc_time`) / 60) * 60) AS `time_key`, + COUNT(1) AS `count` + FROM reminders + WHERE + `utc_time` < DATE_ADD(NOW(), INTERVAL 1 DAY) AND + `utc_time` >= NOW() AND + `enabled` = 1 + GROUP BY `time_key` + ORDER BY `time_key`" + ) + .fetch_all(pool.inner()) + .await + .unwrap(); + + Ok(json!({ "backlog": backlog.backlog, "schedule": schedule })) +}