tetratto_core/database/
reports.rs1use oiseau::cache::Cache;
2use crate::model::moderation::AuditLogEntry;
3use crate::model::{Error, Result, auth::User, moderation::Report, permissions::FinePermission};
4use crate::{auto_method, DataManager};
5
6use oiseau::PostgresRow;
7
8use oiseau::{execute, get, query_rows, params};
9
10impl DataManager {
11 pub(crate) fn get_report_from_row(x: &PostgresRow) -> Report {
13 Report {
14 id: get!(x->0(i64)) as usize,
15 created: get!(x->1(i64)) as usize,
16 owner: get!(x->2(i64)) as usize,
17 content: get!(x->3(String)),
18 asset: get!(x->4(i64)) as usize,
19 asset_type: serde_json::from_str(&get!(x->5(String))).unwrap(),
20 }
21 }
22
23 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:{}");
24
25 pub async fn get_reports(&self, batch: usize, page: usize) -> Result<Vec<Report>> {
31 let conn = match self.0.connect().await {
32 Ok(c) => c,
33 Err(e) => return Err(Error::DatabaseConnection(e.to_string())),
34 };
35
36 let res = query_rows!(
37 &conn,
38 "SELECT * FROM reports ORDER BY created DESC LIMIT $1 OFFSET $2",
39 &[&(batch as i64), &((page * batch) as i64)],
40 |x| { Self::get_report_from_row(x) }
41 );
42
43 if res.is_err() {
44 return Err(Error::GeneralNotFound("report".to_string()));
45 }
46
47 Ok(res.unwrap())
48 }
49
50 pub async fn create_report(&self, data: Report) -> Result<()> {
55 let conn = match self.0.connect().await {
56 Ok(c) => c,
57 Err(e) => return Err(Error::DatabaseConnection(e.to_string())),
58 };
59
60 let res = execute!(
61 &conn,
62 "INSERT INTO reports VALUES ($1, $2, $3, $4, $5, $6)",
63 params![
64 &(data.id as i64),
65 &(data.created as i64),
66 &(data.owner as i64),
67 &data.content.as_str(),
68 &(data.asset as i64),
69 &serde_json::to_string(&data.asset_type).unwrap().as_str(),
70 ]
71 );
72
73 if let Err(e) = res {
74 return Err(Error::DatabaseError(e.to_string()));
75 }
76
77 Ok(())
79 }
80
81 pub async fn delete_report(&self, id: usize, user: User) -> Result<()> {
82 self.get_report_by_id(id).await?;
83
84 if !user.permissions.check(FinePermission::MANAGE_REPORTS) {
85 return Err(Error::NotAllowed);
86 }
87
88 let conn = match self.0.connect().await {
89 Ok(c) => c,
90 Err(e) => return Err(Error::DatabaseConnection(e.to_string())),
91 };
92
93 let res = execute!(&conn, "DELETE FROM reports WHERE id = $1", &[&(id as i64)]);
94
95 if let Err(e) = res {
96 return Err(Error::DatabaseError(e.to_string()));
97 }
98
99 self.0.1.remove(format!("atto.report:{}", id)).await;
100
101 self.create_audit_log_entry(AuditLogEntry::new(
103 user.id,
104 format!("invoked `delete_report` with x value `{id}`"),
105 ))
106 .await?;
107
108 Ok(())
110 }
111}