Skip to content

Lightweight native Discord client for Windows, Linux and macOS, written in Rust. No Electron, no browser engine.

63.5 KB
Raw Blame
//! `--demo` mode: a simulated Discord, so RustCord and Rencord
//! can be tried without an account. Everything flows through the same
//! gateway-event code paths as the real client.

use crate::backend::{spawn_theme_fetch, Command, Emitter, Event};
use discord::gateway::GatewayEvent;
use discord::model::{Id, Message};
use serde::Deserialize;
use serde_json::{json, Value};
use std::sync::atomic::{AtomicU64, Ordering};
use std::sync::Arc;
use std::time::{Duration, SystemTime, UNIX_EPOCH};
use tokio::sync::mpsc::UnboundedReceiver;
use tokio::time::sleep;

const ME: u64 = 1000;
const FERRIS: u64 = 1001;
const CLIPPY: u64 = 1002;
const CORRO: u64 = 1003;
const BOT: u64 = 1004;
/// Discord's own system account (official notifications).
const SYSTEM: u64 = 1005;

const G_RUST: u64 = 10;
const C_RUST_TEXT: u64 = 11;
const C_GENERAL: u64 = 12;
const C_RENCORD: u64 = 13;
const C_LINKS: u64 = 14;
const C_RUST_VOICE_CAT: u64 = 15;
const C_HANGOUT: u64 = 16;
/// Many GIFs at once (clips and files), for playback performance.
const C_GIFS: u64 = 17;
/// Stickers of every kind, for playback and the sticker popout.
const C_STICKERS: u64 = 18;

const G_VEN: u64 = 20;
const C_VEN_CAT: u64 = 21;
const C_VEN_CHAT: u64 = 22;
const C_THEMES: u64 = 23;
const C_MOD_ONLY: u64 = 24;

const DM_FERRIS: u64 = 30;
const DM_GROUP: u64 = 31;
const DM_CLIPPY: u64 = 32;
const DM_SYSTEM: u64 = 33;
const DM_REQUEST: u64 = 34;

fn now_ms() -> u64 {
    SystemTime::now().duration_since(UNIX_EPOCH).map(|d| d.as_millis() as u64).unwrap_or(0)
}

fn iso(ms: u64) -> String {
    chrono::DateTime::from_timestamp_millis(ms as i64)
        .unwrap_or_default()
        .to_rfc3339()
}

struct IdGen(AtomicU64);

impl IdGen {
    fn next(&self) -> u64 {
        let n = self.0.fetch_add(1, Ordering::Relaxed) & 0xFFF;
        Id::from_timestamp_ms(now_ms()).0 | n
    }
}

fn user(id: u64) -> Value {
    // The legacy discriminator only picks which of Discord's default avatars is used.
    let (username, global, bot, disc) = match id {
        ME => ("you", "You", false, "0001"),
        // (avatars stay Discord's defaults in the demo)
        FERRIS => ("ferris", "Ferris", false, "0004"),
        CLIPPY => ("clippy", "Clippy", false, "0003"),
        CORRO => ("corro", "Corro the Unsafe Rusturchin", false, "0005"),
        BOT => ("rencord-bot", "Rencord Bot", true, "0002"),
        SYSTEM => ("discord", "Discord", false, "0000"),
        _ => ("someone", "Someone", false, "0"),
    };
    // Server tags (the chip after the name).
    let tag = match id {
        ME | FERRIS => Some((G_RUST, "RUST")),
        CORRO => Some((G_VEN, "VEN")),
        _ => None,
    };
    let primary_guild = tag.map(|(g, t)| json!({ "identity_guild_id": g.to_string(), "identity_enabled": true, "tag": t, "badge": null }));
    json!({
        "id": id.to_string(), "username": username, "global_name": global, "avatar": null, "bot": bot,
        "discriminator": disc, "primary_guild": primary_guild, "system": id == SYSTEM,
        // A Nitro gradient display name on you.
        "display_name_styles": if id == ME { json!({ "font_id": 11, "effect_id": 2, "colors": [0x5865F2, 0xEB459E] }) } else { Value::Null },
        // Verified app flag on the demo bot.
        "public_flags": if id == BOT { 1 << 16 } else { 0 },
    })
}

fn profile(user_id: u64, guild: Option<u64>) -> Value {
    let (bio, pronouns, accent) = match user_id {
        ME => ("Trying out **RustCord** 🦀", "they/them", 0x5865F2),
        FERRIS => ("Rust's unofficial mascot. I like `cargo`, crabs and *memory safety*.", "it/its", 0xE8590C),
        CLIPPY => ("It looks like you're reading my bio. Would you like help with that? 📎", "he/him", 0xFEE75C),
        CORRO => ("unsafe { be_spiky() }", "they/them", 0xEB459E),
        BOT => ("I answer `ping`.", "", 0x57F287),
        _ => ("", "", 0x5865F2),
    };
    let roles = guild.map(|g| member_roles(user_id, g)).unwrap_or_default();
    json!({
        "user": user(user_id),
        "user_profile": { "bio": bio, "pronouns": pronouns, "accent_color": accent },
        "guild_member": guild.map(|_| json!({ "roles": roles, "joined_at": iso(now_ms() - 400 * 86_400_000) })),
        "badges": [],
        "mutual_guilds": [{ "id": G_RUST.to_string() }, { "id": G_VEN.to_string() }],
    })
}

/// Coloured roles: (Rust Lounge id, Vencord Refugees id, name, colour, position, role icon)
const ROLES: &[(u64, u64, &str, u32, i32, Option<&str>)] = &[
    (17, 25, "Crab", 0xE8590C, 4, Some("🦀")),
    (18, 26, "Paperclip", 0xFEE75C, 3, Some("📎")),
    (19, 27, "Unsafe", 0xEB459E, 2, None),
    (40, 41, "Bots", 0x57F287, 1, None),
];

fn roles_json(guild: u64) -> Value {
    let mut roles = vec![json!({ "id": guild.to_string(), "name": "@everyone", "permissions": "3072", "position": 0 })];
    for (rust, ven, name, color, pos, emoji) in ROLES {
        let id = if guild == G_RUST { rust } else { ven };
        roles.push(json!({ "id": id.to_string(), "name": name, "color": color, "position": pos, "permissions": "0", "unicode_emoji": emoji }));
    }
    Value::Array(roles)
}

fn member_roles(author: u64, guild: u64) -> Vec<String> {
    let index = match author {
        FERRIS => 0,
        CLIPPY => 1,
        CORRO => 2,
        BOT => 3,
        _ => return Vec::new(),
    };
    let (rust, ven, ..) = ROLES[index];
    vec![if guild == G_RUST { rust } else { ven }.to_string()]
}

/// Starting reactions on some scripted messages.
fn reactions_for(text: &str) -> Value {
    let r = |emoji: &str, count: u32, me: bool| json!({ "count": count, "me": me, "emoji": { "id": null, "name": emoji } });
    if text.starts_with("Welcome to **RustCord**") {
        json!([r("🦀", 5, false), r("👍", 2, true)])
    } else if text.starts_with("Markdown works") {
        json!([r("🔥", 3, false)])
    } else if text.starts_with("crab rave") {
        json!([r("🦀", 2, false), r("🎉", 1, false)])
    } else {
        json!([])
    }
}

fn reaction_event(name: &str, channel: Id, msg: Id, user: u64, emoji: &str) -> (String, Value) {
    (
        name.to_string(),
        json!({
            "user_id": user.to_string(), "channel_id": channel.to_string(), "message_id": msg.to_string(),
            "guild_id": guild_of(channel.0).map(|g| g.to_string()),
            "emoji": { "id": null, "name": emoji },
        }),
    )
}

fn guild_of(channel: u64) -> Option<u64> {
    match channel {
        11..=16 => Some(G_RUST),
        21..=24 => Some(G_VEN),
        _ => None,
    }
}

