You've already forked AstralRinth
forked from didirus/AstralRinth
Reports (#165)
* Reports WIP * Finish reports * Clippy fixes Co-authored-by: Geometrically <geometrically@pop-os.localdomain>
This commit is contained in:
@@ -17,6 +17,11 @@ pub struct Category {
|
||||
pub category: String,
|
||||
}
|
||||
|
||||
pub struct ReportType {
|
||||
pub id: ReportTypeId,
|
||||
pub report_type: String,
|
||||
}
|
||||
|
||||
pub struct License {
|
||||
pub id: LicenseId,
|
||||
pub short: String,
|
||||
@@ -354,22 +359,61 @@ impl GameVersion {
|
||||
Ok(result)
|
||||
}
|
||||
|
||||
pub async fn list_type<'a, E>(version_type: &str, exec: E) -> Result<Vec<String>, DatabaseError>
|
||||
pub async fn list_filter<'a, E>(
|
||||
version_type_option: Option<&str>,
|
||||
major_option: Option<bool>,
|
||||
exec: E,
|
||||
) -> Result<Vec<String>, DatabaseError>
|
||||
where
|
||||
E: sqlx::Executor<'a, Database = sqlx::Postgres>,
|
||||
{
|
||||
let result = sqlx::query!(
|
||||
"
|
||||
SELECT version FROM game_versions
|
||||
WHERE type = $1
|
||||
ORDER BY created DESC
|
||||
",
|
||||
version_type
|
||||
)
|
||||
.fetch_many(exec)
|
||||
.try_filter_map(|e| async { Ok(e.right().map(|c| c.version)) })
|
||||
.try_collect::<Vec<String>>()
|
||||
.await?;
|
||||
let result;
|
||||
|
||||
if let Some(version_type) = version_type_option {
|
||||
if let Some(major) = major_option {
|
||||
result = sqlx::query!(
|
||||
"
|
||||
SELECT version FROM game_versions
|
||||
WHERE major = $1 AND type = $2
|
||||
ORDER BY created DESC
|
||||
",
|
||||
major,
|
||||
version_type
|
||||
)
|
||||
.fetch_many(exec)
|
||||
.try_filter_map(|e| async { Ok(e.right().map(|c| c.version)) })
|
||||
.try_collect::<Vec<String>>()
|
||||
.await?;
|
||||
} else {
|
||||
result = sqlx::query!(
|
||||
"
|
||||
SELECT version FROM game_versions
|
||||
WHERE type = $1
|
||||
ORDER BY created DESC
|
||||
",
|
||||
version_type
|
||||
)
|
||||
.fetch_many(exec)
|
||||
.try_filter_map(|e| async { Ok(e.right().map(|c| c.version)) })
|
||||
.try_collect::<Vec<String>>()
|
||||
.await?;
|
||||
}
|
||||
} else if let Some(major) = major_option {
|
||||
result = sqlx::query!(
|
||||
"
|
||||
SELECT version FROM game_versions
|
||||
WHERE major = $1
|
||||
ORDER BY created DESC
|
||||
",
|
||||
major
|
||||
)
|
||||
.fetch_many(exec)
|
||||
.try_filter_map(|e| async { Ok(e.right().map(|c| c.version)) })
|
||||
.try_collect::<Vec<String>>()
|
||||
.await?;
|
||||
} else {
|
||||
result = Vec::new();
|
||||
}
|
||||
|
||||
Ok(result)
|
||||
}
|
||||
@@ -755,3 +799,129 @@ impl<'a> DonationPlatformBuilder<'a> {
|
||||
Ok(DonationPlatformId(result.id))
|
||||
}
|
||||
}
|
||||
|
||||
pub struct ReportTypeBuilder<'a> {
|
||||
pub name: Option<&'a str>,
|
||||
}
|
||||
|
||||
impl ReportType {
|
||||
pub fn builder() -> ReportTypeBuilder<'static> {
|
||||
ReportTypeBuilder { name: None }
|
||||
}
|
||||
|
||||
pub async fn get_id<'a, E>(name: &str, exec: E) -> Result<Option<ReportTypeId>, DatabaseError>
|
||||
where
|
||||
E: sqlx::Executor<'a, Database = sqlx::Postgres>,
|
||||
{
|
||||
if !name
|
||||
.chars()
|
||||
.all(|c| c.is_ascii_alphanumeric() || c == '-' || c == '_')
|
||||
{
|
||||
return Err(DatabaseError::InvalidIdentifier(name.to_string()));
|
||||
}
|
||||
|
||||
let result = sqlx::query!(
|
||||
"
|
||||
SELECT id FROM report_types
|
||||
WHERE name = $1
|
||||
",
|
||||
name
|
||||
)
|
||||
.fetch_optional(exec)
|
||||
.await?;
|
||||
|
||||
Ok(result.map(|r| ReportTypeId(r.id)))
|
||||
}
|
||||
|
||||
pub async fn get_name<'a, E>(id: ReportTypeId, exec: E) -> Result<String, DatabaseError>
|
||||
where
|
||||
E: sqlx::Executor<'a, Database = sqlx::Postgres>,
|
||||
{
|
||||
let result = sqlx::query!(
|
||||
"
|
||||
SELECT name FROM report_types
|
||||
WHERE id = $1
|
||||
",
|
||||
id as ReportTypeId
|
||||
)
|
||||
.fetch_one(exec)
|
||||
.await?;
|
||||
|
||||
Ok(result.name)
|
||||
}
|
||||
|
||||
pub async fn list<'a, E>(exec: E) -> Result<Vec<String>, DatabaseError>
|
||||
where
|
||||
E: sqlx::Executor<'a, Database = sqlx::Postgres>,
|
||||
{
|
||||
let result = sqlx::query!(
|
||||
"
|
||||
SELECT name FROM report_types
|
||||
"
|
||||
)
|
||||
.fetch_many(exec)
|
||||
.try_filter_map(|e| async { Ok(e.right().map(|c| c.name)) })
|
||||
.try_collect::<Vec<String>>()
|
||||
.await?;
|
||||
|
||||
Ok(result)
|
||||
}
|
||||
|
||||
// TODO: remove loaders with mods using them
|
||||
pub async fn remove<'a, E>(name: &str, exec: E) -> Result<Option<()>, DatabaseError>
|
||||
where
|
||||
E: sqlx::Executor<'a, Database = sqlx::Postgres>,
|
||||
{
|
||||
use sqlx::Done;
|
||||
|
||||
let result = sqlx::query!(
|
||||
"
|
||||
DELETE FROM report_types
|
||||
WHERE name = $1
|
||||
",
|
||||
name
|
||||
)
|
||||
.execute(exec)
|
||||
.await?;
|
||||
|
||||
if result.rows_affected() == 0 {
|
||||
// Nothing was deleted
|
||||
Ok(None)
|
||||
} else {
|
||||
Ok(Some(()))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl<'a> ReportTypeBuilder<'a> {
|
||||
/// The name of the report type. Must be ASCII alphanumeric or `-`/`_`
|
||||
pub fn name(self, name: &'a str) -> Result<ReportTypeBuilder<'a>, DatabaseError> {
|
||||
if name
|
||||
.chars()
|
||||
.all(|c| c.is_ascii_alphanumeric() || c == '-' || c == '_')
|
||||
{
|
||||
Ok(Self { name: Some(name) })
|
||||
} else {
|
||||
Err(DatabaseError::InvalidIdentifier(name.to_string()))
|
||||
}
|
||||
}
|
||||
|
||||
pub async fn insert<'b, E>(self, exec: E) -> Result<ReportTypeId, DatabaseError>
|
||||
where
|
||||
E: sqlx::Executor<'b, Database = sqlx::Postgres>,
|
||||
{
|
||||
let result = sqlx::query!(
|
||||
"
|
||||
INSERT INTO report_types (name)
|
||||
VALUES ($1)
|
||||
ON CONFLICT (name) DO NOTHING
|
||||
RETURNING id
|
||||
",
|
||||
self.name
|
||||
)
|
||||
.fetch_one(exec)
|
||||
.await?;
|
||||
|
||||
Ok(ReportTypeId(result.id))
|
||||
}
|
||||
}
|
||||
|
||||
@@ -86,6 +86,13 @@ generate_ids!(
|
||||
"SELECT EXISTS(SELECT 1 FROM users WHERE id=$1)",
|
||||
UserId
|
||||
);
|
||||
generate_ids!(
|
||||
pub generate_report_id,
|
||||
ReportId,
|
||||
8,
|
||||
"SELECT EXISTS(SELECT 1 FROM reports WHERE id=$1)",
|
||||
ReportId
|
||||
);
|
||||
|
||||
#[derive(Copy, Clone, Debug, PartialEq, Eq, Type)]
|
||||
#[sqlx(transparent)]
|
||||
@@ -130,6 +137,13 @@ pub struct LoaderId(pub i32);
|
||||
#[sqlx(transparent)]
|
||||
pub struct CategoryId(pub i32);
|
||||
|
||||
#[derive(Copy, Clone, Debug, Type)]
|
||||
#[sqlx(transparent)]
|
||||
pub struct ReportId(pub i64);
|
||||
#[derive(Copy, Clone, Debug, Type)]
|
||||
#[sqlx(transparent)]
|
||||
pub struct ReportTypeId(pub i32);
|
||||
|
||||
#[derive(Copy, Clone, Debug, Type)]
|
||||
#[sqlx(transparent)]
|
||||
pub struct FileId(pub i64);
|
||||
@@ -180,3 +194,13 @@ impl From<VersionId> for ids::VersionId {
|
||||
ids::VersionId(id.0 as u64)
|
||||
}
|
||||
}
|
||||
impl From<ids::ReportId> for ReportId {
|
||||
fn from(id: ids::ReportId) -> Self {
|
||||
ReportId(id.0 as i64)
|
||||
}
|
||||
}
|
||||
impl From<ReportId> for ids::ReportId {
|
||||
fn from(id: ReportId) -> Self {
|
||||
ids::ReportId(id.0 as u64)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -6,6 +6,7 @@ use thiserror::Error;
|
||||
pub mod categories;
|
||||
pub mod ids;
|
||||
pub mod mod_item;
|
||||
pub mod report_item;
|
||||
pub mod team_item;
|
||||
pub mod user_item;
|
||||
pub mod version_item;
|
||||
|
||||
@@ -300,6 +300,16 @@ impl Mod {
|
||||
return Ok(None);
|
||||
};
|
||||
|
||||
sqlx::query!(
|
||||
"
|
||||
DELETE FROM reports
|
||||
WHERE mod_id = $1
|
||||
",
|
||||
id as ModId,
|
||||
)
|
||||
.execute(exec)
|
||||
.await?;
|
||||
|
||||
sqlx::query!(
|
||||
"
|
||||
DELETE FROM mods_categories
|
||||
@@ -453,13 +463,13 @@ impl Mod {
|
||||
categories: m
|
||||
.categories
|
||||
.unwrap_or_default()
|
||||
.split(",")
|
||||
.split(',')
|
||||
.map(|x| x.to_string())
|
||||
.collect(),
|
||||
versions: m
|
||||
.versions
|
||||
.unwrap_or_default()
|
||||
.split(",")
|
||||
.split(',')
|
||||
.map(|x| VersionId(x.parse().unwrap_or_default()))
|
||||
.collect(),
|
||||
donation_urls: vec![],
|
||||
@@ -531,8 +541,8 @@ impl Mod {
|
||||
slug: m.slug.clone(),
|
||||
body: m.body.clone(),
|
||||
},
|
||||
categories: m.categories.unwrap_or_default().split(",").map(|x| x.to_string()).collect(),
|
||||
versions: m.versions.unwrap_or_default().split(",").map(|x| VersionId(x.parse().unwrap_or_default())).collect(),
|
||||
categories: m.categories.unwrap_or_default().split(',').map(|x| x.to_string()).collect(),
|
||||
versions: m.versions.unwrap_or_default().split(',').map(|x| VersionId(x.parse().unwrap_or_default())).collect(),
|
||||
donation_urls: vec![],
|
||||
status: crate::models::mods::ModStatus::from_str(&m.status_name),
|
||||
license_id: m.short,
|
||||
|
||||
153
src/database/models/report_item.rs
Normal file
153
src/database/models/report_item.rs
Normal file
@@ -0,0 +1,153 @@
|
||||
use super::ids::*;
|
||||
|
||||
pub struct Report {
|
||||
pub id: ReportId,
|
||||
pub report_type_id: ReportTypeId,
|
||||
pub mod_id: Option<ModId>,
|
||||
pub version_id: Option<VersionId>,
|
||||
pub user_id: Option<UserId>,
|
||||
pub body: String,
|
||||
pub reporter: UserId,
|
||||
pub created: chrono::DateTime<chrono::Utc>,
|
||||
}
|
||||
|
||||
pub struct QueryReport {
|
||||
pub id: ReportId,
|
||||
pub report_type: String,
|
||||
pub mod_id: Option<ModId>,
|
||||
pub version_id: Option<VersionId>,
|
||||
pub user_id: Option<UserId>,
|
||||
pub body: String,
|
||||
pub reporter: UserId,
|
||||
pub created: chrono::DateTime<chrono::Utc>,
|
||||
}
|
||||
|
||||
impl Report {
|
||||
pub async fn insert(
|
||||
&self,
|
||||
transaction: &mut sqlx::Transaction<'_, sqlx::Postgres>,
|
||||
) -> Result<(), sqlx::error::Error> {
|
||||
sqlx::query!(
|
||||
"
|
||||
INSERT INTO reports (
|
||||
id, report_type_id, mod_id, version_id, user_id,
|
||||
body, reporter
|
||||
)
|
||||
VALUES (
|
||||
$1, $2, $3, $4, $5,
|
||||
$6, $7
|
||||
)
|
||||
",
|
||||
self.id as ReportId,
|
||||
self.report_type_id as ReportTypeId,
|
||||
self.mod_id.map(|x| x.0 as i64),
|
||||
self.version_id.map(|x| x.0 as i64),
|
||||
self.user_id.map(|x| x.0 as i64),
|
||||
self.body,
|
||||
self.reporter as UserId
|
||||
)
|
||||
.execute(&mut *transaction)
|
||||
.await?;
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub async fn get<'a, E>(id: ReportId, exec: E) -> Result<Option<QueryReport>, sqlx::Error>
|
||||
where
|
||||
E: sqlx::Executor<'a, Database = sqlx::Postgres> + Copy,
|
||||
{
|
||||
let result = sqlx::query!(
|
||||
"
|
||||
SELECT rt.name, r.mod_id, r.version_id, r.user_id, r.body, r.reporter, r.created
|
||||
FROM reports r
|
||||
INNER JOIN report_types rt ON rt.id = r.report_type_id
|
||||
WHERE r.id = $1
|
||||
",
|
||||
id as ReportId,
|
||||
)
|
||||
.fetch_optional(exec)
|
||||
.await?;
|
||||
|
||||
if let Some(row) = result {
|
||||
Ok(Some(QueryReport {
|
||||
id,
|
||||
report_type: row.name,
|
||||
mod_id: row.mod_id.map(ModId),
|
||||
version_id: row.version_id.map(VersionId),
|
||||
user_id: row.user_id.map(UserId),
|
||||
body: row.body,
|
||||
reporter: UserId(row.reporter),
|
||||
created: row.created,
|
||||
}))
|
||||
} else {
|
||||
Ok(None)
|
||||
}
|
||||
}
|
||||
|
||||
pub async fn get_many<'a, E>(
|
||||
version_ids: Vec<ReportId>,
|
||||
exec: E,
|
||||
) -> Result<Vec<QueryReport>, sqlx::Error>
|
||||
where
|
||||
E: sqlx::Executor<'a, Database = sqlx::Postgres> + Copy,
|
||||
{
|
||||
use futures::stream::TryStreamExt;
|
||||
|
||||
let version_ids_parsed: Vec<i64> = version_ids.into_iter().map(|x| x.0).collect();
|
||||
let versions = sqlx::query!(
|
||||
"
|
||||
SELECT r.id, rt.name, r.mod_id, r.version_id, r.user_id, r.body, r.reporter, r.created
|
||||
FROM reports r
|
||||
INNER JOIN report_types rt ON rt.id = r.report_type_id
|
||||
WHERE r.id IN (SELECT * FROM UNNEST($1::bigint[]))
|
||||
",
|
||||
&version_ids_parsed
|
||||
)
|
||||
.fetch_many(exec)
|
||||
.try_filter_map(|e| async {
|
||||
Ok(e.right().map(|row| QueryReport {
|
||||
id: ReportId(row.id),
|
||||
report_type: row.name,
|
||||
mod_id: row.mod_id.map(ModId),
|
||||
version_id: row.version_id.map(VersionId),
|
||||
user_id: row.user_id.map(UserId),
|
||||
body: row.body,
|
||||
reporter: UserId(row.reporter),
|
||||
created: row.created,
|
||||
}))
|
||||
})
|
||||
.try_collect::<Vec<QueryReport>>()
|
||||
.await?;
|
||||
|
||||
Ok(versions)
|
||||
}
|
||||
|
||||
pub async fn remove_full<'a, E>(id: ReportId, exec: E) -> Result<Option<()>, sqlx::Error>
|
||||
where
|
||||
E: sqlx::Executor<'a, Database = sqlx::Postgres> + Copy,
|
||||
{
|
||||
let result = sqlx::query!(
|
||||
"
|
||||
SELECT EXISTS(SELECT 1 FROM reports WHERE id = $1)
|
||||
",
|
||||
id as ReportId
|
||||
)
|
||||
.fetch_one(exec)
|
||||
.await?;
|
||||
|
||||
if !result.exists.unwrap_or(false) {
|
||||
return Ok(None);
|
||||
}
|
||||
|
||||
sqlx::query!(
|
||||
"
|
||||
DELETE FROM reports WHERE id = $1
|
||||
",
|
||||
id as ReportId,
|
||||
)
|
||||
.execute(exec)
|
||||
.await?;
|
||||
|
||||
Ok(Some(()))
|
||||
}
|
||||
}
|
||||
@@ -239,6 +239,16 @@ impl User {
|
||||
.execute(exec)
|
||||
.await?;
|
||||
|
||||
sqlx::query!(
|
||||
"
|
||||
DELETE FROM reports
|
||||
WHERE user_id = $1
|
||||
",
|
||||
id as UserId,
|
||||
)
|
||||
.execute(exec)
|
||||
.await?;
|
||||
|
||||
sqlx::query!(
|
||||
"
|
||||
DELETE FROM team_members
|
||||
|
||||
@@ -217,6 +217,16 @@ impl Version {
|
||||
return Ok(None);
|
||||
}
|
||||
|
||||
sqlx::query!(
|
||||
"
|
||||
DELETE FROM reports
|
||||
WHERE version_id = $1
|
||||
",
|
||||
id as VersionId,
|
||||
)
|
||||
.execute(exec)
|
||||
.await?;
|
||||
|
||||
sqlx::query!(
|
||||
"
|
||||
DELETE FROM game_versions_versions gvv
|
||||
@@ -569,13 +579,13 @@ impl Version {
|
||||
game_versions: v
|
||||
.game_versions
|
||||
.unwrap_or_default()
|
||||
.split(",")
|
||||
.split(',')
|
||||
.map(|x| x.to_string())
|
||||
.collect(),
|
||||
loaders: v
|
||||
.loaders
|
||||
.unwrap_or_default()
|
||||
.split(",")
|
||||
.split(',')
|
||||
.map(|x| x.to_string())
|
||||
.collect(),
|
||||
featured: v.featured,
|
||||
@@ -683,8 +693,8 @@ impl Version {
|
||||
downloads: v.downloads,
|
||||
release_channel: v.release_channel,
|
||||
files,
|
||||
game_versions: v.game_versions.unwrap_or_default().split(",").map(|x| x.to_string()).collect(),
|
||||
loaders: v.loaders.unwrap_or_default().split(",").map(|x| x.to_string()).collect(),
|
||||
game_versions: v.game_versions.unwrap_or_default().split(',').map(|x| x.to_string()).collect(),
|
||||
loaders: v.loaders.unwrap_or_default().split(',').map(|x| x.to_string()).collect(),
|
||||
featured: v.featured,
|
||||
dependencies,
|
||||
}
|
||||
@@ -714,6 +724,7 @@ pub struct FileHash {
|
||||
pub hash: Vec<u8>,
|
||||
}
|
||||
|
||||
#[derive(Clone)]
|
||||
pub struct QueryVersion {
|
||||
pub id: VersionId,
|
||||
pub mod_id: ModId,
|
||||
@@ -733,6 +744,7 @@ pub struct QueryVersion {
|
||||
pub dependencies: Vec<(VersionId, String)>,
|
||||
}
|
||||
|
||||
#[derive(Clone)]
|
||||
pub struct QueryFile {
|
||||
pub id: FileId,
|
||||
pub url: String,
|
||||
|
||||
@@ -306,7 +306,8 @@ async fn main() -> std::io::Result<()> {
|
||||
.configure(routes::versions_config)
|
||||
.configure(routes::teams_config)
|
||||
.configure(routes::users_config)
|
||||
.configure(routes::moderation_config),
|
||||
.configure(routes::moderation_config)
|
||||
.configure(routes::reports_config),
|
||||
)
|
||||
.default_service(web::get().to(routes::not_found))
|
||||
})
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
use thiserror::Error;
|
||||
|
||||
pub use super::mods::{ModId, VersionId};
|
||||
pub use super::reports::ReportId;
|
||||
pub use super::teams::TeamId;
|
||||
pub use super::users::UserId;
|
||||
|
||||
@@ -107,6 +108,7 @@ base62_id_impl!(ModId, ModId);
|
||||
base62_id_impl!(UserId, UserId);
|
||||
base62_id_impl!(VersionId, VersionId);
|
||||
base62_id_impl!(TeamId, TeamId);
|
||||
base62_id_impl!(ReportId, ReportId);
|
||||
|
||||
pub mod base62_impl {
|
||||
use serde::de::{self, Deserializer, Visitor};
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
pub mod error;
|
||||
pub mod ids;
|
||||
pub mod mods;
|
||||
pub mod reports;
|
||||
pub mod teams;
|
||||
pub mod users;
|
||||
|
||||
39
src/models/reports.rs
Normal file
39
src/models/reports.rs
Normal file
@@ -0,0 +1,39 @@
|
||||
use super::ids::Base62Id;
|
||||
use crate::models::ids::UserId;
|
||||
use chrono::{DateTime, Utc};
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
#[derive(Copy, Clone, PartialEq, Eq, Serialize, Deserialize)]
|
||||
#[serde(from = "Base62Id")]
|
||||
#[serde(into = "Base62Id")]
|
||||
pub struct ReportId(pub u64);
|
||||
|
||||
#[derive(Serialize, Deserialize)]
|
||||
pub struct Report {
|
||||
pub id: ReportId,
|
||||
pub report_type: String,
|
||||
pub item_id: String,
|
||||
pub item_type: ItemType,
|
||||
pub reporter: UserId,
|
||||
pub body: String,
|
||||
pub created: DateTime<Utc>,
|
||||
}
|
||||
|
||||
#[derive(Serialize, Deserialize, Clone)]
|
||||
pub enum ItemType {
|
||||
Mod,
|
||||
Version,
|
||||
User,
|
||||
Unknown,
|
||||
}
|
||||
|
||||
impl ItemType {
|
||||
pub fn as_str(&self) -> &'static str {
|
||||
match self {
|
||||
ItemType::Mod => "mod",
|
||||
ItemType::Version => "version",
|
||||
ItemType::User => "user",
|
||||
ItemType::Unknown => "unknown",
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -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),
|
||||
|
||||
@@ -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")]
|
||||
|
||||
@@ -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))
|
||||
}
|
||||
|
||||
@@ -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
181
src/routes/reports.rs
Normal 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(""))
|
||||
}
|
||||
}
|
||||
@@ -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(""))
|
||||
}
|
||||
}
|
||||
|
||||
@@ -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(""))
|
||||
|
||||
@@ -14,8 +14,8 @@ pub mod indexing;
|
||||
|
||||
#[derive(Error, Debug)]
|
||||
pub enum SearchError {
|
||||
#[error("Error while connecting to the MeiliSearch database: {0}")]
|
||||
IndexDBError(#[from] meilisearch_sdk::errors::Error),
|
||||
#[error("MeiliSearch Error: {0}")]
|
||||
MeiliSearchError(#[from] meilisearch_sdk::errors::Error),
|
||||
#[error("Error while serializing or deserializing JSON: {0}")]
|
||||
SerDeError(#[from] serde_json::Error),
|
||||
#[error("Error while parsing an integer: {0}")]
|
||||
@@ -30,7 +30,7 @@ impl actix_web::ResponseError for SearchError {
|
||||
fn status_code(&self) -> StatusCode {
|
||||
match self {
|
||||
SearchError::EnvError(..) => StatusCode::INTERNAL_SERVER_ERROR,
|
||||
SearchError::IndexDBError(..) => StatusCode::INTERNAL_SERVER_ERROR,
|
||||
SearchError::MeiliSearchError(..) => StatusCode::BAD_REQUEST,
|
||||
SearchError::SerDeError(..) => StatusCode::BAD_REQUEST,
|
||||
SearchError::IntParsingError(..) => StatusCode::BAD_REQUEST,
|
||||
SearchError::InvalidIndex(..) => StatusCode::BAD_REQUEST,
|
||||
@@ -41,7 +41,7 @@ impl actix_web::ResponseError for SearchError {
|
||||
HttpResponse::build(self.status_code()).json(ApiError {
|
||||
error: match self {
|
||||
SearchError::EnvError(..) => "environment_error",
|
||||
SearchError::IndexDBError(..) => "indexdb_error",
|
||||
SearchError::MeiliSearchError(..) => "meilisearch_error",
|
||||
SearchError::SerDeError(..) => "invalid_input",
|
||||
SearchError::IntParsingError(..) => "invalid_input",
|
||||
SearchError::InvalidIndex(..) => "invalid_input",
|
||||
|
||||
Reference in New Issue
Block a user