* Reports WIP

* Finish reports

* Clippy fixes

Co-authored-by: Geometrically <geometrically@pop-os.localdomain>
This commit is contained in:
Geometrically
2021-02-13 12:11:13 -07:00
committed by GitHub
parent 3df740702c
commit 109d7d87bd
21 changed files with 1158 additions and 238 deletions

View File

@@ -21,7 +21,7 @@ pub fn config(cfg: &mut ServiceConfig) {
pub enum AuthorizationError {
#[error("Environment Error")]
EnvError(#[from] dotenv::Error),
#[error("An unknown database error occured")]
#[error("An unknown database error occured: {0}")]
SqlxDatabaseError(#[from] sqlx::Error),
#[error("Database Error: {0}")]
DatabaseError(#[from] crate::database::models::DatabaseError),

View File

@@ -6,6 +6,7 @@ mod mod_creation;
mod moderation;
mod mods;
mod not_found;
mod reports;
mod tags;
mod teams;
mod users;
@@ -84,6 +85,12 @@ pub fn moderation_config(cfg: &mut web::ServiceConfig) {
cfg.service(web::scope("moderation").service(moderation::mods));
}
pub fn reports_config(cfg: &mut web::ServiceConfig) {
cfg.service(reports::reports);
cfg.service(reports::report_create);
cfg.service(reports::delete_report);
}
#[derive(thiserror::Error, Debug)]
pub enum ApiError {
#[error("Environment Error")]

View File

@@ -1,11 +1,9 @@
use super::ApiError;
use crate::auth::check_is_moderator_from_headers;
use crate::database;
use crate::models::mods::{ModId, ModStatus};
use crate::models::teams::TeamId;
use crate::models::mods::{Mod, ModStatus};
use actix_web::{get, web, HttpRequest, HttpResponse};
use serde::{Deserialize, Serialize};
use sqlx::types::chrono::{DateTime, Utc};
use serde::Deserialize;
use sqlx::PgPool;
#[derive(Deserialize)]
@@ -18,42 +16,6 @@ fn default_count() -> i16 {
100
}
/// A mod returned from the API moderation routes
#[derive(Serialize)]
pub struct ModerationMod {
/// The ID of the mod, encoded as a base62 string.
pub id: ModId,
/// The slug of a mod, used for vanity URLs
pub slug: Option<String>,
/// The team of people that has ownership of this mod.
pub team: TeamId,
/// The title or name of the mod.
pub title: String,
/// A short description of the mod.
pub description: String,
/// The long description of the mod.
pub body: String,
/// The date at which the mod was first published.
pub published: DateTime<Utc>,
/// The date at which the mod was first published.
pub updated: DateTime<Utc>,
/// The status of the mod
pub status: ModStatus,
/// The total number of downloads the mod has had.
pub downloads: u32,
/// The URL of the icon of the mod
pub icon_url: Option<String>,
/// An optional link to where to submit bugs or issues with the mod.
pub issues_url: Option<String>,
/// An optional link to the source code for the mod.
pub source_url: Option<String>,
/// An optional link to the mod's wiki page or other relevant information.
pub wiki_url: Option<String>,
/// An optional link to the mod's discord
pub discord_url: Option<String>,
}
#[get("mods")]
pub async fn mods(
req: HttpRequest,
@@ -64,9 +26,9 @@ pub async fn mods(
use futures::stream::TryStreamExt;
let mods = sqlx::query!(
let mod_ids = sqlx::query!(
"
SELECT * FROM mods
SELECT id FROM mods
WHERE status = (
SELECT id FROM statuses WHERE status = $1
)
@@ -77,28 +39,17 @@ pub async fn mods(
count.count as i64
)
.fetch_many(&**pool)
.try_filter_map(|e| async {
Ok(e.right().map(|m| ModerationMod {
id: database::models::ids::ModId(m.id).into(),
slug: m.slug,
team: database::models::ids::TeamId(m.team_id).into(),
title: m.title,
description: m.description,
body: m.body,
published: m.published,
icon_url: m.icon_url,
issues_url: m.issues_url,
source_url: m.source_url,
status: ModStatus::Processing,
updated: m.updated,
downloads: m.downloads as u32,
wiki_url: m.wiki_url,
discord_url: m.discord_url,
}))
})
.try_collect::<Vec<ModerationMod>>()
.try_filter_map(|e| async { Ok(e.right().map(|m| database::models::ids::ModId(m.id))) })
.try_collect::<Vec<database::models::ModId>>()
.await
.map_err(|e| ApiError::DatabaseError(e.into()))?;
let mods: Vec<Mod> = database::models::mod_item::Mod::get_many_full(mod_ids, &**pool)
.await
.map_err(|e| ApiError::DatabaseError(e.into()))?
.into_iter()
.map(super::mods::convert_mod)
.collect();
Ok(HttpResponse::Ok().json(mods))
}

View File

@@ -192,7 +192,7 @@ pub async fn mod_get(
}
}
fn convert_mod(data: database::models::mod_item::QueryMod) -> models::mods::Mod {
pub fn convert_mod(data: database::models::mod_item::QueryMod) -> models::mods::Mod {
let m = data.inner;
models::mods::Mod {
@@ -392,6 +392,7 @@ pub async fn mod_edit(
"No database entry for status provided.".to_string(),
)
})?;
sqlx::query!(
"
UPDATE mods
@@ -406,7 +407,7 @@ pub async fn mod_edit(
.map_err(|e| ApiError::DatabaseError(e.into()))?;
if mod_item.status.is_searchable() && !status.is_searchable() {
delete_from_index(id.into(), config).await?;
delete_from_index(mod_id, config).await?;
} else if !mod_item.status.is_searchable() && status.is_searchable() {
let index_mod = crate::search::indexing::local_import::query_one(
mod_id.into(),

181
src/routes/reports.rs Normal file
View File

@@ -0,0 +1,181 @@
use crate::auth::{check_is_moderator_from_headers, get_user_from_headers};
use crate::models::ids::{ModId, UserId, VersionId};
use crate::models::reports::{ItemType, Report};
use crate::routes::ApiError;
use actix_web::{delete, get, post, web, HttpRequest, HttpResponse};
use serde::Deserialize;
use sqlx::PgPool;
#[derive(Deserialize)]
pub struct CreateReport {
pub report_type: String,
pub item_id: String,
pub item_type: ItemType,
pub body: String,
}
#[post("report")]
pub async fn report_create(
req: HttpRequest,
pool: web::Data<PgPool>,
new_report: web::Json<CreateReport>,
) -> Result<HttpResponse, ApiError> {
let mut transaction = pool
.begin()
.await
.map_err(|e| ApiError::DatabaseError(e.into()))?;
let current_user = get_user_from_headers(req.headers(), &mut *transaction).await?;
let id = crate::database::models::generate_report_id(&mut transaction).await?;
let report_type = crate::database::models::categories::ReportType::get_id(
&*new_report.report_type,
&mut *transaction,
)
.await?
.ok_or_else(|| {
ApiError::InvalidInputError(format!("Invalid report type: {}", new_report.report_type))
})?;
let mut report = crate::database::models::report_item::Report {
id,
report_type_id: report_type,
mod_id: None,
version_id: None,
user_id: None,
body: new_report.body.clone(),
reporter: current_user.id.into(),
created: chrono::Utc::now(),
};
match new_report.item_type {
ItemType::Mod => {
report.mod_id = Some(serde_json::from_str::<ModId>(&*new_report.item_id)?.into())
}
ItemType::Version => {
report.version_id =
Some(serde_json::from_str::<VersionId>(&*new_report.item_id)?.into())
}
ItemType::User => {
report.user_id = Some(serde_json::from_str::<UserId>(&*new_report.item_id)?.into())
}
ItemType::Unknown => {
return Err(ApiError::InvalidInputError(format!(
"Invalid report item type: {}",
new_report.item_type.as_str()
)))
}
}
report
.insert(&mut transaction)
.await
.map_err(|e| ApiError::DatabaseError(e.into()))?;
transaction
.commit()
.await
.map_err(|e| ApiError::DatabaseError(e.into()))?;
Ok(HttpResponse::Ok().json(Report {
id: id.into(),
report_type: new_report.report_type.clone(),
item_id: new_report.item_id.clone(),
item_type: new_report.item_type.clone(),
reporter: current_user.id,
body: new_report.body.clone(),
created: chrono::Utc::now(),
}))
}
#[derive(Deserialize)]
pub struct ResultCount {
#[serde(default = "default_count")]
count: i16,
}
fn default_count() -> i16 {
100
}
#[get("report")]
pub async fn reports(
req: HttpRequest,
pool: web::Data<PgPool>,
count: web::Query<ResultCount>,
) -> Result<HttpResponse, ApiError> {
check_is_moderator_from_headers(req.headers(), &**pool).await?;
use futures::stream::TryStreamExt;
let report_ids = sqlx::query!(
"
SELECT id FROM reports
ORDER BY created ASC
LIMIT $1;
",
count.count as i64
)
.fetch_many(&**pool)
.try_filter_map(|e| async {
Ok(e.right()
.map(|m| crate::database::models::ids::ReportId(m.id)))
})
.try_collect::<Vec<crate::database::models::ids::ReportId>>()
.await
.map_err(|e| ApiError::DatabaseError(e.into()))?;
let query_reports = crate::database::models::report_item::Report::get_many(report_ids, &**pool)
.await
.map_err(|e| ApiError::DatabaseError(e.into()))?;
let mut reports = Vec::new();
for x in query_reports {
let mut item_id = "".to_string();
let mut item_type = ItemType::Unknown;
if let Some(mod_id) = x.mod_id {
item_id = serde_json::to_string::<ModId>(&mod_id.into())?;
item_type = ItemType::Mod;
} else if let Some(version_id) = x.version_id {
item_id = serde_json::to_string::<VersionId>(&version_id.into())?;
item_type = ItemType::Version;
} else if let Some(user_id) = x.user_id {
item_id = serde_json::to_string::<UserId>(&user_id.into())?;
item_type = ItemType::User;
}
reports.push(Report {
id: x.id.into(),
report_type: x.report_type,
item_id,
item_type,
reporter: x.reporter.into(),
body: x.body,
created: x.created,
})
}
Ok(HttpResponse::Ok().json(reports))
}
#[delete("report/{id}")]
pub async fn delete_report(
req: HttpRequest,
pool: web::Data<PgPool>,
info: web::Path<(crate::models::reports::ReportId,)>,
) -> Result<HttpResponse, ApiError> {
check_is_moderator_from_headers(req.headers(), &**pool).await?;
let result = crate::database::models::report_item::Report::remove_full(
info.into_inner().0.into(),
&**pool,
)
.await
.map_err(|e| ApiError::DatabaseError(e.into()))?;
if result.is_some() {
Ok(HttpResponse::Ok().body(""))
} else {
Ok(HttpResponse::NotFound().body(""))
}
}

View File

@@ -1,7 +1,7 @@
use super::ApiError;
use crate::auth::check_is_admin_from_headers;
use crate::database::models;
use crate::database::models::categories::{DonationPlatform, License};
use crate::database::models::categories::{DonationPlatform, License, ReportType};
use actix_web::{delete, get, put, web, HttpRequest, HttpResponse};
use models::categories::{Category, GameVersion, Loader};
use sqlx::PgPool;
@@ -125,6 +125,7 @@ pub async fn loader_delete(
pub struct GameVersionQueryData {
#[serde(rename = "type")]
type_: Option<String>,
major: Option<bool>,
}
#[get("game_version")]
@@ -132,8 +133,9 @@ pub async fn game_version_list(
pool: web::Data<PgPool>,
query: web::Query<GameVersionQueryData>,
) -> Result<HttpResponse, ApiError> {
if let Some(type_) = &query.type_ {
let results = GameVersion::list_type(type_, &**pool).await?;
if query.type_.is_some() || query.major.is_some() {
let results =
GameVersion::list_filter(query.type_.as_deref(), query.major, &**pool).await?;
Ok(HttpResponse::Ok().json(results))
} else {
let results = GameVersion::list(&**pool).await?;
@@ -337,3 +339,49 @@ pub async fn donation_platform_delete(
Ok(HttpResponse::NotFound().body(""))
}
}
#[get("report_type")]
pub async fn report_type_list(pool: web::Data<PgPool>) -> Result<HttpResponse, ApiError> {
let results = ReportType::list(&**pool).await?;
Ok(HttpResponse::Ok().json(results))
}
#[put("report_type/{name}")]
pub async fn report_type_create(
req: HttpRequest,
pool: web::Data<PgPool>,
loader: web::Path<(String,)>,
) -> Result<HttpResponse, ApiError> {
check_is_admin_from_headers(req.headers(), &**pool).await?;
let name = loader.into_inner().0;
let _id = ReportType::builder().name(&name)?.insert(&**pool).await?;
Ok(HttpResponse::Ok().body(""))
}
#[delete("report_type/{name}")]
pub async fn report_type_delete(
req: HttpRequest,
pool: web::Data<PgPool>,
report_type: web::Path<(String,)>,
) -> Result<HttpResponse, ApiError> {
check_is_admin_from_headers(req.headers(), &**pool).await?;
let name = report_type.into_inner().0;
let mut transaction = pool.begin().await.map_err(models::DatabaseError::from)?;
let result = ReportType::remove(&name, &mut transaction).await?;
transaction
.commit()
.await
.map_err(models::DatabaseError::from)?;
if result.is_some() {
Ok(HttpResponse::Ok().body(""))
} else {
Ok(HttpResponse::NotFound().body(""))
}
}

View File

@@ -11,10 +11,10 @@ use sqlx::PgPool;
use std::borrow::Borrow;
use std::sync::Arc;
#[derive(Serialize, Deserialize)]
#[derive(Serialize, Deserialize, Clone)]
pub struct VersionListFilters {
pub game_versions: Option<Vec<String>>,
pub loaders: Option<Vec<String>>,
pub game_versions: Option<String>,
pub loaders: Option<String>,
pub featured: Option<bool>,
}
@@ -38,8 +38,14 @@ pub async fn version_list(
if mod_exists.unwrap_or(false) {
let version_ids = database::models::Version::get_mod_versions(
id,
filters.game_versions,
filters.loaders,
filters
.game_versions
.as_ref()
.map(|x| serde_json::from_str(x).unwrap_or_default()),
filters
.loaders
.as_ref()
.map(|x| serde_json::from_str(x).unwrap_or_default()),
&**pool,
)
.await
@@ -49,17 +55,35 @@ pub async fn version_list(
.await
.map_err(|e| ApiError::DatabaseError(e.into()))?;
let mut response = Vec::new();
for version in versions {
if let Some(featured) = filters.featured {
if featured {
response.push(convert_version(version))
}
} else {
response.push(convert_version(version))
}
let mut response = versions
.iter()
.cloned()
.filter(|version| {
filters
.featured
.map(|featured| featured == version.featured)
.unwrap_or(true)
})
.map(convert_version)
.collect::<Vec<_>>();
// Attempt to populate versions with "auto featured" versions
if response.is_empty() && !versions.is_empty() && filters.featured.unwrap_or(false) {
database::models::categories::GameVersion::list_filter(None, Some(true), &**pool)
.await?
.into_iter()
.for_each(|major_version| {
versions
.iter()
.find(|version| version.game_versions.contains(&major_version))
.map(|version| response.push(convert_version(version.clone())))
.unwrap_or(());
});
}
response.sort_by(|a, b| b.date_published.cmp(&a.date_published));
response.dedup_by(|a, b| a.id == b.id);
Ok(HttpResponse::Ok().json(response))
} else {
Ok(HttpResponse::NotFound().body(""))