From fb320f0338fc9d9b5e6ba3993989e39fd310903f Mon Sep 17 00:00:00 2001 From: Brandon Thomas Date: Fri, 17 Sep 2021 02:50:14 -0400 Subject: [PATCH] endpoint to count voices --- src/http_server/endpoints/moderation/mod.rs | 1 + .../moderation/stats/get_voice_count_stats.rs | 137 ++++++++++++++++++ .../endpoints/moderation/stats/mod.rs | 1 + src/main.rs | 9 ++ 4 files changed, 148 insertions(+) create mode 100644 src/http_server/endpoints/moderation/stats/get_voice_count_stats.rs create mode 100644 src/http_server/endpoints/moderation/stats/mod.rs diff --git a/src/http_server/endpoints/moderation/mod.rs b/src/http_server/endpoints/moderation/mod.rs index 71ea71de02..afd7a69415 100644 --- a/src/http_server/endpoints/moderation/mod.rs +++ b/src/http_server/endpoints/moderation/mod.rs @@ -1,6 +1,7 @@ pub mod approval; pub mod ip_bans; pub mod jobs; +pub mod stats; pub mod user_bans; pub mod user_roles; pub mod users; \ No newline at end of file diff --git a/src/http_server/endpoints/moderation/stats/get_voice_count_stats.rs b/src/http_server/endpoints/moderation/stats/get_voice_count_stats.rs new file mode 100644 index 0000000000..dc2c06880a --- /dev/null +++ b/src/http_server/endpoints/moderation/stats/get_voice_count_stats.rs @@ -0,0 +1,137 @@ +use actix_http::Error; +use actix_http::http::header; +use actix_web::cookie::Cookie; +use actix_web::dev::HttpResponseBuilder; +use actix_web::error::ResponseError; +use actix_web::http::StatusCode; +use actix_web::web::Path; +use actix_web::{Responder, web, HttpResponse, error, HttpRequest}; +use chrono::{DateTime, Utc}; +use crate::http_server::web_utils::ip_address::get_request_ip; +use crate::http_server::web_utils::response_success_helpers::simple_json_success; +use crate::http_server::web_utils::serialize_as_json_error::serialize_as_json_error; +use crate::server_state::ServerState; +use log::{info, warn, log}; +use regex::Regex; +use sqlx::error::DatabaseError; +use sqlx::error::Error::Database; +use sqlx::mysql::MySqlDatabaseError; +use std::fmt; +use std::sync::Arc; + +#[derive(Serialize)] +pub struct GetVoiceCountStatsResponse { + pub success: bool, + pub all_voices_count_including_deleted: i64, + pub public_voices_count: i64, +} + +#[derive(Debug, Serialize)] +pub enum GetVoiceCountStatsError { + ServerError, + Unauthorized, +} + +impl ResponseError for GetVoiceCountStatsError { + fn status_code(&self) -> StatusCode { + match *self { + GetVoiceCountStatsError::ServerError => StatusCode::INTERNAL_SERVER_ERROR, + GetVoiceCountStatsError::Unauthorized => StatusCode::UNAUTHORIZED, + } + } + + fn error_response(&self) -> HttpResponse { + serialize_as_json_error(self) + } +} + +// NB: Not using DeriveMore since Clion doesn't understand it. +impl fmt::Display for GetVoiceCountStatsError { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + write!(f, "{:?}", self) + } +} + +pub async fn get_voice_count_stats_handler( + http_request: HttpRequest, + server_state: web::Data> +) -> Result { + + let maybe_user_session = server_state + .session_checker + .maybe_get_user_session(&http_request, &server_state.mysql_pool) + .await + .map_err(|e| { + warn!("Session checker error: {:?}", e); + GetVoiceCountStatsError::ServerError + })?; + + let user_session = match maybe_user_session { + Some(session) => session, + None => { + warn!("not logged in"); + return Err(GetVoiceCountStatsError::Unauthorized); + } + }; + + // TODO: Not a good fit for this permission. + if !user_session.can_edit_other_users_tts_models { + warn!("user is not allowed to edit user tts: {}", user_session.user_token); + return Err(GetVoiceCountStatsError::Unauthorized); + } + + // NB: Lookup failure is Err(RowNotFound). + let maybe_result = sqlx::query_as!( + VoiceStats, + r#" +SELECT public_count, all_count FROM ( + (SELECT count(*) as public_count + FROM tts_models + WHERE user_deleted_at IS NULL + AND mod_deleted_at IS NULL) as pc, + (SELECT count(*) as all_count + FROM tts_models) as ac +) + "#, + ) + .fetch_one(&server_state.mysql_pool) + .await; + + let result : VoiceStats = match maybe_result { + Ok(result) => result, + Err(err) => { + match err { + RowNotFound => { + // NB: Not Found for null results means nothing is pending in the queue + VoiceStats { + all_count: -1, + public_count: -1, + } + }, + _ => { + warn!("get tts pending count error: {:?}", err); + return Err(GetVoiceCountStatsError::ServerError) + } + } + }, + }; + + let response = GetVoiceCountStatsResponse { + success: true, + all_voices_count_including_deleted: result.all_count, + public_voices_count: result.public_count, + }; + + let body = serde_json::to_string(&response) + .map_err(|e| GetVoiceCountStatsError::ServerError)?; + + Ok(HttpResponse::Ok() + .content_type("application/json") + .body(body)) +} + +#[derive(Serialize)] +pub struct VoiceStats { + pub public_count: i64, + pub all_count: i64, +} diff --git a/src/http_server/endpoints/moderation/stats/mod.rs b/src/http_server/endpoints/moderation/stats/mod.rs new file mode 100644 index 0000000000..a2441d1780 --- /dev/null +++ b/src/http_server/endpoints/moderation/stats/mod.rs @@ -0,0 +1 @@ +pub mod get_voice_count_stats; \ No newline at end of file diff --git a/src/main.rs b/src/main.rs index 51a0c13297..6c68977882 100644 --- a/src/main.rs +++ b/src/main.rs @@ -46,6 +46,7 @@ use crate::http_server::endpoints::moderation::ip_bans::get_ip_ban::get_ip_ban_h use crate::http_server::endpoints::moderation::ip_bans::list_ip_bans::list_ip_bans_handler; use crate::http_server::endpoints::moderation::jobs::get_tts_inference_queue_count::get_tts_inference_queue_count_handler; use crate::http_server::endpoints::moderation::jobs::get_w2l_inference_queue_count::get_w2l_inference_queue_count_handler; +use crate::http_server::endpoints::moderation::stats::get_voice_count_stats::get_voice_count_stats_handler; use crate::http_server::endpoints::moderation::user_bans::ban_user::ban_user_handler; use crate::http_server::endpoints::moderation::user_bans::list_banned_users::list_banned_users_handler; use crate::http_server::endpoints::moderation::user_roles::list_roles::list_user_roles_handler; @@ -462,6 +463,14 @@ pub async fn serve(server_state: ServerState) -> AnyhowResult<()> .route(web::head().to(|| HttpResponse::Ok())) ) ) + .service( + web::scope("/stats") + .service( + web::resource("/tts_voices") + .route(web::get().to(get_voice_count_stats_handler)) + .route(web::head().to(|| HttpResponse::Ok())) + ) + ) ) // ==================== TTS ==================== .service(