use common::{ constant::LOG_PAGE_LIMIT, error::Error, model::{Id, Report, ReportStatus}, time::now_ms, }; use super::{Connection, all, community, exec, one, user}; use crate::error::ServerError; struct Raw { id: Id, created_at: u64, reporter_id: Option, target_id: Option, message_id: Option, community_id: Option, body: Option, reason: String, status: ReportStatus, handled_by: Option, } pub async fn is_open( reporter_id: Id, target_id: Id, message_id: Option, db: &Connection, ) -> Result { one( db, "SELECT EXISTS (SELECT 1 FROM report WHERE reporter_id = ?1 AND target_id = ?2 AND message_id IS ?3 AND status = ?4)", (reporter_id, target_id, message_id, ReportStatus::Open.as_str()), |r| r.get(), ) .await } pub async fn insert( reporter_id: Id, target_id: Id, message_id: Option, community_id: Option, body: Option<&str>, reason: &str, db: &Connection, ) -> Result<(), ServerError> { exec( db, "INSERT INTO report (created_at, reporter_id, target_id, message_id, community_id, body, reason, status) VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8)", ( now_ms(), reporter_id, target_id, message_id, community_id, body, reason, ReportStatus::Open.as_str(), ), ) .await } pub async fn list( status: Option, db: &Connection, ) -> Result, ServerError> { let raws = all( db, "SELECT id, created_at, reporter_id, target_id, message_id, community_id, body, reason, status, handled_by FROM report WHERE ?1 IS NULL OR status = ?1 ORDER BY id DESC LIMIT ?2", (status.map(ReportStatus::as_str), LOG_PAGE_LIMIT), |r| { Ok(Raw { id: r.get()?, created_at: r.get()?, reporter_id: r.get()?, target_id: r.get()?, message_id: r.get()?, community_id: r.get()?, body: r.get()?, reason: r.get()?, status: r.named()?, handled_by: r.get()?, }) }, ) .await?; let mut reports = Vec::new(); for raw in raws { let community = match raw.community_id { Some(id) => match community::label(id, db).await { Ok(label) => Some(label), Err(ServerError::Wire(Error::NotFound)) => None, Err(error) => return Err(error), }, None => None, }; reports.push(Report { id: raw.id, created_at: raw.created_at, reporter: user::read_optional(raw.reporter_id, db).await?, target: user::read_optional(raw.target_id, db).await?, message_id: raw.message_id, community_id: raw.community_id, community, body: raw.body, reason: raw.reason, status: raw.status, handled_by: user::read_optional(raw.handled_by, db).await?, }); } Ok(reports) } pub async fn handle( report_id: Id, status: ReportStatus, handled_by: Id, db: &Connection, ) -> Result, ServerError> { one( db, "UPDATE report SET status = ?2, handled_by = ?3 WHERE id = ?1 AND status = ?4 RETURNING target_id", (report_id, status.as_str(), handled_by, ReportStatus::Open.as_str()), |r| r.get(), ) .await }