garage44.eu/jeroen/cartopolis

logclone: git clone https://garage44.eu/jeroen/cartopolis.git

.. /crates/simulator/src/fediverse/posts.rs

raw

//! A community's public posts: the rules, over a `&Connection`
//! (`docs/notes/fediverse.md`).
//!
//! Plain functions, like `communities`, so the tests below run every rule
//! against a real database with no network. What goes out to other servers
//! because of a change here is decided by the caller (`fediverse::http`), which
//! is the one place that knows this server's public address.
//!
//! The rules:
//!
//! 1. **A community's moderators switch posts on**, and choose its address
//!    (`handle`) the first time. The handle never changes afterwards and is
//!    never handed out again, even after the community is gone: other servers
//!    know it by it. It must not be anybody's username either, because both
//!    are found the same way (`@name@server`).
//! 2. **Members write posts** (or only moderators, for a notice board), and a
//!    post written here always has a place.
//! 3. **Anybody signed in may reply**, here or on another server: a public post
//!    is public.
//! 4. **The author edits and deletes; a moderator hides.** Deleting is the
//!    author taking it back everywhere; hiding is the community saying "not
//!    here".
//! 5. **Reports from other servers wait for a moderator**, who hides the post
//!    or dismisses the report.

use cartopolis_core::point::PointView;
use cartopolis_core::posts::{
    is_handle, FollowDto, NewPost, PersonPosts, PostAuthor, PostDto, PostPicture, PostPlace,
    PostReport, PostThread, PublicCommunity, PublicInfo, PublicSettings, ReportAction, SourceKind,
    WhoPosts, MAX_PICTURE_ALT, MAX_PLACE_NAME, MAX_POST_TEXT, MAX_WARNING, POSTS_PAGE,
};
use cartopolis_core::CommunityRole;
use rusqlite::{params, Connection, OptionalExtension};
use uuid::Uuid;

use crate::communities;

/// Why a request about posts was refused, in words the client can show.
#[derive(Debug, thiserror::Error, PartialEq, Eq)]
pub enum Refusal {
    #[error("no such community")]
    NoSuchCommunity,
    #[error("this community has no public posts")]
    PostsOff,
    #[error("only a moderator may do that")]
    NotAModerator,
    #[error("only members of this community may post here")]
    NotAMember,
    #[error("only moderators post here")]
    ModeratorsOnly,
    #[error("an address is lower-case letters, digits and _, at most 30")]
    BadHandle,
    #[error("that address is taken")]
    HandleTaken,
    #[error("a community's address can't be changed once it has one")]
    HandleFixed,
    #[error("choose an address for the community first")]
    NeedsHandle,
    #[error("a post needs some text")]
    Empty,
    #[error("that is too long")]
    TooLong,
    #[error("that is not a place on Earth")]
    BadPlace,
    #[error("a picture is a hash in the picture store")]
    BadPicture,
    #[error("no such post")]
    NoSuchPost,
    #[error("only its author may change or delete a post")]
    NotYours,
    #[error("no such report")]
    NoSuchReport,
    #[error("no such person")]
    NoSuchPerson,
    #[error("the server could not store that: {0}")]
    Storage(String),
}

impl From<rusqlite::Error> for Refusal {
    fn from(e: rusqlite::Error) -> Self {
        Refusal::Storage(e.to_string())
    }
}

impl From<communities::Refusal> for Refusal {
    fn from(e: communities::Refusal) -> Self {
        match e {
            communities::Refusal::NoSuchCommunity => Refusal::NoSuchCommunity,
            communities::Refusal::NotAModerator => Refusal::NotAModerator,
            other => Refusal::Storage(other.to_string()),
        }
    }
}

/// The public half of a community, as stored.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Public {
    pub handle: String,
    pub enabled: bool,
    pub who_posts: WhoPosts,
}

fn who_of(n: i64) -> WhoPosts {
    if n == 1 {
        WhoPosts::Moderators
    } else {
        WhoPosts::Members
    }
}

fn who_number(w: WhoPosts) -> i64 {
    match w {
        WhoPosts::Members => 0,
        WhoPosts::Moderators => 1,
    }
}

/// A community's public half, if posts were ever switched on.
pub fn public(conn: &Connection, community: Uuid) -> Result<Option<Public>, Refusal> {
    Ok(conn
        .query_row(
            "SELECT handle, enabled, who_posts FROM community_public WHERE community = ?1",
            params![community.to_string()],
            |r| {
                Ok(Public {
                    handle: r.get(0)?,
                    enabled: r.get::<_, i64>(1)? != 0,
                    who_posts: who_of(r.get(2)?),
                })
            },
        )
        .optional()?)
}

/// The community a handle names, if posts are on there.
pub fn community_by_handle(conn: &Connection, handle: &str) -> Result<Option<Uuid>, Refusal> {
    let id: Option<String> = conn
        .query_row(
            "SELECT community FROM community_public WHERE handle = ?1 AND enabled = 1",
            params![handle],
            |r| r.get(0),
        )
        .optional()?;
    Ok(id.and_then(|s| Uuid::parse_str(&s).ok()))
}

fn community_exists(conn: &Connection, community: Uuid) -> Result<bool, Refusal> {
    Ok(conn
        .query_row(
            "SELECT 1 FROM communities WHERE id = ?1",
            params![community.to_string()],
            |_| Ok(()),
        )
        .optional()?
        .is_some())
}

/// Whether a handle is free: not another community's, not a retired one, and
/// not anybody's username (folded, since a username may have capitals and
/// `@name@server` is looked up without them) โ€” nor its reader's name
/// (`{handle}.reader`).
pub fn handle_free(conn: &Connection, handle: &str) -> Result<bool, Refusal> {
    let taken: bool = conn.query_row(
        "SELECT EXISTS (SELECT 1 FROM community_public WHERE handle = ?1)
             OR EXISTS (SELECT 1 FROM retired_handles WHERE handle = ?1)
             OR EXISTS (SELECT 1 FROM accounts
                        WHERE lower(username) = ?1 OR lower(username) = ?1 || '.reader')",
        params![handle],
        |r| r.get(0),
    )?;
    Ok(!taken)
}

/// A moderator switches posts on or off, chooses who may write them, and โ€” the
/// first time โ€” the community's address.
pub fn set_public(
    conn: &Connection,
    by: &str,
    community: Uuid,
    settings: &PublicSettings,
    now_ms: i64,
) -> Result<Public, Refusal> {
    match communities::role(conn, community, by)? {
        Some(r) if r.moderates() => {}
        Some(_) => return Err(Refusal::NotAModerator),
        None if community_exists(conn, community)? => return Err(Refusal::NotAModerator),
        None => return Err(Refusal::NoSuchCommunity),
    }
    let existing = public(conn, community)?;
    let handle = match (&existing, settings.handle.as_deref().map(str::trim)) {
        (Some(p), None) => p.handle.clone(),
        (Some(p), Some(h)) if h == p.handle => p.handle.clone(),
        (Some(_), Some(_)) => return Err(Refusal::HandleFixed),
        (None, None) => return Err(Refusal::NeedsHandle),
        (None, Some(h)) => {
            if !is_handle(h) {
                return Err(Refusal::BadHandle);
            }
            if !handle_free(conn, h)? {
                return Err(Refusal::HandleTaken);
            }
            h.to_string()
        }
    };
    conn.execute(
        "INSERT INTO community_public (community, handle, enabled, who_posts, created_ms)
         VALUES (?1, ?2, ?3, ?4, ?5)
         ON CONFLICT (community) DO UPDATE SET enabled = ?3, who_posts = ?4",
        params![
            community.to_string(),
            handle,
            settings.enabled,
            who_number(settings.who_posts),
            now_ms
        ],
    )?;
    Ok(Public {
        handle,
        enabled: settings.enabled,
        who_posts: settings.who_posts,
    })
}

