//! `manage seed [--demo]`: baseline data, plus optional demo content.
//!
//! Every step looks its row up by a natural key (category slug, reaction key,
//! tag slug, demo username, demo topic title) and only inserts what is
//! missing, so running it again changes nothing, and it never edits rows an
//! operator has since changed.
//!
//! * `seed` — what a real forum can keep: a category tree three levels deep
//! with distinct colors, a members-only category (`min_trust_level = 0`: any
//! signed-in account) and a min-trust one (Regular, 3), the default reaction
//! types, a few tags, and a pinned welcome topic in Announcements by the
//! oldest staff account ([`seed_welcome`]). The welcome is made once, ever:
//! a `seed_markers` row records it, so editing, renaming or deleting it
//! never brings it back. With no staff account yet it is skipped until a
//! later run.
//! * `seed --demo` — fake people and conversations for development: `demo-*`
//! accounts at every trust tier (verified, password [`DEMO_PASSWORD`]),
//! topics with replies, an edited post, a soft-deleted post, reactions,
//! bookmarks, tags, a pinned topic, spread over the last few weeks; and the
//! moderation tools in use: staff-only Announcements (members reply, no
//! reactions), a
//! read-only window (`council`: Basic and up read, Regulars and up post),
//! a locked topic, a post moderated by staff with its original hidden, and
//! a pending flag, with their moderation-log lines. It is
//! never run by the image, compose or `AUTO_MIGRATE`; `manage` refuses it
//! when `PUBLIC_URL` is https unless `--allow-public` is given.
use anyhow::{bail, Context, Result};
use chrono::{DateTime, Duration, FixedOffset, Utc};
use sea_orm::*;
use uuid::Uuid;
use crate::auth;
use crate::entities::{
bookmarks, categories, post_flags, post_reactions, post_revisions, posts, reaction_types, tags, topic_tags, topics,
users,
};
use crate::markdown;
/// Password of every `demo-*` account (documented in the README). Demo data is
/// for development only.
pub const DEMO_PASSWORD: &str = "recourse-demo";
/// A category to seed: `(slug, name, color, parent slug, min trust, description)`.
pub struct CategorySeed {
pub slug: &'static str,
pub name: &'static str,
pub color: &'static str,
pub parent: Option<&'static str>,
pub min_trust: Option<i32>,
pub description: &'static str,
/// Posting rules (`crate::policy::PostingRule` columns).
pub topic_min_trust: Option<i32>,
pub reply_min_trust: Option<i32>,
}
const fn cat(
slug: &'static str,
name: &'static str,
color: &'static str,
parent: Option<&'static str>,
min_trust: Option<i32>,
description: &'static str,
) -> CategorySeed {
CategorySeed { slug, name, color, parent, min_trust, description, topic_min_trust: None, reply_min_trust: None }
}
/// Parents come before their children. `announcements` and `general` are
/// also created by the forum migration; listing them keeps `seed` complete on
/// its own.
pub const CATEGORIES: &[CategorySeed] = &[
cat("announcements", "Announcements", "#E45735", None, None, "Official announcements and news."),
cat("general", "General", "#0088CC", None, None, "General discussion about anything."),
cat("development", "Development", "#25AAE2", None, None, "Building things: code, tools and infrastructure."),
cat("backend", "Backend", "#3AB54A", Some("development"), None, "Servers, APIs and everything behind them."),
cat("databases", "Databases", "#12A89D", Some("backend"), None, "Schemas, queries, migrations and tuning."),
cat("frontend", "Frontend", "#F7941D", Some("development"), None, "HTML, CSS, htmx and the browser."),
cat("hobbies", "Hobbies", "#9EB83B", None, None, "What we do when we're not at a keyboard."),
cat("games", "Games", "#BF1E2E", Some("hobbies"), None, "Video, board, card and tabletop games."),
cat("board-games", "Board Games", "#652D90", Some("games"), None, "Cardboard, dice and meeples."),
cat("feedback", "Site Feedback", "#808281", None, None, "Bugs, ideas and questions about this forum."),
cat("members", "Members Lounge", "#D4AF37", None, Some(0), "Members only: visible to signed-in accounts."),
cat("regulars", "Regulars' Corner", "#ED207B", None, Some(3), "For trust level 3 (Regular) and up."),
];
/// The reaction types the reactions migration installs.
pub const REACTIONS: &[(&str, &str)] = &[("heart", "\u{2764}\u{FE0F}"), ("star", "\u{2B50}"), ("thumbsup", "\u{1F44D}")];
/// `(name, slug)`.
pub const TAGS: &[(&str, &str)] = &[
("rust", "rust"),
("postgres", "postgres"),
("htmx", "htmx"),
("help", "help"),
("meta", "meta"),
("show-and-tell", "show-and-tell"),
];
/// What a run created (everything else already existed).
#[derive(Debug, Default, PartialEq, Eq)]
pub struct Report {
pub categories: usize,
pub reactions: usize,
pub tags: usize,
pub users: usize,
pub topics: usize,
pub posts: usize,
/// The welcome topic ([`seed_welcome`]); `None` for `seed_demo`.
pub welcome: Option<Welcome>,
}
impl Report {
/// Nothing new (the welcome aside).
pub fn is_empty(&self) -> bool {
Report { welcome: None, ..*self } == Report::default()
}
}
/// What became of the welcome topic.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Welcome {
Created,
/// Its marker is there: made before (and maybe since edited or deleted).
AlreadySeeded,
/// No staff account to write it.
NoStaff,
/// No `announcements` category.
NoCategory,
}
impl Welcome {
/// `manage seed`'s line.
pub fn describe(self) -> &'static str {
match self {
Welcome::Created => "Welcome topic: created.",
Welcome::AlreadySeeded => "Welcome topic: already seeded.",
Welcome::NoStaff => {
"Welcome topic skipped: create a staff account first (manage user create … --staff), then re-run manage seed."
}
Welcome::NoCategory => {
"Welcome topic skipped: there is no `announcements` category (renamed or deleted); nothing was created."
}
}
}
}
/// The `seed_markers` key of the welcome topic.
pub const WELCOME_MARKER: &str = "welcome_topic";
/// The welcome topic's opening post: a starter for staff to edit.
pub const WELCOME_BODY: &str = r#"**What this place is for:** *Staff: replace this line with a sentence or two about this community, who it's for and what belongs here.*
## Getting started
- **Verify your email.** Follow the link we mailed you. Until then you can read but not post; the banner at the top has a "Resend link" button.
- **Trust grows with participation.** Everyone starts as New. Reading, posting and sticking around move you up through Basic, Member, Regular and Leader, and each level unlocks a little more: flagging, creating tags, some categories.
- **Pick a layout.** Profile → Layout switches between Classic (lists) and Focus (tiles with a reader).
- **React, bookmark, watch.** React to a post instead of replying "+1", bookmark posts to find them later, and watch a category to hear about new topics in it.
- **Flag what breaks the rules.** The flag on a post sends it to staff, and enough flags hide it until someone looks.
- **Formatting.** Posts are Markdown: `**bold**`, `*italic*`, links, lists, code blocks and tables. Links to other sites go through an exit page that shows where they lead.
---
*Staff: edit this post to make it yours: the purpose, the rules, who to ask. Renaming or deleting it is fine; `manage seed` won't put it back.*
"#;
/// The pinned welcome topic in Announcements, by the oldest staff account,
/// once ever (see [`WELCOME_MARKER`]). Inserted like a normal topic (one
/// post, its first revision, bumped now, no views) but quietly: nobody is
/// notified, since it's the forum's own furniture.
pub async fn seed_welcome<C: ConnectionTrait + TransactionTrait>(db: &C, app_name: &str) -> Result<Welcome> {
#[derive(FromQueryResult)]
struct Marker {
#[allow(dead_code)]
key: String,
}
let marker = Marker::find_by_statement(Statement::from_sql_and_values(
DbBackend::Postgres,
"SELECT key FROM seed_markers WHERE key = $1",
[WELCOME_MARKER.into()],
))
.one(db)
.await?;
if marker.is_some() {
return Ok(Welcome::AlreadySeeded);
}
let Some(category) = categories::Entity::find().filter(categories::Column::Slug.eq("announcements")).one(db).await?
else {
return Ok(Welcome::NoCategory);
};
let Some(author) = users::Entity::find()
.filter(users::Column::IsStaff.eq(true))
.filter(users::Column::IsActive.eq(true))
.order_by_asc(users::Column::CreatedAt)
.order_by_asc(users::Column::Id)
.one(db)
.await?
else {
return Ok(Welcome::NoStaff);
};
let txn = db.begin().await?;
// The marker first: a concurrent run fails on its primary key instead
// of making a second topic.
let now: DateTime<FixedOffset> = Utc::now().into();
let topic_id = Uuid::now_v7();
txn.execute(Statement::from_sql_and_values(
DbBackend::Postgres,
"INSERT INTO seed_markers (key, note) VALUES ($1, $2)",
[WELCOME_MARKER.into(), format!("topic {topic_id}").into()],
))
.await?;
topics::ActiveModel {
id: Set(topic_id),
category_id: Set(category.id),
user_id: Set(author.id),
title: Set(format!("Welcome to {app_name}")),
is_pinned: Set(true),
is_closed: Set(false),
views: Set(0),
posts_count: Set(1),
created_at: Set(now),
updated_at: Set(now),
bumped_at: Set(now),
deleted_at: Set(None),
deleted_by_id: Set(None),
closed_at: Set(None),
closed_by_id: Set(None),
closed_reason: Set(None),
held_at: Set(None),
}
.insert(&txn)
.await?;
let cooked = markdown::render(WELCOME_BODY);
let post = posts::ActiveModel {
id: Set(Uuid::now_v7()),
topic_id: Set(topic_id),
user_id: Set(author.id),
post_number: Set(1),
raw: Set(WELCOME_BODY.into()),
cooked: Set(cooked.clone()),
created_at: Set(now),
updated_at: Set(now),
edited_at: Set(None),
edit_count: Set(0),
last_editor_id: Set(None),
deleted_at: Set(None),
deleted_by_id: Set(None),
moderated_at: Set(None),
moderated_by_id: Set(None),
hidden_at: Set(None),
}
.insert(&txn)
.await?;
revision(&txn, post.id, 1, author.id, WELCOME_BODY, &cooked, now, "edit").await?;
txn.commit().await?;
Ok(Welcome::Created)
}
/// The baseline: categories, reaction types, tags, and the welcome topic.
pub async fn seed_base<C: ConnectionTrait + TransactionTrait>(db: &C, app_name: &str) -> Result<Report> {
let mut report = Report::default();
let now: DateTime<FixedOffset> = Utc::now().into();
for (position, c) in CATEGORIES.iter().enumerate() {
if categories::Entity::find()
.filter(categories::Column::Slug.eq(c.slug))
.one(db)
.await?
.is_some()
{
continue;
}
let parent_id = match c.parent {
None => None,
Some(slug) => Some(
categories::Entity::find()
.filter(categories::Column::Slug.eq(slug))
.one(db)
.await?
.with_context(|| format!("parent category {slug} is missing"))?
.id,
),
};
categories::ActiveModel {
id: Set(Uuid::now_v7()),
name: Set(c.name.into()),
slug: Set(c.slug.into()),
description: Set(Some(c.description.into())),
color: Set(c.color.into()),
position: Set(position as i32),
parent_id: Set(parent_id),
min_trust_level: Set(c.min_trust),
topic_min_trust: Set(c.topic_min_trust),
reply_min_trust: Set(c.reply_min_trust),
reactions_enabled: Set(true),
reaction_keys: Set(None),
created_at: Set(now),
updated_at: Set(now),
}
.insert(db)
.await
.with_context(|| format!("insert category {}", c.slug))?;
report.categories += 1;
}
for (position, (key, emoji)) in REACTIONS.iter().enumerate() {
if reaction_types::Entity::find()
.filter(reaction_types::Column::Key.eq(*key))
.one(db)
.await?
.is_none()
{
reaction_types::ActiveModel {
id: Set(Uuid::now_v7()),
key: Set((*key).into()),
emoji: Set((*emoji).into()),
position: Set(position as i32),
is_active: Set(true),
created_at: Set(now),
}
.insert(db)
.await?;
report.reactions += 1;
}
}
for (name, slug) in TAGS {
if ensure_tag(db, name, slug, now).await?.1 {
report.tags += 1;
}
}
report.welcome = Some(seed_welcome(db, app_name).await.context("welcome topic")?);
Ok(report)
}
async fn ensure_tag<C: ConnectionTrait>(
db: &C,
name: &str,
slug: &str,
now: DateTime<FixedOffset>,
) -> Result<(Uuid, bool)> {
if let Some(t) = tags::Entity::find().filter(tags::Column::Slug.eq(slug)).one(db).await? {
return Ok((t.id, false));
}
let t = tags::ActiveModel {
id: Set(Uuid::now_v7()),
name: Set(name.into()),
slug: Set(slug.into()),
created_at: Set(now),
}
.insert(db)
.await?;
Ok((t.id, true))
}
/// `(username, trust level, staff, joined days ago)`.
pub const DEMO_USERS: &[(&str, i32, bool, i64)] = &[
("demo-admin", 4, true, 120),
("demo-leader", 4, false, 110),
("demo-regular", 3, false, 90),
("demo-member", 2, false, 60),
("demo-basic", 1, false, 30),
("demo-new", 0, false, 2),
];
/// One demo post: author, minutes after the topic started, body.
struct P(&'static str, i64, &'static str);
/// One demo topic: category, author, title, days ago, pinned, tags, posts
/// (the first is the opening post).
struct T {
category: &'static str,
title: &'static str,
days_ago: i64,
pinned: bool,
tags: &'static [&'static str],
posts: &'static [P],
}
const DEMO_TOPICS: &[T] = &[
T {
category: "announcements",
title: "Welcome to the demo forum",
days_ago: 40,
pinned: true,
tags: &["meta"],
posts: &[
P("demo-admin", 0, "Welcome! This forum is filled with **demo content** so every screen has something on it.\n\nAll `demo-*` accounts share the password from the README."),
P("demo-leader", 30, "Thanks for setting this up. Pinned topics stay at the top of their category."),
P("demo-member", 300, "Glad to be here :)"),
],
},
T {
category: "databases",
title: "Choosing indexes for a topic list",
days_ago: 21,
pinned: false,
tags: &["postgres", "help"],
posts: &[
P("demo-regular", 0, "The latest-topics query sorts by `bumped_at`. Is a plain btree enough?\n\n```sql\nCREATE INDEX ON topics (bumped_at DESC);\n```"),
P("demo-leader", 45, "Yes, and make it partial on `deleted_at IS NULL` if most reads skip deleted topics."),
P("demo-basic", 90, "What about the category filter?"),
P("demo-regular", 180, "A composite `(category_id, bumped_at DESC)` covers that."),
],
},
T {
category: "frontend",
title: "htmx boosted links and fragments",
days_ago: 12,
pinned: false,
tags: &["htmx", "show-and-tell"],
posts: &[
P("demo-member", 0, "Boosting the body means every partial needs `hx-select=\"unset\"`, or it inherits `#content`."),
P("demo-regular", 20, "Same trick for `hx-target`. Took me a while to spot."),
P("demo-new", 60, "This reply was removed by its author."),
],
},
T {
category: "backend",
title: "axum extractors: order matters",
days_ago: 7,
pinned: false,
tags: &["rust"],
posts: &[
P("demo-leader", 0, "The body-consuming extractor (`Form`, `Json`) has to be last."),
P("demo-basic", 15, "Good to know, thanks!"),
],
},
T {
category: "board-games",
title: "What's on your table this month?",
days_ago: 3,
pinned: false,
tags: &[],
posts: &[
P("demo-basic", 0, "Lots of Azul here."),
P("demo-member", 120, "Spirit Island, every week."),
P("demo-leader", 600, "Cascadia with the kids."),
],
},
T {
category: "members",
title: "Members-only: introduce yourself",
days_ago: 15,
pinned: false,
tags: &[],
posts: &[
P("demo-member", 0, "Only signed-in accounts can see this category."),
P("demo-new", 10, "Hi, I'm new!"),
],
},
T {
category: "regulars",
title: "Regulars: moderation notes",
days_ago: 5,
pinned: false,
tags: &["meta"],
posts: &[P("demo-regular", 0, "Trust level 3 and up (and staff) can read this.")],
},
T {
category: "council",
title: "Council: roadmap for next quarter",
days_ago: 4,
pinned: false,
tags: &["meta"],
posts: &[
P("demo-regular", 0, "Basic members can read along here; only Regulars and up can post. Ideas for next quarter?"),
P("demo-leader", 40, "Search filters first, then the mobile app."),
],
},
T {
category: "general",
title: HEATED,
days_ago: 2,
pinned: false,
tags: &[],
posts: &[
P("demo-member", 0, "Settle it once and for all: tabs or spaces?"),
P("demo-basic", 10, "Spaces. Also, has anyone tried the new board game café downtown?"),
P("demo-new", 25, MODERATED_ORIGINAL),
P("demo-regular", 50, "Let's keep it friendly, please."),
],
},
T {
category: "general",
title: "Small talk",
days_ago: 1,
pinned: false,
tags: &[],
posts: &[P("demo-new", 0, "Is it weekend yet?")],
},
];
/// The locked topic, and its moderated post (#3, original hidden).
const HEATED: &str = "Tabs or spaces, once and for all";
/// Every demo post body (the lameness filter's calibration checks them).
pub fn demo_post_bodies() -> Vec<String> {
DEMO_TOPICS.iter().flat_map(|t| t.posts.iter().map(|p| p.2.to_string())).collect()
}
const MODERATED_ORIGINAL: &str = "Anyone who uses tabs is an idiot and should quit programming.";
const MODERATION_NOTE: &str = "Removed: personal attack. Disagree with ideas, not people.";
const LOCK_REASON: &str = "Cooling off: this went in circles.";
/// The read-only window: `(slug, name, color, view, start topics, reply)`.
const COUNCIL: (&str, &str, &str, i32, i32, i32) = ("council", "Leaders' Council", "#1E88E5", 1, 3, 3);
/// The opening post of "Choosing indexes…" is edited once.
const EDITED: (&str, i32, &str) = (
"Choosing indexes for a topic list",
1,
"The latest-topics query sorts by `bumped_at`. Is a plain btree enough?\n\n```sql\nCREATE INDEX ON topics (bumped_at DESC);\n```\n\n**Edit:** we also filter by category.",
);
/// Post 3 of the htmx topic is soft-deleted by its author.
const DELETED: (&str, i32) = ("htmx boosted links and fragments", 3);
/// `(username, reaction key, topic title, post number)`.
const DEMO_REACTIONS: &[(&str, &str, &str, i32)] = &[
("demo-member", "heart", "Welcome to the demo forum", 1),
("demo-basic", "thumbsup", "Welcome to the demo forum", 1),
("demo-regular", "star", "Welcome to the demo forum", 1),
("demo-leader", "thumbsup", "Choosing indexes for a topic list", 4),
("demo-member", "star", "Choosing indexes for a topic list", 2),
("demo-regular", "heart", "htmx boosted links and fragments", 1),
("demo-admin", "thumbsup", "axum extractors: order matters", 1),
];
/// `(username, topic title, post number)`.
const DEMO_BOOKMARKS: &[(&str, &str, i32)] = &[
("demo-member", "Choosing indexes for a topic list", 2),
("demo-member", "axum extractors: order matters", 1),
("demo-basic", "htmx boosted links and fragments", 1),
];
/// Demo accounts and content (after [`seed_base`]).
pub async fn seed_demo(db: &DatabaseConnection) -> Result<Report> {
let mut report = Report::default();
let now = Utc::now();
for (name, level, staff, joined) in DEMO_USERS {
if users::Entity::find().filter(users::Column::Username.eq(*name)).one(db).await?.is_some() {
continue;
}
let email = format!("{name}@demo.invalid");
let user = auth::create_user_direct(db, name, &email, DEMO_PASSWORD, *staff)
.await
.with_context(|| format!("create {name}"))?;
let joined_at: DateTime<FixedOffset> = (now - Duration::days(*joined)).into();
let mut am: users::ActiveModel = user.into();
am.trust_level = Set(*level);
am.created_at = Set(joined_at);
am.email_verified_at = Set(Some(joined_at));
am.update(db).await?;
report.users += 1;
}
demo_categories(db, now).await?;
for t in DEMO_TOPICS {
if topics::Entity::find().filter(topics::Column::Title.eq(t.title)).one(db).await?.is_some() {
continue;
}
let txn = db.begin().await?;
report.posts += demo_topic(&txn, t, now).await.with_context(|| format!("topic {:?}", t.title))?;
txn.commit().await?;
report.topics += 1;
}
for (name, key, title, number) in DEMO_REACTIONS {
let user = user_id(db, name).await?;
let post = post_id(db, title, *number).await?;
let reaction = reaction_types::Entity::find()
.filter(reaction_types::Column::Key.eq(*key))
.one(db)
.await?
.with_context(|| format!("reaction {key}"))?;
let exists = post_reactions::Entity::find()
.filter(post_reactions::Column::PostId.eq(post))
.filter(post_reactions::Column::UserId.eq(user))
.one(db)
.await?
.is_some();
if !exists {
post_reactions::ActiveModel {
id: Set(Uuid::now_v7()),
post_id: Set(post),
user_id: Set(user),
reaction_id: Set(reaction.id),
created_at: Set(now.into()),
}
.insert(db)
.await?;
}
}
demo_moderation(db, now).await?;
for (name, title, number) in DEMO_BOOKMARKS {
let user = user_id(db, name).await?;
let post = post_id(db, title, *number).await?;
let exists = bookmarks::Entity::find()
.filter(bookmarks::Column::PostId.eq(post))
.filter(bookmarks::Column::UserId.eq(user))
.one(db)
.await?
.is_some();
if !exists {
bookmarks::ActiveModel {
id: Set(Uuid::now_v7()),
user_id: Set(user),
post_id: Set(post),
created_at: Set(now.into()),
}
.insert(db)
.await?;
}
}
Ok(report)
}
/// The demo's posting rules: Announcements becomes staff-only for new topics
/// (members still reply) if its rules are still the defaults, and the
/// read-only window category is created.
async fn demo_categories(db: &DatabaseConnection, now: DateTime<Utc>) -> Result<()> {
let admin = users::Entity::find().filter(users::Column::Username.eq("demo-admin")).one(db).await?;
let actor = crate::moderation::Actor::cli(admin.as_ref());
if let Some(a) = categories::Entity::find().filter(categories::Column::Slug.eq("announcements")).one(db).await? {
if a.topic_min_trust.is_none() && a.reply_min_trust.is_none() {
let id = a.id;
let mut am: categories::ActiveModel = a.into();
am.topic_min_trust = Set(Some(crate::policy::STAFF_ONLY));
// Announcements aren't for reacting to either.
am.reactions_enabled = Set(false);
am.updated_at = Set(now.into());
am.update(db).await?;
crate::moderation::log(db, actor, "category_permissions", "category", Some(id), "Announcements", Some("start topics: staff only · reactions: off (demo)"))
.await;
}
}
let (slug, name, color, view, create, reply) = COUNCIL;
if categories::Entity::find().filter(categories::Column::Slug.eq(slug)).one(db).await?.is_none() {
let c = categories::ActiveModel {
id: Set(Uuid::now_v7()),
name: Set(name.into()),
slug: Set(slug.into()),
description: Set(Some("A read-only window: Basic members and up can read; Regulars and up start topics and reply.".into())),
color: Set(color.into()),
position: Set(CATEGORIES.len() as i32),
parent_id: Set(None),
min_trust_level: Set(Some(view)),
topic_min_trust: Set(Some(create)),
reply_min_trust: Set(Some(reply)),
reactions_enabled: Set(true),
reaction_keys: Set(None),
created_at: Set(now.into()),
updated_at: Set(now.into()),
}
.insert(db)
.await?;
crate::moderation::log(db, actor, "category_permissions", "category", Some(c.id), name, Some("read: TL1+ · start topics: TL3+ · reply: TL3+ (demo)"))
.await;
}
Ok(())
}
/// Lock the heated topic, moderate its post #3 with the original hidden, and
/// leave a pending flag on post #2 — once.
async fn demo_moderation(db: &DatabaseConnection, now: DateTime<Utc>) -> Result<()> {
let Some(topic) = topics::Entity::find().filter(topics::Column::Title.eq(HEATED)).one(db).await? else {
return Ok(());
};
if topic.is_closed {
return Ok(());
}
let admin = users::Entity::find()
.filter(users::Column::Username.eq("demo-admin"))
.one(db)
.await?
.context("demo-admin is missing")?;
let actor = crate::moderation::Actor::cli(Some(&admin));
let at: DateTime<FixedOffset> = (now - Duration::hours(30)).into();
let post3 = post_id(db, HEATED, 3).await?;
let p = posts::Entity::find_by_id(post3).one(db).await?.context("post 3")?;
let cooked = markdown::render(MODERATION_NOTE);
revision(db, p.id, 2, admin.id, MODERATION_NOTE, &cooked, at, "moderation").await?;
post_revisions::Entity::update_many()
.col_expr(post_revisions::Column::HiddenAt, sea_orm::sea_query::Expr::value(Some(at)))
.col_expr(post_revisions::Column::HiddenById, sea_orm::sea_query::Expr::value(Some(admin.id)))
.filter(post_revisions::Column::PostId.eq(p.id))
.filter(post_revisions::Column::RevisionNumber.eq(1))
.exec(db)
.await?;
let label = format!("#3 in “{HEATED}”");
let mut am: posts::ActiveModel = p.into();
am.raw = Set(MODERATION_NOTE.into());
am.cooked = Set(cooked);
am.edit_count = Set(1);
am.edited_at = Set(Some(at));
am.last_editor_id = Set(Some(admin.id));
am.moderated_at = Set(Some(at));
am.moderated_by_id = Set(Some(admin.id));
am.update(db).await?;
crate::moderation::log(db, actor, "moderate_post", "post", Some(post3), &label, Some(MODERATION_NOTE)).await;
crate::moderation::log(db, actor, "hide_original", "post", Some(post3), &label, None).await;
let topic_id = topic.id;
let mut t: topics::ActiveModel = topic.into();
t.is_closed = Set(true);
t.closed_at = Set(Some(at));
t.closed_by_id = Set(Some(admin.id));
t.closed_reason = Set(Some(LOCK_REASON.into()));
t.update(db).await?;
crate::moderation::log(db, actor, "lock_topic", "topic", Some(topic_id), &format!("“{HEATED}”"), Some(LOCK_REASON)).await;
let post2 = post_id(db, HEATED, 2).await?;
let flagger = user_id(db, "demo-member").await?;
post_flags::ActiveModel {
id: Set(Uuid::now_v7()),
post_id: Set(post2),
user_id: Set(flagger),
reason: Set("off_topic".into()),
note: Set(Some("Board game café talk in the tabs thread.".into())),
created_at: Set(at),
resolved_at: Set(None),
resolved_by_id: Set(None),
resolution: Set(None),
ip: Set(None),
}
.insert(db)
.await?;
Ok(())
}
async fn user_id<C: ConnectionTrait>(db: &C, name: &str) -> Result<Uuid> {
Ok(users::Entity::find()
.filter(users::Column::Username.eq(name))
.one(db)
.await?
.with_context(|| format!("user {name} is missing"))?
.id)
}
async fn post_id<C: ConnectionTrait>(db: &C, title: &str, number: i32) -> Result<Uuid> {
let topic = topics::Entity::find()
.filter(topics::Column::Title.eq(title))
.one(db)
.await?
.with_context(|| format!("topic {title:?} is missing"))?;
Ok(posts::Entity::find()
.filter(posts::Column::TopicId.eq(topic.id))
.filter(posts::Column::PostNumber.eq(number))
.one(db)
.await?
.with_context(|| format!("post {title:?} #{number} is missing"))?
.id)
}
/// Insert one topic with its posts (revision 1 for each, as the handlers do),
/// the edit and the deletion. Returns the number of posts.
async fn demo_topic<C: ConnectionTrait>(db: &C, t: &T, now: DateTime<Utc>) -> Result<usize> {
let Some(category) = categories::Entity::find()
.filter(categories::Column::Slug.eq(t.category))
.one(db)
.await?
else {
bail!("category {} is missing (run `manage seed` first)", t.category);
};
let start = now - Duration::days(t.days_ago);
let at = |minutes: i64| -> DateTime<FixedOffset> { (start + Duration::minutes(minutes)).into() };
let last = t.posts.last().map(|p| p.1).unwrap_or(0);
let opener = user_id(db, t.posts[0].0).await?;
let topic_id = Uuid::now_v7();
topics::ActiveModel {
id: Set(topic_id),
category_id: Set(category.id),
user_id: Set(opener),
title: Set(t.title.into()),
is_pinned: Set(t.pinned),
is_closed: Set(false),
views: Set(7 * t.posts.len() as i32 + t.days_ago as i32),
posts_count: Set(t.posts.len() as i32),
created_at: Set(at(0)),
updated_at: Set(at(last)),
bumped_at: Set(at(last)),
deleted_at: Set(None),
deleted_by_id: Set(None),
closed_at: Set(None),
closed_by_id: Set(None),
closed_reason: Set(None),
held_at: Set(None),
}
.insert(db)
.await?;
for (i, P(author, minutes, body)) in t.posts.iter().enumerate() {
let number = i as i32 + 1;
let author = user_id(db, author).await?;
let cooked = markdown::render(body);
let post = posts::ActiveModel {
id: Set(Uuid::now_v7()),
topic_id: Set(topic_id),
user_id: Set(author),
post_number: Set(number),
raw: Set((*body).into()),
cooked: Set(cooked.clone()),
created_at: Set(at(*minutes)),
updated_at: Set(at(*minutes)),
edited_at: Set(None),
edit_count: Set(0),
last_editor_id: Set(None),
deleted_at: Set(None),
deleted_by_id: Set(None),
moderated_at: Set(None),
moderated_by_id: Set(None),
hidden_at: Set(None),
}
.insert(db)
.await?;
revision(db, post.id, 1, author, body, &cooked, at(*minutes), "edit").await?;
if (t.title, number) == (EDITED.0, EDITED.1) {
let edited_at = at(*minutes + 25);
let cooked = markdown::render(EDITED.2);
revision(db, post.id, 2, author, EDITED.2, &cooked, edited_at, "edit").await?;
let mut am: posts::ActiveModel = post.clone().into();
am.raw = Set(EDITED.2.into());
am.cooked = Set(cooked);
am.edit_count = Set(1);
am.edited_at = Set(Some(edited_at));
am.last_editor_id = Set(Some(author));
am.updated_at = Set(edited_at);
am.update(db).await?;
} else if (t.title, number) == DELETED {
let mut am: posts::ActiveModel = post.into();
am.deleted_at = Set(Some(at(*minutes + 5)));
am.deleted_by_id = Set(Some(author));
am.update(db).await?;
}
}
for slug in t.tags {
let name = TAGS.iter().find(|(_, s)| s == slug).map(|(n, _)| *n).unwrap_or(slug);
let (tag_id, _) = ensure_tag(db, name, slug, now.into()).await?;
topic_tags::ActiveModel {
id: Set(Uuid::now_v7()),
topic_id: Set(topic_id),
tag_id: Set(tag_id),
}
.insert(db)
.await?;
}
Ok(t.posts.len())
}
#[allow(clippy::too_many_arguments)]
async fn revision<C: ConnectionTrait>(
db: &C,
post_id: Uuid,
number: i32,
editor: Uuid,
raw: &str,
cooked: &str,
at: DateTime<FixedOffset>,
kind: &str,
) -> Result<()> {
post_revisions::ActiveModel {
id: Set(Uuid::now_v7()),
post_id: Set(post_id),
editor_id: Set(Some(editor)),
revision_number: Set(number),
raw: Set(raw.into()),
cooked: Set(cooked.into()),
created_at: Set(at),
kind: Set(kind.into()),
hidden_at: Set(None),
hidden_by_id: Set(None),
}
.insert(db)
.await?;
Ok(())
}
#[cfg(test)]
mod tests {
use super::*;
use std::collections::{HashMap, HashSet};
#[test]
fn category_tree_is_well_formed() {
let mut depth: HashMap<&str, i32> = HashMap::new();
let mut colors = HashSet::new();
assert!(!CATEGORIES.iter().any(|c| c.color.eq_ignore_ascii_case(COUNCIL.2)), "the demo category's color is its own");
for c in CATEGORIES {
assert!(colors.insert(c.color.to_ascii_lowercase()), "color {} reused", c.color);
let d = match c.parent {
None => 1,
Some(p) => depth.get(p).copied().expect("parent listed before child") + 1,
};
assert!(d <= 3, "{} is deeper than three levels", c.slug);
assert!(depth.insert(c.slug, d).is_none(), "slug {} repeated", c.slug);
}
assert_eq!(depth.values().max(), Some(&3), "some branch reaches three levels");
assert!(CATEGORIES.iter().any(|c| c.min_trust == Some(0)), "a members-only category");
assert!(CATEGORIES.iter().any(|c| c.min_trust.is_some_and(|m| m > 0)), "a min-trust category");
}
#[test]
fn demo_content_refers_to_seeded_things() {
let users: HashSet<_> = DEMO_USERS.iter().map(|u| u.0).collect();
let tiers: HashSet<_> = DEMO_USERS.iter().map(|u| u.1).collect();
assert_eq!(tiers.len(), 5, "every trust tier");
let titles: HashSet<_> = DEMO_TOPICS.iter().map(|t| t.title).collect();
assert_eq!(titles.len(), DEMO_TOPICS.len(), "titles are the idempotency key");
for t in DEMO_TOPICS {
assert!(CATEGORIES.iter().any(|c| c.slug == t.category) || t.category == COUNCIL.0);
assert!(t.tags.iter().all(|s| TAGS.iter().any(|(_, slug)| slug == s)));
assert!(t.posts.iter().all(|p| users.contains(p.0)));
assert!(t.posts.windows(2).all(|w| w[0].1 < w[1].1), "posts in time order");
}
let post_exists = |title: &str, n: i32| {
DEMO_TOPICS.iter().any(|t| t.title == title && n >= 1 && n as usize <= t.posts.len())
};
assert!(post_exists(EDITED.0, EDITED.1));
assert!(post_exists(DELETED.0, DELETED.1));
assert!(DEMO_TOPICS.iter().any(|t| t.pinned));
for (u, key, title, n) in DEMO_REACTIONS {
assert!(users.contains(u) && REACTIONS.iter().any(|r| r.0 == *key) && post_exists(title, *n));
}
let pairs: HashSet<_> = DEMO_REACTIONS.iter().map(|r| (r.0, r.2, r.3)).collect();
assert_eq!(pairs.len(), DEMO_REACTIONS.len(), "one reaction per user per post");
for (u, title, n) in DEMO_BOOKMARKS {
assert!(users.contains(u) && post_exists(title, *n));
}
}
}
neiam
/recourse
public · Issues · Pulls · Labels · Forks · Compare · Actions queued · Badges · Packages
⭐
Log in to mark this repository.
36.0 KiB · text
History
313874d