tetratto/crates/core/src/database/reports.rs
2025-06-15 12:19:58 -04:00

113 lines
3.5 KiB
Rust

use oiseau::cache::Cache;
use crate::model::moderation::AuditLogEntry;
use crate::model::{Error, Result, auth::User, moderation::Report, permissions::FinePermission};
use crate::{auto_method, DataManager};
use oiseau::PostgresRow;
use oiseau::{execute, get, query_rows, params};
impl DataManager {
/// Get a [`Report`] from an SQL row.
pub(crate) fn get_report_from_row(x: &PostgresRow) -> Report {
Report {
id: get!(x->0(i64)) as usize,
created: get!(x->1(i64)) as usize,
owner: get!(x->2(i64)) as usize,
content: get!(x->3(String)),
asset: get!(x->4(i64)) as usize,
asset_type: serde_json::from_str(&get!(x->5(String))).unwrap(),
}
}
auto_method!(get_report_by_id(usize as i64)@get_report_from_row -> "SELECT * FROM reports WHERE id = $1" --name="report" --returns=Report --cache-key-tmpl="atto.reports:{}");
/// Get all reports (paginated).
///
/// # Arguments
/// * `batch` - the limit of items in each page
/// * `page` - the page number
pub async fn get_reports(&self, batch: usize, page: usize) -> Result<Vec<Report>> {
let conn = match self.0.connect().await {
Ok(c) => c,
Err(e) => return Err(Error::DatabaseConnection(e.to_string())),
};
let res = query_rows!(
&conn,
"SELECT * FROM reports ORDER BY created DESC LIMIT $1 OFFSET $2",
&[&(batch as i64), &((page * batch) as i64)],
|x| { Self::get_report_from_row(x) }
);
if res.is_err() {
return Err(Error::GeneralNotFound("report".to_string()));
}
Ok(res.unwrap())
}
/// Create a new report in the database.
///
/// # Arguments
/// * `data` - a mock [`Report`] object to insert
pub async fn create_report(&self, data: Report) -> Result<()> {
let conn = match self.0.connect().await {
Ok(c) => c,
Err(e) => return Err(Error::DatabaseConnection(e.to_string())),
};
let res = execute!(
&conn,
"INSERT INTO reports VALUES ($1, $2, $3, $4, $5, $6)",
params![
&(data.id as i64),
&(data.created as i64),
&(data.owner as i64),
&data.content.as_str(),
&(data.asset as i64),
&serde_json::to_string(&data.asset_type).unwrap().as_str(),
]
);
if let Err(e) = res {
return Err(Error::DatabaseError(e.to_string()));
}
// return
Ok(())
}
pub async fn delete_report(&self, id: usize, user: User) -> Result<()> {
if let Err(e) = self.get_report_by_id(id).await {
return Err(e);
}
if !user.permissions.check(FinePermission::MANAGE_REPORTS) {
return Err(Error::NotAllowed);
}
let conn = match self.0.connect().await {
Ok(c) => c,
Err(e) => return Err(Error::DatabaseConnection(e.to_string())),
};
let res = execute!(&conn, "DELETE FROM reports WHERE id = $1", &[&(id as i64)]);
if let Err(e) = res {
return Err(Error::DatabaseError(e.to_string()));
}
self.0.1.remove(format!("atto.report:{}", id)).await;
// create audit log entry
self.create_audit_log_entry(AuditLogEntry::new(
user.id,
format!("invoked `delete_report` with x value `{id}`"),
))
.await?;
// return
Ok(())
}
}