/// The public half of a community as its page draws it, for `caller` (`None`
/// when nobody is signed in).
pub fn info(
    conn: &Connection,
    caller: Option<&str>,
    community: Uuid,
    server: &str,
    federating: bool,
) -> Result<PublicInfo, Refusal> {
    if !community_exists(conn, community)? {
        return Err(Refusal::NoSuchCommunity);
    }
    let role = match caller {
        Some(a) => communities::role(conn, community, a)?,
        None => None,
    };
    let p = public(conn, community)?;
    let followers: i64 = conn.query_row(
        "SELECT COUNT(*) FROM fedi_followers WHERE local = ?1",
        params![group_local(community)],
        |r| r.get(0),
    )?;
    let mut stmt = conn.prepare(
        "SELECT a.username, a.host, a.name, a.kind, f.accepted
         FROM community_follows f JOIN fedi_actors a ON a.id = f.actor
         WHERE f.community = ?1 ORDER BY f.created_ms",
    )?;
    let follows = stmt
        .query_map(params![community.to_string()], |r| {
            let kind: String = r.get(3)?;
            Ok(FollowDto {
                address: format!("{}@{}", r.get::<_, String>(0)?, r.get::<_, String>(1)?),
                name: r.get(2)?,
                kind: if kind == "Group" {
                    SourceKind::Community
                } else {
                    SourceKind::Account
                },
                accepted: r.get::<_, i64>(4)? != 0,
            })
        })?
        .collect::<Result<Vec<_>, _>>()?;
    let card = match &p {
        Some(p) if p.enabled => conn
            .query_row(
                "SELECT name, about, picture FROM communities WHERE id = ?1",
                params![community.to_string()],
                |r| {
                    Ok(PublicCommunity {
                        id: community,
                        name: r.get(0)?,
                        about: r.get(1)?,
                        picture: r.get(2)?,
                    })
                },
            )
            .optional()?,
        _ => None,
    };
    let open_reports: i64 = if role.is_some_and(CommunityRole::moderates) {
        conn.query_row(
            "SELECT COUNT(*) FROM post_reports WHERE community = ?1 AND resolved_ms IS NULL",
            params![community.to_string()],
            |r| r.get(0),
        )?
    } else {
        0
    };
    let may_post = match (&p, role) {
        (Some(p), Some(r)) if p.enabled => match p.who_posts {
            WhoPosts::Members => true,
            WhoPosts::Moderators => r.moderates(),
        },
        _ => false,
    };
    Ok(PublicInfo {
        address: p.as_ref().map(|p| format!("{}@{server}", p.handle)),
        settings: PublicSettings {
            enabled: p.as_ref().is_some_and(|p| p.enabled),
            handle: p.as_ref().map(|p| p.handle.clone()),
            who_posts: p.as_ref().map(|p| p.who_posts).unwrap_or_default(),
        },
        followers: u32::try_from(followers).unwrap_or(u32::MAX),
        follows,
        may_post,
        may_moderate: role.is_some_and(CommunityRole::moderates),
        federating,
        community: card,
        open_reports: u32::try_from(open_reports).unwrap_or(u32::MAX),
    })
}

/// The follower-table key for a community.
#[must_use]
pub fn group_local(community: Uuid) -> String {
    format!("c:{community}")
}

/// The key-table name of a community's reader (`super::reader_url`).
#[must_use]
pub fn reader_local(community: Uuid) -> String {
    format!("r:{community}")
}

/// The follower-table key for an account.
#[must_use]
pub fn person_local(account: &str) -> String {
    format!("u:{account}")
}

/// Trimmed and bounded, or refused.
fn clean_text(text: &str) -> Result<String, Refusal> {
    let t = text.trim();
    if t.is_empty() {
        return Err(Refusal::Empty);
    }
    if t.chars().count() > MAX_POST_TEXT {
        return Err(Refusal::TooLong);
    }
    Ok(t.to_string())
}

/// At most `max` characters of `s`, trimmed.
fn cut(s: &str, max: usize) -> String {
    s.trim().chars().take(max).collect()
}

/// An optional line of text: trimmed, `None` when blank, refused when longer
/// than `max` characters.
fn clean_optional(text: Option<&str>, max: usize) -> Result<Option<String>, Refusal> {
    let Some(t) = text.map(str::trim).filter(|t| !t.is_empty()) else {
        return Ok(None);
    };
    if t.chars().count() > max {
        return Err(Refusal::TooLong);
    }
    Ok(Some(t.to_string()))
}

fn clean_place(place: &PostPlace) -> Result<PostPlace, Refusal> {
    if !place.in_range() {
        return Err(Refusal::BadPlace);
    }
    let name = place
        .name
        .as_deref()
        .map(str::trim)
        .filter(|n| !n.is_empty())
        .map(|n| n.chars().take(MAX_PLACE_NAME).collect());
    Ok(PostPlace {
        name,
        ..place.clone()
    })
}

/// Whether `account` may write a post in `community` now.
fn may_post(conn: &Connection, community: Uuid, account: &str) -> Result<Public, Refusal> {
    if !community_exists(conn, community)? {
        return Err(Refusal::NoSuchCommunity);
    }
    let p = public(conn, community)?
        .filter(|p| p.enabled)
        .ok_or(Refusal::PostsOff)?;
    match (communities::role(conn, community, account)?, p.who_posts) {
        (None, _) => Err(Refusal::NotAMember),
        (Some(r), WhoPosts::Moderators) if !r.moderates() => Err(Refusal::ModeratorsOnly),
        _ => Ok(p),
    }
}

