captcha stats

This commit is contained in:
realaravinth 2021-07-27 15:28:21 +05:30
parent 9bc11f3518
commit 1d759fcb25
No known key found for this signature in database
GPG key ID: AD9F0F08E855ED88
18 changed files with 249 additions and 159 deletions

View file

@ -14,6 +14,19 @@
"nullable": [] "nullable": []
} }
}, },
"044e2036a518de2ccac9318ccba07f7ce10e4a1c1d51d0128ea5e8cb94358ac5": {
"query": "INSERT INTO mcaptcha_pow_confirmed_stats \n (config_id, time) VALUES ((SELECT config_id FROM mcaptcha_config WHERE key = $1), $2)",
"describe": {
"columns": [],
"parameters": {
"Left": [
"Text",
"Timestamptz"
]
},
"nullable": []
}
},
"06699fda6b1542bf4544c0bdece91531a3020c24c9c76bcf967980e71ee25b42": { "06699fda6b1542bf4544c0bdece91531a3020c24c9c76bcf967980e71ee25b42": {
"query": "SELECT email, secret FROM mcaptcha_users WHERE name = ($1)", "query": "SELECT email, secret FROM mcaptcha_users WHERE name = ($1)",
"describe": { "describe": {
@ -40,38 +53,6 @@
] ]
} }
}, },
"174457087e02e07bfe52618cc8b5525067fa1722684f37a30004074a499774ee": {
"query": "SELECT time FROM mcaptcha_pow_confirmed_stats WHERE config_id = (\n SELECT config_id FROM mcaptcha_config where key = $1)",
"describe": {
"columns": [
{
"ordinal": 0,
"name": "time",
"type_info": "Timestamptz"
}
],
"parameters": {
"Left": [
"Text"
]
},
"nullable": [
false
]
}
},
"1be6274d5cc6d16f38285b8a62c9f66e8c3014cd403bc599598e911023bfeedb": {
"query": "INSERT INTO mcaptcha_pow_fetched_stats \n (config_id) VALUES ((SELECT config_id FROM mcaptcha_config WHERE key = $1))",
"describe": {
"columns": [],
"parameters": {
"Left": [
"Text"
]
},
"nullable": []
}
},
"238569a64d7dbd252e3b27204f207e8a8548109717b89495ddf8f9a870c7c75d": { "238569a64d7dbd252e3b27204f207e8a8548109717b89495ddf8f9a870c7c75d": {
"query": "UPDATE mcaptcha_config SET name = $1, duration = $2 \n WHERE user_id = (SELECT ID FROM mcaptcha_users WHERE name = $3)\n AND key = $4", "query": "UPDATE mcaptcha_config SET name = $1, duration = $2 \n WHERE user_id = (SELECT ID FROM mcaptcha_users WHERE name = $3)\n AND key = $4",
"describe": { "describe": {
@ -168,6 +149,27 @@
] ]
} }
}, },
"4303f5c6ef98e0de9d8d3c2d781d3ffaa3dee5f7d27db831d327b26f03ba9d68": {
"query": "SELECT time FROM mcaptcha_pow_confirmed_stats \n WHERE \n config_id = (\n SELECT config_id FROM mcaptcha_config \n WHERE \n key = $1\n AND\n user_id = (\n SELECT \n ID FROM mcaptcha_users WHERE name = $2))\n ORDER BY time DESC",
"describe": {
"columns": [
{
"ordinal": 0,
"name": "time",
"type_info": "Timestamptz"
}
],
"parameters": {
"Left": [
"Text",
"Text"
]
},
"nullable": [
false
]
}
},
"45d9e9fb6344fe3a18c2529d50c935d3837bfe25c96595beb6970d6067720578": { "45d9e9fb6344fe3a18c2529d50c935d3837bfe25c96595beb6970d6067720578": {
"query": "insert into mcaptcha_users \n (name , password, email, secret) values ($1, $2, $3, $4)", "query": "insert into mcaptcha_users \n (name , password, email, secret) values ($1, $2, $3, $4)",
"describe": { "describe": {
@ -339,13 +341,14 @@
] ]
} }
}, },
"73b9bddce90d59193430c5ec38b77ad7bc0e94bac74dcde7ab9949a86cfbddca": { "726a794f7599b78ab749d9f887f5c28db38f072b41f691bde35d23ba0dd72409": {
"query": "INSERT INTO mcaptcha_pow_solved_stats \n (config_id) VALUES ((SELECT config_id FROM mcaptcha_config WHERE key = $1))", "query": "INSERT INTO mcaptcha_pow_fetched_stats \n (config_id, time) VALUES ((SELECT config_id FROM mcaptcha_config WHERE key = $1), $2)",
"describe": { "describe": {
"columns": [], "columns": [],
"parameters": { "parameters": {
"Left": [ "Left": [
"Text" "Text",
"Timestamptz"
] ]
}, },
"nullable": [] "nullable": []
@ -404,8 +407,8 @@
"nullable": [] "nullable": []
} }
}, },
"85a3482fc65dab99cd01f51411f0567d303018bbb6483a0020db33180ce12cfb": { "84484cb6892db29121816bc5bff5702b9e857e20aa14e79d080d78ae7593153b": {
"query": "SELECT time FROM mcaptcha_pow_solved_stats WHERE config_id = \n (SELECT config_id FROM mcaptcha_config where key = $1)", "query": "SELECT time FROM mcaptcha_pow_solved_stats \n WHERE config_id = (\n SELECT config_id FROM mcaptcha_config \n WHERE \n key = $1\n AND\n user_id = (\n SELECT \n ID FROM mcaptcha_users WHERE name = $2)) \n ORDER BY time DESC",
"describe": { "describe": {
"columns": [ "columns": [
{ {
@ -416,6 +419,7 @@
], ],
"parameters": { "parameters": {
"Left": [ "Left": [
"Text",
"Text" "Text"
] ]
}, },
@ -450,18 +454,6 @@
] ]
} }
}, },
"931879575bb70dece5596bfae18f55a628d10627e4b6825e54642b254ca4ee64": {
"query": "INSERT INTO mcaptcha_pow_confirmed_stats \n (config_id) VALUES ((SELECT config_id FROM mcaptcha_config WHERE key = $1))",
"describe": {
"columns": [],
"parameters": {
"Left": [
"Text"
]
},
"nullable": []
}
},
"94901d49666b3097b1fed832966697c4a1e3937beb2bd0431df4857402a4de04": { "94901d49666b3097b1fed832966697c4a1e3937beb2bd0431df4857402a4de04": {
"query": "INSERT INTO mcaptcha_levels (\n difficulty_factor, \n visitor_threshold,\n config_id) VALUES (\n $1, $2, (\n SELECT config_id FROM mcaptcha_config WHERE key = ($3) AND\n user_id = (\n SELECT ID from mcaptcha_users WHERE name = $4\n )\n ));", "query": "INSERT INTO mcaptcha_levels (\n difficulty_factor, \n visitor_threshold,\n config_id) VALUES (\n $1, $2, (\n SELECT config_id FROM mcaptcha_config WHERE key = ($3) AND\n user_id = (\n SELECT ID from mcaptcha_users WHERE name = $4\n )\n ));",
"describe": { "describe": {
@ -595,6 +587,27 @@
] ]
} }
}, },
"c399efd5db1284dcb470c40f9b076851f77498c75a63a3b151d4a111bd3e2957": {
"query": "SELECT time FROM mcaptcha_pow_fetched_stats\n WHERE \n config_id = (\n SELECT \n config_id FROM mcaptcha_config \n WHERE \n key = $1\n AND\n user_id = (\n SELECT \n ID FROM mcaptcha_users WHERE name = $2))\n ORDER BY time DESC",
"describe": {
"columns": [
{
"ordinal": 0,
"name": "time",
"type_info": "Timestamptz"
}
],
"parameters": {
"Left": [
"Text",
"Text"
]
},
"nullable": [
false
]
}
},
"ca9d5241f1234d1825f7ead391ebe9099fca776e7101ac6e1761881606def5fa": { "ca9d5241f1234d1825f7ead391ebe9099fca776e7101ac6e1761881606def5fa": {
"query": "DELETE FROM mcaptcha_users WHERE name = ($1)", "query": "DELETE FROM mcaptcha_users WHERE name = ($1)",
"describe": { "describe": {
@ -620,6 +633,19 @@
"nullable": [] "nullable": []
} }
}, },
"dbe4307651d94bc6db4f1d8b2c6d076fde6280983d59593216d7765cbbdd669c": {
"query": "INSERT INTO mcaptcha_pow_solved_stats \n (config_id, time) VALUES ((SELECT config_id FROM mcaptcha_config WHERE key = $1), $2)",
"describe": {
"columns": [],
"parameters": {
"Left": [
"Text",
"Timestamptz"
]
},
"nullable": []
}
},
"dcf0d4f9d803dcb1d6f775899f79595f9c78d46633e0ec822303284430df7a3d": { "dcf0d4f9d803dcb1d6f775899f79595f9c78d46633e0ec822303284430df7a3d": {
"query": "-- gets all unread notifications a user has\nSELECT \n mcaptcha_notifications.id,\n mcaptcha_notifications.heading,\n mcaptcha_notifications.message,\n mcaptcha_notifications.received,\n mcaptcha_users.name\nFROM\n mcaptcha_notifications \nINNER JOIN \n mcaptcha_users \nON \n mcaptcha_notifications.tx = mcaptcha_users.id\nWHERE \n mcaptcha_notifications.rx = (\n SELECT \n id \n FROM \n mcaptcha_users\n WHERE\n name = $1\n )\nAND \n mcaptcha_notifications.read IS NULL;\n", "query": "-- gets all unread notifications a user has\nSELECT \n mcaptcha_notifications.id,\n mcaptcha_notifications.heading,\n mcaptcha_notifications.message,\n mcaptcha_notifications.received,\n mcaptcha_users.name\nFROM\n mcaptcha_notifications \nINNER JOIN \n mcaptcha_users \nON \n mcaptcha_notifications.tx = mcaptcha_users.id\nWHERE \n mcaptcha_notifications.rx = (\n SELECT \n id \n FROM \n mcaptcha_users\n WHERE\n name = $1\n )\nAND \n mcaptcha_notifications.read IS NULL;\n",
"describe": { "describe": {
@ -711,25 +737,5 @@
}, },
"nullable": [] "nullable": []
} }
},
"fc6b52054ea35458f597bcd3bd9a99029fca816f1e65a9e12cfd7ea4acc33838": {
"query": "SELECT time FROM mcaptcha_pow_fetched_stats WHERE config_id = \n (SELECT config_id FROM mcaptcha_config where key = $1)",
"describe": {
"columns": [
{
"ordinal": 0,
"name": "time",
"type_info": "Timestamptz"
}
],
"parameters": {
"Left": [
"Text"
]
},
"nullable": [
false
]
}
} }
} }