/// The sticker popout's lookups for #stickers: `/stickers/{id}`, the server
/// card `/stickers/{id}/guild` and `/sticker-packs` (shapes as Discord sends
/// them, 2026-11-23; the ids are real stickers, so the pictures load).
fn sticker_api(path: &str) -> Result<Value, String> {
    let pack = |id: &str, name: &str| json!({ "id": id, "name": name, "format_type": 3, "type": 1, "pack_id": "823972583707377686" });
    if path == "/sticker-packs" {
        return Ok(json!({ "sticker_packs": [{
            "id": "823972583707377686", "name": "Chaos Cat",
            "description": "Need to express some frustration? Anger? Want revenge? Chaos Cat can help.",
            "stickers": [pack("823973720266899506", "Mischievous"), pack("823973812748025937", "Evil"), pack("823974092700254238", "Laugh"), pack("823974203929526292", "Taunt"), pack("823974530686648440", "Screaming")],
        }] }));
    }
    let here = |id: &str, name: &str, format: u8| json!({ "id": id, "name": name, "format_type": format, "type": 2, "guild_id": G_RUST.to_string(), "available": true });
    match path {
        "/stickers/823974530686648440" => Ok(pack("823974530686648440", "Screaming")),
        "/stickers/1317593362869522502" => Ok(here("1317593362869522502", "TurtleDance", 4)),
        "/stickers/865264423663697941" => Ok(here("865264423663697941", "DogChamp", 1)),
        "/stickers/859902015018237973" => Ok(json!({ "id": "859902015018237973", "name": "CaughtIn4k", "format_type": 2, "type": 2, "guild_id": "321845546534830085", "available": true })),
        "/stickers/859902015018237973/guild" => Ok(json!({
            "id": "321845546534830085", "name": "Emoji.gg", "icon": null, "approximate_presence_count": 12345,
            "approximate_member_count": 98765, "features": ["DISCOVERABLE"],
            "stickers": [
                { "id": "859902015018237973", "name": "CaughtIn4k", "format_type": 2 },
                { "id": "1242614475618652180", "name": "Rock", "format_type": 2 },
                { "id": "1317593362869522502", "name": "TurtleDance", "format_type": 4 },
                { "id": "865264423663697941", "name": "DogChamp", "format_type": 1 },
                { "id": "875544476985212958", "name": "Love", "format_type": 1 },
            ],
        })),
        _ => Err("Unknown Sticker".into()),
    }
}