/// A post written here: its id is also the tail of its fediverse id
/// (`{base}/ap/p/{id}`).
pub fn create_post(
    conn: &Connection,
    author: &str,
    community: Uuid,
    new: &NewPost,
    base: &str,
    now_ms: i64,
) -> Result<Uuid, Refusal> {
    may_post(conn, community, author)?;
    let text = clean_text(&new.text)?;
    let place = clean_place(&new.place)?;
    if [&new.picture, &new.snapshot]
        .iter()
        .any(|p| p.as_deref().is_some_and(|p| !crate::assets::is_hash(p)))
    {
        return Err(Refusal::BadPicture);
    }
    let warning = clean_optional(new.warning.as_deref(), MAX_WARNING)?;
    let picture_alt = clean_optional(new.picture_alt.as_deref(), MAX_PICTURE_ALT)?;
    let id = Uuid::new_v4();
    let view = place.view;
    conn.execute(
        "INSERT INTO posts (id, community, parent, ap_id, author_account, text, picture,
                            lat, lng, place_name, view_alt, view_pitch, view_yaw, created_ms,
                            snapshot, warning, sensitive, picture_alt)
         VALUES (?1, ?2, NULL, ?3, ?4, ?5, ?6, ?7, ?8, ?9, ?10, ?11, ?12, ?13, ?14, ?15, ?16,
                 ?17)",
        params![
            id.to_string(),
            community.to_string(),
            super::post_url(base, id),
            author,
            text,
            new.picture,
            place.latitude,
            place.longitude,
            place.name,
            view.map(|v| v.altitude),
            view.map(|v| f64::from(v.pitch)),
            view.map(|v| f64::from(v.yaw)),
            now_ms,
            new.snapshot,
            warning,
            new.sensitive && new.picture.is_some(),
            picture_alt.filter(|_| new.picture.is_some())
        ],
    )?;
    Ok(id)
}

/// The post a reply should hang under: `id` itself if it is a post, its parent
/// if it is a reply. Hidden posts take no replies. Answers the community, that
/// post, and the fediverse id of `id` itself, which is what the reply answers.
fn thread_root(conn: &Connection, id: Uuid) -> Result<(Uuid, Uuid, String), Refusal> {
    let row: Option<(String, Option<String>, String)> = conn
        .query_row(
            &format!("SELECT community, parent, ap_id FROM posts WHERE id = ?1 AND {SHOWN}"),
            params![id.to_string()],
            |r| Ok((r.get(0)?, r.get(1)?, r.get(2)?)),
        )
        .optional()?;
    let (community, parent, ap_id) = row.ok_or(Refusal::NoSuchPost)?;
    let community = Uuid::parse_str(&community).map_err(|_| Refusal::NoSuchPost)?;
    let root = match parent {
        Some(p) => Uuid::parse_str(&p).map_err(|_| Refusal::NoSuchPost)?,
        None => id,
    };
    Ok((community, root, ap_id))
}

/// A reply written here, by anybody signed in.
pub fn create_reply(
    conn: &Connection,
    author: &str,
    to: Uuid,
    text: &str,
    base: &str,
    now_ms: i64,
) -> Result<(Uuid, Uuid), Refusal> {
    let text = clean_text(text)?;
    let (community, root, answers) = thread_root(conn, to)?;
    if !public(conn, community)?.is_some_and(|p| p.enabled) {
        return Err(Refusal::PostsOff);
    }
    let id = Uuid::new_v4();
    conn.execute(
        "INSERT INTO posts (id, community, parent, ap_id, author_account, text, created_ms,
                            in_reply_to)
         VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8)",
        params![
            id.to_string(),
            community.to_string(),
            root.to_string(),
            super::post_url(base, id),
            author,
            text,
            now_ms,
            answers
        ],
    )?;
    Ok((id, community))
}

/// Everything about one post or reply.
#[derive(Debug, Clone, PartialEq)]
pub struct PostRow {
    pub id: Uuid,
    pub community: Uuid,
    pub parent: Option<Uuid>,
    pub ap_id: String,
    pub author_account: Option<String>,
    pub author_actor: Option<String>,
    pub via_actor: Option<String>,
    pub text: String,
    pub picture: Option<String>,
    pub snapshot: Option<String>,
    pub place: Option<PostPlace>,
    pub url: Option<String>,
    pub created_ms: i64,
    pub edited_ms: Option<i64>,
    /// Hidden by a moderator, or from a blocked server.
    pub hidden: bool,
    /// The fediverse id of the post or reply this reply answers; `None` for a
    /// post, and for a reply stored before it was kept (it answers `parent`).
    pub in_reply_to: Option<String>,
    pub warning: Option<String>,
    pub sensitive: bool,
    pub picture_alt: Option<String>,
    pub more_pictures: Vec<PostPicture>,
}

/// SQL, over an unaliased `posts` row, that is true when its author or the
/// source that brought it lives on a blocked server (`blocklist`). Such a
/// post stays stored, so an unblock brings it back, and reads as hidden.
macro_rules! from_blocked_server {
    () => {
        "EXISTS (SELECT 1 FROM fedi_actors a
             WHERE a.id IN (posts.author_actor, posts.via_actor)
                 AND EXISTS (SELECT 1 FROM fedi_server_blocks b
                     WHERE a.host = b.host OR a.host LIKE '%.' || b.host))"
    };
}

/// SQL, over an unaliased `posts` row, that is true when readers see it.
const SHOWN: &str = concat!("(hidden_by IS NULL AND NOT ", from_blocked_server!(), ")");