View file

@ -257,8 +257,10 @@ pub struct StatsPayload {
async fn get_stats( async fn get_stats(
payload: web::Json<StatsPayload>, payload: web::Json<StatsPayload>,
data: AppData, data: AppData,
id: Identity,
) -> ServiceResult<impl Responder> { ) -> ServiceResult<impl Responder> {
let stats = Stats::new(&payload.key, &data.db).await?; let username = id.identity().unwrap();
let stats = Stats::new(&username, &payload.key, &data.db).await?;
let stats = StatsUnixTimestamp::from_stats(&stats); let stats = StatsUnixTimestamp::from_stats(&stats);
Ok(HttpResponse::Ok().json(&stats)) Ok(HttpResponse::Ok().json(&stats))
} }

View file

@ -139,7 +139,7 @@ async fn update_levels(
defense.build()?; defense.build()?;
let mut futs = Vec::with_capacity(payload.levels.len() + 2); let mut futs = Vec::with_capacity(payload.levels.len() + 2);
let del_fut = sqlx::query!( sqlx::query!(
"DELETE FROM mcaptcha_levels "DELETE FROM mcaptcha_levels
WHERE config_id = ( WHERE config_id = (
SELECT config_id FROM mcaptcha_config where key = ($1) SELECT config_id FROM mcaptcha_config where key = ($1)
@ -150,7 +150,8 @@ async fn update_levels(
&payload.key, &payload.key,
&username &username
) )
.execute(&data.db); //.await?; .execute(&data.db)
.await?;
let update_fut = sqlx::query!( let update_fut = sqlx::query!(
"UPDATE mcaptcha_config SET name = $1, duration = $2 "UPDATE mcaptcha_config SET name = $1, duration = $2
@ -163,7 +164,6 @@ async fn update_levels(
) )
.execute(&data.db); //.await?; .execute(&data.db); //.await?;
futs.push(del_fut);
futs.push(update_fut); futs.push(update_fut);
for level in payload.levels.iter() { for level in payload.levels.iter() {
@ -291,9 +291,7 @@ mod tests {
assert_eq!(res_levels, add_level.levels); assert_eq!(res_levels, add_level.levels);
// 3. update level // 3. update level
let levels = vec![L1, L2]; let levels = vec![L1, L2];
let update_level = UpdateLevels { let update_level = UpdateLevels {
key: key.key.clone(), key: key.key.clone(),
levels: levels.clone(), levels: levels.clone(),

View file

@ -65,7 +65,10 @@ pub async fn get_config(
match res.exists { match res.exists {
Some(true) => { Some(true) => {
match data.captcha.get_pow(payload.key.clone()).await { match data.captcha.get_pow(payload.key.clone()).await {
Some(config) => Ok(HttpResponse::Ok().json(config)), Some(config) => {
record_fetch(&payload.key, &data.db).await;
Ok(HttpResponse::Ok().json(config))
}
None => { None => {
init_mcaptcha(&data, &payload.key).await?; init_mcaptcha(&data, &payload.key).await?;
let config = data let config = data

View file

@ -14,12 +14,23 @@
* You should have received a copy of the GNU Affero General Public License * You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>. * along with this program. If not, see <https://www.gnu.org/licenses/>.
*/ */
use std::fmt::Debug;
use sqlx::types::time::OffsetDateTime; use sqlx::types::time::OffsetDateTime;
#[derive(Clone)]
pub struct Date { pub struct Date {
pub time: OffsetDateTime, pub time: OffsetDateTime,
} }
impl Debug for Date {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("Date")
.field("time", &self.print_date())
.finish()
}
}
pub const MINUTE: i64 = 60; pub const MINUTE: i64 = 60;
pub const HOUR: i64 = MINUTE * 60; pub const HOUR: i64 = MINUTE * 60;
pub const DAY: i64 = HOUR * 24; pub const DAY: i64 = HOUR * 24;
@ -45,9 +56,15 @@ impl Date {
} }
} }
/// print relative time from date
pub fn print_date(&self) -> String { pub fn print_date(&self) -> String {
Self::format(&self.time) Self::format(&self.time)
} }
/// print date
pub fn date(&self) -> String {
self.time.format("%F %r %z")
}
} }
#[cfg(test)] #[cfg(test)]

View file

@ -66,7 +66,6 @@ pub mod routes {
pub sitekey: Sitekey, pub sitekey: Sitekey,
pub notifications: &'static str, pub notifications: &'static str,
pub settings: Settings, pub settings: Settings,
pub stats: &'static str,
} }
impl Panel { impl Panel {
@ -76,11 +75,10 @@ pub mod routes {
sitekey: Sitekey::new(), sitekey: Sitekey::new(),
notifications: "/notifications", notifications: "/notifications",
settings: Settings::new(), settings: Settings::new(),
stats: "/stats",
} }
} }
pub const fn get_sitemap() -> [&'static str; 6] { pub const fn get_sitemap() -> [&'static str; 5] {
const PANEL: Panel = Panel::new(); const PANEL: Panel = Panel::new();
const S: [&str; 2] = Sitekey::get_sitemap(); const S: [&str; 2] = Sitekey::get_sitemap();
@ -90,7 +88,6 @@ pub mod routes {
S[0], S[0],
S[1], S[1],
Settings::get_sitemap()[0], Settings::get_sitemap()[0],
PANEL.stats,
] ]
} }
} }

View file

@ -16,11 +16,9 @@
*/ */
use actix_identity::Identity; use actix_identity::Identity;
use actix_web::{web, HttpResponse, Responder}; use actix_web::{web, HttpResponse, Responder};
use futures::{future::TryFutureExt, try_join};
use sailfish::TemplateOnce; use sailfish::TemplateOnce;
use crate::errors::*; use crate::errors::*;
use crate::stats::fetch::Stats;
use crate::AppData; use crate::AppData;
const PAGE: &str = "SiteKeys"; const PAGE: &str = "SiteKeys";
@ -79,7 +77,7 @@ pub async fn edit_sitekey(
.fetch_one(&data.db) .fetch_one(&data.db)
.await?; .await?;
let levels_fut = sqlx::query_as!( let levels = sqlx::query_as!(
Level, Level,
"SELECT "SELECT
difficulty_factor, visitor_threshold difficulty_factor, visitor_threshold
@ -89,9 +87,7 @@ pub async fn edit_sitekey(
&config.config_id &config.config_id
) )
.fetch_all(&data.db) .fetch_all(&data.db)
.err_into(); .await?;
let (_stats, levels) = try_join!(Stats::new(&key, &data.db), levels_fut)?;
let body = IndexPage::new(config, levels, key).render_once().unwrap(); let body = IndexPage::new(config, levels, key).render_once().unwrap();
Ok(HttpResponse::Ok() Ok(HttpResponse::Ok()

View file

@ -45,15 +45,22 @@ struct IndexPage {
name: String, name: String,
key: String, key: String,
levels: Vec<Level>, levels: Vec<Level>,
stats: Stats,
} }
impl IndexPage { impl IndexPage {
fn new(config: McaptchaConfig, levels: Vec<Level>, key: String) -> Self { fn new(
stats: Stats,
config: McaptchaConfig,
levels: Vec<Level>,
key: String,
) -> Self {
IndexPage { IndexPage {
duration: config.duration as u32, duration: config.duration as u32,
name: config.name, name: config.name,
levels, levels,
key, key,
stats,
} }
} }
} }
@ -91,9 +98,11 @@ pub async fn view_sitekey(
.fetch_all(&data.db) .fetch_all(&data.db)
.err_into(); .err_into();
let (_stats, levels) = try_join!(Stats::new(&key, &data.db), levels_fut)?; let (stats, levels) = try_join!(Stats::new(&username, &key, &data.db), levels_fut)?;
let body = IndexPage::new(config, levels, key).render_once().unwrap(); let body = IndexPage::new(stats, config, levels, key)
.render_once()
.unwrap();
Ok(HttpResponse::Ok() Ok(HttpResponse::Ok()
.content_type("text/html; charset=utf-8") .content_type("text/html; charset=utf-8")
.body(body)) .body(body))

View file

@ -14,13 +14,11 @@
* You should have received a copy of the GNU Affero General Public License * You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>. * along with this program. If not, see <https://www.gnu.org/licenses/>.
*/ */
use actix_web::{web, HttpResponse, Responder};
use serde::{Deserialize, Serialize}; use serde::{Deserialize, Serialize};
use sqlx::PgPool; use sqlx::PgPool;
use crate::date::Date; use crate::date::Date;
use crate::errors::*; use crate::errors::*;
use crate::AppData;
#[derive(Debug, Clone, Deserialize, Serialize)] #[derive(Debug, Clone, Deserialize, Serialize)]
pub struct StatsUnixTimestamp { pub struct StatsUnixTimestamp {
@ -29,6 +27,7 @@ pub struct StatsUnixTimestamp {
pub confirms: Vec<i64>, pub confirms: Vec<i64>,
} }
#[derive(Debug, Clone)]
pub struct Stats { pub struct Stats {
pub config_fetches: Vec<Date>, pub config_fetches: Vec<Date>,
pub solves: Vec<Date>, pub solves: Vec<Date>,
@ -40,21 +39,11 @@ pub struct StatsPayload {
pub key: String, pub key: String,
} }
#[my_codegen::post(path = "crate::V1_API_ROUTES.auth.login", wrap = "crate::CheckLogin")]
async fn get_stats(
payload: web::Json<StatsPayload>,
data: AppData,
) -> ServiceResult<impl Responder> {
let stats = Stats::new(&payload.key, &data.db).await?;
let stats = StatsUnixTimestamp::from_stats(&stats);
Ok(HttpResponse::Ok().json(&stats))
}
impl Stats { impl Stats {
pub async fn new(key: &str, db: &PgPool) -> ServiceResult<Self> { pub async fn new(user: &str, key: &str, db: &PgPool) -> ServiceResult<Self> {
let config_fetches_fut = runners::fetch_config_fetched(key, db); let config_fetches_fut = runners::fetch_config_fetched(user, key, db);
let solves_fut = runners::fetch_solve(key, db); let solves_fut = runners::fetch_solve(user, key, db);
let confirms_fut = runners::fetch_confirm(key, db); let confirms_fut = runners::fetch_confirm(user, key, db);
let (config_fetches, solves, confirms) = let (config_fetches, solves, confirms) =
futures::try_join!(config_fetches_fut, solves_fut, confirms_fut)?; futures::try_join!(config_fetches_fut, solves_fut, confirms_fut)?;
@ -99,14 +88,26 @@ pub mod runners {
/// featch PoWConfig fetches /// featch PoWConfig fetches
#[inline] #[inline]
pub async fn fetch_config_fetched( pub async fn fetch_config_fetched(
user: &str,
key: &str, key: &str,
db: &PgPool, db: &PgPool,
) -> ServiceResult<Vec<Date>> { ) -> ServiceResult<Vec<Date>> {
let records = sqlx::query_as!( let records = sqlx::query_as!(
Date, Date,
"SELECT time FROM mcaptcha_pow_fetched_stats WHERE config_id = "SELECT time FROM mcaptcha_pow_fetched_stats
(SELECT config_id FROM mcaptcha_config where key = $1)", WHERE
config_id = (
SELECT
config_id FROM mcaptcha_config
WHERE
key = $1
AND
user_id = (
SELECT
ID FROM mcaptcha_users WHERE name = $2))
ORDER BY time DESC",
&key, &key,
&user,
) )
.fetch_all(db) .fetch_all(db)
.await?; .await?;
@ -116,12 +117,25 @@ pub mod runners {
/// featch PoWConfig solves /// featch PoWConfig solves
#[inline] #[inline]
pub async fn fetch_solve(key: &str, db: &PgPool) -> ServiceResult<Vec<Date>> { pub async fn fetch_solve(
user: &str,
key: &str,
db: &PgPool,
) -> ServiceResult<Vec<Date>> {
let records = sqlx::query_as!( let records = sqlx::query_as!(
Date, Date,
"SELECT time FROM mcaptcha_pow_solved_stats WHERE config_id = "SELECT time FROM mcaptcha_pow_solved_stats
(SELECT config_id FROM mcaptcha_config where key = $1)", WHERE config_id = (
SELECT config_id FROM mcaptcha_config
WHERE
key = $1
AND
user_id = (
SELECT
ID FROM mcaptcha_users WHERE name = $2))
ORDER BY time DESC",
&key, &key,
&user
) )
.fetch_all(db) .fetch_all(db)
.await?; .await?;
@ -131,12 +145,26 @@ pub mod runners {
/// featch PoWConfig confirms /// featch PoWConfig confirms
#[inline] #[inline]
pub async fn fetch_confirm(key: &str, db: &PgPool) -> ServiceResult<Vec<Date>> { pub async fn fetch_confirm(
user: &str,
key: &str,
db: &PgPool,
) -> ServiceResult<Vec<Date>> {
let records = sqlx::query_as!( let records = sqlx::query_as!(
Date, Date,
"SELECT time FROM mcaptcha_pow_confirmed_stats WHERE config_id = ( "SELECT time FROM mcaptcha_pow_confirmed_stats
SELECT config_id FROM mcaptcha_config where key = $1)", WHERE
&key config_id = (
SELECT config_id FROM mcaptcha_config
WHERE
key = $1
AND
user_id = (
SELECT
ID FROM mcaptcha_users WHERE name = $2))
ORDER BY time DESC",
&key,
&user
) )
.fetch_all(db) .fetch_all(db)
.await?; .await?;
@ -165,7 +193,7 @@ mod tests {
let (_, _, _, token_key) = add_levels_util(NAME, PASSWORD).await; let (_, _, _, token_key) = add_levels_util(NAME, PASSWORD).await;
let key = token_key.key.clone(); let key = token_key.key.clone();
let stats = Stats::new(&key, &data.db).await.unwrap(); let stats = Stats::new(&NAME, &key, &data.db).await.unwrap();
assert_eq!(stats.config_fetches.len(), 0); assert_eq!(stats.config_fetches.len(), 0);
assert_eq!(stats.solves.len(), 0); assert_eq!(stats.solves.len(), 0);
@ -177,7 +205,7 @@ mod tests {
record_confirm(&key, &data.db) record_confirm(&key, &data.db)
); );
let stats = Stats::new(&key, &data.db).await.unwrap(); let stats = Stats::new(&NAME, &key, &data.db).await.unwrap();
assert_eq!(stats.config_fetches.len(), 1); assert_eq!(stats.config_fetches.len(), 1);
assert_eq!(stats.solves.len(), 1); assert_eq!(stats.solves.len(), 1);

View file

@ -15,15 +15,18 @@
* along with this program. If not, see <https://www.gnu.org/licenses/>. * along with this program. If not, see <https://www.gnu.org/licenses/>.
*/ */
use sqlx::types::time::OffsetDateTime;
use sqlx::PgPool; use sqlx::PgPool;
/// record PoWConfig fetches /// record PoWConfig fetches
#[inline] #[inline]
pub async fn record_fetch(key: &str, db: &PgPool) { pub async fn record_fetch(key: &str, db: &PgPool) {
let now = OffsetDateTime::now_utc();
let _ = sqlx::query!( let _ = sqlx::query!(
"INSERT INTO mcaptcha_pow_fetched_stats "INSERT INTO mcaptcha_pow_fetched_stats
(config_id) VALUES ((SELECT config_id FROM mcaptcha_config WHERE key = $1))", (config_id, time) VALUES ((SELECT config_id FROM mcaptcha_config WHERE key = $1), $2)",
&key, &key,
&now,
) )
.execute(db) .execute(db)
.await; .await;
@ -32,10 +35,12 @@ pub async fn record_fetch(key: &str, db: &PgPool) {
/// record PoWConfig solves /// record PoWConfig solves
#[inline] #[inline]
pub async fn record_solve(key: &str, db: &PgPool) { pub async fn record_solve(key: &str, db: &PgPool) {
let now = OffsetDateTime::now_utc();
let _ = sqlx::query!( let _ = sqlx::query!(
"INSERT INTO mcaptcha_pow_solved_stats "INSERT INTO mcaptcha_pow_solved_stats
(config_id) VALUES ((SELECT config_id FROM mcaptcha_config WHERE key = $1))", (config_id, time) VALUES ((SELECT config_id FROM mcaptcha_config WHERE key = $1), $2)",
&key, &key,
&now,
) )
.execute(db) .execute(db)
.await; .await;
@ -44,10 +49,12 @@ pub async fn record_solve(key: &str, db: &PgPool) {
/// record PoWConfig confirms /// record PoWConfig confirms
#[inline] #[inline]
pub async fn record_confirm(key: &str, db: &PgPool) { pub async fn record_confirm(key: &str, db: &PgPool) {
let now = OffsetDateTime::now_utc();
let _ = sqlx::query!( let _ = sqlx::query!(
"INSERT INTO mcaptcha_pow_confirmed_stats "INSERT INTO mcaptcha_pow_confirmed_stats
(config_id) VALUES ((SELECT config_id FROM mcaptcha_config WHERE key = $1))", (config_id, time) VALUES ((SELECT config_id FROM mcaptcha_config WHERE key = $1), $2)",
&key, &key,
&now
) )
.execute(db) .execute(db)
.await; .await;

View file

@ -21,4 +21,5 @@
max-width: 50%; max-width: 50%;
margin: 50px auto; margin: 50px auto;
border-radius: 5px; border-radius: 5px;
flex-direction: column;
} }

View file

@ -27,4 +27,5 @@
.inner-container { .inner-container {
@include inner-container; @include inner-container;
flex-direction: column;
} }

View file

@ -30,14 +30,6 @@
</div> </div>
</a> </a>
</li> </li>
<li class="secondary-menu__item">
<a class="secondary-menu__item-link" href="<.= crate::PAGES.panel.sitekey.list .>">
<img class="secondary-menu__icon" src="<.= crate::BAR_CHART.0 .>" alt="<.= crate::BAR_CHART.1 .>" />
<div class="secondary-menu__item-name">
Statistics
</div>
</a>
</li>
<li class="secondary-menu__item"> <li class="secondary-menu__item">
<a class="secondary-menu__item-link" href="<.= crate::PAGES.panel.settings.home .>"> <a class="secondary-menu__item-link" href="<.= crate::PAGES.panel.settings.home .>">
<img class="secondary-menu__icon" src="<.= crate::SETTINGS_ICON.0 .>" alt="<.= crate::SETTINGS_ICON.1 .>" /> <img class="secondary-menu__icon" src="<.= crate::SETTINGS_ICON.0 .>" alt="<.= crate::SETTINGS_ICON.1 .>" />

View file

@ -20,7 +20,7 @@
.notification__table { .notification__table {
@include table; @include table;
margin: auto; margin: 20px auto;
} }
.notification__title-text { .notification__title-text {

View file

@ -4,4 +4,11 @@
<. for (count, level) in levels.iter().enumerate() { .> <. for (count, level) in levels.iter().enumerate() { .>
<. include!("./existing-level.html"); .> <. include!("./existing-level.html"); .>
<. } .> <. } .>
<. include!("./__form-bottom.html"); .> <./* synchronise with "./__form-bottom.html" Lines below should break form */.>
</form>
<. include!("./stats.html"); .>
</div>
<!-- end of container -->
</main>
<. include!("../../../components/footers.html"); .>

View file

@ -0,0 +1,26 @@
<div class="sitekey__stats-container">
<. let tables = [("Configuration Fetches", &stats.config_fetches), ("Proofs generated", &stats.solves), ("Grants Verified", &stats.confirms)]; .>
<. for table in tables.iter() { .>
<table class="notification__table">
<thead class="notification__heading">
<tr>
<th colspan="4" class="notification__title-text"><.= table.0 .></th>
</tr>
</thead>
<tbody class="notification__body">
<. for (count, val) in table.1.iter().enumerate() { .>
<tr class="notification__item">
<td>
<h3 class="notification__item-heading">
<.= count + 1 .>
</h3>
</td>
<td>
<p class="notification__item-text"><.= val.date() .></p>
</td>
</tr>
<. } .>
</tbody>
</table>
<. }; .>
</div>