fn message(id: u64, channel: u64, author: u64, content: &str) -> Value {
    // Markers in the scripted text add an image or turn the message into a forward.
    if content.starts_with("[[video]]") {
        // A YouTube link, embedded the way Discord gets it.
        let link = "https://www.youtube.com/watch?v=dQw4w9WgXcQ";
        let mut v = message(id, channel, author, link);
        v["embeds"] = json!([{
            "type": "video", "url": link, "color": 0xFF0000,
            "provider": { "name": "YouTube", "url": "https://www.youtube.com" },
            "author": { "name": "Rick Astley", "url": "https://www.youtube.com/@RickAstleyYT" },
            "title": "Rick Astley - Never Gonna Give You Up (Official Video)",
            "description": "The official video for “Never Gonna Give You Up” by Rick Astley.",
            "thumbnail": { "url": "https://i.ytimg.com/vi/dQw4w9WgXcQ/maxresdefault.jpg", "width": 1280, "height": 720 },
            "video": { "url": "https://www.youtube.com/embed/dQw4w9WgXcQ", "width": 1280, "height": 720 },
        }]);
        return v;
    }
    // "[[sticker:id:format:name]]": a sticker message (Discord's own Lottie
    // stickers and server APNG / GIF ones animate).
    if let Some(spec) = content.strip_prefix("[[sticker:").and_then(|r| r.strip_suffix("]]")) {
        let mut parts = spec.splitn(3, ':');
        let (sid, format, name) = (parts.next().unwrap_or("0"), parts.next().unwrap_or("1"), parts.next().unwrap_or(""));
        let mut v = message(id, channel, author, "");
        v["sticker_items"] = json!([{ "id": sid, "name": name, "format_type": format.parse::<u8>().unwrap_or(1) }]);
        return v;
    }
    if let Some(which) = content.strip_prefix("[[embed:").and_then(|r| r.strip_suffix("]]")) {
        // Embeds as Discord's API delivers them, one per kind RustCord draws.
        let cdn = |n: u32| format!("https://cdn.discordapp.com/embed/avatars/{n}.png");
        let (text, embeds): (String, Value) = match which {
            // Everything a bot's rich embed can carry.
            "rich" => (String::new(), json!([{
                "type": "rich", "color": 0x57F287, "url": "https://www.rust-lang.org",
                "author": { "name": "Ferris the Crab", "url": "https://rustacean.net", "icon_url": cdn(0), "proxy_icon_url": cdn(0) },
                "title": "Release notes: **RustCord** embeds",
                "description": "A description with *markdown*, `code`, a [masked link](https://example.com), a mention <@1001> and a channel <#12>.\n> and a quote\n- a list item",
                "fields": [
                    { "name": "Inline one", "value": "first of three", "inline": true },
                    { "name": "Inline two", "value": "`second`", "inline": true },
                    { "name": "Inline three", "value": "third", "inline": true },
                    { "name": "Half", "value": "two share a row", "inline": true },
                    { "name": "Half", "value": "as halves", "inline": true },
                    { "name": "Full width", "value": "A field that isn't inline takes the whole row.", "inline": false },
                ],
                "thumbnail": { "url": cdn(1), "proxy_url": cdn(1), "width": 256, "height": 256 },
                "image": { "url": "https://rustacean.net/assets/rustacean-flat-happy.png", "width": 1200, "height": 800 },
                "footer": { "text": "Footer text", "icon_url": cdn(2), "proxy_icon_url": cdn(2) },
                "timestamp": iso(now_ms() - 3_600_000),
            }])),
            // A link preview: site name, title, description, small thumbnail.
            "link" => ("https://www.rust-lang.org/learn".into(), json!([{
                "type": "link", "url": "https://www.rust-lang.org/learn",
                "provider": { "name": "Rust Programming Language", "url": "https://www.rust-lang.org" },
                "title": "Learn Rust",
                "description": "A language empowering everyone to build reliable and efficient software.",
                "thumbnail": { "url": cdn(3), "proxy_url": cdn(3), "width": 256, "height": 256 },
            }])),
            // An article: its thumbnail is the big picture.
            "article" => ("https://github.com/rust-lang/rust".into(), json!([{
                "type": "article", "url": "https://github.com/rust-lang/rust",
                "provider": { "name": "GitHub" },
                "title": "GitHub - rust-lang/rust: Empowering everyone to build reliable and efficient software.",
                "description": "Empowering everyone to build reliable and efficient software. - rust-lang/rust",
                "thumbnail": { "url": "https://opengraph.githubassets.com/1/rust-lang/rust", "width": 1200, "height": 600 },
            }])),
            // Four embeds sharing a URL merge into one gallery (a tweet's photos).
            "gallery" => (String::new(), {
                let img = |n: u32| json!({ "url": cdn(n), "proxy_url": cdn(n), "width": 256, "height": 256 });
                json!([
                    { "type": "rich", "url": "https://twitter.com/rustlang/status/1", "color": 0x1DA1F2,
                      "author": { "name": "Rust Language (@rustlang)", "url": "https://twitter.com/rustlang", "icon_url": cdn(4), "proxy_icon_url": cdn(4) },
                      "description": "Four pictures in one post.", "image": img(0),
                      "footer": { "text": "Twitter", "icon_url": cdn(5), "proxy_icon_url": cdn(5) }, "timestamp": iso(now_ms() - 90_000_000) },
                    { "type": "rich", "url": "https://twitter.com/rustlang/status/1", "image": img(1) },
                    { "type": "rich", "url": "https://twitter.com/rustlang/status/1", "image": img(2) },
                    { "type": "rich", "url": "https://twitter.com/rustlang/status/1", "image": img(3) },
                ])
            }),
            // A link inside a spoiler hides its embed too.
            "spoiler" => ("the ending: ||https://www.rust-lang.org/learn||".into(), json!([{
                "type": "link", "url": "https://www.rust-lang.org/learn", "title": "Learn Rust",
                "description": "Hidden until you click it.",
            }])),
            "spotify" => ("https://open.spotify.com/track/4cOdK2wGLETKBW3PvgPWqT".into(), json!([{
                "type": "link", "url": "https://open.spotify.com/track/4cOdK2wGLETKBW3PvgPWqT",
                "provider": { "name": "Spotify", "url": "https://spotify.com/" },
                "title": "Never Gonna Give You Up", "description": "Rick Astley · Whenever You Need Somebody · Song · 1987",
                "thumbnail": { "url": "https://i.scdn.co/image/ab67616d0000b27315ebbedaacef61af53e4d38b", "width": 640, "height": 640 },
            }])),
            "soundcloud" => ("https://soundcloud.com/forss/flickermood".into(), json!([{
                "type": "video", "url": "https://soundcloud.com/forss/flickermood", "color": 0xFF5500,
                "provider": { "name": "SoundCloud", "url": "https://soundcloud.com/" },
                "author": { "name": "Forss", "url": "https://soundcloud.com/forss" },
                "title": "Flickermood", "description": "From the Soulhack album",
                "thumbnail": { "url": "https://i1.sndcdn.com/artworks-000067273316-smsiqx-t500x500.jpg", "width": 500, "height": 500 },
                "video": { "url": "https://w.soundcloud.com/player/?url=https%3A%2F%2Fapi.soundcloud.com%2Ftracks%2F293&auto_play=false&show_artwork=true&visual=true&origin=twitter", "width": 435, "height": 400 },
            }])),
            "vimeo" => ("https://vimeo.com/76979871".into(), json!([{
                "type": "video", "url": "https://vimeo.com/76979871", "color": 0x1AB7EA,
                "provider": { "name": "Vimeo", "url": "https://vimeo.com/" },
                "author": { "name": "Vimeo Staff", "url": "https://vimeo.com/staff" },
                "title": "The New Vimeo Player (You Know, For Videos)",
                "thumbnail": { "url": "https://i.vimeocdn.com/video/452001751-8216e0571c251a09d7a8387550942d89f7f86f6398f8ed886e639b0dd50d3c90-d_1280", "width": 1280, "height": 720 },
                "video": { "url": "https://player.vimeo.com/video/76979871?app_id=122963", "width": 1280, "height": 720 },
            }])),
            // A link straight to a video file: Discord proxies it and plays it itself.
            "mp4" => ("https://interactive-examples.mdn.mozilla.net/media/cc0-videos/flower.mp4".into(), json!([{
                "type": "video", "url": "https://interactive-examples.mdn.mozilla.net/media/cc0-videos/flower.mp4",
                "video": { "url": "https://interactive-examples.mdn.mozilla.net/media/cc0-videos/flower.mp4",
                           "proxy_url": "https://interactive-examples.mdn.mozilla.net/media/cc0-videos/flower.mp4", "width": 960, "height": 540 },
                "thumbnail": { "url": "https://interactive-examples.mdn.mozilla.net/media/cc0-videos/flower.jpg", "width": 960, "height": 540 },
            }])),
            _ => (String::new(), json!([])),
        };
        let mut v = message(id, channel, author, &text);
        v["embeds"] = embeds;
        if which == "rich" {
            v["reactions"] = json!([
                { "count": 2, "me": true, "emoji": { "id": null, "name": "👍" } },
                { "count": 7, "me": false, "emoji": { "id": null, "name": "🎉" } },
            ]);
        }
        return v;
    }
    if content.starts_with("[[attvideo]]") {
        let mut v = message(id, channel, author, "a video attachment, and a spoilered picture");
        v["attachments"] = json!([
            { "id": "901", "filename": "flower.mp4", "size": 1_113_000,
              "url": "https://interactive-examples.mdn.mozilla.net/media/cc0-videos/flower.mp4",
              "proxy_url": "https://interactive-examples.mdn.mozilla.net/media/cc0-videos/flower.jpg",
              "content_type": "video/mp4", "width": 960, "height": 540 },
            { "id": "902", "filename": "SPOILER_rustacean.png", "size": 46286,
              "url": "https://rustacean.net/assets/rustacean-flat-happy.png",
              "proxy_url": "https://rustacean.net/assets/rustacean-flat-happy.png",
              "content_type": "image/png", "width": 1200, "height": 800 },
        ]);
        return v;
    }
    if content.starts_with("[[token]]") {
        // A bot "token card" like the ones crypto-call servers post: author
        // with icon, code chips and emoji, footer, and a row of buttons.
        let mut v = message(id, channel, author, "");
        let refreshed = now_ms() / 1000 - 100_000;
        let desc = format!("🟣 Solana @ 🐋 Orca *(WP)*\n\n**Token Stats:**\n💰 **USD:** `$1.47`\n🧢 **MC:** `$89.55M` ➡ `$210.77M` `[29d ATH]`\n🫗 **LIQ:** `$630.49K` `[0.97× 1H]` · 😐\n📊 **VOL:** `$285.27K` · Age: `[1034d]` 🙂\n📉 **1H:** `$8.98K` · `[-1.0%]` 🅱️ `101` 🆂 `37` 😐\n\n**Extra Stats:**\n👥 **TH:** `50.59%`\n🛡️ **AUDIT:** Mint ❔ · Freeze ✅\n🔗 **LINKS:** [Website](https://example.com) · [X](https://x.com)\n\n🔄 **REFRESHED:** <t:{refreshed}:R>\n\n📌 **TIP:** [**Trade on Example!**](https://example.com)");
        v["embeds"] = json!([{
            "type": "rich", "color": 0x5865F2,
            "author": { "name": "⬅️ TOKEN IMAGE", "icon_url": "https://cdn.discordapp.com/embed/avatars/2.png" },
            "title": "$ORCA [$89.55M / -1.0%]",
            "description": desc,
            "footer": { "text": "©2026 Example Tokens. Not financial advice.", "icon_url": "https://cdn.discordapp.com/embed/avatars/1.png" },
        }]);
        v["components"] = json!([{ "type": 1, "components": [
            { "type": 2, "style": 2, "custom_id": "close", "emoji": { "name": "❌" } },
            { "type": 2, "style": 2, "custom_id": "copy", "label": "Copy CA", "emoji": { "name": "📋" } },
            { "type": 2, "style": 1, "custom_id": "refresh", "label": "Refresh", "emoji": { "name": "🔄" } },
            { "type": 2, "style": 2, "custom_id": "img", "label": "Token Img", "emoji": { "name": "🖼️" } }
        ] }]);
        return v;
    }
    if content.starts_with("[[gifv]]") {
        // A GIF link, as Discord embeds it: a looping MP4 clip ("gifv").
        let link = "https://giphy.com/gifs/xT9IgG50Fb7Mi0prBC";
        let mut v = message(id, channel, author, link);
        v["embeds"] = json!([{
            "type": "gifv", "url": link, "provider": { "name": "GIPHY" },
            "thumbnail": { "url": "https://media.giphy.com/media/xT9IgG50Fb7Mi0prBC/giphy_s.gif", "width": 480, "height": 270 },
            "video": { "url": "https://media.giphy.com/media/xT9IgG50Fb7Mi0prBC/giphy.mp4", "width": 480, "height": 270 },
        }]);
        return v;
    }
    if let Some(gid) = content.strip_prefix("[[gifv:").and_then(|r| r.strip_suffix("]]")) {
        // Any Giphy clip by id (the #gifs channel).
        let link = format!("https://giphy.com/gifs/{gid}");
        let mut v = message(id, channel, author, &link);
        v["embeds"] = json!([{
            "type": "gifv", "url": link, "provider": { "name": "GIPHY" },
            "thumbnail": { "url": format!("https://media.giphy.com/media/{gid}/giphy_s.gif"), "width": 480, "height": 270 },
            "video": { "url": format!("https://media.giphy.com/media/{gid}/giphy.mp4"), "width": 480, "height": 270 },
        }]);
        return v;
    }
    if let Some(gid) = content.strip_prefix("[[gif:").and_then(|r| r.strip_suffix("]]")) {
        // A GIF file, as an attachment.
        let url = format!("https://media.giphy.com/media/{gid}/giphy.gif");
        let mut v = message(id, channel, author, "");
        v["attachments"] = json!([{
            "id": "901", "filename": format!("{gid}.gif"), "size": 1_800_000,
            "url": url, "proxy_url": url, "content_type": "image/gif", "width": 480, "height": 270,
        }]);
        return v;
    }
    if let Some(rest) = content.strip_prefix("[[img]]") {
        let mut v = message(id, channel, author, rest.trim());
        v["attachments"] = json!([{
            "id": "900", "filename": "rustacean-flat-happy.png", "size": 46286,
            "url": "https://rustacean.net/assets/rustacean-flat-happy.png",
            "proxy_url": "https://rustacean.net/assets/rustacean-flat-happy.png",
            "content_type": "image/png", "width": 1200, "height": 800,
        }]);
        return v;
    }
    if let Some(rest) = content.strip_prefix("[[fwd]]") {
        let mut v = message(id, channel, author, "");
        v["message_reference"] = json!({ "type": 1, "channel_id": C_GENERAL.to_string(), "guild_id": G_RUST.to_string(), "message_id": "1" });
        v["message_snapshots"] = json!([{ "message": { "content": rest.trim(), "timestamp": iso(now_ms() - 3_600_000), "attachments": [] } }]);
        return v;
    }
    let guild = guild_of(channel);
    json!({
        "id": id.to_string(),
        "channel_id": channel.to_string(),
        "guild_id": guild.map(|g| g.to_string()),
        "author": user(author),
        "member": guild.map(|g| json!({ "roles": member_roles(author, g) })),
        "content": content,
        "timestamp": iso(Id(id).timestamp_ms()),
        "edited_timestamp": null,
        "attachments": [],
        "embeds": [],
        "mentions": [],
        "reactions": reactions_for(content),
        "type": 0,
    })
}