const POST_COLUMNS: &str = concat!(
    "id, community, parent, ap_id, author_account, author_actor, via_actor,
     text, picture, lat, lng, place_name, view_alt, view_pitch, view_yaw, url, created_ms,
     edited_ms, (hidden_by IS NOT NULL OR ",
    from_blocked_server!(),
    "), snapshot, in_reply_to, warning, sensitive, picture_alt, more_pictures"
);

fn read_row(r: &rusqlite::Row<'_>) -> rusqlite::Result<PostRow> {
    let uuid = |s: String| Uuid::parse_str(&s).unwrap_or_default();
    let lat: Option<f64> = r.get(9)?;
    let lng: Option<f64> = r.get(10)?;
    let alt: Option<f64> = r.get(12)?;
    let pitch: Option<f64> = r.get(13)?;
    let yaw: Option<f64> = r.get(14)?;
    #[allow(clippy::cast_possible_truncation)]
    let view = match (alt, pitch, yaw) {
        (Some(altitude), Some(p), Some(y)) => Some(PointView {
            altitude,
            pitch: p as f32,
            yaw: y as f32,
        }),
        _ => None,
    };
    Ok(PostRow {
        id: uuid(r.get(0)?),
        community: uuid(r.get(1)?),
        parent: r.get::<_, Option<String>>(2)?.map(uuid),
        ap_id: r.get(3)?,
        author_account: r.get(4)?,
        author_actor: r.get(5)?,
        via_actor: r.get(6)?,
        text: r.get(7)?,
        picture: r.get(8)?,
        place: lat.zip(lng).map(|(latitude, longitude)| PostPlace {
            latitude,
            longitude,
            name: r.get(11).ok().flatten(),
            view,
        }),
        url: r.get(15)?,
        created_ms: r.get(16)?,
        edited_ms: r.get(17)?,
        hidden: r.get(18)?,
        snapshot: r.get(19)?,
        in_reply_to: r.get(20)?,
        warning: r.get(21)?,
        sensitive: r.get(22)?,
        picture_alt: r.get(23)?,
        more_pictures: r
            .get::<_, Option<String>>(24)?
            .and_then(|j| serde_json::from_str(&j).ok())
            .unwrap_or_default(),
    })
}

/// One post or reply by id, hidden or not.
pub fn row(conn: &Connection, id: Uuid) -> Result<Option<PostRow>, Refusal> {
    Ok(conn
        .query_row(
            &format!("SELECT {POST_COLUMNS} FROM posts WHERE id = ?1"),
            params![id.to_string()],
            read_row,
        )
        .optional()?)
}

/// Every copy of a fediverse object here (one per community it is in).
pub fn rows_by_ap_id(conn: &Connection, ap_id: &str) -> Result<Vec<PostRow>, Refusal> {
    let mut stmt = conn.prepare(&format!(
        "SELECT {POST_COLUMNS} FROM posts WHERE ap_id = ?1"
    ))?;
    let rows = stmt.query_map(params![ap_id], read_row)?;
    Ok(rows.collect::<Result<_, _>>()?)
}

/// The replies under a post, oldest first, hidden ones left out.
pub fn replies_of(conn: &Connection, root: Uuid) -> Result<Vec<PostRow>, Refusal> {
    let mut stmt = conn.prepare(&format!(
        "SELECT {POST_COLUMNS} FROM posts WHERE parent = ?1 AND {SHOWN}
         ORDER BY created_ms, id"
    ))?;
    let rows = stmt.query_map(params![root.to_string()], read_row)?;
    Ok(rows.collect::<Result<_, _>>()?)
}

/// Who wrote a row, as a reader is shown them.
fn author_of(conn: &Connection, row: &PostRow, server: &str) -> Result<PostAuthor, Refusal> {
    match &row.author_account {
        Some(account) => local_author(conn, account, server),
        None => remote_author(conn, row.author_actor.as_deref().unwrap_or_default()),
    }
}

/// An account here, as a reader is shown it.
pub fn local_author(conn: &Connection, account: &str, server: &str) -> Result<PostAuthor, Refusal> {
    let name: String = conn
        .query_row(
            "SELECT username FROM accounts WHERE id = ?1",
            params![account],
            |r| r.get(0),
        )
        .optional()?
        .unwrap_or_else(|| crate::db::DELETED_ACCOUNT_NAME.to_string());
    Ok(PostAuthor {
        address: format!("{name}@{server}"),
        name,
        local: true,
    })
}

/// An actor elsewhere, as a reader is shown it: its name when we have read
/// it, its id otherwise.
pub fn remote_author(conn: &Connection, actor: &str) -> Result<PostAuthor, Refusal> {
    Ok(actor_label(conn, actor)?.unwrap_or_else(|| PostAuthor {
        name: actor.to_string(),
        address: actor.to_string(),
        local: false,
    }))
}

/// Somebody here likes a post (`on`), or stops (`!on`). Their like is kept
/// as any other, under their own actor, so the count is one count. Answers
/// whether anything changed.
pub fn like(
    conn: &Connection,
    account: &str,
    id: Uuid,
    on: bool,
    base: &str,
    now_ms: i64,
) -> Result<(PostRow, bool), Refusal> {
    let post = row(conn, id)?
        .filter(|r| !r.hidden)
        .ok_or(Refusal::NoSuchPost)?;
    let actor = super::person_url(base, account);
    let changed = if on {
        conn.execute(
            "INSERT OR IGNORE INTO post_votes (object, actor, activity, value, created_ms)
             VALUES (?1, ?2, ?3, 1, ?4)",
            params![post.ap_id, actor, like_id(base, account, id), now_ms],
        )? == 1
    } else {
        unvote(conn, &actor, None, Some(&post.ap_id))? > 0
    };
    Ok((post, changed))
}

/// The id of somebody here's like of a post: one per person and post, so an
/// Undo can name it.
#[must_use]
pub fn like_id(base: &str, account: &str, post: Uuid) -> String {
    format!("{}/likes/{post}", super::person_url(base, account))
}

/// The id of somebody here's boost of a post.
#[must_use]
pub fn boost_id(base: &str, account: &str, post: Uuid) -> String {
    format!("{}/boosts/{post}", super::person_url(base, account))
}

/// Somebody passes a post on (`actor`, here or elsewhere), or takes it back.
/// Answers whether anything changed. Only a post that is here counts.
pub fn boost(
    conn: &Connection,
    object: &str,
    actor: &str,
    activity: &str,
    on: bool,
    now_ms: i64,
) -> Result<bool, Refusal> {
    if on {
        if rows_by_ap_id(conn, object)?.is_empty() {
            return Ok(false);
        }
        Ok(conn.execute(
            "INSERT OR IGNORE INTO post_boosts (object, actor, activity, created_ms)
             VALUES (?1, ?2, ?3, ?4)",
            params![object, actor, activity, now_ms],
        )? == 1)
    } else {
        Ok(conn.execute(
            "DELETE FROM post_boosts WHERE actor = ?2 AND (object = ?1 OR activity = ?3)",
            params![object, actor, activity],
        )? > 0)
    }
}

/// How a remote account is shown, if we have it.
fn actor_label(conn: &Connection, actor: &str) -> Result<Option<PostAuthor>, Refusal> {
    Ok(conn
        .query_row(
            "SELECT name, username, host FROM fedi_actors WHERE id = ?1",
            params![actor],
            |r| {
                let name: String = r.get(0)?;
                let address = format!("{}@{}", r.get::<_, String>(1)?, r.get::<_, String>(2)?);
                Ok(PostAuthor {
                    name: if name.trim().is_empty() {
                        address.clone()
                    } else {
                        name
                    },
                    address,
                    local: false,
                })
            },
        )
        .optional()?)
}

/// A row as the feed shows it to `caller`.
pub fn dto(
    conn: &Connection,
    row: &PostRow,
    caller: Option<&str>,
    server: &str,
) -> Result<PostDto, Refusal> {
    let replies: i64 = if row.parent.is_none() {
        conn.query_row(
            &format!("SELECT COUNT(*) FROM posts WHERE parent = ?1 AND {SHOWN}"),
            params![row.id.to_string()],
            |r| r.get(0),
        )?
    } else {
        0
    };
    let via = match &row.via_actor {
        Some(a) => actor_label(conn, a)?.map(|l| l.address),
        None => None,
    };
    let (likes, dislikes): (i64, i64) = conn.query_row(
        "SELECT COALESCE(SUM(value > 0), 0), COALESCE(SUM(value < 0), 0)
         FROM post_votes WHERE object = ?1",
        params![row.ap_id],
        |r| Ok((r.get(0)?, r.get(1)?)),
    )?;
    let boosts: i64 = conn.query_row(
        "SELECT COUNT(*) FROM post_boosts WHERE object = ?1",
        params![row.ap_id],
        |r| r.get(0),
    )?;
    // The caller's own like and boost are stored under their actor, which
    // ends in their account id (`person_url`).
    let (liked, boosted) = match caller {
        Some(me) => {
            let mine = format!("%/ap/u/{me}");
            let has = |table: &str| -> rusqlite::Result<bool> {
                conn.query_row(
                    &format!(
                        "SELECT EXISTS (SELECT 1 FROM {table} WHERE object = ?1 AND actor LIKE ?2)"
                    ),
                    params![row.ap_id, mine],
                    |r| r.get(0),
                )
            };
            (has("post_votes")?, has("post_boosts")?)
        }
        None => (false, false),
    };
    let answers = match (row.parent, row.in_reply_to.as_deref()) {
        (Some(_), Some(to)) => match rows_by_ap_id(conn, to)?
            .into_iter()
            .find(|r| r.community == row.community)
        {
            Some(r) => Some(author_of(conn, &r, server)?.name),
            None => None,
        },
        _ => None,
    };
    Ok(PostDto {
        id: row.id,
        community: row.community,
        parent: row.parent,
        author: author_of(conn, row, server)?,
        via,
        text: row.text.clone(),
        picture: row.picture.clone(),
        snapshot: row.snapshot.clone(),
        place: row.place.clone(),
        url: row.url.clone(),
        created_ms: row.created_ms,
        edited_ms: row.edited_ms,
        replies: u32::try_from(replies).unwrap_or(0),
        mine: caller.is_some() && row.author_account.as_deref() == caller,
        likes: u32::try_from(likes).unwrap_or(0),
        dislikes: u32::try_from(dislikes).unwrap_or(0),
        boosts: u32::try_from(boosts).unwrap_or(0),
        liked,
        boosted,
        answers,
        warning: row.warning.clone(),
        sensitive: row.sensitive,
        picture_alt: row.picture_alt.clone(),
        more_pictures: row.more_pictures.clone(),
    })
}

/// A page of a community's posts, newest first, older than `before_ms` when it
/// is given. Readable by anybody while posts are on: they are public.
pub fn feed(
    conn: &Connection,
    community: Uuid,
    caller: Option<&str>,
    before_ms: Option<i64>,
    server: &str,
) -> Result<Vec<PostDto>, Refusal> {
    if !community_exists(conn, community)? {
        return Err(Refusal::NoSuchCommunity);
    }
    if !public(conn, community)?.is_some_and(|p| p.enabled) {
        return Ok(Vec::new());
    }
    let mut stmt = conn.prepare(&format!(
        "SELECT {POST_COLUMNS} FROM posts
         WHERE community = ?1 AND parent IS NULL AND {SHOWN} AND created_ms < ?2
         ORDER BY created_ms DESC, id LIMIT ?3"
    ))?;
    let rows = stmt
        .query_map(
            params![
                community.to_string(),
                before_ms.unwrap_or(i64::MAX),
                i64::try_from(POSTS_PAGE).unwrap_or(30)
            ],
            read_row,
        )?
        .collect::<Result<Vec<_>, _>>()?;
    rows.iter().map(|r| dto(conn, r, caller, server)).collect()
}

/// A post and its replies.
pub fn thread(
    conn: &Connection,
    id: Uuid,
    caller: Option<&str>,
    server: &str,
) -> Result<PostThread, Refusal> {
    let post = row(conn, id)?
        .filter(|r| !r.hidden)
        .ok_or(Refusal::NoSuchPost)?;
    let root = post.parent.unwrap_or(post.id);
    let post = if root == post.id {
        post
    } else {
        row(conn, root)?
            .filter(|r| !r.hidden)
            .ok_or(Refusal::NoSuchPost)?
    };
    if !public(conn, post.community)?.is_some_and(|p| p.enabled) {
        return Err(Refusal::NoSuchPost);
    }
    let replies = replies_of(conn, root)?
        .iter()
        .map(|r| dto(conn, r, caller, server))
        .collect::<Result<_, _>>()?;
    Ok(PostThread {
        post: dto(conn, &post, caller, server)?,
        replies,
    })
}

/// The author takes a post back. A post goes with its replies (they answer
/// something that is no longer there). Answers what was deleted, so the caller
/// can tell other servers.
pub fn delete(conn: &Connection, by: &str, id: Uuid) -> Result<Vec<PostRow>, Refusal> {
    let post = row(conn, id)?.ok_or(Refusal::NoSuchPost)?;
    if post.author_account.as_deref() != Some(by) {
        return Err(Refusal::NotYours);
    }
    remove_with_replies(conn, &post)
}

fn remove_with_replies(conn: &Connection, post: &PostRow) -> Result<Vec<PostRow>, Refusal> {
    let mut gone = vec![post.clone()];
    if post.parent.is_none() {
        let mut stmt = conn.prepare(&format!(
            "SELECT {POST_COLUMNS} FROM posts WHERE parent = ?1"
        ))?;
        gone.extend(
            stmt.query_map(params![post.id.to_string()], read_row)?
                .collect::<Result<Vec<_>, _>>()?,
        );
    }
    let tx = conn.unchecked_transaction()?;
    for p in &gone {
        let id = p.id.to_string();
        tx.execute("DELETE FROM posts WHERE id = ?1", params![id])?;
        tx.execute("DELETE FROM post_mentions WHERE post = ?1", params![id])?;
        tx.execute("DELETE FROM post_reports WHERE post = ?1", params![id])?;
        // Votes are on the object, which another community here may still hold.
        tx.execute(
            "DELETE FROM post_votes WHERE object = ?1
                 AND NOT EXISTS (SELECT 1 FROM posts WHERE ap_id = ?1)",
            params![p.ap_id],
        )?;
    }
    tx.commit()?;
    Ok(gone)
}

/// The author changes the words of a post or reply written here. Answers the
/// row as it is now, so the caller can tell other servers.
pub fn edit(
    conn: &Connection,
    by: &str,
    id: Uuid,
    text: &str,
    now_ms: i64,
) -> Result<PostRow, Refusal> {
    let post = row(conn, id)?
        .filter(|r| !r.hidden)
        .ok_or(Refusal::NoSuchPost)?;
    if post.author_account.as_deref() != Some(by) {
        return Err(Refusal::NotYours);
    }
    if !public(conn, post.community)?.is_some_and(|p| p.enabled) {
        return Err(Refusal::PostsOff);
    }
    let text = clean_text(text)?;
    conn.execute(
        "UPDATE posts SET text = ?2, edited_ms = ?3 WHERE id = ?1",
        params![id.to_string(), text, now_ms],
    )?;
    row(conn, id)?.ok_or(Refusal::NoSuchPost)
}

/// Keep who a post written here mentions, as resolved when it was written or
/// edited: what was there before is replaced.
pub fn set_mentions(
    conn: &Connection,
    post: Uuid,
    mentions: &[super::objects::Mention],
) -> Result<(), Refusal> {
    let id = post.to_string();
    conn.execute("DELETE FROM post_mentions WHERE post = ?1", params![id])?;
    for m in mentions {
        conn.execute(
            "INSERT OR IGNORE INTO post_mentions (post, actor, name, href) VALUES (?1, ?2, ?3, ?4)",
            params![id, m.actor, m.name, m.href],
        )?;
    }
    Ok(())
}

/// Who a post written here mentions.
pub fn mentions_of(conn: &Connection, post: Uuid) -> Result<Vec<super::objects::Mention>, Refusal> {
    let mut stmt =
        conn.prepare("SELECT actor, name, href FROM post_mentions WHERE post = ?1 ORDER BY rowid")?;
    let rows = stmt.query_map(params![post.to_string()], |r| {
        Ok(super::objects::Mention {
            actor: r.get(0)?,
            name: r.get(1)?,
            href: r.get(2)?,
        })
    })?;
    Ok(rows.collect::<Result<_, _>>()?)
}

/// Somebody elsewhere likes (`value` 1) or dislikes (-1) a post here. Answers
/// whether the post is here at all; a vote on anything else is not kept.
pub fn vote(
    conn: &Connection,
    object: &str,
    actor: &str,
    activity: &str,
    value: i64,
    now_ms: i64,
) -> Result<bool, Refusal> {
    if rows_by_ap_id(conn, object)?.is_empty() {
        return Ok(false);
    }
    conn.execute(
        "INSERT INTO post_votes (object, actor, activity, value, created_ms)
         VALUES (?1, ?2, ?3, ?4, ?5)
         ON CONFLICT (object, actor) DO UPDATE SET activity = ?3, value = ?4, created_ms = ?5",
        params![object, actor, activity, value.signum(), now_ms],
    )?;
    Ok(true)
}

/// Somebody takes a vote back, named by the vote's own id or by what it was on.
pub fn unvote(
    conn: &Connection,
    actor: &str,
    activity: Option<&str>,
    object: Option<&str>,
) -> Result<usize, Refusal> {
    let mut n = 0;
    if let Some(a) = activity {
        n += conn.execute(
            "DELETE FROM post_votes WHERE activity = ?1 AND actor = ?2",
            params![a, actor],
        )?;
    }
    if let Some(o) = object {
        n += conn.execute(
            "DELETE FROM post_votes WHERE object = ?1 AND actor = ?2",
            params![o, actor],
        )?;
    }
    Ok(n)
}

/// Another server reports a post here: a report for the moderators of each
/// community it is in. Answers how many were filed.
pub fn report(
    conn: &Connection,
    object: &str,
    reporter: &str,
    reason: &str,
    now_ms: i64,
) -> Result<usize, Refusal> {
    let reason: String = reason.trim().chars().take(MAX_POST_TEXT * 2).collect();
    let mut n = 0;
    for post in rows_by_ap_id(conn, object)? {
        if post.hidden {
            continue;
        }
        // One open report per post and reporter: a server that sends its
        // report twice has still made one.
        let open: bool = conn.query_row(
            "SELECT EXISTS (SELECT 1 FROM post_reports
                            WHERE post = ?1 AND reporter = ?2 AND resolved_ms IS NULL)",
            params![post.id.to_string(), reporter],
            |r| r.get(0),
        )?;
        if open {
            continue;
        }
        conn.execute(
            "INSERT INTO post_reports (id, community, post, reporter, reason, created_ms)
             VALUES (?1, ?2, ?3, ?4, ?5, ?6)",
            params![
                Uuid::new_v4().to_string(),
                post.community.to_string(),
                post.id.to_string(),
                reporter,
                reason,
                now_ms
            ],
        )?;
        n += 1;
    }
    Ok(n)
}

