add tts categories to model list results

This commit is contained in:
Brandon Thomas committed 2021-12-29 02:50:50 -05:00
1 parent e78e1079e3
commit 654f826598
4 files changed
+106 -6

No files matched your search

@@ -0,0 +1,80 @@
use anyhow::anyhow;
use chrono::{DateTime, Utc};
use crate::util::anyhow_result::AnyhowResult;
use log::warn;
use sqlx::MySqlPool;
use std::collections::{HashSet, HashMap};
/// Map of model_token => vec<category tokens>
#[derive(Serialize, Default)]
pub struct TtsModelCategoryMap {
pub model_to_category_tokens: HashMap<String, HashSet<String>>,
}
pub async fn fetch_tts_model_category_map(mysql_pool: &MySqlPool)
-> AnyhowResult<TtsModelCategoryMap>
{
let assignments = list_tts_model_category_assignments(mysql_pool).await?;
let mut map : HashMap<String, HashSet<String>> = HashMap::new();
for assignment in assignments.iter() {
if !map.contains_key(&assignment.tts_model_token) {
map.insert(assignment.tts_model_token.clone(), HashSet::new());
}
map.get_mut(&assignment.tts_model_token).map(|hashset| {
hashset.insert(assignment.category_token.clone())
});
}
Ok(TtsModelCategoryMap {
model_to_category_tokens: map,
})
}
#[derive(Serialize)]
pub struct CategoryAssignment {
pub tts_model_token: String,
pub category_token: String,
}
// NB: This shows for all models, including deleted and unapproved.
// However, it does not return deleted/unapproved categories.
pub async fn list_tts_model_category_assignments(mysql_pool: &MySqlPool) -> AnyhowResult<Vec<CategoryAssignment>> {
let maybe_results = sqlx::query_as!(
CategoryAssignment,
r#"
SELECT
assignments.model_token AS tts_model_token,
assignments.category_token
FROM
tts_category_assignments AS assignments
JOIN
tts_models AS tts
ON assignments.model_token = tts.token
WHERE
tts.is_locked_from_use IS FALSE
AND tts.user_deleted_at IS NULL
AND tts.mod_deleted_at IS NULL
"#,
)
.fetch_all(mysql_pool)
.await;
match maybe_results {
Err(err) => {
match err {
sqlx::Error::RowNotFound => {
Ok(Vec::new())
},
_ => {
warn!("list tts model category assignments db error: {:?}", err);
Err(anyhow!("error with query: {:?}", err))
}
}
},
Ok(results) => Ok(results),
}
}
@@ -1 +1,2 @@
pub mod get_category_by_token;
pub mod get_category_by_token;
pub mod list_tts_model_category_assignments;
@@ -79,7 +79,7 @@ impl ResponseError for ListTtsCategoriesError {
}
}
// NB: Not using DeriveMore since Clion doesn't understand it.
// NB: Not using derive_more::Display since Clion doesn't understand it.
impl fmt::Display for ListTtsCategoriesError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "{:?}", self)
@@ -1,23 +1,24 @@
use actix_http::Error;
use actix_http::http::header;
use actix_web::cookie::Cookie;
use actix_web::HttpResponseBuilder;
use actix_web::cookie::Cookie;
use actix_web::error::ResponseError;
use actix_web::http::StatusCode;
use actix_web::{Responder, web, HttpResponse, error, HttpRequest, HttpMessage};
use chrono::{DateTime, Utc};
use crate::database::queries::categories::list_tts_model_category_assignments::fetch_tts_model_category_map;
use crate::database::queries::list_tts_models::list_tts_models;
use crate::http_server::web_utils::ip_address::get_request_ip;
use crate::http_server::web_utils::response_error_helpers::to_simple_json_error;
use crate::server_state::ServerState;
use crate::util::anyhow_result::AnyhowResult;
use derive_more::{Display, Error};
use log::{info, warn, log, error};
use regex::Regex;
use sqlx::MySqlPool;
use sqlx::error::DatabaseError;
use sqlx::error::Error::Database;
use sqlx::mysql::MySqlDatabaseError;
use std::collections::HashSet;
use std::fmt;
use std::sync::Arc;
#[derive(Serialize, Clone)]
@@ -29,6 +30,11 @@ pub struct TtsModelRecordForResponse {
pub creator_display_name: String,
pub creator_gravatar_hash: String,
pub title: String,
/// Category assignments
/// From non-deleted, mod-approved categories only
pub category_tokens: HashSet<String>,
pub created_at: DateTime<Utc>,
pub updated_at: DateTime<Utc>,
}
@@ -39,7 +45,7 @@ pub struct ListTtsModelsSuccessResponse {
pub models: Vec<TtsModelRecordForResponse>,
}
#[derive(Debug, Display)]
#[derive(Debug)]
pub enum ListTtsModelsError {
ServerError,
}
@@ -73,6 +79,13 @@ impl ResponseError for ListTtsModelsError {
}
}
// NB: Not using derive_more::Display since Clion doesn't understand it.
impl fmt::Display for ListTtsModelsError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "{:?}", self)
}
}
pub async fn list_tts_models_handler(
http_request: HttpRequest,
server_state: web::Data<Arc<ServerState>>) -> Result<HttpResponse, ListTtsModelsError>
@@ -126,6 +139,9 @@ async fn get_all_models(mysql_pool: &MySqlPool) -> AnyhowResult<Vec<TtsModelReco
false
).await?;
let model_categories_map
= fetch_tts_model_category_map(mysql_pool).await?;
models.sort_by(|a, b| (&a.title).cmp(&b.title));
let models_for_response = models.into_iter()
@@ -138,6 +154,9 @@ async fn get_all_models(mysql_pool: &MySqlPool) -> AnyhowResult<Vec<TtsModelReco
creator_display_name: model.creator_display_name.clone(),
creator_gravatar_hash: model.creator_gravatar_hash.clone(),
title: model.title.clone(),
category_tokens: model_categories_map.model_to_category_tokens.get(&model.model_token)
.map(|hash| hash.clone())
.unwrap_or(HashSet::new()),
created_at: model.created_at.clone(),
updated_at: model.updated_at.clone(),
}