fn chan(id: u64, kind: u8, name: &str, parent: Option<u64>, position: i32) -> Value {
    // A couple of channels start with unread messages.
    let last = matches!(id, C_RENCORD | C_VEN_CHAT).then(|| Id::from_timestamp_ms(now_ms() - 60_000).0.to_string());
    json!({
        "id": id.to_string(), "type": kind, "name": name, "position": position,
        "parent_id": parent.map(|p| p.to_string()), "permission_overwrites": [],
        "last_message_id": last,
    })
}

fn ready() -> Value {
    let mut mod_only = chan(C_MOD_ONLY, 0, "mod-only", Some(C_VEN_CAT), 3);
    // @everyone is denied VIEW_CHANNEL here, so RustCord's permission
    // calculation hides it like the official client would.
    mod_only["permission_overwrites"] = json!([{ "id": G_VEN.to_string(), "type": 0, "allow": "0", "deny": "1024" }]);

    json!({
        "v": 9,
        "user": user(ME),
        "session_id": "demo",
        "guilds": [
            {
                "id": G_RUST.to_string(), "name": "Rust Lounge", "icon": null, "owner_id": ME.to_string(),
                "roles": roles_json(G_RUST),
                "voice_states": [{ "user_id": CLIPPY.to_string(), "channel_id": C_HANGOUT.to_string() }],
                "channels": [
                    chan(C_RUST_TEXT, 4, "Text Channels", None, 0),
                    chan(C_GENERAL, 0, "general", Some(C_RUST_TEXT), 0),
                    chan(C_RENCORD, 0, "rencord-dev", Some(C_RUST_TEXT), 1),
                    chan(C_LINKS, 0, "🔗・links", Some(C_RUST_TEXT), 2),
                    chan(C_GIFS, 0, "gifs", Some(C_RUST_TEXT), 3),
                    chan(C_STICKERS, 0, "stickers", Some(C_RUST_TEXT), 4),
                    chan(C_RUST_VOICE_CAT, 4, "Voice Channels", None, 1),
                    chan(C_HANGOUT, 2, "Hangout", Some(C_RUST_VOICE_CAT), 0),
                ],
            },
            {
                "id": G_VEN.to_string(), "name": "Vencord Refugees", "icon": null, "owner_id": FERRIS.to_string(),
                "roles": roles_json(G_VEN),
                "channels": [
                    chan(C_VEN_CAT, 4, "Chat", None, 0),
                    chan(C_VEN_CHAT, 0, "chat", Some(C_VEN_CAT), 0),
                    chan(C_THEMES, 0, "themes", Some(C_VEN_CAT), 1),
                    mod_only,
                ],
            },
        ],
        "private_channels": [
            { "id": DM_FERRIS.to_string(), "type": 1, "recipients": [user(FERRIS)], "last_message_id": Id::from_timestamp_ms(now_ms() - 60_000).0.to_string() },
            { "id": DM_GROUP.to_string(), "type": 3, "name": "crab rave planning", "recipients": [user(FERRIS), user(CORRO)],
              "last_message_id": Id::from_timestamp_ms(now_ms() - 120_000).0.to_string() },
            { "id": DM_CLIPPY.to_string(), "type": 1, "recipients": [user(CLIPPY)], "last_message_id": Id::from_timestamp_ms(now_ms() - 600_000).0.to_string() },
            { "id": DM_SYSTEM.to_string(), "type": 1, "recipients": [user(SYSTEM)], "last_message_id": Id::from_timestamp_ms(now_ms() - 86_400_000).0.to_string() },
            // A message request (someone you don't share a server with).
            { "id": DM_REQUEST.to_string(), "type": 1, "recipients": [user(CORRO)], "is_message_request": true,
              "last_message_id": Id::from_timestamp_ms(now_ms() - 300_000).0.to_string() },
        ],
        "merged_members": [
            [{ "user_id": ME.to_string(), "roles": [] }],
            [{ "user_id": ME.to_string(), "roles": [] }],
        ],
        "user_settings": {},
        // Unread channels and mention badges.
        "read_state": [
            { "id": C_RENCORD.to_string(), "last_message_id": "1", "mention_count": 2 },
            { "id": DM_GROUP.to_string(), "last_message_id": "1", "mention_count": 1 },
        ],
        "presences": [
            { "user": { "id": FERRIS.to_string() }, "status": "online", "activities": [
                { "type": 4, "name": "Custom Status", "state": "rewriting it in Rust", "emoji": { "name": "🦀" } } ] },
            { "user": { "id": CLIPPY.to_string() }, "status": "idle", "activities": [
                { "type": 0, "name": "Visual Studio Code" }, { "type": 2, "name": "Spotify" } ] },
            { "user": { "id": CORRO.to_string() }, "status": "dnd", "activities": [] },
        ],
        "relationships": [
            { "id": FERRIS.to_string(), "type": 1, "user": user(FERRIS) },
            { "id": CLIPPY.to_string(), "type": 1, "user": user(CLIPPY) },
            { "id": CORRO.to_string(), "type": 3, "user": user(CORRO) },
        ],
        "sessions": [{ "session_id": "all", "status": "online" }],
    })
}

/// The member list Discord would stream for a server (grouped by hoisted role).
fn member_list(guild: u64) -> Value {
    let presence = |id: u64, status: &str, activities: Value| json!({ "user": { "id": id.to_string() }, "status": status, "activities": activities });
    let member = |id: u64, status: &str, activities: Value| json!({ "member": {
        "user": user(id), "roles": member_roles(id, guild), "presence": presence(id, status, activities),
        // Clippy boosts the server (the gem after the name).
        "premium_since": if id == CLIPPY { json!("2026-03-04T18:00:00+00:00") } else { Value::Null },
    } });
    let group = |id: String, count: u32| json!({ "group": { "id": id, "count": count } });
    let role = |i: usize| (if guild == G_RUST { ROLES[i].0 } else { ROLES[i].1 }).to_string();
    let items = json!([
        group(role(0), 1),
        member(FERRIS, "online", json!([{ "type": 4, "name": "Custom Status", "state": "rewriting it in Rust", "emoji": { "name": "🦀" } }])),
        group(role(1), 1),
        member(CLIPPY, "idle", json!([{ "type": 0, "name": "Visual Studio Code" }, { "type": 2, "name": "Spotify" }])),
        group(role(2), 1),
        member(CORRO, "dnd", json!([])),
        group(role(3), 1),
        member(BOT, "online", json!([{ "type": 0, "name": "with crabs" }])),
        group("online".into(), 1),
        member(ME, "online", json!([{ "type": 4, "name": "Custom Status", "state": "rewriting it in Rust", "emoji": { "name": "🦀" } }])),
    ]);
    json!({
        "guild_id": guild.to_string(), "id": "everyone", "member_count": 5, "online_count": 5,
        "ops": [{ "op": "SYNC", "range": [0, 99], "items": items }],
    })
}