fn must_moderate(conn: &Connection, community: Uuid, by: &str) -> Result<(), Refusal> {
    match communities::role(conn, community, by)? {
        Some(r) if r.moderates() => Ok(()),
        None if !community_exists(conn, community)? => Err(Refusal::NoSuchCommunity),
        _ => Err(Refusal::NotAModerator),
    }
}

/// The open reports in a community, oldest first, for its moderators.
pub fn open_reports(
    conn: &Connection,
    by: &str,
    community: Uuid,
    server: &str,
) -> Result<Vec<PostReport>, Refusal> {
    must_moderate(conn, community, by)?;
    let mut stmt = conn.prepare(
        "SELECT id, post, reporter, reason, created_ms FROM post_reports
         WHERE community = ?1 AND resolved_ms IS NULL ORDER BY created_ms",
    )?;
    let rows: Vec<(String, String, String, String, i64)> = stmt
        .query_map(params![community.to_string()], |r| {
            Ok((r.get(0)?, r.get(1)?, r.get(2)?, r.get(3)?, r.get(4)?))
        })?
        .collect::<Result<_, _>>()?;
    let mut out = Vec::new();
    for (id, post, reporter, reason, created_ms) in rows {
        let (Ok(id), Ok(post)) = (Uuid::parse_str(&id), Uuid::parse_str(&post)) else {
            continue;
        };
        let Some(post) = row(conn, post)? else {
            continue;
        };
        // Somebody here reports under their own actor (`person_url`).
        let here: Option<String> = conn
            .query_row(
                "SELECT username FROM accounts WHERE ?1 LIKE '%/ap/u/' || id",
                params![reporter],
                |r| r.get(0),
            )
            .optional()?;
        let reporter = match (here, actor_label(conn, &reporter)?) {
            (Some(name), _) => format!("{name}@{server}"),
            (None, Some(l)) => l.address,
            (None, None) => super::fetch::host_of(&reporter).unwrap_or(reporter),
        };
        out.push(PostReport {
            id,
            post: dto(conn, &post, Some(by), server)?,
            reporter,
            reason,
            created_ms,
        });
    }
    Ok(out)
}

