//! Staff pages: the flag queue (`/admin/flags`), users and their sanctions
//! (`/admin/users`), and the moderation log (`/admin/log`). Each is a table
//! in Classic and cards in Focus, like the other admin pages; actions are
//! inline (htmx swaps the item they act on). The rules are
//! `crate::moderation`'s.
use std::collections::HashMap;
use axum::extract::{Form, Path, Query, State};
use axum::http::{HeaderMap, StatusCode};
use axum::response::{IntoResponse, Response};
use chrono::{Duration, Utc};
use minijinja::context;
use sea_orm::*;
use serde::{Deserialize, Serialize};
use tracing::error;
use uuid::Uuid;
use super::focus::{view_for, ViewMode};
use super::render;
use crate::entities::{moderation_log, post_flags, posts, topics, users};
use crate::middleware::UserContext;
use crate::moderation::{self, Actor, FlagCounts, FlaggerRecord, Sanction};
use crate::policy::{self, FlagThreshold};
use crate::timeutil::{abs, rel};
use crate::AppState;
fn ise<E: std::fmt::Display>(ctx: &'static str) -> impl Fn(E) -> StatusCode {
move |e| {
error!(error = %e, "{ctx}");
StatusCode::INTERNAL_SERVER_ERROR
}
}
fn require_staff(u: &UserContext) -> Result<(), StatusCode> {
if u.user.is_staff {
Ok(())
} else {
Err(StatusCode::FORBIDDEN)
}
}
#[derive(Debug, Default, Deserialize)]
pub struct ViewQuery {
pub view: Option<String>,
/// `/admin/users?q=` and `/admin/log?q=`: filter.
pub q: Option<String>,
/// `/admin/flags?author=` / `?flagger=`, `/admin/log?user=`: one user's.
pub author: Option<Uuid>,
pub flagger: Option<Uuid>,
pub user: Option<Uuid>,
}
/// Times a user has been silenced or suspended (from the log).
async fn sanction_count(state: &AppState, user_id: Uuid) -> Result<u64, StatusCode> {
moderation_log::Entity::find()
.filter(moderation_log::Column::TargetId.eq(user_id))
.filter(moderation_log::Column::Action.is_in(["silence_user", "suspend_user"]))
.count(state.db.as_ref())
.await
.map_err(ise("count sanctions"))
}
// --- the flag queue ---------------------------------------------------------
/// One flag, for staff.
#[derive(Serialize, Clone)]
pub struct FlagRow {
pub flagger: String,
pub flagger_id: Uuid,
pub reason: String,
pub reason_label: &'static str,
pub note: Option<String>,
pub created_rel: String,
pub created_abs: String,
/// The flagger is flag-shadowbanned: recorded, not counted.
pub ignored: bool,
/// Their record: upheld / dismissed / pending.
pub record: FlaggerRecord,
}
/// A flagged post in the queue.
#[derive(Serialize)]
pub struct QueueItem {
pub post_id: Uuid,
pub post_number: i32,
pub topic_id: Uuid,
pub topic_title: String,
pub topic_locked: bool,
pub author: String,
pub author_id: Uuid,
pub author_staff: bool,
pub author_silenced: Option<String>,
pub author_suspended: Option<String>,
/// At a glance: trust level, account age, past sanctions, and their own
/// record as a flagger.
pub author_trust: i32,
pub author_age: String,
pub author_sanctions: u64,
pub author_record: FlaggerRecord,
pub author_flags_ignored: bool,
pub cooked: String,
pub deleted: bool,
pub moderated: bool,
pub hidden: bool,
/// Counted flags, and those from shadowbanned flaggers (collapsed).
pub flags: Vec<FlagRow>,
pub ignored_flags: Vec<FlagRow>,
pub reasons: Vec<(String, usize)>,
/// The auto-hide's inputs: counted flaggers, readers, their share.
pub counts: FlagCounts,
pub share_pct: String,
pub would_hide: bool,
/// Resolved since the page loaded (the swapped-in stub).
pub resolved: Option<String>,
}
/// A post's pending flags, for the moderation form.
pub async fn pending_flags_for(state: &AppState, post_id: Uuid) -> Result<Vec<FlagRow>, StatusCode> {
let rows = post_flags::Entity::find()
.filter(post_flags::Column::PostId.eq(post_id))
.filter(post_flags::Column::ResolvedAt.is_null())
.find_also_related(users::Entity)
.all(state.db.as_ref())
.await
.map_err(ise("load flags"))?;
flag_rows(state, rows).await
}
async fn flag_rows(
state: &AppState,
rows: Vec<(post_flags::Model, Option<users::Model>)>,
) -> Result<Vec<FlagRow>, StatusCode> {
let mut records: HashMap<Uuid, FlaggerRecord> = HashMap::new();
let mut out = Vec::with_capacity(rows.len());
for (f, u) in rows {
let record = match records.get(&f.user_id) {
Some(r) => *r,
None => {
let r = moderation::flagger_record(state.db.as_ref(), f.user_id).await.map_err(ise("flag record"))?;
records.insert(f.user_id, r);
r
}
};
out.push(FlagRow {
flagger: u.as_ref().map(|u| u.username.clone()).unwrap_or_else(|| "unknown".into()),
flagger_id: f.user_id,
reason_label: policy::flag_reason_label(&f.reason),
reason: f.reason,
note: f.note,
created_rel: rel(f.created_at),
created_abs: abs(f.created_at),
ignored: u.as_ref().is_some_and(|u| u.flags_ignored_at.is_some()),
record,
});
}
Ok(out)
}
async fn queue_item(state: &AppState, post: posts::Model) -> Result<QueueItem, StatusCode> {
let db = state.db.as_ref();
let topic = topics::Entity::find_by_id(post.topic_id).one(db).await.map_err(ise("load topic"))?;
let author = users::Entity::find_by_id(post.user_id).one(db).await.map_err(ise("load author"))?;
let flags = pending_flags_for(state, post.id).await?;
let (ignored_flags, flags): (Vec<FlagRow>, Vec<FlagRow>) = flags.into_iter().partition(|f| f.ignored);
let mut reasons: Vec<(String, usize)> = Vec::new();
for f in &flags {
match reasons.iter_mut().find(|(l, _)| l == f.reason_label) {
Some((_, n)) => *n += 1,
None => reasons.push((f.reason_label.to_string(), 1)),
}
}
let counts = moderation::flag_counts(db, &post).await.map_err(ise("flag counts"))?;
let t = state.config.flag_threshold;
Ok(QueueItem {
post_id: post.id,
post_number: post.post_number,
topic_id: post.topic_id,
topic_title: topic.as_ref().map(|t| t.title.clone()).unwrap_or_default(),
topic_locked: topic.as_ref().is_some_and(|t| t.is_closed),
author: author.as_ref().map(|u| u.username.clone()).unwrap_or_else(|| "unknown".into()),
author_id: post.user_id,
author_staff: author.as_ref().is_some_and(|u| u.is_staff),
author_silenced: author.as_ref().and_then(policy::silence).map(|s| format!("silenced{}", s.until_text())),
author_suspended: author.as_ref().and_then(policy::suspension).map(|s| format!("suspended{}", s.until_text())),
author_trust: author.as_ref().map(|u| u.trust_level).unwrap_or(0),
author_age: author.as_ref().map(|u| rel(u.created_at)).unwrap_or_default(),
author_sanctions: sanction_count(state, post.user_id).await?,
author_record: moderation::flagger_record(db, post.user_id).await.map_err(ise("author record"))?,
author_flags_ignored: author.as_ref().is_some_and(|u| u.flags_ignored_at.is_some()),
cooked: post.cooked,
deleted: post.deleted_at.is_some(),
moderated: post.moderated_at.is_some(),
hidden: post.hidden_at.is_some(),
flags,
ignored_flags,
reasons,
share_pct: format!("{:.0}%", FlagThreshold::share(counts.flaggers, counts.readers) * 100.0),
would_hide: t.should_hide(counts.flaggers, counts.readers),
counts,
resolved: None,
})
}
/// Every post with pending flags: those with counted flags first (hidden
/// ones first, then most flagged), and apart, those flagged only by
/// shadowbanned flaggers.
async fn queue(
state: &AppState,
author: Option<Uuid>,
flagger: Option<Uuid>,
) -> Result<(Vec<QueueItem>, Vec<QueueItem>), StatusCode> {
let mut find = post_flags::Entity::find()
.select_only()
.column(post_flags::Column::PostId)
.distinct()
.filter(post_flags::Column::ResolvedAt.is_null());
if let Some(f) = flagger {
find = find.filter(post_flags::Column::UserId.eq(f));
}
let ids: Vec<Uuid> = find
.into_tuple()
.all(state.db.as_ref())
.await
.map_err(ise("load queue"))?;
let mut find = posts::Entity::find().filter(posts::Column::Id.is_in(ids));
if let Some(a) = author {
find = find.filter(posts::Column::UserId.eq(a));
}
let posts = find
.all(state.db.as_ref())
.await
.map_err(ise("load flagged posts"))?;
let mut items = Vec::with_capacity(posts.len());
for p in posts {
items.push(queue_item(state, p).await?);
}
items.sort_by(|a, b| b.hidden.cmp(&a.hidden).then(b.flags.len().cmp(&a.flags.len())));
Ok(items.into_iter().partition(|i| !i.flags.is_empty()))
}
/// `/admin/flags`
pub async fn flags_page(
State(state): State<AppState>,
Query(q): Query<ViewQuery>,
headers: HeaderMap,
user: UserContext,
) -> Result<Response, StatusCode> {
require_staff(&user)?;
let view = view_for(&state, q.view.as_deref(), Some(&user), &headers);
let (items, shadow) = queue(&state, q.author, q.flagger).await?;
let t = state.config.flag_threshold;
let filter_user = match q.author.or(q.flagger) {
Some(id) => users::Entity::find_by_id(id).one(state.db.as_ref()).await.map_err(ise("load filter user"))?,
None => None,
};
let filter = filter_user.map(|u| context! {
username => u.username, id => u.id, role => if q.author.is_some() { "author" } else { "flagger" },
});
let page = render(
&state,
if view.mode == ViewMode::Focus { "admin/flags_focus.html" } else { "admin/flags.html" },
context! {
title => "Flags",
app_name => state.config.app_name,
user => user.user,
items => items,
shadow => shadow,
mode => view.mode.as_str(),
filter => filter,
nav => "flags",
threshold => context! { ratio_pct => format!("{:.0}%", t.ratio * 100.0), min_flags => t.min_flags, enough_flags => t.enough_flags },
durations => DURATIONS,
},
)?;
Ok(view.respond(page))
}
/// What a queue action answers with: the item again (htmx), or the queue.
async fn queue_response(state: &AppState, post_id: Uuid, mode: Option<&str>, resolved: Option<&str>) -> Result<Response, StatusCode> {
let post = posts::Entity::find_by_id(post_id)
.one(state.db.as_ref())
.await
.map_err(ise("reload post"))?
.ok_or(StatusCode::NOT_FOUND)?;
let mut item = queue_item(state, post).await?;
item.resolved = resolved.map(str::to_string);
let focus = mode == Some("focus");
Ok(render(
state,
if focus { "admin/_flag_card.html" } else { "admin/_flag_row.html" },
context! { item => item, mode => if focus { "focus" } else { "classic" }, durations => DURATIONS },
)?
.into_response())
}
#[derive(Debug, Default, Deserialize)]
pub struct QueueForm {
pub mode: Option<String>,
pub reason: Option<String>,
pub note: Option<String>,
pub hide_original: Option<String>,
}
/// Dismiss a post's flags (and show it again if they hid it).
pub async fn flags_dismiss(
State(state): State<AppState>,
Path(post_id): Path<Uuid>,
user: UserContext,
Form(f): Form<QueueForm>,
) -> Result<Response, StatusCode> {
moderation::dismiss_flags(&state, Actor::web(&user.user), post_id).await?;
queue_response(&state, post_id, f.mode.as_deref(), Some("Flags dismissed")).await
}
/// Delete the post (upholds its flags).
pub async fn flags_delete(
State(state): State<AppState>,
Path(post_id): Path<Uuid>,
user: UserContext,
Form(f): Form<QueueForm>,
) -> Result<Response, StatusCode> {
require_staff(&user)?;
moderation::delete_post(&state, Actor::web(&user.user), post_id).await?;
queue_response(&state, post_id, f.mode.as_deref(), Some("Post deleted, flags upheld")).await
}
/// Replace the post with a staff note (upholds its flags).
pub async fn flags_moderate(
State(state): State<AppState>,
Path(post_id): Path<Uuid>,
user: UserContext,
Form(f): Form<QueueForm>,
) -> Result<Response, StatusCode> {
moderation::moderate_post(
&state,
Actor::web(&user.user),
post_id,
f.note.as_deref().unwrap_or(""),
f.hide_original.is_some(),
)
.await?;
queue_response(&state, post_id, f.mode.as_deref(), Some("Post moderated, flags upheld")).await
}
/// Lock the post's topic (the flags stay pending: a lock doesn't decide them).
pub async fn flags_lock(
State(state): State<AppState>,
Path(post_id): Path<Uuid>,
user: UserContext,
Form(f): Form<QueueForm>,
) -> Result<Response, StatusCode> {
require_staff(&user)?;
let post = posts::Entity::find_by_id(post_id)
.one(state.db.as_ref())
.await
.map_err(ise("load post"))?
.ok_or(StatusCode::NOT_FOUND)?;
moderation::set_locked(&state, Actor::web(&user.user), post.topic_id, true, f.reason.as_deref()).await?;
queue_response(&state, post_id, f.mode.as_deref(), None).await
}
// --- users ------------------------------------------------------------------
/// The sanction lengths offered (`duration` field): label, hours (0 =
/// until lifted).
pub const DURATIONS: [(&str, &str); 6] =
[("1h", "1 hour"), ("24h", "1 day"), ("72h", "3 days"), ("168h", "1 week"), ("720h", "30 days"), ("", "Until lifted")];
/// "24h" → 24 hours from now; blank → None (until lifted).
pub fn parse_duration(s: Option<&str>) -> Result<Option<chrono::DateTime<Utc>>, StatusCode> {
match s.map(str::trim) {
None | Some("") => Ok(None),
Some(v) => {
let (n, unit) = v.split_at(v.len() - 1);
let n: i64 = n.parse().map_err(|_| StatusCode::BAD_REQUEST)?;
let d = match unit {
"h" => Duration::hours(n),
"d" => Duration::days(n),
_ => return Err(StatusCode::BAD_REQUEST),
};
Ok(Some(Utc::now() + d))
}
}
}
/// A user, for staff.
#[derive(Serialize)]
pub struct UserRow {
pub id: Uuid,
pub username: String,
pub email: String,
pub is_staff: bool,
pub is_active: bool,
pub trust_level: i32,
pub joined: String,
pub silenced: Option<String>,
pub suspended: Option<String>,
pub flags_ignored: bool,
pub record: FlaggerRecord,
/// Flags on their posts staff upheld.
pub flagged_upheld: u64,
}
async fn user_row(state: &AppState, u: users::Model) -> Result<UserRow, StatusCode> {
let record = moderation::flagger_record(state.db.as_ref(), u.id).await.map_err(ise("flag record"))?;
let flagged_upheld = post_flags::Entity::find()
.filter(post_flags::Column::Resolution.eq("upheld"))
.inner_join(posts::Entity)
.filter(posts::Column::UserId.eq(u.id))
.count(state.db.as_ref())
.await
.map_err(ise("count upheld"))?;
let reason = |r: &Option<String>| r.as_ref().map(|r| format!(": {r}")).unwrap_or_default();
Ok(UserRow {
silenced: policy::silence(&u).map(|s| format!("Silenced{}{}", s.until_text(), reason(&s.reason))),
suspended: policy::suspension(&u).map(|s| format!("Suspended{}{}", s.until_text(), reason(&s.reason))),
flags_ignored: u.flags_ignored_at.is_some(),
id: u.id,
username: u.username,
email: u.email,
is_staff: u.is_staff,
is_active: u.is_active,
trust_level: u.trust_level,
joined: rel(u.created_at),
record,
flagged_upheld,
})
}
/// `/admin/users?q=`
pub async fn users_page(
State(state): State<AppState>,
Query(q): Query<ViewQuery>,
headers: HeaderMap,
user: UserContext,
) -> Result<Response, StatusCode> {
require_staff(&user)?;
let view = view_for(&state, q.view.as_deref(), Some(&user), &headers);
let mut find = users::Entity::find().order_by_asc(users::Column::Username);
let search = q.q.as_deref().map(str::trim).filter(|s| !s.is_empty());
if let Some(s) = search {
find = find.filter(
Condition::any()
.add(users::Column::Username.contains(s))
.add(users::Column::Email.contains(s)),
);
}
let all = find.limit(200).all(state.db.as_ref()).await.map_err(ise("load users"))?;
let mut rows = Vec::with_capacity(all.len());
for u in all {
rows.push(user_row(&state, u).await?);
}
let page = render(
&state,
if view.mode == ViewMode::Focus { "admin/users_focus.html" } else { "admin/users.html" },
context! {
title => "Users",
app_name => state.config.app_name,
user => user.user,
users => rows,
nav => "users",
q => search,
mode => view.mode.as_str(),
durations => DURATIONS,
},
)?;
Ok(view.respond(page))
}
/// `/admin/users/{id}`: one user, with their sanctions controls, their
/// flags (as author and as flagger) and their moderation-log entries.
pub async fn user_page(
State(state): State<AppState>,
Path(id): Path<Uuid>,
Query(q): Query<ViewQuery>,
headers: HeaderMap,
user: UserContext,
) -> Result<Response, StatusCode> {
require_staff(&user)?;
let view = view_for(&state, q.view.as_deref(), Some(&user), &headers);
let target = users::Entity::find_by_id(id)
.one(state.db.as_ref())
.await
.map_err(ise("load user"))?
.ok_or(StatusCode::NOT_FOUND)?;
let row = user_row(&state, target).await?;
let raised = post_flags::Entity::find()
.filter(post_flags::Column::UserId.eq(id))
.order_by_desc(post_flags::Column::CreatedAt)
.limit(50)
.find_also_related(posts::Entity)
.all(state.db.as_ref())
.await
.map_err(ise("load raised flags"))?;
let received = post_flags::Entity::find()
.inner_join(posts::Entity)
.filter(posts::Column::UserId.eq(id))
.order_by_desc(post_flags::Column::CreatedAt)
.limit(50)
.find_also_related(users::Entity)
.all(state.db.as_ref())
.await
.map_err(ise("load received flags"))?;
let flag_ctx = |f: &post_flags::Model, who: String, post: Option<Uuid>| context! {
reason => policy::flag_reason_label(&f.reason), note => f.note.clone(), when => rel(f.created_at),
status => f.resolution.clone().unwrap_or_else(|| "pending".into()), who => who, post_id => post.unwrap_or(f.post_id),
};
let raised: Vec<minijinja::Value> =
raised.iter().map(|(f, _)| flag_ctx(f, String::new(), None)).collect();
let received: Vec<minijinja::Value> = received
.iter()
.map(|(f, u)| flag_ctx(f, u.as_ref().map(|u| u.username.clone()).unwrap_or_default(), None))
.collect();
let log = log_rows(
&state,
moderation_log::Entity::find()
.filter(Condition::any().add(moderation_log::Column::ActorId.eq(id)).add(moderation_log::Column::TargetId.eq(id)))
.order_by_desc(moderation_log::Column::CreatedAt)
.limit(30),
)
.await?;
let page = render(&state, "admin/user.html", context! {
title => format!("@{}", row.username),
app_name => state.config.app_name,
user => user.user,
u => row,
raised => raised,
received => received,
log => log,
nav => "users",
// The card's actions answer with a card.
mode => "focus",
durations => DURATIONS,
})?;
Ok(view.respond(page))
}
#[derive(Debug, Default, Deserialize)]
pub struct SanctionForm {
pub reason: Option<String>,
/// See [`DURATIONS`].
pub duration: Option<String>,
/// `classic` / `focus`: which fragment to answer with.
pub mode: Option<String>,
/// Acting from the queue: answer with this post's queue item.
pub post: Option<Uuid>,
}
async fn user_response(state: &AppState, user_id: Uuid, f: &SanctionForm) -> Result<Response, StatusCode> {
if let Some(post) = f.post {
return queue_response(state, post, f.mode.as_deref(), None).await;
}
let u = users::Entity::find_by_id(user_id)
.one(state.db.as_ref())
.await
.map_err(ise("reload user"))?
.ok_or(StatusCode::NOT_FOUND)?;
let row = user_row(state, u).await?;
let focus = f.mode.as_deref() == Some("focus");
Ok(render(
state,
if focus { "admin/_user_card.html" } else { "admin/_user_row.html" },
context! { u => row, mode => if focus { "focus" } else { "classic" }, durations => DURATIONS },
)?
.into_response())
}
/// `POST /admin/users/{id}/{action}`: silence, suspend, unsilence,
/// unsuspend, flag-shadowban, flag-unshadowban.
pub async fn user_action(
State(state): State<AppState>,
Path((id, action)): Path<(Uuid, String)>,
user: UserContext,
Form(f): Form<SanctionForm>,
) -> Result<Response, StatusCode> {
require_staff(&user)?;
let db = state.db.as_ref();
let actor = Actor::web(&user.user);
let reason = f.reason.as_deref();
match action.as_str() {
"silence" => {
moderation::sanction(db, actor, id, Sanction::Silence, reason, parse_duration(f.duration.as_deref())?).await?;
}
"suspend" => {
moderation::sanction(db, actor, id, Sanction::Suspend, reason, parse_duration(f.duration.as_deref())?).await?;
}
"unsilence" => {
moderation::lift(db, actor, id, Sanction::Silence).await?;
}
"unsuspend" => {
moderation::lift(db, actor, id, Sanction::Suspend).await?;
}
"flag-shadowban" => {
moderation::set_flags_ignored(db, actor, id, true, reason).await?;
}
"flag-unshadowban" => {
moderation::set_flags_ignored(db, actor, id, false, reason).await?;
}
_ => return Err(StatusCode::NOT_FOUND),
}
user_response(&state, id, &f).await
}
// --- the log ----------------------------------------------------------------
#[derive(Serialize)]
pub struct LogRow {
pub actor_id: Option<Uuid>,
pub target_user_id: Option<Uuid>,
pub when: String,
pub when_abs: String,
pub actor: String,
pub source: String,
pub action: String,
pub action_label: &'static str,
pub target_kind: String,
pub target_label: String,
pub target_href: Option<String>,
pub reason: Option<String>,
}
/// A person's words for a log action.
pub fn action_label(a: &str) -> &'static str {
match a {
"lock_topic" => "Locked topic",
"unlock_topic" => "Unlocked topic",
"pin_topic" => "Pinned topic",
"unpin_topic" => "Unpinned topic",
"delete_topic" => "Deleted topic",
"restore_topic" => "Restored topic",
"delete_post" => "Deleted post",
"restore_post" => "Restored post",
"moderate_post" => "Moderated post",
"hide_original" => "Hid original",
"unhide_original" => "Showed original",
"restore_post_body" => "Restored post body",
"auto_hide" => "Auto-hid post",
"dismiss_flags" => "Dismissed flags",
"silence_user" => "Silenced",
"unsilence_user" => "Lifted silence",
"suspend_user" => "Suspended",
"unsuspend_user" => "Lifted suspension",
"flag_shadowban" => "Ignored flags",
"flag_unshadowban" => "Counted flags again",
"category_permissions" => "Changed category permissions",
_ => "Other",
}
}
/// `/admin/log?q=` (q filters action, target or reason).
pub async fn log_page(
State(state): State<AppState>,
Query(q): Query<ViewQuery>,
headers: HeaderMap,
user: UserContext,
) -> Result<Response, StatusCode> {
require_staff(&user)?;
let view = view_for(&state, q.view.as_deref(), Some(&user), &headers);
let mut find = moderation_log::Entity::find().order_by_desc(moderation_log::Column::CreatedAt);
if let Some(u) = q.user {
find = find.filter(
Condition::any().add(moderation_log::Column::ActorId.eq(u)).add(moderation_log::Column::TargetId.eq(u)),
);
}
let search = q.q.as_deref().map(str::trim).filter(|s| !s.is_empty());
if let Some(s) = search {
find = find.filter(
Condition::any()
.add(moderation_log::Column::Action.contains(s))
.add(moderation_log::Column::TargetLabel.contains(s))
.add(moderation_log::Column::Reason.contains(s)),
);
}
let entries = log_rows(&state, find.limit(300)).await?;
let filter_user = match q.user {
Some(id) => users::Entity::find_by_id(id).one(state.db.as_ref()).await.map_err(ise("load filter user"))?,
None => None,
};
let page = render(
&state,
if view.mode == ViewMode::Focus { "admin/log_focus.html" } else { "admin/log.html" },
context! {
title => "Moderation log",
app_name => state.config.app_name,
user => user.user,
entries => entries,
q => search,
nav => "log",
filter => filter_user.map(|u| context! { username => u.username, id => u.id }),
},
)?;
Ok(view.respond(page))
}
async fn log_rows(state: &AppState, find: Select<moderation_log::Entity>) -> Result<Vec<LogRow>, StatusCode> {
let rows = find.all(state.db.as_ref()).await.map_err(ise("load log"))?;
let actor_ids: Vec<Uuid> = rows.iter().filter_map(|r| r.actor_id).collect();
let names: HashMap<Uuid, String> = users::Entity::find()
.filter(users::Column::Id.is_in(actor_ids))
.all(state.db.as_ref())
.await
.map_err(ise("load actors"))?
.into_iter()
.map(|u| (u.id, u.username))
.collect();
Ok(rows
.into_iter()
.map(|r| LogRow {
actor_id: r.actor_id,
target_user_id: (r.target_kind == "user").then_some(r.target_id).flatten(),
when: rel(r.created_at),
when_abs: abs(r.created_at),
actor: match (r.actor_id.and_then(|id| names.get(&id)), r.source.as_str()) {
(Some(n), _) => n.clone(),
(None, "system") => "system".into(),
(None, "cli") => "operator (CLI)".into(),
(None, _) => "deleted account".into(),
},
action_label: action_label(&r.action),
target_href: r.target_id.map(|id| match r.target_kind.as_str() {
"post" => format!("/p/{id}"),
"topic" => format!("/t/{id}"),
"user" => format!("/admin/users/{id}"),
_ => format!("/admin/categories/{id}/edit"),
}),
action: r.action,
source: r.source,
target_kind: r.target_kind,
target_label: r.target_label,
reason: r.reason,
})
.collect())
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn durations_parse() {
assert!(parse_duration(None).unwrap().is_none());
assert!(parse_duration(Some("")).unwrap().is_none());
let d = parse_duration(Some("24h")).unwrap().unwrap();
assert!((d - Utc::now() - Duration::hours(24)).num_seconds().abs() < 5);
assert!(parse_duration(Some("3d")).unwrap().is_some());
assert!(parse_duration(Some("x")).is_err());
for (v, _) in DURATIONS {
assert!(parse_duration(Some(v)).is_ok());
}
}
}
neiam
/recourse
public · Issues · Pulls · Labels · Forks · Compare · Actions running · Badges · Packages
⭐
Log in to mark this repository.
27.3 KiB · text
History
3d71adc