fn demo_settings() -> discord::settings_proto::UserSettings {
    use discord::settings_proto::{CustomStatus, Favorite, Folder, UserSettings};
    let mut s = UserSettings::new(
        vec![Folder {
            id: Some(1),
            name: Some("Rust Stuff".into()),
            color: Some(0xE8590C),
            guild_ids: vec![Id(G_RUST), Id(G_VEN)],
        }],
        "online",
        Some(CustomStatus { text: "rewriting it in Rust".into(), emoji_name: Some("🦀".into()), ..Default::default() }),
    );
    // A pinned DM, two favourite channels and a Favourites category.
    let fav = |id: u64, nickname: Option<&str>, category: bool, position: u32, parent: Option<u64>| Favorite {
        id: Id(id),
        nickname: nickname.map(String::from),
        category,
        position,
        parent_id: parent.map(Id),
        collapsed: false,
    };
    s.favorites.channels = vec![
        fav(DM_CLIPPY, None, false, 0, None),
        fav(C_GENERAL, Some("💬・talking"), false, 1, None),
        fav(900, Some("Channels"), true, 2, None),
        fav(C_THEMES, None, false, 3, Some(900)),
    ];
    s
}

/// Scripted history per channel, oldest → newest.
fn script(channel: u64) -> &'static [(u64, &'static str)] {
    match channel {
        C_GENERAL => &[
            (FERRIS, "Welcome to **RustCord** 🦀 a native Discord client written in Rust. No Electron, no web runtime."),
            (CLIPPY, "It looks like you're trying to chat. Would you like help with that?"),
            (CORRO, "**Rencord** is RustCord's built-in mod system, RustCord's own take on Vencord. Open ⚙️ → *Rencord Plugins* to toggle things."),
            (FERRIS, "Markdown works: *italics*, __underline__, ~~strike~~, `inline code`, ||spoilers (click me)|| and [masked links](https://www.rust-lang.org)."),
            (CLIPPY, "```rust\nfn main() {\n    println!(\"Hello from RustCord!\");\n}\n```"),
            (CORRO, "> quotes render too\n- and so do\n- bullet lists\n-# and subtext"),
            (FERRIS, "Try sending a link like https://example.com/page?id=42&utm_source=newsletter&fbclid=IwAR0abc and **ClearURLs** strips the trackers before it's sent."),
            (CLIPPY, "Keep watching this channel: people here edit and delete messages a lot. **MessageLogger** keeps them visible 👀"),
            (FERRIS, "[[img]] new profile picture, thoughts?"),
            (CORRO, "Click anyone's name or avatar for their profile. Right-click a message for the full menu."),
            (BOT, "Say `ping` and I'll answer."),
            (CLIPPY, "[[gifv]]"),
            (BOT, "[[token]]"),
            (CORRO, "[[sticker:823974530686648440:3:Screaming]]"),
        ],
        C_RENCORD => &[
            (CORRO, "# Writing a Rencord plugin"),
            (CORRO, "Implement the `Plugin` trait. Hooks: `before_send`, `before_edit`, `message_create`, `message_update`, `message_delete`, `typing`, `message_actions`."),
            (FERRIS, "Settings are declarative (`SettingDef::bool`, `::text`, `::select`) and RustCord renders the UI for you, like Vencord's `definePluginSettings`."),
            (CLIPPY, "A plugin that panics gets disabled instead of crashing the client."),
            (FERRIS, "[[fwd]] Welcome to **RustCord** 🦀 a native Discord client written in Rust."),
        ],
        C_LINKS => &[
            (FERRIS, "https://www.rust-lang.org"),
            (BOT, "[[embed:rich]]"),
            (CORRO, "Mentions: <@1001> <@1002> <#12> <#13> @everyone and ||a spoiler that is long enough to show its rounded corners|| plus <t:1700000000:R>"),
            (FERRIS, "[[embed:link]]"),
            (CLIPPY, "[[embed:article]]"),
            (BOT, "[[embed:gallery]]"),
            (CORRO, "[[embed:spoiler]]"),
            (FERRIS, "[[video]]"),
            (CLIPPY, "[[embed:vimeo]]"),
            (CORRO, "[[embed:soundcloud]]"),
            (FERRIS, "[[embed:spotify]]"),
            (CLIPPY, "[[embed:mp4]]"),
            (CORRO, "[[attvideo]]"),
            (CLIPPY, "<https://github.com/Vendicated/Vencord> (Vencord, the inspiration)"),
            (CORRO, "egui: https://github.com/emilk/egui"),
        ],
        C_GIFS => &[
            (FERRIS, "[[gifv:xT9IgG50Fb7Mi0prBC]]"),
            (CLIPPY, "[[gifv:JIX9t2j0ZTN9S]]"),
            (CORRO, "[[gif:13CoXDiaCcCoyk]]"),
            (FERRIS, "[[gifv:3oEjI6SIIHBdRxXI40]]"),
            (CLIPPY, "[[gifv:l0MYt5jPR6QX5pnqM]]"),
            (CORRO, "[[gif:mlvseq9yvZhba]]"),
            (FERRIS, "[[gifv:26ufdipQqU2lhNA4g]]"),
            (CLIPPY, "[[gifv:3o7abKhOpu0NwenH3O]]"),
            (CORRO, "[[gif:11sBLVxNs7v6WA]]"),
            (FERRIS, "[[gifv:3oriO0OEd9QIDdllqo]]"),
            (CLIPPY, "[[gif:JIX9t2j0ZTN9S]]"),
            (CORRO, "[[gifv:13CoXDiaCcCoyk]]"),
        ],
        // One sticker of each kind (PNG and GIF from this server, APNG from a
        // public server you're not in, Lottie from a Discord pack), the
        // animated ones last so they're in view.
        C_STICKERS => &[
            (CORRO, "[[sticker:865264423663697941:1:DogChamp]]"),
            (FERRIS, "[[sticker:859902015018237973:2:CaughtIn4k]]"),
            (CLIPPY, "[[sticker:1317593362869522502:4:TurtleDance]]"),
            (CORRO, "[[sticker:823974530686648440:3:Screaming]]"),
        ],
        C_VEN_CHAT => &[
            (FERRIS, "Coming from Vencord? Your favourite plugins can be ported to Rencord."),
            (CORRO, "So far: **MessageLogger** and **ClearURLs**."),
        ],
        C_THEMES => &[
            (CLIPPY, "Themes: ⚙ → **Themes**, then paste a Vencord/BetterDiscord theme URL."),
            (CLIPPY, "RustCord can't run CSS, but it translates the theme's color variables (`--background-primary`, `--text-normal`, `--brand-experiment`, …) into native colors."),
            (FERRIS, "QuickCSS works the same way: `:root { --brand-experiment: #e8590c; }`"),
        ],
        DM_FERRIS => &[
            (FERRIS, "hey! this is a DM. In demo mode everything is simulated locally 🦀"),
        ],
        DM_GROUP => &[
            (CORRO, "crab rave at 8?"),
            (FERRIS, "🦀🦀🦀"),
        ],
        DM_CLIPPY => &[
            (CLIPPY, "It looks like you're writing a Discord client. Need a hand?"),
            (CLIPPY, "[[video]]"),
        ],
        DM_REQUEST => &[
            (CORRO, "hey, saw your crate on crates.io, got a minute?"),
        ],
        DM_SYSTEM => &[
            (SYSTEM, "**Welcome to Discord!** This is where official notifications about your account show up."),
        ],
        _ => &[],
    }
}

const FILLER: &[(u64, &str)] = &[
    (FERRIS, "anyone tried the new borrow checker diagnostics?"),
    (CORRO, "unsafe { fun() }"),
    (CLIPPY, "`clone()` on a Copy type? I'll allow it this time."),
    (FERRIS, "fearless concurrency, fearful deadlines"),
    (CORRO, "cargo build --release and go make a coffee"),
    (CLIPPY, "have you considered adding more lifetimes"),
];

const MESSAGE_GAP_MS: u64 = 170_000;
const PAGE: u64 = 50;