/// A moderator closes a report: hiding the post, or leaving it. Hiding closes
/// every open report on that post. Answers the post when it was hidden, so the
/// caller can withdraw one written here.
pub fn resolve_report(
    conn: &Connection,
    by: &str,
    community: Uuid,
    report: Uuid,
    action: ReportAction,
    now_ms: i64,
) -> Result<Option<PostRow>, Refusal> {
    must_moderate(conn, community, by)?;
    let post: String = conn
        .query_row(
            "SELECT post FROM post_reports WHERE id = ?1 AND community = ?2",
            params![report.to_string(), community.to_string()],
            |r| r.get(0),
        )
        .optional()?
        .ok_or(Refusal::NoSuchReport)?;
    match action {
        ReportAction::Dismiss => {
            conn.execute(
                "UPDATE post_reports SET resolved_by = ?2, resolved = 'dismissed', resolved_ms = ?3
                 WHERE id = ?1",
                params![report.to_string(), by, now_ms],
            )?;
            Ok(None)
        }
        ReportAction::Hide => {
            let id = Uuid::parse_str(&post).map_err(|_| Refusal::NoSuchPost)?;
            let row = hide(conn, by, id)?;
            conn.execute(
                "UPDATE post_reports SET resolved_by = ?2, resolved = 'hidden', resolved_ms = ?3
                 WHERE post = ?1 AND resolved_ms IS NULL",
                params![post, by, now_ms],
            )?;
            Ok(Some(row))
        }
    }
}

/// A person's public posts, newest first, for their page. Only somebody who has
/// written one has a page: everybody else is not findable from outside.
pub fn person_posts(
    conn: &Connection,
    username: &str,
    caller: Option<&str>,
    server: &str,
) -> Result<PersonPosts, Refusal> {
    let found: Option<(String, String, Option<String>)> = conn
        .query_row(
            "SELECT id, username, picture FROM accounts
             WHERE lower(username) = lower(?1) AND disabled = 0",
            params![username],
            |r| Ok((r.get(0)?, r.get(1)?, r.get(2)?)),
        )
        .optional()?;
    let (account, username, picture) = found.ok_or(Refusal::NoSuchPerson)?;
    let mut stmt = conn.prepare(&format!(
        "SELECT {POST_COLUMNS} FROM posts WHERE id IN
             (SELECT p.id FROM posts p JOIN community_public c ON c.community = p.community
              WHERE p.author_account = ?1 AND p.parent IS NULL AND p.hidden_by IS NULL
                  AND c.enabled = 1)
         ORDER BY created_ms DESC LIMIT ?2"
    ))?;
    let rows = stmt
        .query_map(
            params![account, i64::try_from(POSTS_PAGE).unwrap_or(30)],
            read_row,
        )?
        .collect::<Result<Vec<_>, _>>()?;
    // A moderator of a public community is findable before they post (they
    // answer for it), so their page is there, empty.
    let moderates_public: bool = conn.query_row(
        "SELECT EXISTS (SELECT 1 FROM community_members m
                        JOIN community_public p ON p.community = m.community
                        WHERE m.account = ?1 AND m.role < 2 AND p.enabled = 1)",
        params![account],
        |r| r.get(0),
    )?;
    if rows.is_empty() && !moderates_public {
        return Err(Refusal::NoSuchPerson);
    }
    Ok(PersonPosts {
        address: format!("{username}@{server}"),
        picture,
        posts: rows
            .iter()
            .map(|r| dto(conn, r, caller, server))
            .collect::<Result<_, _>>()?,
    })
}

