//! Who may do what: the moderation rules as plain functions of the rows
//! involved, with the sentence a person sees when they can't.
//!
//! The writes (`crate::actions`, `crate::moderation`) refuse with these, and
//! the pages and the API use the same functions to decide which controls to
//! show and why one is missing, so a control is shown exactly when the write
//! behind it would succeed.
//!
//! * Posting rules ([`PostingRule`]): per category, who may start a topic and
//! who may reply (reacting follows the reply rule). Separate from read
//! visibility (`categories.min_trust_level`), which is still checked first.
//! Not inherited at run time: a staff-only parent can hold an open
//! subcategory. A new subcategory starts with its parent's rules.
//! * Locks: a locked topic takes no replies, reactions or edits, except from
//! staff. Bookmarks (private) and flags (abuse reports must always work)
//! still do.
//! * Sanctions ([`Sanction`]): silenced = read only (no posting, replying,
//! editing, reacting, flagging, tagging); suspended = can't sign in.
//! * Flags: verified, not silenced, trust level `MIN_TRUST_TO_FLAG` (default
//! 1) or staff, not your own post, once per post.
//! * Auto-hide ([`FlagThreshold`]): a post is hidden pending review when its
//! flaggers are a large enough share of the people who have read it.
use chrono::{DateTime, FixedOffset, Utc};
use serde::Serialize;
use crate::entities::{categories, topics, users};
/// The stored value meaning "staff only" (above every trust level).
pub const STAFF_ONLY: i32 = 5;
/// Who may start a topic, or reply, in a category.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum PostingRule {
/// Anyone who can read the category (and is signed in, verified, not
/// silenced).
Viewers,
/// That trust level or higher.
MinTrust(i32),
/// Staff only.
Staff,
}
impl PostingRule {
/// From `topic_min_trust` / `reply_min_trust`.
pub fn from_column(v: Option<i32>) -> Self {
match v {
None => Self::Viewers,
Some(n) if n >= STAFF_ONLY => Self::Staff,
Some(n) => Self::MinTrust(n.clamp(0, 4)),
}
}
pub fn to_column(self) -> Option<i32> {
match self {
Self::Viewers => None,
Self::MinTrust(n) => Some(n),
Self::Staff => Some(STAFF_ONLY),
}
}
/// A form's `viewers` / `0`..`4` / `staff` (blank = viewers). None for
/// anything else.
pub fn parse(s: &str) -> Option<Self> {
match s.trim() {
"" | "viewers" | "everyone" => Some(Self::Viewers),
"staff" => Some(Self::Staff),
n => n.parse::<i32>().ok().filter(|n| (0..=4).contains(n)).map(Self::MinTrust),
}
}
/// The form value [`Self::parse`] reads back.
pub fn form_value(self) -> String {
match self {
Self::Viewers => "viewers".into(),
Self::MinTrust(n) => n.to_string(),
Self::Staff => "staff".into(),
}
}
/// `everyone` / `min_trust` / `staff`, for the API.
pub fn kind(self) -> &'static str {
match self {
Self::Viewers => "everyone",
Self::MinTrust(_) => "min_trust",
Self::Staff => "staff",
}
}
pub fn min_trust(self) -> Option<i32> {
match self {
Self::MinTrust(n) => Some(n),
_ => None,
}
}
/// A badge: "TL3+", "Staff", or None for the default.
pub fn badge(self) -> Option<String> {
match self {
Self::Viewers => None,
Self::MinTrust(0) => Some("Signed-in".into()),
Self::MinTrust(n) => Some(format!("TL{n}+")),
Self::Staff => Some("Staff".into()),
}
}
pub fn admits(self, user: &users::Model) -> bool {
user.is_staff
|| match self {
Self::Viewers => true,
Self::MinTrust(n) => user.trust_level >= n,
Self::Staff => false,
}
}
}
/// The category's rule for starting topics.
pub fn topic_rule(c: &categories::Model) -> PostingRule {
PostingRule::from_column(c.topic_min_trust)
}
/// The category's rule for replying (and reacting).
pub fn reply_rule(c: &categories::Model) -> PostingRule {
PostingRule::from_column(c.reply_min_trust)
}
/// Which reactions a category offers. Not inherited at run time: a new
/// subcategory copies its parent's (like the posting rules).
#[derive(Clone, Debug, Default, PartialEq, Eq)]
pub enum ReactionRule {
/// Every active reaction type (the default).
#[default]
All,
/// Reactions off: none shown, none taken. Existing ones are kept.
Off,
/// Only these reaction type keys.
Only(Vec<String>),
}
impl ReactionRule {
pub fn of(c: &categories::Model) -> Self {
Self::from_columns(c.reactions_enabled, c.reaction_keys.as_deref())
}
pub fn from_columns(enabled: bool, keys: Option<&str>) -> Self {
if !enabled {
return Self::Off;
}
match keys {
None => Self::All,
Some(k) => {
let keys: Vec<String> = k.split(',').map(str::trim).filter(|k| !k.is_empty()).map(String::from).collect();
if keys.is_empty() { Self::Off } else { Self::Only(keys) }
}
}
}
/// `(reactions_enabled, reaction_keys)`.
pub fn to_columns(&self) -> (bool, Option<String>) {
match self {
Self::All => (true, None),
Self::Off => (false, None),
Self::Only(keys) => (true, Some(keys.join(","))),
}
}
pub fn is_off(&self) -> bool {
*self == Self::Off
}
pub fn allows(&self, key: &str) -> bool {
match self {
Self::All => true,
Self::Off => false,
Self::Only(keys) => keys.iter().any(|k| k == key),
}
}
/// `all`, `none` or `some` (the API's and the forms' word).
pub fn mode(&self) -> &'static str {
match self {
Self::All => "all",
Self::Off => "none",
Self::Only(_) => "some",
}
}
pub fn keys(&self) -> Vec<String> {
match self {
Self::Only(k) => k.clone(),
_ => Vec::new(),
}
}
/// A badge for staff views, None for the default.
pub fn badge(&self, emoji_of: impl Fn(&str) -> Option<String>) -> Option<String> {
match self {
Self::All => None,
Self::Off => Some("No reactions".into()),
Self::Only(keys) => Some(format!(
"Reactions: {}",
keys.iter().map(|k| emoji_of(k).unwrap_or_else(|| k.clone())).collect::<Vec<_>>().join(" ")
)),
}
}
}
/// Reacting in `c` with `key` (None = clearing your reaction, always fine
/// unless reactions are off).
pub fn reaction_block(c: &categories::Model, key: Option<&str>) -> Option<Block> {
let rule = ReactionRule::of(c);
if rule.is_off() {
return Some(Block::new("reactions_off", "Reactions are off in this category."));
}
match key {
Some(k) if !rule.allows(k) => Some(Block::new("reaction_not_offered", "That reaction isn't offered in this category.")),
_ => None,
}
}
/// Why something is refused: a stable `code` for programs, a sentence for
/// people.
#[derive(Clone, Debug, PartialEq, Eq, Serialize)]
pub struct Block {
pub code: &'static str,
pub message: String,
}
impl Block {
pub fn new(code: &'static str, message: impl Into<String>) -> Self {
Self { code, message: message.into() }
}
}
fn level_name(n: i32) -> String {
format!("trust level {n} ({})", crate::trust::tier_name(n))
}
/// A silence or suspension in force.
#[derive(Clone, Debug, PartialEq, Eq, Serialize)]
pub struct Sanction {
pub since: DateTime<Utc>,
/// None = until lifted.
pub until: Option<DateTime<Utc>>,
pub reason: Option<String>,
}
impl Sanction {
fn active(
since: Option<DateTime<FixedOffset>>,
until: Option<DateTime<FixedOffset>>,
reason: &Option<String>,
now: DateTime<Utc>,
) -> Option<Self> {
let since = since?;
if until.is_some_and(|u| u <= now) {
return None;
}
Some(Self {
since: since.with_timezone(&Utc),
until: until.map(|u| u.with_timezone(&Utc)),
reason: reason.clone().filter(|r| !r.trim().is_empty()),
})
}
/// " until 3 Dec 2026 14:00 UTC" or "".
pub fn until_text(&self) -> String {
self.until.map(|u| format!(" until {}", u.format("%-d %b %Y %H:%M UTC"))).unwrap_or_default()
}
fn with_reason(&self, head: String) -> String {
match &self.reason {
Some(r) => format!("{head}: {r}"),
None => format!("{head}."),
}
}
}
/// The user's silence, if one is in force.
pub fn silence(u: &users::Model) -> Option<Sanction> {
Sanction::active(u.silenced_at, u.silenced_until, &u.silence_reason, Utc::now())
}
/// The user's suspension, if one is in force.
pub fn suspension(u: &users::Model) -> Option<Sanction> {
Sanction::active(u.suspended_at, u.suspended_until, &u.suspend_reason, Utc::now())
}
/// "You're silenced until …: reason" (the banner and every refusal).
pub fn silence_message(s: &Sanction) -> String {
s.with_reason(format!("Read-only{}", s.until_text()))
}
/// The longest cooldown (a silence: read-only for a while). Anything longer
/// is a suspension, or a conversation.
pub const MAX_COOLDOWN_DAYS: i64 = 90;
/// What the login page says to a suspended account.
pub fn suspension_message(s: &Sanction) -> String {
s.with_reason(format!("This account is suspended{}", s.until_text()))
}
/// Account-level: silenced accounts can't write. (Unverified addresses are
/// `crate::handlers::may_write`, checked alongside.)
pub fn silenced_block(u: &users::Model) -> Option<Block> {
silence(u).map(|s| Block::new("silenced", silence_message(&s)))
}
/// Starting a topic in `c` (read access already established).
pub fn create_block(u: &users::Model, c: &categories::Model) -> Option<Block> {
match topic_rule(c) {
r if r.admits(u) => None,
PostingRule::Staff => Some(Block::new("staff_only", "Only staff can start topics here.")),
PostingRule::MinTrust(n) => {
Some(Block::new("trust_level", format!("Starting topics here needs {}.", level_name(n))))
}
PostingRule::Viewers => None,
}
}
/// "Locked by staff: reason."
pub fn lock_message(t: &topics::Model) -> String {
match t.closed_reason.as_deref().map(str::trim).filter(|r| !r.is_empty()) {
Some(r) => format!("Locked by staff: {r}"),
None => "Locked by staff.".into(),
}
}
/// Replying to (or reacting in, or editing a post of) `t` in `c`.
pub fn reply_block(u: &users::Model, c: &categories::Model, t: &topics::Model) -> Option<Block> {
if t.is_closed && !u.is_staff {
return Some(Block::new("locked", lock_message(t)));
}
match reply_rule(c) {
r if r.admits(u) => None,
PostingRule::Staff => Some(Block::new("staff_only", "Only staff can reply here.")),
PostingRule::MinTrust(n) => {
Some(Block::new("trust_level", format!("Replying here needs {}.", level_name(n))))
}
PostingRule::Viewers => None,
}
}
/// Flagging a post by `author_id`.
pub fn flag_block(u: &users::Model, author_id: uuid::Uuid, min_trust_to_flag: i32) -> Option<Block> {
if u.id == author_id {
return Some(Block::new("own_post", "You can't flag your own post."));
}
if !u.is_staff && u.trust_level < min_trust_to_flag {
return Some(Block::new("trust_level", format!("Flagging needs {}.", level_name(min_trust_to_flag))));
}
None
}
/// Why a flag was raised.
pub const FLAG_REASONS: [(&str, &str); 4] = [
("spam", "Spam"),
("abusive", "Abusive or harassing"),
("off_topic", "Off-topic"),
("other", "Something else"),
];
pub fn flag_reason_label(key: &str) -> &'static str {
FLAG_REASONS.iter().find(|(k, _)| *k == key).map(|(_, l)| *l).unwrap_or("Something else")
}
/// When flags hide a post pending review (`FLAG_HIDE_*`).
///
/// A post is hidden when at least `min_flags` people count as flaggers and
/// either they are at least `ratio` of its readers, or there are
/// `enough_flags` of them whatever the readership (so a post read by
/// thousands doesn't need hundreds of flags). Readers are the distinct
/// accounts that have read the topic at or past this post (`topic_reads`),
/// not counting its author; the share is taken over at least the flaggers
/// themselves, so a post no one is recorded as reading (zero readers) is
/// decided by `min_flags` alone.
#[derive(Clone, Copy, Debug)]
pub struct FlagThreshold {
pub ratio: f64,
pub min_flags: u64,
pub enough_flags: u64,
}
impl FlagThreshold {
pub fn should_hide(&self, flaggers: u64, readers: u64) -> bool {
if flaggers == 0 || flaggers < self.min_flags {
return false;
}
if flaggers >= self.enough_flags {
return true;
}
let over = readers.max(flaggers) as f64;
flaggers as f64 >= self.ratio * over - 1e-9
}
/// The share, for the queue (0.0 with no flaggers).
pub fn share(flaggers: u64, readers: u64) -> f64 {
if flaggers == 0 {
0.0
} else {
flaggers as f64 / readers.max(flaggers) as f64
}
}
}
#[cfg(test)]
mod tests {
use super::*;
use chrono::Duration;
use uuid::Uuid;
fn user(level: i32, staff: bool) -> users::Model {
let now = Utc::now().into();
users::Model {
id: Uuid::now_v7(),
username: "u".into(),
email: "u@x".into(),
password_hash: String::new(),
is_active: true,
is_staff: staff,
preferred_sort: "latest".into(),
preferred_view: "classic".into(),
reaction_notifications: true,
trust_level: level,
created_at: now,
updated_at: now,
last_login_at: None,
email_verified_at: Some(now),
avatar_data: None,
avatar_content_type: None,
silenced_at: None,
silenced_until: None,
silence_reason: None,
suspended_at: None,
suspended_until: None,
suspend_reason: None,
flags_ignored_at: None,
}
}
fn category(topic: Option<i32>, reply: Option<i32>) -> categories::Model {
let now = Utc::now().into();
categories::Model {
id: Uuid::now_v7(),
name: "c".into(),
slug: "c".into(),
description: None,
color: "#000".into(),
position: 0,
parent_id: None,
min_trust_level: None,
topic_min_trust: topic,
reply_min_trust: reply,
reactions_enabled: true,
reaction_keys: None,
created_at: now,
updated_at: now,
}
}
#[test]
fn reaction_rules() {
let mut c = category(None, None);
assert_eq!(ReactionRule::of(&c), ReactionRule::All);
assert!(reaction_block(&c, Some("heart")).is_none());
c.reaction_keys = Some("heart, +1".into());
let r = ReactionRule::of(&c);
assert!(r.allows("heart") && r.allows("+1") && !r.allows("laugh"));
assert_eq!(reaction_block(&c, Some("laugh")).unwrap().code, "reaction_not_offered");
assert!(reaction_block(&c, None).is_none(), "clearing is fine");
assert_eq!(r.to_columns(), (true, Some("heart,+1".into())));
c.reactions_enabled = false;
assert_eq!(ReactionRule::of(&c), ReactionRule::Off);
assert_eq!(reaction_block(&c, None).unwrap().code, "reactions_off");
assert_eq!(ReactionRule::from_columns(true, Some(" , ")), ReactionRule::Off, "an empty set is off");
assert_eq!(ReactionRule::Off.badge(|_| None).as_deref(), Some("No reactions"));
assert!(ReactionRule::All.badge(|_| None).is_none());
}
fn topic(locked: bool) -> topics::Model {
let now = Utc::now().into();
topics::Model {
id: Uuid::now_v7(),
category_id: Uuid::now_v7(),
user_id: Uuid::now_v7(),
title: "t".into(),
is_pinned: false,
is_closed: locked,
views: 0,
posts_count: 1,
created_at: now,
updated_at: now,
bumped_at: now,
deleted_at: None,
deleted_by_id: None,
closed_at: locked.then_some(now),
closed_by_id: None,
closed_reason: locked.then(|| "cooling off".into()),
held_at: None,
}
}
#[test]
fn rules_round_trip_through_their_column_and_form() {
for r in [PostingRule::Viewers, PostingRule::MinTrust(0), PostingRule::MinTrust(3), PostingRule::Staff] {
assert_eq!(PostingRule::from_column(r.to_column()), r);
assert_eq!(PostingRule::parse(&r.form_value()), Some(r));
}
assert_eq!(PostingRule::parse(""), Some(PostingRule::Viewers));
assert_eq!(PostingRule::parse("9"), None);
assert_eq!(PostingRule::from_column(Some(42)), PostingRule::Staff);
}
#[test]
fn staff_only_announcements_and_read_only_windows() {
let announcements = category(Some(STAFF_ONLY), None);
let member = user(2, false);
let staff = user(0, true);
assert_eq!(create_block(&member, &announcements).unwrap().code, "staff_only");
assert!(create_block(&staff, &announcements).is_none());
assert!(reply_block(&member, &announcements, &topic(false)).is_none());
let window = category(Some(3), Some(3));
assert_eq!(create_block(&user(1, false), &window).unwrap().code, "trust_level");
assert!(reply_block(&user(1, false), &window, &topic(false)).unwrap().message.contains("trust level 3"));
assert!(create_block(&user(3, false), &window).is_none());
assert!(reply_block(&user(4, false), &window, &topic(false)).is_none());
}
#[test]
fn a_lock_stops_everyone_but_staff() {
let open = category(None, None);
let b = reply_block(&user(4, false), &open, &topic(true)).unwrap();
assert_eq!(b.code, "locked");
assert_eq!(b.message, "Locked by staff: cooling off");
assert!(reply_block(&user(0, true), &open, &topic(true)).is_none());
}
#[test]
fn sanctions_end_on_time() {
let mut u = user(2, false);
assert!(silence(&u).is_none());
u.silenced_at = Some((Utc::now() - Duration::hours(1)).into());
u.silenced_until = Some((Utc::now() + Duration::hours(1)).into());
u.silence_reason = Some("heated".into());
let s = silence(&u).unwrap();
assert!(silence_message(&s).starts_with("Read-only until "));
assert!(silence_message(&s).ends_with(": heated"));
assert_eq!(silenced_block(&u).unwrap().code, "silenced");
u.silenced_until = Some((Utc::now() - Duration::minutes(1)).into());
assert!(silence(&u).is_none(), "expired");
u.suspended_at = Some(Utc::now().into());
assert_eq!(suspension_message(&suspension(&u).unwrap()), "This account is suspended.");
}
#[test]
fn who_may_flag() {
let me = user(1, false);
assert_eq!(flag_block(&me, me.id, 1).unwrap().code, "own_post");
assert_eq!(flag_block(&user(0, false), Uuid::now_v7(), 1).unwrap().code, "trust_level");
assert!(flag_block(&user(0, true), Uuid::now_v7(), 1).is_none());
assert!(flag_block(&me, Uuid::now_v7(), 1).is_none());
}
#[test]
fn auto_hide_boundaries() {
let t = FlagThreshold { ratio: 0.1, min_flags: 2, enough_flags: 10 };
// Below / at the ratio.
assert!(!t.should_hide(2, 21), "2/21 is under 10%");
assert!(t.should_hide(2, 20), "2/20 is exactly 10%");
assert!(!t.should_hide(4, 41));
assert!(t.should_hide(4, 40));
// The minimum-flags guard: one flag never hides, even 1 of 1.
assert!(!t.should_hide(1, 1));
assert!(!t.should_hide(1, 0));
// Zero recorded readers: the share is over the flaggers themselves.
assert!(t.should_hide(2, 0));
assert!(!t.should_hide(0, 0));
// Many readers: enough flags hide whatever the share.
assert!(!t.should_hide(9, 1000));
assert!(t.should_hide(10, 1000));
assert_eq!(FlagThreshold::share(2, 0), 1.0);
assert_eq!(FlagThreshold::share(0, 5), 0.0);
}
}
neiam
/recourse
public · Issues · Pulls · Labels · Forks · Compare · Actions queued · Badges · Packages
⭐
Log in to mark this repository.
20.4 KiB · text
History
4ed675a