/// A newest-first page of fake history, ending before `before`.
fn history(channel: u64, before: Option<u64>) -> Vec<Value> {
    let now = now_ms();
    let end = before.map(|b| Id(b).timestamp_ms()).unwrap_or(now - 30_000);
    let depth = (now.saturating_sub(end)) / (PAGE * MESSAGE_GAP_MS);
    if depth >= 3 {
        return Vec::new();
    }
    let lines = script(channel);
    if lines.is_empty() {
        return Vec::new();
    }
    let count = if channel == C_GENERAL || before.is_some() { PAGE } else { lines.len() as u64 };
    // Scripted lines are minutes apart; older filler is hours apart so the
    // history spans several days (and date dividers show up).
    let scripted = if before.is_none() { lines.len() as u64 } else { 0 };
    (0..count)
        .map(|k| {
            let ts = if k < scripted {
                end - (k + 1) * MESSAGE_GAP_MS
            } else {
                end - scripted * MESSAGE_GAP_MS - (k + 1 - scripted) * 5 * 3_600_000
            };
            let id = Id::from_timestamp_ms(ts).0 + k;
            let (author, text) = if before.is_none() && (k as usize) < lines.len() {
                lines[lines.len() - 1 - k as usize]
            } else {
                FILLER[(k as usize + depth as usize) % FILLER.len()]
            };
            message(id, channel, author, text)
        })
        .collect()
}

fn dispatch(em: &Emitter, name: &str, data: Value) {
    em.emit(Event::Gateway(GatewayEvent::Dispatch { name: name.into(), data }));
}

enum Then {
    Nothing,
    Edit(&'static str),
    Delete,
}

/// What the fake server remembers: every message it produced (so replies and
/// forwards can include the original, like Discord does) and uploaded files.
#[derive(Default)]
struct DemoState {
    messages: std::sync::Mutex<std::collections::HashMap<u64, Value>>,
    files: std::sync::Mutex<std::collections::HashMap<String, Vec<u8>>>,
    /// Each channel's pins, newest first (filled on first use).
    pins: std::sync::Mutex<std::collections::HashMap<u64, Vec<Value>>>,
}

impl DemoState {
    fn remember(&self, v: &Value) {
        if let Some(id) = Id::from_value(&v["id"]) {
            if let Ok(mut m) = self.messages.lock() {
                m.insert(id.0, v.clone());
            }
        }
    }

    fn get(&self, id: Id) -> Option<Value> {
        self.messages.lock().ok()?.get(&id.0).cloned()
    }