/// A moderator hides a post or reply from the community. It stays in the
/// database, so the decision is on record, and stops being shown or served.
pub fn hide(conn: &Connection, by: &str, id: Uuid) -> Result<PostRow, Refusal> {
    let post = row(conn, id)?.ok_or(Refusal::NoSuchPost)?;
    match communities::role(conn, post.community, by)? {
        Some(r) if r.moderates() => {}
        _ => return Err(Refusal::NotAModerator),
    }
    conn.execute(
        "UPDATE posts SET hidden_by = ?2 WHERE id = ?1",
        params![id.to_string(), by],
    )?;
    // Hidden is what any report on it asked for.
    conn.execute(
        "UPDATE post_reports SET resolved_by = ?2, resolved = 'hidden', resolved_ms = ?3
         WHERE post = ?1 AND resolved_ms IS NULL",
        params![id.to_string(), by, super::now_ms()],
    )?;
    Ok(post)
}

/// A post or reply that arrived from another server.
#[derive(Debug, Clone, PartialEq)]
pub struct Remote {
    pub ap_id: String,
    pub author_actor: String,
    pub via_actor: Option<String>,
    pub text: String,
    pub picture: Option<String>,
    pub place: Option<PostPlace>,
    pub url: Option<String>,
    pub created_ms: i64,
    /// The post here it answers, for a reply.
    pub parent: Option<Uuid>,
    /// What it answers, by fediverse id, for a reply: `parent`'s, or one of
    /// the replies under it.
    pub in_reply_to: Option<String>,
    /// Its content warning, whether its pictures are sensitive, what the
    /// first shows in words, and the pictures after the first.
    pub warning: Option<String>,
    pub sensitive: bool,
    pub picture_alt: Option<String>,
    pub more_pictures: Vec<PostPicture>,
}

/// Store a post from elsewhere in a community. Answers its id here, or `None`
/// when it was already here (a server may deliver the same thing twice).
pub fn store_remote(
    conn: &Connection,
    community: Uuid,
    post: &Remote,
) -> Result<Option<Uuid>, Refusal> {
    if !public(conn, community)?.is_some_and(|p| p.enabled) {
        return Err(Refusal::PostsOff);
    }
    let text: String = post.text.trim().chars().take(MAX_POST_TEXT * 4).collect();
    let place = post.place.as_ref().filter(|p| p.in_range());
    let view = place.and_then(|p| p.view);
    let id = Uuid::new_v4();
    let n = conn.execute(
        "INSERT OR IGNORE INTO posts (id, community, parent, ap_id, author_actor, via_actor, text,
                                      picture, lat, lng, place_name, view_alt, view_pitch,
                                      view_yaw, url, created_ms, in_reply_to, warning, sensitive,
                                      picture_alt, more_pictures)
         VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8, ?9, ?10, ?11, ?12, ?13, ?14, ?15, ?16, ?17,
                 ?18, ?19, ?20, ?21)",
        params![
            id.to_string(),
            community.to_string(),
            post.parent.map(|p| p.to_string()),
            post.ap_id,
            post.author_actor,
            post.via_actor,
            text,
            post.picture,
            place.map(|p| p.latitude),
            place.map(|p| p.longitude),
            place.and_then(|p| p.name.clone()),
            view.map(|v| v.altitude),
            view.map(|v| f64::from(v.pitch)),
            view.map(|v| f64::from(v.yaw)),
            post.url,
            post.created_ms,
            post.parent.and(post.in_reply_to.as_deref()),
            post.warning.as_deref().map(|w| cut(w, MAX_WARNING)),
            post.sensitive,
            post.picture_alt.as_deref().map(|a| cut(a, MAX_PICTURE_ALT)),
            (!post.more_pictures.is_empty())
                .then(|| serde_json::to_string(&post.more_pictures).unwrap_or_default())
        ],
    )?;
    Ok((n == 1).then_some(id))
}

/// What a post from elsewhere says and shows, as read on arrival or on an
/// edit (`inbox::read_content`).
#[derive(Debug, Clone, Default)]
pub struct Content {
    pub text: String,
    pub picture: Option<String>,
    pub picture_alt: Option<String>,
    pub more_pictures: Vec<PostPicture>,
    /// How many pictures the post listed, copied or not: an edit that lists
    /// some but whose copies all failed keeps the pictures it had.
    pub pictures_listed: usize,
    pub warning: Option<String>,
    pub sensitive: bool,
}

/// Another server says a post changed. Only its own author's server may say
/// so, which the caller has checked.
pub fn update_remote(
    conn: &Connection,
    ap_id: &str,
    author_actor: &str,
    content: &Content,
    now_ms: i64,
) -> Result<usize, Refusal> {
    let text: String = content
        .text
        .trim()
        .chars()
        .take(MAX_POST_TEXT * 4)
        .collect();
    let n = conn.execute(
        "UPDATE posts SET text = ?3, edited_ms = ?4, warning = ?5, sensitive = ?6
         WHERE ap_id = ?1 AND author_actor = ?2",
        params![
            ap_id,
            author_actor,
            text,
            now_ms,
            content.warning.as_deref().map(|w| cut(w, MAX_WARNING)),
            content.sensitive
        ],
    )?;
    if content.picture.is_some() || content.pictures_listed == 0 {
        conn.execute(
            "UPDATE posts SET picture = ?3, picture_alt = ?4, more_pictures = ?5
             WHERE ap_id = ?1 AND author_actor = ?2",
            params![
                ap_id,
                author_actor,
                content.picture,
                content
                    .picture_alt
                    .as_deref()
                    .map(|a| cut(a, MAX_PICTURE_ALT)),
                (!content.more_pictures.is_empty())
                    .then(|| serde_json::to_string(&content.more_pictures).unwrap_or_default())
            ],
        )?;
    }
    Ok(n)
}

/// Another server says a post is gone. Its replies here go with it.
pub fn delete_remote(conn: &Connection, ap_id: &str, author_actor: &str) -> Result<usize, Refusal> {
    let mut n = 0;
    for post in rows_by_ap_id(conn, ap_id)? {
        if post.author_actor.as_deref() == Some(author_actor) {
            n += remove_with_replies(conn, &post)?.len();
        }
    }
    Ok(n)
}