    /// The channel's pins after pinning / unpinning `change` (None: just
    /// list them). Until you change them, the first two scripted messages
    /// of the channel are "pinned".
    fn pins(&self, channel: Id, change: Option<(Id, bool)>) -> Vec<Value> {
        let Ok(mut all) = self.pins.lock() else { return Vec::new() };
        let list = all.entry(channel.0).or_insert_with(|| {
            let mut first: Vec<Value> = history(channel.0, None).into_iter().rev().take(2).collect();
            first.iter_mut().for_each(|v| v["pinned"] = json!(true));
            first
        });
        if let Some((msg, pinned)) = change {
            list.retain(|v| Id::from_value(&v["id"]) != Some(msg));
            if let Some(mut v) = self.get(msg).filter(|_| pinned) {
                v["pinned"] = json!(true);
                list.insert(0, v);
            }
        }
        list.clone()
    }
}

/// Background chatter in #general that exercises MessageLogger.
async fn live_script(em: Emitter, ids: Arc<IdGen>, state: Arc<DemoState>) {
    let lines: &[(u64, &str, Then)] = &[
        (FERRIS, "just shipped a release build, it idles at 60 MB of RAM 📉", Then::Edit("just shipped a release build, it idles at 45 MB of RAM 📉 (measured properly this time)")),
        (CORRO, "i'm going to delete this message before anyone sees it", Then::Delete),
        (CLIPPY, "fun fact: egui redraws only when something changes", Then::Nothing),
        (FERRIS, "teh borrow checker is my friend", Then::Edit("the borrow checker is my friend")),
        (CORRO, "transmute go brrr", Then::Delete),
        (CLIPPY, "remember to run `cargo clippy` 📎", Then::Nothing),
    ];
    let mut i = 0usize;
    loop {
        sleep(Duration::from_secs(8)).await;
        let (author, text, then) = &lines[i % lines.len()];
        i += 1;
        dispatch(&em, "TYPING_START", json!({ "channel_id": C_GENERAL.to_string(), "user_id": author.to_string() }));
        sleep(Duration::from_secs(2)).await;
        let id = ids.next();
        let v = message(id, C_GENERAL, *author, text);
        state.remember(&v);
        dispatch(&em, "MESSAGE_CREATE", v);
        sleep(Duration::from_secs(5)).await;
        match then {
            Then::Nothing => {}
            Then::Edit(new) => dispatch(&em, "MESSAGE_UPDATE", json!({
                "id": id.to_string(), "channel_id": C_GENERAL.to_string(), "guild_id": G_RUST.to_string(),
                "content": new, "edited_timestamp": iso(now_ms()),
            })),
            Then::Delete => dispatch(&em, "MESSAGE_DELETE", json!({
                "id": id.to_string(), "channel_id": C_GENERAL.to_string(), "guild_id": G_RUST.to_string(),
            })),
        }
    }
}

pub async fn run(mut rx: UnboundedReceiver<Command>, em: Emitter) {
    let ids = Arc::new(IdGen(AtomicU64::new(0)));
    let state = Arc::new(DemoState::default());
    let client = reqwest::Client::new();
    let mut started = false;
    // "Show that I use RustCord", as the pretend registry last heard it.
    let mut registry_share = true;

    while let Some(cmd) = rx.recv().await {
        match cmd {
            Command::Login { .. } => {
                em.emit(Event::Gateway(GatewayEvent::Connecting));
                sleep(Duration::from_millis(300)).await;
                em.emit(Event::Settings(demo_settings()));
                em.emit(Event::Gateway(GatewayEvent::Connected));
                dispatch(&em, "READY", ready());
                if !started {
                    started = true;
                    tokio::spawn(live_script(em.clone(), ids.clone(), state.clone()));
                }
            }
            Command::FetchMessages { channel, before } => {
                let (em, state) = (em.clone(), state.clone());
                // (Dev aid: RUSTCORD_DEMO_HISTORY_MS slows older pages down, to
                // watch the stand-in messages while they load.)
                let wait = if before.is_some() { crate::diagnostics::dev_var("RUSTCORD_DEMO_HISTORY_MS").ok().and_then(|v| v.parse().ok()).unwrap_or(150) } else { 150 };
                tokio::spawn(async move {
                    sleep(Duration::from_millis(wait)).await;
                    let page = history(channel.0, before.map(|b| b.0));
                    page.iter().for_each(|v| state.remember(v));
                    let msgs: Vec<Message> = page.iter().filter_map(|v| Message::deserialize(v).ok()).collect();
                    em.emit(Event::Messages { channel, before, result: Ok(msgs) });
                });
            }
            Command::FetchBytes(url) => {
                let result = state
                    .files
                    .lock()
                    .ok()
                    .and_then(|f| f.get(&url).cloned())
                    .map(Arc::<[u8]>::from)
                    .ok_or_else(|| "file not found".to_string());
                em.emit(Event::Bytes { url, result });
            }
            Command::Send(out) => {
                let (em, ids, state) = (em.clone(), ids.clone(), state.clone());
                tokio::spawn(async move {
                    sleep(Duration::from_millis(120)).await;
                    let id = ids.next();
                    let mut v = message(id, out.channel_id.0, ME, &out.content);
                    v["nonce"] = json!(out.nonce);
                    // Like Discord: replies carry the original, forwards carry a snapshot.
                    if let Some(r) = &out.message_reference {
                        let source = state.get(r.message_id);
                        v["message_reference"] = json!({
                            "type": r.kind, "message_id": r.message_id.to_string(),
                            "channel_id": r.channel_id.to_string(), "guild_id": r.guild_id.map(|g| g.to_string()),
                        });
                        match (r.kind, source) {
                            (0, Some(src)) => {
                                v["type"] = json!(19);
                                v["referenced_message"] = src;
                            }
                            (0, None) => v["type"] = json!(19),
                            (_, Some(src)) => {
                                v["message_snapshots"] = json!([{ "message": {
                                    "content": src["content"], "attachments": src["attachments"],
                                    "embeds": src["embeds"], "timestamp": src["timestamp"],
                                } }]);
                            }
                            (_, None) => {}
                        }
                    }
                    // Serve uploaded files back from memory so they show up in the demo.
                    let attachments: Vec<Value> = out
                        .uploads
                        .iter()
                        .enumerate()
                        .map(|(i, u)| {
                            let uri = format!("bytes://demo-upload/{}/{}", out.nonce, u.filename);
                            let bytes: Vec<u8> = u.read_all().map(|b| b.to_vec()).unwrap_or_default();
                            if let Some(ctx) = em.ctx() {
                                ctx.include_bytes(uri.clone(), bytes.clone());
                            }
                            if let Ok(mut f) = state.files.lock() {
                                f.insert(uri.clone(), bytes.clone());
                            }
                            let dims = image::ImageReader::new(std::io::Cursor::new(&bytes))
                                .with_guessed_format()
                                .ok()
                                .and_then(|r| r.into_dimensions().ok());
                            json!({
                                "id": i.to_string(), "filename": u.filename, "size": bytes.len(),
                                "url": uri, "proxy_url": uri,
                                "content_type": dims.map(|_| "image/png"),
                                "width": dims.map(|d| d.0), "height": dims.map(|d| d.1),
                            })
                        })
                        .collect();
                    v["attachments"] = Value::Array(attachments);
                    state.remember(&v);
                    dispatch(&em, "MESSAGE_CREATE", v);
                    sleep(Duration::from_millis(1500)).await;
                    let (name, data) = reaction_event("MESSAGE_REACTION_ADD", out.channel_id, Id(id), FERRIS, "🦀");
                    dispatch(&em, &name, data);
                    if out.content.to_lowercase().contains("ping") {
                        dispatch(&em, "TYPING_START", json!({ "channel_id": out.channel_id.to_string(), "user_id": BOT.to_string() }));
                        sleep(Duration::from_millis(900)).await;
                        let mut reply = message(ids.next(), out.channel_id.0, BOT, "pong! 🏓");
                        reply["referenced_message"] = message(id, out.channel_id.0, ME, &out.content);
                        reply["type"] = json!(19);
                        dispatch(&em, "MESSAGE_CREATE", reply);
                    }
                });
            }
            Command::Edit { channel, id, content } => dispatch(&em, "MESSAGE_UPDATE", json!({
                "id": id.to_string(), "channel_id": channel.to_string(),
                "guild_id": guild_of(channel.0).map(|g| g.to_string()),
                "content": content, "edited_timestamp": iso(now_ms()),
            })),
            Command::Delete { channel, id } => dispatch(&em, "MESSAGE_DELETE", json!({
                "id": id.to_string(), "channel_id": channel.to_string(),
            })),
            Command::React { channel, msg, emoji, add } => {
                let event = if add { "MESSAGE_REACTION_ADD" } else { "MESSAGE_REACTION_REMOVE" };
                let (name, mut data) = reaction_event(event, channel, msg, ME, "");
                data["emoji"] = serde_json::to_value(&emoji).unwrap_or_default();
                dispatch(&em, &name, data);
            }
            Command::Pin { channel, msg, pinned } => {
                state.pins(channel, Some((msg, pinned)));
                dispatch(&em, "MESSAGE_UPDATE", json!({
                    "id": msg.to_string(), "channel_id": channel.to_string(), "pinned": pinned,
                }));
                dispatch(&em, "CHANNEL_PINS_UPDATE", json!({ "channel_id": channel.to_string(), "last_pin_timestamp": iso(now_ms()) }));
            }
            Command::FetchProfile { user, guild } => {
                let em = em.clone();
                tokio::spawn(async move {
                    sleep(Duration::from_millis(200)).await;
                    let result = discord::model::UserProfile::deserialize(&profile(user.0, guild.map(|g| g.0)))
                        .map_err(|e| e.to_string());
                    em.emit(Event::Profile { user, guild, result });
                });
            }
            Command::OpenDm(user) => {
                let id = 3000 + user.0;
                em.emit(Event::DmOpened(json!({ "id": id.to_string(), "type": 1, "recipients": [crate::demo::user(user.0)] })));
            }
            Command::FetchTheme(url) => spawn_theme_fetch(client.clone(), url, em.clone()),
            Command::SubscribeMembers { guild, .. } => {
                dispatch(&em, "GUILD_MEMBER_LIST_UPDATE", member_list(guild.0));
            }
            Command::FetchPins(channel) => {
                let pinned: Vec<Message> = state.pins(channel, None).iter().filter_map(|v| Message::deserialize(v).ok()).collect();
                em.emit(Event::Pins { channel, result: Ok(pinned) });
            }
            Command::Search { query, filters, .. } => {
                // The words and who wrote it; the other filters aren't modelled.
                let q = filters.content.to_lowercase();
                let mut hits: Vec<Message> = state
                    .messages
                    .lock()
                    .map(|m| m.values().filter(|v| v["content"].as_str().is_some_and(|c| c.to_lowercase().contains(&q))).cloned().collect::<Vec<_>>())
                    .unwrap_or_default()
                    .iter()
                    .filter_map(|v| Message::deserialize(v).ok())
                    .filter(|m| filters.author_id.is_empty() || filters.author_id.contains(&m.author.id))
                    .collect();
                hits.sort_by_key(|m| std::cmp::Reverse(m.id));
                hits.truncate(25);
                em.emit(Event::Search { query, result: Ok((hits.len() as u64, hits)) });
            }
            Command::RequestMembers { .. } | Command::SearchMembers { .. } => {}
            Command::StreamCreate { .. } | Command::StreamWatch(_) | Command::StreamDelete(_) | Command::StreamSetPaused { .. } => {}
            Command::GoLiveConnect { .. } | Command::WatchConnect { .. } => {}
            Command::MemberRole { .. }
            | Command::EditChannel { .. }
            | Command::DeleteChannel(_)
            | Command::CreateChannel { .. }
            | Command::GuildSettings { .. }
            | Command::LeaveGuild(_) => {
                em.emit(Event::Info("Demo mode: nothing is changed on Discord.".into()));
            }
            Command::LeaveGroup { channel, .. } => {
                dispatch(&em, "CHANNEL_DELETE", json!({ "id": channel.to_string(), "type": 3 }));
            }
            // A made-up player, so the controller can be tried without Spotify.
            Command::Spotify(request) => {
                use crate::backend::SpotifyRequest;
                use discord::spotify::{Command as Sp, Player, Playlist};
                static PLAYER: std::sync::Mutex<Option<Player>> = std::sync::Mutex::new(None);
                let mut p = PLAYER.lock().unwrap_or_else(|e| e.into_inner());
                let player = p.get_or_insert_with(|| Player {
                    playing: true,
                    track: "Crab Rave".into(),
                    artists: "Noisestorm".into(),
                    art: None,
                    progress_ms: 47_000,
                    duration_ms: 158_000,
                    shuffle: false,
                    repeat: "off".into(),
                    volume: Some(60),
                    device: Some("This PC".into()),
                    link: None,
                });
                match request {
                    SpotifyRequest::Playlists => {
                        let list = ["Ferris' Focus Mix", "Rewrite It In Rust Radio", "Borrow Checker Blues"]
                            .iter()
                            .map(|n| Playlist { name: (*n).into(), uri: format!("spotify:playlist:{n}"), image: None, link: String::new() })
                            .collect();
                        em.emit(Event::SpotifyMyPlaylists(Ok(list)));
                        continue;
                    }
                    SpotifyRequest::Do(cmd) => match cmd {
                        Sp::Play => player.playing = true,
                        Sp::Pause => player.playing = false,
                        Sp::Next | Sp::Previous | Sp::PlayContext(_) => player.progress_ms = 0,
                        Sp::Seek(ms) => player.progress_ms = ms,
                        Sp::Shuffle(on) => player.shuffle = on,
                        Sp::Repeat(m) => player.repeat = m,
                        Sp::Volume(v) => player.volume = Some(v),
                        Sp::Transfer(_) => {}
                    },
                    SpotifyRequest::State => {}
                }
                em.emit(Event::SpotifyPlayer(Ok((Some(player.clone()), Vec::new()))));
            }
            Command::AddServer { request, .. } => em.emit(Event::AddServer { request, result: Err("Demo mode: nothing is changed on Discord.".into()), captcha: None }),
            Command::CreateInvite { channel, .. } => em.emit(Event::Invite { channel, result: Ok("https://discord.gg/rustcord-demo".into()) }),
            Command::SendInvite { user, .. } => em.emit(Event::InviteSent { user, result: Ok(()) }),
            Command::Ignore { user, on } => em.emit(Event::Ignored { user, on, result: Ok(()) }),
            Command::AnswerRequest { channel, accept } => {
                if accept {
                    dispatch(&em, "CHANNEL_UPDATE", json!({ "id": channel.to_string(), "type": 1, "recipients": [user(CORRO)] }));
                } else {
                    dispatch(&em, "CHANNEL_DELETE", json!({ "id": channel.to_string(), "type": 1 }));
                }
            }
            Command::FetchRequestPreviews(_) | Command::FetchApps(_) => {}
            Command::FetchQuests | Command::EnrollQuest { .. } => {
                em.emit(Event::Quests(Err("Quests come from Discord, so they need a real account (this is the demo).".into())));
            }
            Command::FetchShop => em.emit(Event::Shop(Err("The Shop comes from Discord, so it needs a real account (this is the demo).".into()))),
            Command::FetchNitro => em.emit(Event::Nitro(Ok(Vec::new()))),
            Command::VoiceConnect { .. } | Command::VoiceDisconnect | Command::VoiceSelfState { .. } | Command::Camera(_) | Command::SpotifyPoll { .. } | Command::VoiceUserVolume { .. } | Command::VoiceBitrate(_) | Command::GatewaySend(_) | Command::RpcUser(_) | Command::RpcActivities(_) => {}
            Command::VoiceState { .. } => em.emit(Event::Error("Voice needs a real account (this is the demo).".into())),
            // Who reacted (the reaction tooltip).
            Command::Api { tag, path, .. } if path.contains("/reactions/") => {
                em.emit(Event::Api { tag, result: Ok(json!([user(FERRIS), user(CLIPPY), user(CORRO)])) });
            }
            // A friend nickname: saved, and echoed back the way Discord's gateway does.
            Command::Api { tag, path, body, .. } if path.starts_with("/users/@me/relationships/") && body.as_ref().is_some_and(|b| b.get("nickname").is_some()) => {
                let id = path.rsplit('/').next().unwrap_or_default().to_string();
                let nickname = body.map(|b| b["nickname"].clone()).unwrap_or(Value::Null);
                em.emit(Event::Api { tag, result: Ok(Value::Null) });
                dispatch(&em, "RELATIONSHIP_UPDATE", json!({ "id": id, "type": 1, "nickname": nickname }));
            }
            // Saving account settings (the server list after a drag, …): kept locally.
            Command::Api { tag, path, body: Some(_), .. } if path == "/users/@me/settings-proto/1" => em.emit(Event::Api { tag, result: Ok(json!({})) }),
            // Your linked accounts (Settings → Connections, and the /fortnite,
            // /spotify, /roblox… commands).
            Command::Api { tag, path, .. } if path == "/users/@me/connections" => {
                em.emit(Event::Api {
                    tag,
                    result: Ok(json!([
                        { "type": "epicgames", "id": "e1", "name": "CrabbyBuilder", "visibility": 1, "verified": true },
                        { "type": "roblox", "id": "156", "name": "builderman", "visibility": 1, "verified": true },
                        { "type": "spotify", "id": "demo-you", "name": "You", "visibility": 1, "verified": true },
                        { "type": "youtube", "id": "UCdemo0000000000000000000", "name": "You Tube", "visibility": 0, "verified": true },
                        { "type": "steam", "id": "76561190000000000", "name": "crabby", "visibility": 1, "verified": true },
                        { "type": "github", "id": "9", "name": "you-dev", "visibility": 1, "verified": true },
                    ])),
                });
            }
            // The sticker popout's lookups (#stickers).
            Command::Api { tag, path, .. } if path.starts_with("/stickers/") || path == "/sticker-packs" => {
                em.emit(Event::Api { tag, result: sticker_api(&path) });
            }
            Command::Api { tag, .. } | Command::ApiRaw { tag, .. } | Command::ApiReason { tag, .. } | Command::ApiUpload { tag, .. } | Command::Account { tag, .. } => em.emit(Event::Api { tag, result: Err("Needs a real account (this is the demo).".into()) }),
            Command::SpotifyPlaylists => em.emit(Event::Api {
                tag: "spotify:playlists".into(),
                result: Ok(json!([
                    ["Crab Rave Essentials", "https://open.spotify.com/playlist/demo1"],
                    ["Compile Time Chill", "https://open.spotify.com/playlist/demo2"],
                ])),
            }),
            // The RustCord badge: you (since four months ago, on it now) and
            // Ferris (a year, not on it right now). With the setting off you
            // drop out of the list, like the real service does.
            Command::Registry { me, share, .. } => {
                registry_share = share;
                let now = now_ms() / 1000;
                em.emit(Event::Registry(crate::registry::Answer { now, users: vec![(me, share.then_some((now - 122 * 86_400, now)))] }));
            }
            Command::RegistryLookup(users) => {
                let now = now_ms() / 1000;
                let row = |id: Id| match id.0 {
                    ME if registry_share => Some((now - 122 * 86_400, now)),
                    FERRIS => Some((now - 365 * 86_400, now - 3 * 86_400)),
                    _ => None,
                };
                em.emit(Event::Registry(crate::registry::Answer { now, users: users.into_iter().map(|id| (id, row(id))).collect() }));
            }
            Command::SpotifyPlay { .. } => em.emit(Event::Error("Listen Along needs a real account (this is the demo).".into())),
            Command::SendFriendRequest(name) => em.emit(Event::FriendRequest(Ok(name))),
            Command::FetchGuildProfile(guild) => {
                let (name, tag) = if guild.0 == G_VEN { ("Vencord-ish", "VEN") } else { ("Rust Lounge", "RUST") };
                let result = discord::model::GuildProfile::deserialize(&json!({
                    "id": guild.to_string(), "name": name, "member_count": 1024, "online_count": 117,
                    "description": "Native Discord clients and the crabs who build them.", "brand_color_primary": "#3BA5E8",
                    "tag": tag, "traits": [
                        { "emoji_name": "🦀", "label": "Rust" }, { "emoji_name": "🎨", "label": "Theming" },
                        { "emoji_name": "🧩", "label": "Plugins" }, { "emoji_name": "⚡", "label": "Speed" }, { "emoji_name": "🛠️", "label": "Tools" }
                    ],
                }))
                .map_err(|e| e.to_string());
                em.emit(Event::GuildProfile { guild, result });
            }
            Command::FetchMentions => {
                let mentions_me = |v: &Value| {
                    v["content"].as_str().is_some_and(|c| c.contains(&format!("<@{ME}>")) || c.contains("@everyone") || c.contains("@here"))
                };
                let mut found: Vec<Value> = history(C_GENERAL, None).into_iter().filter(|v| mentions_me(v)).collect();
                if let Ok(m) = state.messages.lock() {
                    found.extend(m.values().filter(|v| mentions_me(v)).cloned());
                }
                let mut msgs: Vec<Message> = found.iter().filter_map(|v| Message::deserialize(v).ok()).collect();
                msgs.sort_by_key(|m| std::cmp::Reverse(m.id));
                msgs.dedup_by_key(|m| m.id);
                msgs.truncate(25);
                em.emit(Event::Mentions(Ok(msgs)));
            }
            Command::FetchGifs(query) => {
                em.emit(Event::Gifs { query, result: Err("GIFs come from Discord, so they need a real account (this is the demo).".into()) });
            }
            Command::SetStatus { status, .. } => {
                dispatch(&em, "SESSIONS_REPLACE", json!([{ "session_id": "all", "status": status }]));
            }
            Command::AddFriendSolved { .. } => {}
            Command::AcceptStranger { user: who } => {
                dispatch(&em, "RELATIONSHIP_ADD", json!({ "id": who.to_string(), "type": 1, "user": user(who.0) }));
            }
            Command::Relationship { user: who, add, .. } => {
                if add {
                    dispatch(&em, "RELATIONSHIP_ADD", json!({ "id": who.to_string(), "type": 1, "user": user(who.0) }));
                } else {
                    dispatch(&em, "RELATIONSHIP_REMOVE", json!({ "id": who.to_string(), "type": 1 }));
                }
                em.emit(Event::RelationshipDone { user: who });
            }
            Command::Typing(_)
            | Command::Token(_)
            | Command::SubscribeGuild(_)
            | Command::Logout { .. }
            | Command::EndSession { .. }
            | Command::Ack { .. }
            | Command::AckManual { .. } => {}
        }
    }
}