/// Everything a remote account wrote here goes (it was deleted at home).
pub fn forget_actor(conn: &Connection, actor: &str) -> Result<(), Refusal> {
    let mut stmt = conn.prepare(&format!(
        "SELECT {POST_COLUMNS} FROM posts WHERE author_actor = ?1"
    ))?;
    let rows = stmt
        .query_map(params![actor], read_row)?
        .collect::<Result<Vec<_>, _>>()?;
    for r in rows {
        remove_with_replies(conn, &r)?;
    }
    conn.execute(
        "DELETE FROM fedi_followers WHERE actor = ?1",
        params![actor],
    )?;
    Ok(())
}

/// A moderator blocks an account elsewhere from the community, and hides what
/// it wrote here.
pub fn block_actor(
    conn: &Connection,
    by: &str,
    community: Uuid,
    actor: &str,
    now_ms: i64,
) -> Result<(), Refusal> {
    match communities::role(conn, community, by)? {
        Some(r) if r.moderates() => {}
        _ => return Err(Refusal::NotAModerator),
    }
    conn.execute(
        "INSERT OR REPLACE INTO community_actor_blocks (community, actor, blocked_by, added_ms)
         VALUES (?1, ?2, ?3, ?4)",
        params![community.to_string(), actor, by, now_ms],
    )?;
    conn.execute(
        "UPDATE posts SET hidden_by = ?3
         WHERE community = ?1 AND author_actor = ?2 AND hidden_by IS NULL",
        params![community.to_string(), actor, by],
    )?;
    conn.execute(
        "DELETE FROM fedi_followers WHERE local = ?1 AND actor = ?2",
        params![group_local(community), actor],
    )?;
    Ok(())
}

/// Whether a community's moderators blocked `actor`.
pub fn actor_blocked(conn: &Connection, community: Uuid, actor: &str) -> Result<bool, Refusal> {
    Ok(conn
        .query_row(
            "SELECT 1 FROM community_actor_blocks WHERE community = ?1 AND actor = ?2",
            params![community.to_string(), actor],
            |_| Ok(()),
        )
        .optional()?
        .is_some())
}

/// The picture hashes public posts name: the only pictures in the store that
/// may be served without a session.
pub fn picture_is_public(conn: &Connection, hash: &str) -> Result<bool, Refusal> {
    Ok(conn
        .query_row(
            "SELECT 1 FROM posts p JOIN community_public c ON c.community = p.community
             WHERE (p.picture = ?1 OR p.snapshot = ?1) AND p.hidden_by IS NULL
                 AND c.enabled = 1 LIMIT 1",
            params![hash],
            |_| Ok(()),
        )
        .optional()?
        .is_some())
}

/// A community is gone: its posts, followers and follows go, and its handle is
/// retired rather than freed.
pub fn forget_community(conn: &Connection, community: Uuid, now_ms: i64) -> Result<(), Refusal> {
    let id = community.to_string();
    if let Some(p) = public(conn, community)? {
        conn.execute(
            "INSERT OR IGNORE INTO retired_handles (handle, retired_ms) VALUES (?1, ?2)",
            params![p.handle, now_ms],
        )?;
    }
    for table in [
        "posts",
        "community_public",
        "community_follows",
        "community_actor_blocks",
    ] {
        conn.execute(
            &format!("DELETE FROM {table} WHERE community = ?1"),
            params![id],
        )?;
    }
    conn.execute(
        "DELETE FROM fedi_followers WHERE local = ?1",
        params![group_local(community)],
    )?;
    for key in [group_local(community), reader_local(community)] {
        conn.execute("DELETE FROM fedi_keys WHERE actor = ?1", params![key])?;
    }
    conn.execute("DELETE FROM post_reports WHERE community = ?1", params![id])?;
    Ok(())
}

/// An account is deleted: what it wrote goes (with the replies under its
/// posts), and so do its followers. Answers the rows.
///
/// When other servers know the account (it has a key: it posted, or answered
/// for a public community), what to tell them is kept in `fedi_gone_accounts`
/// for the delivery worker, which knows this server's address where the caller
/// may not (an account deleted from the shell). The key stays: the deletion
/// is signed with it, and the account's actor answers 410 Gone while it is
/// there.
pub fn forget_account(
    conn: &Connection,
    account: &str,
    now_ms: i64,
) -> Result<Vec<PostRow>, Refusal> {
    let mut stmt = conn.prepare(&format!(
        "SELECT {POST_COLUMNS} FROM posts WHERE author_account = ?1"
    ))?;
    super::notices::forget_account(conn, account)?;
    let rows = stmt
        .query_map(params![account], read_row)?
        .collect::<Result<Vec<_>, _>>()?;
    let known: bool = conn.query_row(
        "SELECT EXISTS (SELECT 1 FROM fedi_keys WHERE actor = ?1)",
        params![person_local(account)],
        |r| r.get(0),
    )?;
    if known {
        // Everybody who was sent anything of theirs: their followers, the
        // followers of each community they wrote in, and whoever they answered
        // or named.
        let mut also: Vec<String> = Vec::new();
        let mut communities: Vec<Uuid> = Vec::new();
        for r in &rows {
            if !communities.contains(&r.community) {
                communities.push(r.community);
            }
            if let Some(parent) = r.parent.and_then(|p| row(conn, p).ok().flatten()) {
                also.extend(parent.author_actor);
            }
            also.extend(mentions_of(conn, r.id)?.into_iter().map(|m| m.actor));
        }
        let mut inboxes = super::delivery::inboxes(conn, Some(&person_local(account)), &also)?;
        for c in communities {
            inboxes.extend(super::delivery::inboxes(conn, Some(&group_local(c)), &[])?);
        }
        inboxes.sort();
        inboxes.dedup();
        let posts: Vec<&str> = rows.iter().map(|r| r.ap_id.as_str()).collect();
        conn.execute(
            "INSERT OR REPLACE INTO fedi_gone_accounts (account, inboxes, posts, gone_ms)
             VALUES (?1, ?2, ?3, ?4)",
            params![
                account,
                serde_json::to_string(&inboxes).unwrap_or_else(|_| "[]".into()),
                serde_json::to_string(&posts).unwrap_or_else(|_| "[]".into()),
                now_ms
            ],
        )?;
    }
    let mut gone = Vec::new();
    for r in &rows {
        if row(conn, r.id)?.is_some() {
            gone.extend(remove_with_replies(conn, r)?);
        }
    }
    conn.execute(
        "DELETE FROM fedi_followers WHERE local = ?1",
        params![person_local(account)],
    )?;
    Ok(gone)
}

/// Whether an account that is gone was known to other servers: its actor
/// answers 410 Gone rather than 404.
pub fn account_gone(conn: &Connection, account: &str) -> Result<bool, Refusal> {
    Ok(conn.query_row(
        "SELECT EXISTS (SELECT 1 FROM fedi_keys WHERE actor = ?1)
            AND NOT EXISTS (SELECT 1 FROM accounts WHERE id = ?2)",
        params![person_local(account), account],
        |r| r.get(0),
    )?)
}

#[cfg(test)]
mod tests;