Skip to content

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

91.0 KB
Raw Blame
//! Background tokio runtime that owns all networking. The UI thread talks to it
//! with [`Command`]s and receives [`Event`]s.

use discord::gateway::{self, GatewayCommand, GatewayEvent};
use discord::model::{Id, Message, OutgoingMessage, ReactionEmoji, UserProfile};
use discord::Http;
use eframe::egui;
use std::collections::VecDeque;
use tokio::sync::mpsc::{unbounded_channel, UnboundedReceiver, UnboundedSender};
use tokio::task::JoinHandle;

/// What the Spotify controller asks for.
#[derive(Clone, Debug)]
pub enum SpotifyRequest {
    State,
    Playlists,
    Do(discord::spotify::Command),
}

pub enum Command {
    /// Start a session (at launch, on a switch of account, on Ctrl+R),
    /// replacing the one before. Its events carry `session`, so the app can
    /// ignore what a replaced session still sends.
    Login { session: u64, account: Option<Id>, token: String },
    /// Discord replaced the session's login token: requests use this one now.
    Token(String),
    /// Log out: the session is ended at Discord too (as its own client does), so
    /// the token is worth nothing afterwards. `done` hears when Discord has
    /// answered (or couldn't be reached), for a caller about to close the app.
    Logout { done: Option<std::sync::mpsc::Sender<()>> },
    /// End another saved account's session at Discord (it logged out from
    /// Manage Accounts while not the active one).
    EndSession { token: String, done: Option<std::sync::mpsc::Sender<()>> },
    FetchMessages { channel: Id, before: Option<Id> },
    Send(OutgoingMessage),
    Edit { channel: Id, id: Id, content: String },
    Delete { channel: Id, id: Id },
    Typing(Id),
    React { channel: Id, msg: Id, emoji: ReactionEmoji, add: bool },
    Pin { channel: Id, msg: Id, pinned: bool },
    FetchProfile { user: Id, guild: Option<Id> },
    OpenDm(Id),
    /// Download a file (audio attachments).
    FetchBytes(String),
    /// Change status / custom status live (op 3) and save it to the account.
    SetStatus { status: String, custom: Option<discord::settings_proto::CustomStatus> },
    /// Mark read up to `msg`.
    Ack { channel: Id, msg: Id },
    /// Mark unread from `msg`.
    AckManual { channel: Id, msg: Id, mentions: u32 },
    /// Accept/add (true) or remove/decline (false) a relationship.
    /// `location`: where the click was, as Discord's client names it
    /// ("Friends", "User Profile", "DM Channel", "Context Menu").
    /// Friend-list changes go out one at a time, paced (see `relationship_queue`).
    Relationship { user: Id, add: bool, location: &'static str },
    /// Accept a stranger's friend request once you've confirmed it (Discord's
    /// "Accept friend request?" pop-up).
    AcceptStranger { user: Id },
    /// Add a friend again, with the captcha the person solved for it
    /// (`stranger`: the request was confirmed as a stranger's).
    AddFriendSolved { user: Id, captcha: discord::model::CaptchaAnswer, stranger: bool },
    /// Subscribe to a server's member list for a channel (op 37), first
    /// `windows` × 100 rows.
    SubscribeMembers { guild: Id, channel: Id, windows: usize },
    /// Ask for a server's events as they happen without opening it (the
    /// server of the call you're in): see `guild_subscription`.
    SubscribeGuild(Id),
    FetchPins(Id),
    /// The server card behind a server tag.
    FetchGuildProfile(Id),
    /// Give / take a role (then refresh that profile).
    MemberRole { guild: Id, user: Id, role: Id, add: bool },
    EditChannel { channel: Id, patch: serde_json::Value },
    DeleteChannel(Id),
    CreateChannel { guild: Id, body: serde_json::Value },
    /// "Add a Server": create one or join one by invite (with a solved
    /// captcha when Discord asked for one). Answered as `Event::AddServer`.
    AddServer { request: crate::features::AddServerRequest, captcha: Option<discord::model::CaptchaAnswer> },
    /// An invite to a channel: expiry in seconds (0 = never), uses (0 = no
    /// limit), and "Invite a Guest" (temporary membership).
    CreateInvite { channel: Id, max_age: u32, max_uses: u32, temporary: bool },
    /// The invite modal's per-friend "Invite": the link sent as a message to
    /// their DM (opened first when there isn't one yet), like Discord does.
    SendInvite { user: Id, dm: Option<Id>, content: String, nonce: String },
    GuildSettings { guild: Id, patch: serde_json::Value },
    LeaveGuild(Id),
    /// Leave a group DM (or close a DM); `silent` suppresses the system leave message.
    LeaveGroup { channel: Id, silent: bool },
    /// Accept (true) / ignore a message request.
    AnswerRequest { channel: Id, accept: bool },
    FetchRequestPreviews(Vec<Id>),
    SendFriendRequest(String),
    /// Game names / icons for Game Collection.
    FetchApps(Vec<Id>),
    /// Ignore someone (Discord's "Ignore"), or stop ignoring them.
    Ignore { user: Id, on: bool },
    /// Op 8: member info (roles, nickname) for these users in a server.
    RequestMembers { guild: Id, users: Vec<Id> },
    /// `query` is the search box's text (it names the results); `filters`
    /// what it asks Discord for.
    Search { guild: Option<Id>, channel: Id, query: String, filters: discord::http::SearchQuery },
    /// Recent mentions for the inbox.
    FetchMentions,
    /// Trending GIFs (None) or a GIF search.
    FetchGifs(Option<String>),
    FetchTheme(String),
    /// Quests + Orbs balance.
    FetchQuests,
    /// Accept a quest (with its sealed traffic metadata), then refresh.
    EnrollQuest { quest: Id, sealed: Option<String> },
    FetchShop,
    /// Nitro subscriptions (for Nitro Home).
    FetchNitro,
    /// Ask the gateway to put you in (or take you out of: `channel` None) a
    /// voice channel: op 4.
    VoiceState { guild: Option<Id>, channel: Option<Id>, mute: bool, deaf: bool },
    /// Both halves of the voice credentials arrived: start the call.
    /// `gen` tags the call's events, so a replaced call's late events are ignored.
    VoiceConnect { gen: u64, user: Id, session_id: String, token: String, endpoint: String, server: Id, channel: Id },
    /// End the call (the op 4 to leave is sent separately).
    VoiceDisconnect,
    /// Mute / deafen changed: applied to the running call and sent as one voice state.
    VoiceSelfState { mute: bool, deaf: bool },
    /// Look at what your Spotify is playing and put it in (or take it out of) your
    /// presence. `share`: "Share your detected activities" is on.
    SpotifyPoll { share: bool, user: Id, fresh: bool },
    /// Turn the camera on (this device id; "" = the first camera) or off, in the running call.
    Camera(Option<String>),
    /// Send a raw gateway payload (e.g. op 31, the soundboard sounds request).
    GatewaySend(serde_json::Value),
    /// Who READY tells Rich Presence programs they talk to.
    RpcUser(serde_json::Value),
    /// The games' Rich Presence activities now (application ID, RPC activity):
    /// resolved (name, images) and put in your presence. Empty clears them.
    RpcActivities(Vec<(String, serde_json::Value)>),
    /// How loud one person plays (0.0–2.0; 0 for a local mute). Kept for later calls too.
    VoiceUserVolume { user: Id, volume: f32 },
    /// The call's outgoing voice bitrate (bit/s), from its channel.
    VoiceBitrate(u32),
    /// Any REST call (settings screens use this): the answer comes back as
    /// `Event::Api` with the same `tag`.
    Api { tag: String, method: reqwest::Method, path: String, body: Option<serde_json::Value> },
    /// A REST call answered whatever its status, as `Ok({"status", "body"})`
    /// (pages that read fields of an error, like the domain proof).
    ApiRaw { tag: String, method: reqwest::Method, path: String, body: Option<serde_json::Value> },
    /// `Api` with an audit-log reason (`X-Audit-Log-Reason`, as Discord's
    /// client sends with kicks, bans and timeouts).
    ApiReason { tag: String, method: reqwest::Method, path: String, body: Option<serde_json::Value>, reason: String },
    /// A multipart POST (stickers, soundboard sounds): text fields plus one
    /// file (name, bytes, MIME type). Answered as `Event::Api`.
    ApiUpload { tag: String, path: String, fields: Vec<(String, String)>, file: (String, Vec<u8>, String) },
    /// An account change (username, email, password, logging a device out).
    /// Discord may answer "verify it's you": that comes back as
    /// `Ok({"__mfa": {ticket, methods}})`; send it again with `mfa` =
    /// (ticket, method, the code or password). Bodies are never logged.
    Account { tag: String, method: reqwest::Method, path: String, body: Option<serde_json::Value>, mfa: Option<(String, String, String)> },

    /// Listen Along: play this Spotify track from `position_ms`.
    SpotifyPlay { track: String, position_ms: u64 },
    /// `/spotify playlist`: your public playlists, answered as `Event::Api`
    /// under "spotify:playlists" (an array of `[name, link]`).
    SpotifyPlaylists,
    /// The Spotify controller (Settings → Experimental): what's playing, your
    /// playlists, or something to do. Answered as `Event::Spotify*`.
    Spotify(SpotifyRequest),
    /// (Re)start the RustCord registry loop for this account: say hello and
    /// keep saying it (`share` off: ask to be hidden instead; `invisible`:
    /// say nothing, so you don't show as on RustCord right now).
    Registry { me: Id, share: bool, invisible: bool },
    /// Ask the registry whether these users are on RustCord (profiles being drawn).
    RegistryLookup(Vec<Id>),
    /// Op 8 by name: members whose username / nickname starts with `query`.
    SearchMembers { guild: Id, query: String },
    /// Go Live, op 18: ask to stream in this call.
    StreamCreate { guild: Option<Id>, channel: Id },
    /// Op 20: ask to watch this stream.
    StreamWatch(String),
    /// Op 19: stop streaming / watching this stream.
    StreamDelete(String),
    /// Op 22.
    StreamSetPaused { key: String, paused: bool },
    /// Open your stream's media connection (needs the running call).
    GoLiveConnect { gen: u64, cfg: voice::StreamConfig, source: voice::ScreenSource, quality: voice::StreamQuality, audio: bool },
    /// Open a watched stream's media connection.
    WatchConnect { gen: u64, cfg: voice::StreamConfig },
}

pub enum Event {
    Gateway(GatewayEvent),
    Messages { channel: Id, before: Option<Id>, result: Result<Vec<Message>, String> },
    SendFailed { channel: Id, nonce: String, error: String },
    /// Discord wants a captcha solved before it takes this friend request.
    FriendCaptcha { user: Id, challenge: crate::captcha_view::Challenge, stranger: bool },
    /// Accepting this person's friend request needs confirming: you share
    /// no friends or small servers with them.
    FriendStranger { user: Id },
    /// A queued friend-list change for this person has been sent (or dropped).
    RelationshipDone { user: Id },
    /// Discord wants a captcha solved before it takes this message.
    SendCaptcha { msg: Box<discord::model::OutgoingMessage>, challenge: crate::captcha_view::Challenge },
    /// "Add a Server" answered: the server's ID, or why not (with the
    /// captcha Discord wants solved first, if that's why).
    AddServer { request: crate::features::AddServerRequest, result: Result<Id, String>, captcha: Option<crate::captcha_view::Challenge> },
    /// The Spotify controller: what your Spotify is doing (and your devices
    /// when nothing is playing).
    SpotifyPlayer(Result<(Option<discord::spotify::Player>, Vec<discord::spotify::Device>), String>),
    SpotifyMyPlaylists(Result<Vec<discord::spotify::Playlist>, String>),
    /// A controller action Spotify refused.
    SpotifyFailed(String),
    Error(String),
    Theme { source: String, result: Result<String, String> },
    Profile { user: Id, guild: Option<Id>, result: Result<UserProfile, String> },
    /// A DM channel object to switch to.
    DmOpened(serde_json::Value),
    Bytes { url: String, result: Result<std::sync::Arc<[u8]>, String> },
    /// Account settings (folders, status, custom status) from settings-proto.
    Settings(discord::settings_proto::UserSettings),
    Pins { channel: Id, result: Result<Vec<Message>, String> },
    /// Discord refused a pin / unpin (`pinned` is what was asked for): the
    /// message goes back to what it was.
    PinFailed { channel: Id, msg: Id, pinned: bool, error: String },
    Search { query: String, result: Result<(u64, Vec<Message>), String> },
    Mentions(Result<Vec<Message>, String>),
    GuildProfile { guild: Id, result: Result<discord::model::GuildProfile, String> },
    /// An invite link was made (for this channel).
    Invite { channel: Id, result: Result<String, String> },
    /// The invite modal's "Invite" to someone went out (or didn't).
    InviteSent { user: Id, result: Result<(), String> },
    /// Ignoring someone (or stopping) worked, or didn't.
    Ignored { user: Id, on: bool, result: Result<(), String> },
    /// Something worked: tell the user.
    Info(String),
    /// Left a group DM (REST succeeded; gateway `CHANNEL_DELETE` may also follow).
    GroupLeft(Id),
    /// First message of each message request.
    RequestPreviews(Vec<(Id, Message)>),
    /// A friend request by username: Ok(name) or why not.
    FriendRequest(Result<String, String>),
    Apps(Vec<discord::model::AppInfo>),
    Gifs { query: Option<String>, result: Result<Vec<discord::model::Gif>, String> },
    /// Quests and the Orbs balance (None if that call failed).
    Quests(Result<(discord::commerce::QuestList, Option<u64>), String>),
    Shop(Result<discord::commerce::Shop, String>),
    Nitro(Result<Vec<discord::commerce::Subscription>, String>),
    /// Answer to `Command::Api`.
    Api { tag: String, result: Result<serde_json::Value, String> },
    /// Something happened in the voice call (with its `VoiceConnect` generation).
    Voice(u64, voice::VoiceEvent),
    /// A call started: where its participants' camera pictures can be read.
    CameraFeeds(std::sync::Arc<voice::CameraFeeds>),
    /// The camera: on (its handle, for the preview), off, or why it couldn't start.
    Camera(Result<Option<std::sync::Arc<voice::Camera>>, String>),
    /// A Go Live connection (yours or one you watch) changed, with its generation.
    Stream(u64, voice::StreamEvent),
    /// A Go Live connection started: its handle (yours, or the one you watch).
    StreamHandle(u64, Option<std::sync::Arc<voice::StreamHandle>>, Option<std::sync::Arc<voice::WatchHandle>>),
    /// The account as of the last session (from disk), to show while the
    /// gateway connects. Ignored once the real READY has arrived.
    CachedReady(serde_json::Value),
    /// A game set or cleared its Rich Presence (local RPC).
    Rpc(crate::rpc::RpcEvent),
    /// Whether some users are on RustCord, as of now (the RustCord badge).
    Registry(crate::registry::Answer),
}

/// Your last presence (status + custom status) on disk, so the next launch
/// can connect without waiting for the account settings.
mod presence_cache {
    use discord::model::Id;
    use std::sync::Mutex;

    /// The account whose status is kept (the one logged in; one at a time).
    static ACCOUNT: Mutex<Option<Id>> = Mutex::new(None);

    pub fn set_account(account: Option<Id>) {
        if let Ok(mut a) = ACCOUNT.lock() {
            *a = account;
        }
    }

    fn path() -> Option<std::path::PathBuf> {
        let account = (*ACCOUNT.lock().ok()?)?;
        crate::accounts::config_folder(account).map(|d| d.join("presence.json"))
    }

    pub fn load() -> Option<serde_json::Value> {
        let text = std::fs::read_to_string(path()?).ok()?;
        serde_json::from_str(&text).ok().filter(|v: &serde_json::Value| v["status"].is_string())
    }

    pub fn save(presence: &serde_json::Value) {
        if let Some(p) = path() {
            let _ = std::fs::create_dir_all(p.parent().unwrap_or(&p));
            let _ = std::fs::write(p, presence.to_string());
        }
    }
}

/// Most 100-member windows a member list grows to. Discord's own client
/// never subscribes to more than 3 ranges of a channel; 5 got the session
/// closed with 4002 (and again after every reconnect).
pub const MAX_MEMBER_WINDOWS: usize = 3;

/// Op 37: lazy guild subscription (member list + typing) for one channel.
pub fn member_subscription(guild: Id, channel: Id, windows: usize) -> serde_json::Value {
    let ranges: Vec<[usize; 2]> = (0..windows.clamp(1, MAX_MEMBER_WINDOWS)).map(|i| [i * 100, i * 100 + 99]).collect();
    serde_json::json!({
        "op": 37,
        "d": { "subscriptions": { guild.to_string(): {
            "typing": true, "threads": true, "activities": true, "member_updates": false,
            "members": [], "channels": { channel.to_string(): ranges }, "thread_member_lists": [],
        } } }
    })
}

/// Op 37 for a server as a whole: its typing, activities and threads, and
/// with them its events one by one. A server that isn't subscribed to is only
/// summarised now and then (PASSIVE_UPDATE_V2), too slowly for the list of
/// people in a call. Discord's client keeps the call's server subscribed too.
pub fn guild_subscription(guild: Id) -> serde_json::Value {
    serde_json::json!({
        "op": 37,
        "d": { "subscriptions": { guild.to_string(): { "typing": true, "threads": true, "activities": true } } }
    })
}

/// Sends events to the app. Events of a session carry its number
/// (see `Command::Login`); the rest (Rich Presence, the friend queue) none.
#[derive(Clone)]
pub struct Emitter {
    tx: std::sync::mpsc::Sender<(Option<u64>, Event)>,
    /// The window's context, once there is a window (the backend starts
    /// before it, so a launch's login is under way while it is made).
    ctx: std::sync::Arc<std::sync::OnceLock<egui::Context>>,
    session: Option<u64>,
}

impl Emitter {
    pub fn ctx(&self) -> Option<&egui::Context> {
        self.ctx.get()
    }

    /// Asks the window for a frame (for callbacks off the async threads).
    pub fn waker(&self) -> impl Fn() + Clone + Send + Sync + 'static {
        let ctx = self.ctx.clone();
        move || {
            if let Some(ctx) = ctx.get() {
                ctx.request_repaint();
            }
        }
    }

    /// This emitter for one session's events.
    pub fn for_session(&self, session: u64) -> Self {
        Self { session: Some(session), ..self.clone() }
    }

    pub fn emit(&self, e: Event) {
        // Every redraw lays out and paints the whole window, so gateway
        // traffic (constant on a big account: presence changes from every
        // server, member list churn…) mustn't each cost one. Events that
        // change something you're likely looking at are drawn within
        // 100 ms; the rest wait for the regular once-a-second frame.
        // Replies to things you did still show immediately.
        let delay = match &e {
            Event::Gateway(GatewayEvent::Dispatch { name, .. }) => match name.as_str() {
                "READY" | "READY_SUPPLEMENTAL" | "RESUMED" | "VOICE_CHANNEL_EFFECT_SEND" => Some(0),
                "MESSAGE_CREATE" | "MESSAGE_UPDATE" | "MESSAGE_DELETE" | "MESSAGE_DELETE_BULK" | "MESSAGE_ACK"
                | "TYPING_START" | "CHANNEL_CREATE" | "CHANNEL_UPDATE" | "CHANNEL_DELETE" | "CHANNEL_RECIPIENT_ADD" | "CHANNEL_RECIPIENT_REMOVE" | "THREAD_CREATE" | "THREAD_UPDATE" | "THREAD_DELETE" | "CHANNEL_PINS_UPDATE"
                | "GUILD_CREATE" | "GUILD_DELETE" | "GUILD_MEMBERS_CHUNK" | "GUILD_MEMBER_LIST_UPDATE"
                | "VOICE_STATE_UPDATE" | "VOICE_SERVER_UPDATE" | "CALL_CREATE" | "CALL_UPDATE" | "CALL_DELETE"
                | "STREAM_CREATE" | "STREAM_SERVER_UPDATE" | "STREAM_UPDATE" | "STREAM_DELETE"
                | "RELATIONSHIP_ADD" | "RELATIONSHIP_UPDATE"
                | "RELATIONSHIP_REMOVE" | "INTERACTION_FAILURE" | "MESSAGE_POLL_VOTE_ADD" | "MESSAGE_POLL_VOTE_REMOVE" => Some(100),
                n if n.starts_with("MESSAGE_REACTION") => Some(100),
                // PRESENCE_UPDATE, GUILD_MEMBER_UPDATE, SESSIONS_REPLACE,
                // settings, role and emoji changes…
                _ => None,
            },
            _ => Some(0),
        };
        let _ = self.tx.send((self.session, e));
        // (Before the window exists, its first frame picks the events up.)
        let Some(ctx) = self.ctx.get() else { return };
        match delay {
            Some(0) => ctx.request_repaint(),
            Some(ms) => ctx.request_repaint_after(std::time::Duration::from_millis(ms)),
            None => {}
        }
    }
}

pub struct Backend {
    tx: UnboundedSender<Command>,
    pub rx: std::sync::mpsc::Receiver<(Option<u64>, Event)>,
    ctx: std::sync::Arc<std::sync::OnceLock<egui::Context>>,
}

impl Backend {
    /// Start the networking thread (before the window: see [`Backend::attach`]).
    pub fn spawn(demo: bool) -> Self {
        let (cmd_tx, cmd_rx) = unbounded_channel();
        let (ev_tx, ev_rx) = std::sync::mpsc::channel();
        let ctx = std::sync::Arc::new(std::sync::OnceLock::new());
        let emitter = Emitter { tx: ev_tx, ctx: ctx.clone(), session: None };
        std::thread::Builder::new()
            .name("rustcord-net".into())
            .spawn(move || {
                let rt = tokio::runtime::Builder::new_multi_thread()
                    .worker_threads(2)
                    // (See `net_images`: no bursts of blocking threads.)
                    .max_blocking_threads(4)
                    .on_thread_park(crate::diagnostics::release_this_threads_memory)
                    .enable_all()
                    .build()
                    .expect("tokio runtime");
                rt.block_on(async move {
                    if demo {
                        crate::demo::run(cmd_rx, emitter).await
                    } else {
                        run(cmd_rx, emitter).await
                    }
                });
            })
            .expect("spawn network thread");
        Self { tx: cmd_tx, rx: ev_rx, ctx }
    }

    /// The window is up: events from now on ask it for frames.
    pub fn attach(&self, ctx: egui::Context) {
        let _ = self.ctx.set(ctx);
    }

    pub fn send(&self, cmd: Command) {
        let _ = self.tx.send(cmd);
    }
}

/// One friend-list change waiting its turn in [`relationship_queue`].
struct RelJob {
    http: Http,
    user: Id,
    op: RelOp,
    /// Where it was clicked (None: a follow-up of an earlier change for the
    /// same person, which keeps that one's location).
    location: Option<&'static str>,
}

enum RelOp {
    Add,
    Remove,
    /// Accept a stranger's request once you've confirmed it.
    AcceptStranger,
    /// Add again with a solved captcha.
    Solved { captcha: discord::model::CaptchaAnswer, stranger: bool },
}

/// Gap between two friend-list changes: a person clicking through a list.
const REL_GAP: std::time::Duration = std::time::Duration::from_millis(1500);
/// After `REL_BURST` changes within `REL_WINDOW`, the gap grows to this.
const REL_SLOW_GAP: std::time::Duration = std::time::Duration::from_secs(8);
const REL_BURST: usize = 5;
const REL_WINDOW: std::time::Duration = std::time::Duration::from_secs(60);
/// Discord said "slow down" (429) during a change: nothing more for this long.
const REL_BACKOFF: std::time::Duration = std::time::Duration::from_secs(30);

/// Friend-list changes (accept, add, decline, remove) go out one at a time,
/// paced like a person clicking, never all at once. Accepting many requests
/// in a burst (each its own parallel request, none saying where it was
/// clicked) got an account locked by Discord until its password was reset.
/// A captcha or an account error drops the rest of the queue.
async fn relationship_queue(mut rx: UnboundedReceiver<RelJob>, em: Emitter) {
    use std::time::Instant;
    let mut recent: VecDeque<Instant> = VecDeque::new();
    let mut last: Option<Instant> = None;
    let mut backoff_until: Option<Instant> = None;
    // Where each person's last change was clicked (for the follow-ups).
    let mut locations: std::collections::HashMap<Id, &'static str> = std::collections::HashMap::new();
    while let Some(job) = rx.recv().await {
        let now = Instant::now();
        while recent.front().is_some_and(|t| now.duration_since(*t) > REL_WINDOW) {
            recent.pop_front();
        }
        let gap = if recent.len() >= REL_BURST { REL_SLOW_GAP } else { REL_GAP };
        // Not a metronome: 0-40 % on top.
        let gap = gap.mul_f64(1.0 + rand::random::<f64>() * 0.4);
        let mut ready = last.map_or(now, |l| l + gap);
        if let Some(b) = backoff_until {
            ready = ready.max(b);
        }
        if ready > now {
            log::info!("friends: next friend-list change in {:.1}s ({} queued)", (ready - now).as_secs_f32(), rx.len() + 1);
            tokio::time::sleep_until(tokio::time::Instant::from_std(ready)).await;
        }

        let RelJob { http, user, op, location } = job;
        let location = match location {
            Some(l) => {
                locations.insert(user, l);
                l
            }
            None => locations.get(&user).copied().unwrap_or("Friends"),
        };
        let limited = discord::http::rate_limit_count();
        let (add, result) = match &op {
            RelOp::Add => (true, http.add_friend(user, location).await),
            RelOp::Remove => (false, http.remove_relationship(user, location).await),
            RelOp::AcceptStranger => (true, http.add_friend_with(user, None, true, location).await),
            RelOp::Solved { captcha, stranger } => (true, http.add_friend_with(user, Some(captcha), *stranger, location).await),
        };
        let sent = Instant::now();
        last = Some(sent);
        recent.push_back(sent);
        if discord::http::rate_limit_count() != limited {
            log::warn!("friends: Discord rate-limited a friend-list change; waiting {}s before the next", REL_BACKOFF.as_secs());
            backoff_until = Some(sent + REL_BACKOFF);
        }

        let mut stop = None;
        if let Err(e) = result {
            let error = format!("{e:#}");
            let code = discord::http::ApiError::code_of(&e);
            let status = e.downcast_ref::<discord::http::ApiError>().map(|a| a.status);
            let captcha = crate::captcha_view::Challenge::from_error(&error);
            let needs_confirming = code == Some(discord::http::STRANGER_REQUEST_NEEDS_CONFIRMATION);
            match &op {
                // A stranger's request: Discord asks you to confirm (like its client does).
                RelOp::Add | RelOp::Solved { stranger: false, .. } if needs_confirming => {
                    log::info!("friends: accepting {user}'s request needs confirming (no mutual friends or small servers)");
                    em.emit(Event::FriendStranger { user });
                }
                RelOp::Solved { .. } => {
                    let error = if captcha.is_some() { "Discord didn't accept the captcha. Try again.".to_string() } else { error };
                    em.emit(Event::Error(format!("Couldn't add friend: {error}")));
                    stop = Some("Discord wanted a captcha");
                }
                _ => match captcha.filter(|_| add) {
                    Some(challenge) => {
                        em.emit(Event::FriendCaptcha { user, challenge, stranger: matches!(op, RelOp::AcceptStranger) });
                        stop = Some("Discord wanted a captcha");
                    }
                    None => {
                        let what = if matches!(op, RelOp::AcceptStranger) { "Couldn't accept the friend request" } else { "Couldn't update friend" };
                        em.emit(Event::Error(format!("{what}: {error}")));
                        // Signed out, locked or asked to verify: don't keep going.
                        if matches!(status, Some(401 | 403)) || code == Some(40002) {
                            stop = Some("Discord refused the change");
                        }
                    }
                },
            }
        }
        em.emit(Event::RelationshipDone { user });
        if let Some(why) = stop {
            let mut dropped = 0;
            while let Ok(j) = rx.try_recv() {
                dropped += 1;
                em.emit(Event::RelationshipDone { user: j.user });
            }
            if dropped > 0 {
                log::warn!("friends: {why}; dropped {dropped} queued friend-list changes");
                let s = if dropped == 1 { "" } else { "s" };
                em.emit(Event::Error(format!("{why}, so the other {dropped} friend request change{s} weren't sent. Try them again later.")));
            }
        }
    }
}

/// A message waiting its turn in [`send_queue`], with the emitter of the
/// session that sent it.
struct SendJob {
    http: Http,
    em: Emitter,
    kind: SendKind,
}

enum SendKind {
    Message(OutgoingMessage),
    /// "Invite" in the invite dialog: open the DM if there's none, then send the link.
    Invite { user: Id, dm: Option<Id>, content: String, nonce: String },
}

/// Least time between two invites from the invite dialog (plus 0-50 %): a
/// person going down a list of friends, not a script mailing out a link.
const INVITE_GAP: std::time::Duration = std::time::Duration::from_millis(1200);

/// Messages go out one at a time, in the order they were written, like
/// Discord's own client (its message queue). Messages typed in quick
/// succession were parallel requests racing each other, a burst no person
/// makes (and they could arrive out of order). Messages with files skip the
/// queue (see `Command::Send`), so a big upload doesn't hold up the chat.
async fn send_queue(mut rx: UnboundedReceiver<SendJob>) {
    use std::time::Instant;
    let mut last_invite: Option<Instant> = None;
    while let Some(SendJob { http, em, kind }) = rx.recv().await {
        match kind {
            SendKind::Message(msg) => send_message(&http, msg, &em).await,
            SendKind::Invite { user, dm, content, nonce } => {
                if let Some(last) = last_invite {
                    let ready = last + INVITE_GAP.mul_f64(1.0 + rand::random::<f64>() * 0.5);
                    tokio::time::sleep_until(tokio::time::Instant::from_std(ready)).await;
                }
                // (The new DM itself arrives over the gateway: CHANNEL_CREATE.)
                let result = async {
                    let channel = match dm {
                        Some(c) => c,
                        None => {
                            let v = http.open_dm(user).await.map_err(|e| format!("{e:#}"))?;
                            Id::from_value(&v["id"]).ok_or("Discord didn't return the DM")?
                        }
                    };
                    let msg = OutgoingMessage { channel_id: channel, content, nonce, ..Default::default() };
                    http.send_message(&msg).await.map(|_| ()).map_err(|e| format!("{e:#}"))
                }
                .await;
                last_invite = Some(Instant::now());
                em.emit(Event::InviteSent { user, result });
            }
        }
    }
}

/// Send one message; a captcha Discord demands for it goes to the person.
async fn send_message(http: &Http, msg: OutgoingMessage, em: &Emitter) {
    let Err(e) = http.send_message(&msg).await else { return };
    let error = format!("{e:#}");
    // Once per message, and not for uploads, whose files would have to be sent again.
    match crate::captcha_view::Challenge::from_error(&error) {
        Some(challenge) if msg.captcha.is_none() && msg.uploads.is_empty() => em.emit(Event::SendCaptcha { msg: Box::new(msg), challenge }),
        Some(_) => em.emit(Event::SendFailed { channel: msg.channel_id, nonce: msg.nonce, error: "Discord wants a captcha for this message, and RustCord couldn't complete it. Try again, or send it once from Discord itself.".into() }),
        None => em.emit(Event::SendFailed { channel: msg.channel_id, nonce: msg.nonce, error }),
    }
}

/// READY carries the account settings (your folders and theme, and the status
/// you have now, which another device may have changed since last time): hand
/// them to the app, and correct the presence the session was started with.
/// Should a READY come without them, they are read from the API instead.
fn settings_from_ready(ready: &serde_json::Value, sent: &serde_json::Value, gateway: &UnboundedSender<GatewayCommand>, http: &Http, em: &Emitter) {
    let (sent, gateway, em) = (sent.clone(), gateway.clone(), em.clone());
    let apply = move |s: discord::settings_proto::UserSettings| {
        let fresh = gateway::presence_payload(&s.status, s.custom_status.as_ref());
        if fresh != sent {
            let _ = gateway.send(gateway::presence_update(fresh.clone()));
        }
        presence_cache::save(&fresh);
        em.emit(Event::Settings(s));
    };
    match ready["user_settings_proto"].as_str().and_then(|b| discord::settings_proto::decode(b).ok()) {
        Some(s) => apply(s),
        None => {
            let http = http.clone();
            tokio::spawn(async move {
                match http.settings_proto().await {
                    Ok(s) => apply(s),
                    Err(e) => log::warn!("settings: couldn't read account settings: {e}"),
                }
            });
        }
    }
}

/// Where the last looked-up web client build number is kept between runs.
fn client_build_file() -> Option<std::path::PathBuf> {
    crate::accounts::config_dir().map(|d| d.join("client-build.json"))
}

/// Look the web client's build number up again after this long.
const BUILD_CHECK_EVERY: std::time::Duration = std::time::Duration::from_secs(12 * 3600);

/// Bring the identity RustCord presents up to date before the first request
/// (see `discord::fingerprint`): the Chrome version of this PC's WebView2,
/// and the web client build number last looked up. A lookup older than
/// [`BUILD_CHECK_EVERY`] is redone in the background, for the next start:
/// the identity never changes mid-session.
fn load_client_identity() {
    #[cfg(windows)]
    match wry::webview_version() {
        Ok(v) => discord::fingerprint::set_chrome_version(&v),
        Err(e) => log::info!("identity: no WebView2 version ({e}); using the built-in Chrome version"),
    }
    voice::set_user_agent(discord::fingerprint::user_agent());

    let now = std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).map_or(0, |d| d.as_secs());
    let saved = client_build_file().and_then(|f| std::fs::read(f).ok()).and_then(|b| serde_json::from_slice::<serde_json::Value>(&b).ok());
    let (build, checked) = saved.map_or((0, 0), |v| (v["build"].as_u64().unwrap_or(0), v["checked"].as_u64().unwrap_or(0)));
    discord::fingerprint::set_client_build_number(build);
    log::info!("identity: {} {}, web build {}", discord::fingerprint::browser(), discord::fingerprint::browser_version(), discord::fingerprint::client_build_number());
    if now.saturating_sub(checked) < BUILD_CHECK_EVERY.as_secs() {
        return;
    }
    tokio::spawn(async move {
        match discord::fingerprint::fetch_client_build_number().await {
            Ok(latest) => {
                log::info!("identity: the web client is on build {latest} (used from the next start)");
                if let Some(f) = client_build_file() {
                    let _ = std::fs::write(f, serde_json::json!({ "build": latest, "checked": now }).to_string());
                }
            }
            Err(e) => log::info!("identity: couldn't look up the web client's build ({e:#}); keeping {}", discord::fingerprint::client_build_number()),
        }
    });
}

/// Log a session out at Discord, as its own client does, so its token is
/// worth nothing afterwards. `done` hears when Discord has answered (or
/// couldn't be reached).
async fn end_session(http: Http, done: Option<std::sync::mpsc::Sender<()>>) {
    match tokio::time::timeout(std::time::Duration::from_secs(8), http.logout()).await {
        Ok(Ok(())) => log::info!("logout: the session was ended at Discord"),
        Ok(Err(e)) => log::warn!("logout: Discord didn't end the session ({e:#}); it stays listed under Devices until it is logged out there"),
        Err(_) => log::warn!("logout: no answer from Discord; the session stays listed under Devices until it is logged out there"),
    }
    if let Some(done) = done {
        let _ = done.send(());
    }
}

async fn run(mut rx: UnboundedReceiver<Command>, base: Emitter) {
    load_client_identity();
    // Dev aids: RUSTCORD_CAPABILITIES=<number|none> picks what IDENTIFY sends;
    // RUSTCORD_DUMP_SHAPES=<folder> records the shape of gateway events there.
    if let Ok(c) = crate::diagnostics::dev_var("RUSTCORD_CAPABILITIES") {
        gateway::set_capabilities(c.parse().ok());
    }
    if let Ok(dir) = crate::diagnostics::dev_var("RUSTCORD_DUMP_SHAPES") {
        discord::shape::record_to(dir.into());
    }
    // Replaced by the session's own emitter at each login.
    let mut em = base.clone();
    let mut http = Http::new(None);
    let mut gateway: Option<UnboundedSender<GatewayCommand>> = None;
    let mut registry: Option<JoinHandle<()>> = None;
    // The voice call, and where you are (to resend op 4 on mute / deafen).
    let mut call: Option<voice::VoiceHandle> = None;
    let mut voice_where: Option<(Option<Id>, Id, bool, bool)> = None;
    // Your camera is on in the call (voice states say so: `self_video`).
    let mut video_on = false;
    let voice_state = |guild: Option<Id>, channel: Option<Id>, mute: bool, deaf: bool, video: bool| {
        serde_json::json!({
            "op": 4,
            "d": {
                "guild_id": guild.map(|g| g.to_string()),
                "channel_id": channel.map(|c| c.to_string()),
                "self_mute": mute,
                "self_deaf": deaf,
                "self_video": video,
            }
        })
    };
    // Per-person volumes (and local mutes as 0), applied to every call.
    let mut user_volumes: std::collections::HashMap<u64, f32> = std::collections::HashMap::new();
    // The voice channel's bitrate, applied to every call (64 kbit/s until the app says).
    let mut voice_bitrate: Option<u32> = None;
    // Discord hands back a token with each ack; the next ack sends it.
    let ack_token: std::sync::Arc<tokio::sync::Mutex<Option<String>>> = Default::default();
    // Rich Presence: the local discord-ipc pipe, and the games' activities as
    // they go into your presence (with a generation so a slow lookup can't
    // overwrite a newer update).
    let rpc_user: crate::rpc::SharedUser = std::sync::Arc::new(std::sync::Mutex::new(serde_json::Value::Null));
    let rpc_extra: std::sync::Arc<std::sync::Mutex<Vec<serde_json::Value>>> = Default::default();
    // "Listening to Spotify" (beside the games' activities), the token it is read with
    // (None: Spotify isn't connected or doesn't show as status; looked up again later)
    // and whether a look is under way.
    let spotify_now: std::sync::Arc<std::sync::Mutex<Option<serde_json::Value>>> = Default::default();
    let spotify_token: std::sync::Arc<std::sync::Mutex<Option<(Option<String>, std::time::Instant)>>> = Default::default();
    let spotify_busy = std::sync::Arc::new(std::sync::atomic::AtomicBool::new(false));
    let rpc_gen = std::sync::Arc::new(std::sync::atomic::AtomicU64::new(0));
    let rpc_names: std::sync::Arc<std::sync::Mutex<std::collections::HashMap<String, String>>> = Default::default();
    let rpc_assets: std::sync::Arc<std::sync::Mutex<std::collections::HashMap<String, String>>> = Default::default();
    // Each application's uploaded pictures (asset key → ID), looked up once.
    let rpc_asset_ids: std::sync::Arc<std::sync::Mutex<std::collections::HashMap<String, std::collections::HashMap<String, String>>>> = Default::default();
    {
        let (user, em) = (rpc_user.clone(), em.clone());
        tokio::spawn(crate::rpc::serve(user, move |e| em.emit(Event::Rpc(e))));
    }

    // Friend-list changes, one at a time and paced (see `relationship_queue`).
    let rel_queue = {
        let (tx, rx) = unbounded_channel::<RelJob>();
        tokio::spawn(relationship_queue(rx, em.clone()));
        tx
    };
    // Messages, one at a time and in order (see `send_queue`).
    let send_queue = {
        let (tx, rx) = unbounded_channel::<SendJob>();
        tokio::spawn(self::send_queue(rx));
        tx
    };

    while let Some(cmd) = rx.recv().await {
        // (This thread's share of the allocator, now and then.)
        crate::diagnostics::release_this_threads_memory();
        match cmd {
            Command::Login { session, account, token } => {
                if let Some(g) = gateway.take() {
                    let _ = g.send(GatewayCommand::Shutdown);
                }
                if let Some(h) = registry.take() {
                    h.abort();
                }
                em = base.for_session(session);
                presence_cache::set_account(account);
                http = Http::new(Some(token.clone()));
                // Show the account as it was last time while the gateway
                // connects (READY for a big account takes a few seconds).
                if let Some(account) = account {
                    let em = em.clone();
                    tokio::task::spawn_blocking(move || {
                        let start = std::time::Instant::now();
                        if let Some(v) = crate::cache::load_ready(account) {
                            log::info!("cache: account snapshot read in {} ms", start.elapsed().as_millis());
                            em.emit(Event::CachedReady(v));
                        }
                    });
                }
                // Dev aid: RUSTCORD_DUMP_API="/a|/b" saves those GET responses
                // as JSON next to the log (for studying Discord's API shapes).
                if let Ok(paths) = crate::diagnostics::dev_var("RUSTCORD_DUMP_API") {
                    let http = http.clone();
                    tokio::spawn(async move {
                        let dir = directories::ProjectDirs::from("dev", "RustCord", "RustCord").map(|d| d.config_dir().join("api-dump"));
                        let Some(dir) = dir else { return };
                        let _ = std::fs::create_dir_all(&dir);
                        for (i, path) in paths.split('|').filter(|p| !p.is_empty()).enumerate() {
                            let body = match http.request(reqwest::Method::GET, path, None).await {
                                Ok(v) => serde_json::to_string_pretty(&v).unwrap_or_default(),
                                Err(e) => format!("error: {e:#}"),
                            };
                            let _ = std::fs::write(dir.join(format!("{i}.json")), body);
                            log::info!("api dump {i}: {path}");
                        }
                    });
                }
                let (gtx, grx) = unbounded_channel();
                let (em2, http2, gtx2) = (em.clone(), http.clone(), gtx.clone());
                tokio::spawn(async move {
                    // Connect with the status you had last time (cached); the
                    // settings themselves come with READY. Without a cache
                    // (first run), read them first, so an invisible account
                    // never flashes online.
                    let presence = match presence_cache::load() {
                        Some(p) => p,
                        None => match tokio::time::timeout(std::time::Duration::from_secs(6), http2.settings_proto()).await {
                            Ok(Ok(s)) => {
                                let p = gateway::presence_payload(&s.status, s.custom_status.as_ref());
                                presence_cache::save(&p);
                                em2.emit(Event::Settings(s));
                                p
                            }
                            Ok(Err(e)) => {
                                log::warn!("settings: couldn't read account settings: {e}");
                                gateway::presence_payload("online", None)
                            }
                            Err(_) => {
                                log::warn!("settings: timed out reading account settings");
                                gateway::presence_payload("online", None)
                            }
                        },
                    };
                    log::info!("gateway: connecting");
                    let sent = presence.clone();
                    let emit = move |e: GatewayEvent| {
                        // Discord retires the old login as it hands over the new
                        // one: every request from here on sends the new one, not
                        // only those after the app has heard of it.
                        if let GatewayEvent::TokenRefreshed(token) = &e {
                            http2.set_token(token.clone());
                        }
                        if let GatewayEvent::Dispatch { name, data } = &e {
                            if name == "READY" {
                                settings_from_ready(data, &sent, &gtx2, &http2, &em2);
                            }
                        }
                        em2.emit(Event::Gateway(e));
                    };
                    gateway::run(token, presence, grx, emit).await;
                });
                gateway = Some(gtx);
            }
            Command::Token(token) => http.set_token(token),
            Command::SetStatus { status, custom } => {
                if let Some(g) = &gateway {
                    let p = gateway::presence_payload(&status, custom.as_ref());
                    presence_cache::save(&p);
                    let mut extra = rpc_extra.lock().map(|e| e.clone()).unwrap_or_default();
                    extra.extend(spotify_now.lock().ok().and_then(|s| s.clone()));
                    let _ = g.send(gateway::presence_update(crate::rpc::compose(&p, &extra)));
                }
                let (http, em) = (http.clone(), em.clone());
                tokio::spawn(async move {
                    if let Err(e) = http.save_status(&status, custom.as_ref()).await {
                        em.emit(Event::Error(format!("Couldn't save your status: {e:#}")));
                    }
                });
            }
            Command::Ack { channel, msg } => {
                let (http, tok) = (http.clone(), ack_token.clone());
                tokio::spawn(async move {
                    let mut guard = tok.lock().await;
                    if let Ok(next) = http.ack(channel, msg, guard.take()).await {
                        *guard = next;
                    }
                });
            }
            Command::AckManual { channel, msg, mentions } => {
                let http = http.clone();
                tokio::spawn(async move {
                    let _ = http.ack_manual(channel, msg, mentions).await;
                });
            }
            Command::SubscribeMembers { guild, channel, windows } => {
                if let Some(g) = &gateway {
                    let _ = g.send(GatewayCommand::Send(member_subscription(guild, channel, windows)));
                }
            }
            Command::SubscribeGuild(guild) => {
                if let Some(g) = &gateway {
                    let _ = g.send(GatewayCommand::Send(guild_subscription(guild)));
                }
            }
            Command::MemberRole { guild, user, role, add } => {
                let (http, em) = (http.clone(), em.clone());
                tokio::spawn(async move {
                    match http.set_member_role(guild, user, role, add).await {
                        Ok(()) => {
                            let result = http.user_profile(user, Some(guild)).await.map_err(|e| format!("{e:#}"));
                            em.emit(Event::Profile { user, guild: Some(guild), result });
                        }
                        Err(e) => em.emit(Event::Error(format!("Couldn't change the role: {e:#}"))),
                    }
                });
            }
            Command::EditChannel { channel, patch } => {
                let (http, em) = (http.clone(), em.clone());
                tokio::spawn(async move {
                    match http.edit_channel(channel, patch).await {
                        Ok(()) => em.emit(Event::Info("Channel saved.".into())),
                        Err(e) => em.emit(Event::Error(format!("Couldn't save the channel: {e:#}"))),
                    }
                });
            }
            Command::DeleteChannel(channel) => {
                let (http, em) = (http.clone(), em.clone());
                tokio::spawn(async move {
                    match http.delete_channel(channel).await {
                        Ok(()) => em.emit(Event::Info("Channel deleted.".into())),
                        Err(e) => em.emit(Event::Error(format!("Couldn't delete the channel: {e:#}"))),
                    }
                });
            }
            Command::CreateChannel { guild, body } => {
                let (http, em) = (http.clone(), em.clone());
                tokio::spawn(async move {
                    match http.create_channel(guild, body).await {
                        Ok(_) => em.emit(Event::Info("Created.".into())),
                        Err(e) => em.emit(Event::Error(format!("Couldn't create it: {e:#}"))),
                    }
                });
            }
            Command::AddServer { request, captcha } => {
                let (http, em) = (http.clone(), em.clone());
                tokio::spawn(async move {
                    use crate::features::AddServerRequest as R;
                    let result = match &request {
                        R::Create(body) => http.create_guild(body, captcha.as_ref()).await,
                        R::Join { code, input, session } => http.join_invite(code, input, session.as_deref(), captcha.as_ref()).await,
                    };
                    let result = result.map_err(|e| format!("{e:#}"));
                    let captcha = result.as_ref().err().and_then(|e| crate::captcha_view::Challenge::from_error(e));
                    // Discord's own words, without "Discord returned 400:".
                    let result = result.map_err(|e| e.split_once(": ").filter(|(head, _)| head.starts_with("Discord returned")).map_or(e.clone(), |(_, why)| why.to_string()));
                    em.emit(Event::AddServer { request, result, captcha });
                });
            }
            Command::CreateInvite { channel, max_age, max_uses, temporary } => {
                let (http, em) = (http.clone(), em.clone());
                tokio::spawn(async move {
                    let result = http.create_invite(channel, max_age, max_uses, temporary).await.map_err(|e| format!("{e:#}"));
                    em.emit(Event::Invite { channel, result });
                });
            }
            Command::SendInvite { user, dm, content, nonce } => {
                let kind = SendKind::Invite { user, dm, content, nonce };
                let _ = send_queue.send(SendJob { http: http.clone(), em: em.clone(), kind });
            }
            Command::GuildSettings { guild, patch } => {
                let (http, em) = (http.clone(), em.clone());
                tokio::spawn(async move {
                    if let Err(e) = http.guild_settings(guild, patch).await {
                        em.emit(Event::Error(format!("Couldn't save the server setting: {e:#}")));
                    }
                });
            }
            Command::AnswerRequest { channel, accept } => {
                let (http, em) = (http.clone(), em.clone());
                tokio::spawn(async move {
                    if let Err(e) = http.answer_message_request(channel, accept).await {
                        em.emit(Event::Error(format!("Couldn't answer the message request: {e:#}")));
                    }
                });
            }
            Command::FetchRequestPreviews(ids) => {
                let (http, em) = (http.clone(), em.clone());
                tokio::spawn(async move {
                    for chunk in ids.chunks(25) {
                        match http.message_request_previews(chunk).await {
                            Ok(p) => em.emit(Event::RequestPreviews(p)),
                            Err(e) => log::warn!("message request previews: {e:#}"),
                        }
                    }
                });
            }
            Command::Ignore { user, on } => {
                let (http, em) = (http.clone(), em.clone());
                tokio::spawn(async move {
                    let result = http.set_ignored(user, on, "User Profile").await.map_err(|e| format!("{e:#}"));
                    em.emit(Event::Ignored { user, on, result });
                });
            }
            Command::FetchApps(ids) => {
                let (http, em) = (http.clone(), em.clone());
                tokio::spawn(async move {
                    for chunk in ids.chunks(20) {
                        let mut apps = http.apps_public(chunk).await.unwrap_or_else(|e| {
                            log::warn!("game info: {e:#}");
                            Vec::new()
                        });
                        // Box art comes from Discord's game database.
                        match http.games(chunk).await {
                            Ok(games) => {
                                for game in games {
                                    match apps.iter_mut().find(|a| a.id == game.id) {
                                        Some(app) => app.game_cover = game.game_cover,
                                        None => apps.push(game),
                                    }
                                }
                            }
                            Err(e) => log::debug!("game covers: {e:#}"),
                        }
                        if !apps.is_empty() {
                            em.emit(Event::Apps(apps));
                        }
                    }
                });
            }
            Command::SendFriendRequest(name) => {
                let (http, em) = (http.clone(), em.clone());
                tokio::spawn(async move {
                    let r = http.send_friend_request(&name).await.map(|_| name).map_err(|e| format!("{e:#}"));
                    em.emit(Event::FriendRequest(r));
                });
            }
            Command::FetchQuests => {
                let (http, em) = (http.clone(), em.clone());
                tokio::spawn(async move {
                    let (quests, orbs) = tokio::join!(http.quests(), http.orb_balance());
                    em.emit(Event::Quests(quests.map(|q| (q, orbs.ok())).map_err(|e| format!("{e:#}"))));
                });
            }
            Command::EnrollQuest { quest, sealed } => {
                let (http, em) = (http.clone(), em.clone());
                tokio::spawn(async move {
                    match http.enroll_quest(quest, sealed.as_deref()).await {
                        Ok(()) => {
                            em.emit(Event::Info("Quest accepted.".into()));
                            let (quests, orbs) = tokio::join!(http.quests(), http.orb_balance());
                            em.emit(Event::Quests(quests.map(|q| (q, orbs.ok())).map_err(|e| format!("{e:#}"))));
                        }
                        Err(e) => em.emit(Event::Error(format!("Couldn't accept the quest: {e:#}"))),
                    }
                });
            }
            Command::FetchShop => {
                let (http, em) = (http.clone(), em.clone());
                tokio::spawn(async move {
                    em.emit(Event::Shop(http.collectibles_shop().await.map_err(|e| format!("{e:#}"))));
                });
            }
            Command::VoiceState { guild, channel, mute, deaf } => {
                voice_where = channel.map(|c| (guild, c, mute, deaf));
                // (Joining, leaving and rejoining all start without the camera: the
                // call that was sending it is over.)
                if std::mem::take(&mut video_on) {
                    em.emit(Event::Camera(Ok(None)));
                }
                if let Some(g) = &gateway {
                    let _ = g.send(GatewayCommand::Send(voice_state(guild, channel, mute, deaf, false)));
                }
            }
            Command::VoiceConnect { gen, user, session_id, token, endpoint, server, channel } => {
                if let Some(old) = call.take() {
                    old.disconnect();
                }
                let cfg = voice::VoiceConfig { user_id: user.0, session_id, token, endpoint, server_id: server.0, channel_id: channel.0 };
                let em2 = em.clone();
                let handle = voice::VoiceHandle::connect(cfg, tokio::runtime::Handle::current(), move |e| em2.emit(Event::Voice(gen, e)));
                if let Some((_, _, mute, deaf)) = voice_where {
                    handle.set_self_mute(mute);
                    handle.set_self_deaf(deaf);
                }
                for (user, volume) in &user_volumes {
                    handle.set_user_volume(*user, *volume);
                }
                if let Some(bitrate) = voice_bitrate {
                    handle.set_bitrate(bitrate);
                }
                // Other people's cameras: the app reads their pictures from here.
                let feeds = handle.camera_feeds();
                feeds.set_wake(em.waker());
                em.emit(Event::CameraFeeds(feeds));
                call = Some(handle);
            }
            Command::RpcUser(user) => {
                if let Ok(mut u) = rpc_user.lock() {
                    *u = user;
                }
            }
            Command::RpcActivities(list) => {
                let gen = rpc_gen.fetch_add(1, std::sync::atomic::Ordering::SeqCst) + 1;
                let (http, gw) = (http.clone(), gateway.clone());
                let (extra_slot, gen_now, names, assets) = (rpc_extra.clone(), rpc_gen.clone(), rpc_names.clone(), rpc_assets.clone());
                let spotify_slot = spotify_now.clone();
                let asset_ids = rpc_asset_ids.clone();
                tokio::spawn(async move {
                    let mut out = Vec::new();
                    for (client_id, activity) in &list {
                        // The application's name ("Playing <name>"), looked up once.
                        let known = names.lock().ok().and_then(|n| n.get(client_id).cloned());
                        let name = match known {
                            Some(n) => n,
                            None => {
                                let n = http
                                    .request(reqwest::Method::GET, &format!("/oauth2/applications/{client_id}/rpc"), None)
                                    .await
                                    .ok()
                                    .and_then(|v| v["name"].as_str().map(String::from))
                                    .unwrap_or_else(|| "a game".to_string());
                                if let Ok(mut m) = names.lock() {
                                    m.insert(client_id.clone(), n.clone());
                                }
                                n
                            }
                        };
                        // Image URLs become Discord "external assets" (mp:external/…).
                        let wanted: Vec<String> = crate::rpc::image_urls(activity).into_iter().filter(|u| assets.lock().map(|a| !a.contains_key(u)).unwrap_or(true)).collect();
                        if !wanted.is_empty() {
                            let body = serde_json::json!({ "urls": wanted });
                            if let Ok(v) = http.request(reqwest::Method::POST, &format!("/applications/{client_id}/external-assets"), Some(body)).await {
                                if let Ok(mut a) = assets.lock() {
                                    for item in v.as_array().into_iter().flatten() {
                                        if let (Some(url), Some(path)) = (item["url"].as_str(), item["external_asset_path"].as_str()) {
                                            a.insert(url.to_string(), format!("mp:{path}"));
                                        }
                                    }
                                }
                            }
                        }
                        let mut map = assets.lock().map(|a| a.clone()).unwrap_or_default();
                        // Pictures named by key ("map_forest"): the gateway wants
                        // the asset's ID, from the application's asset list.
                        if crate::rpc::names_asset_keys(activity) {
                            let known = asset_ids.lock().ok().and_then(|m| m.get(client_id).cloned());
                            let ids = match known {
                                Some(ids) => ids,
                                None => match http.request(reqwest::Method::GET, &format!("/oauth2/applications/{client_id}/assets"), None).await {
                                    Ok(v) => {
                                        let ids = crate::rpc::asset_ids(&v);
                                        if let Ok(mut m) = asset_ids.lock() {
                                            m.insert(client_id.clone(), ids.clone());
                                        }
                                        ids
                                    }
                                    Err(e) => {
                                        log::warn!("rpc: couldn't list application {client_id}'s assets: {e:#}");
                                        Default::default()
                                    }
                                },
                            };
                            map.extend(ids);
                        }
                        out.push(crate::rpc::to_gateway(client_id, &name, activity, &map));
                    }
                    if gen_now.load(std::sync::atomic::Ordering::SeqCst) != gen {
                        return;
                    }
                    if let Ok(mut e) = extra_slot.lock() {
                        *e = out.clone();
                    }
                    out.extend(spotify_slot.lock().ok().and_then(|s| s.clone()));
                    let base = presence_cache::load().unwrap_or_else(|| gateway::presence_payload("online", None));
                    log::info!("rpc: {} activit{} in presence", out.len(), if out.len() == 1 { "y" } else { "ies" });
                    if let Some(g) = gw {
                        let _ = g.send(gateway::presence_update(crate::rpc::compose(&base, &out)));
                    }
                });
            }
            Command::GatewaySend(payload) => {
                if let Some(g) = &gateway {
                    let _ = g.send(GatewayCommand::Send(payload));
                }
            }
            Command::VoiceBitrate(bitrate) => {
                log::info!("voice: sending at the channel's {} kbit/s", bitrate / 1000);
                voice_bitrate = Some(bitrate);
                if let Some(c) = &call {
                    c.set_bitrate(bitrate);
                }
            }
            Command::VoiceUserVolume { user, volume } => {
                if (volume - 1.0).abs() < 0.005 {
                    user_volumes.remove(&user.0);
                } else {
                    user_volumes.insert(user.0, volume);
                }
                if let Some(c) = &call {
                    c.set_user_volume(user.0, volume);
                }
            }
            Command::VoiceDisconnect => {
                if let Some(c) = call.take() {
                    c.disconnect();
                }
                if std::mem::take(&mut video_on) {
                    em.emit(Event::Camera(Ok(None)));
                }
            }
            Command::SpotifyPoll { share, user, fresh } => {
                use std::sync::atomic::Ordering::SeqCst;
                // (A new gateway session knows nothing of what was sent before.)
                if fresh {
                    if let Ok(mut s) = spotify_now.lock() {
                        *s = None;
                    }
                }
                if spotify_busy.swap(true, SeqCst) {
                    continue;
                }
                let (http, gw, busy) = (http.clone(), gateway.clone(), spotify_busy.clone());
                let (slot, cache, games) = (spotify_now.clone(), spotify_token.clone(), rpc_extra.clone());
                tokio::spawn(async move {
                    let now = async {
                        if !share {
                            return None;
                        }
                        // The token lasts an hour; "no Spotify here" is asked again every ten minutes.
                        let cached = cache.lock().ok().and_then(|c| c.clone()).filter(|(token, at)| at.elapsed().as_secs() < if token.is_some() { 45 * 60 } else { 10 * 60 });
                        let token = match cached {
                            Some((token, _)) => token,
                            None => {
                                let token = match http.spotify_status_token().await {
                                    Ok(Some(token)) => {
                                        log::info!("spotify: connected; watching what it plays");
                                        Some(token)
                                    }
                                    Ok(None) => {
                                        log::info!("spotify: not connected to this account, or \"Display Spotify as your status\" is off");
                                        None
                                    }
                                    Err(e) => {
                                        log::warn!("spotify: couldn't get the connection's token: {e:#}");
                                        None
                                    }
                                };
                                if let Ok(mut c) = cache.lock() {
                                    *c = Some((token.clone(), std::time::Instant::now()));
                                }
                                token
                            }
                        }?;
                        match http.spotify_playing(&token).await {
                            Ok(playing) => {
                                let now_ms = std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).map_or(0, |d| d.as_millis() as u64);
                                playing.and_then(|p| crate::rpc::spotify_activity(&p, user.0, now_ms))
                            }
                            Err(e) => {
                                // An expired token is fetched again on the next look; anything
                                // else (offline, rate limit) keeps what was showing.
                                if e.to_string() == "401" {
                                    if let Ok(mut c) = cache.lock() {
                                        *c = None;
                                    }
                                } else {
                                    log::debug!("spotify: currently-playing answered {e:#}");
                                }
                                slot.lock().ok().and_then(|s| s.clone())
                            }
                        }
                    }
                    .await;
                    let changed = match slot.lock() {
                        Ok(mut s) => {
                            let changed = !crate::rpc::spotify_same(s.as_ref(), now.as_ref());
                            if changed {
                                *s = now.clone();
                            }
                            changed
                        }
                        Err(_) => false,
                    };
                    if changed {
                        match &now {
                            Some(a) => log::info!("spotify: listening to a track ({} ms long) in presence", a["timestamps"]["end"].as_u64().unwrap_or(0).saturating_sub(a["timestamps"]["start"].as_u64().unwrap_or(0))),
                            None => log::info!("spotify: nothing playing; removed from presence"),
                        }
                        if let Some(g) = gw {
                            let base = presence_cache::load().unwrap_or_else(|| gateway::presence_payload("online", None));
                            let mut extra = games.lock().map(|e| e.clone()).unwrap_or_default();
                            extra.extend(now);
                            let _ = g.send(gateway::presence_update(crate::rpc::compose(&base, &extra)));
                        }
                    }
                    busy.store(false, SeqCst);
                });
            }
            Command::Camera(device) => {
                let was_on = video_on;
                let result = match device {
                    None => {
                        if let Some(c) = &call {
                            c.set_camera(None);
                        }
                        video_on = false;
                        Ok(None)
                    }
                    Some(device) => {
                        let wake = em.waker();
                        // Opening a camera takes up to a second: off the async threads. A camera
                        // another preview just let go of can need a moment, hence the retries.
                        let opened = tokio::task::spawn_blocking(move || {
                            let device = if device.is_empty() {
                                voice::cameras().into_iter().next().map(|c| c.id).ok_or_else(|| "no camera is connected".to_string())?
                            } else {
                                device
                            };
                            let mut last = String::new();
                            for attempt in 0..3 {
                                if attempt > 0 {
                                    std::thread::sleep(std::time::Duration::from_millis(400));
                                }
                                let wake = wake.clone();
                                match voice::Camera::open(&device, wake) {
                                    Ok(camera) => return Ok(camera),
                                    Err(e) => last = e,
                                }
                            }
                            Err(last)
                        })
                        .await
                        .unwrap_or_else(|_| Err("the camera could not be started".into()));
                        match (opened, &call) {
                            (Ok(camera), Some(c)) => {
                                if c.set_camera(Some(&camera)) {
                                    video_on = true;
                                    Ok(Some(std::sync::Arc::new(camera)))
                                } else {
                                    Err("the call has ended".to_string())
                                }
                            }
                            (Ok(_), None) => Err("you're not connected to voice".to_string()),
                            (Err(e), _) => Err(e),
                        }
                    }
                };
                if video_on != was_on {
                    if let (Some((guild, channel, mute, deaf)), Some(g)) = (voice_where, &gateway) {
                        let _ = g.send(GatewayCommand::Send(voice_state(guild, Some(channel), mute, deaf, video_on)));
                    }
                }
                em.emit(Event::Camera(result));
            }
            Command::VoiceSelfState { mute, deaf } => {
                // The device gates first (what you hear and send changes at once), then one
                // voice state update tells Discord and everyone else.
                if let Some(c) = &call {
                    c.set_self_mute(mute);
                    c.set_self_deaf(deaf);
                }
                if let (Some((guild, channel, _, _)), Some(g)) = (voice_where, &gateway) {
                    voice_where = Some((guild, channel, mute, deaf));
                    let _ = g.send(GatewayCommand::Send(voice_state(guild, Some(channel), mute, deaf, video_on)));
                } else {
                    log::warn!("voice: mute/deafen changed but no voice channel is known to the backend");
                }
            }
            Command::SpotifyPlay { track, position_ms } => {
                let (http, em) = (http.clone(), em.clone());
                tokio::spawn(async move {
                    if let Err(e) = http.spotify_play(&track, position_ms).await {
                        em.emit(Event::Error(format!("Listen Along: {e:#}")));
                    }
                });
            }
            Command::SpotifyPlaylists => {
                let (http, em) = (http.clone(), em.clone());
                tokio::spawn(async move {
                    let result = http
                        .spotify_playlists()
                        .await
                        .map(|list| serde_json::Value::Array(list.into_iter().map(|(n, u)| serde_json::json!([n, u])).collect()))
                        .map_err(|e| format!("{e:#}"));
                    em.emit(Event::Api { tag: "spotify:playlists".into(), result });
                });
            }
            Command::Spotify(request) => {
                let (http, em) = (http.clone(), em.clone());
                tokio::spawn(async move {
                    match request {
                        SpotifyRequest::State => em.emit(Event::SpotifyPlayer(http.spotify_player().await.map_err(|e| format!("{e:#}")))),
                        SpotifyRequest::Playlists => em.emit(Event::SpotifyMyPlaylists(http.spotify_my_playlists().await.map_err(|e| format!("{e:#}")))),
                        SpotifyRequest::Do(cmd) => match http.spotify_command(&cmd).await {
                            Ok(()) => {
                                // Spotify takes a moment to show the change.
                                tokio::time::sleep(std::time::Duration::from_millis(400)).await;
                                em.emit(Event::SpotifyPlayer(http.spotify_player().await.map_err(|e| format!("{e:#}"))));
                            }
                            Err(e) => em.emit(Event::SpotifyFailed(format!("{e:#}"))),
                        },
                    }
                });
            }
            Command::Registry { me, share, invisible } => {
                if let Some(h) = registry.take() {
                    h.abort();
                }
                // Invisible: no hello (it would say you're online), and no bye
                // either (that would take your badge away).
                if !(share && invisible) {
                    registry = Some(tokio::spawn(crate::registry::run(em.clone(), me, share)));
                }
            }
            Command::RegistryLookup(users) => {
                tokio::spawn(crate::registry::ask(em.clone(), users));
            }
            Command::Api { tag, method, path, body } => {
                let (http, em) = (http.clone(), em.clone());
                tokio::spawn(async move {
                    let result = http.request(method, &path, body).await.map_err(|e| format!("{e:#}"));
                    em.emit(Event::Api { tag, result });
                });
            }
            Command::ApiReason { tag, method, path, body, reason } => {
                let (http, em) = (http.clone(), em.clone());
                tokio::spawn(async move {
                    // Header values must be visible ASCII: percent-encode the rest, like Discord's client.
                    let reason: String = reason
                        .bytes()
                        .map(|b| if (0x20..0x7f).contains(&b) && b != b'%' { (b as char).to_string() } else { format!("%{b:02X}") })
                        .collect();
                    let result = http.request_with(method, &path, body, &[("X-Audit-Log-Reason", reason)]).await.map_err(|e| format!("{e:#}"));
                    em.emit(Event::Api { tag, result });
                });
            }
            Command::ApiUpload { tag, path, fields, file } => {
                let (http, em) = (http.clone(), em.clone());
                tokio::spawn(async move {
                    let result = http.upload_form(&path, &fields, file).await.map_err(|e| format!("{e:#}"));
                    em.emit(Event::Api { tag, result });
                });
            }
            Command::ApiRaw { tag, method, path, body } => {
                let (http, em) = (http.clone(), em.clone());
                tokio::spawn(async move {
                    let result = http
                        .request_raw(method, &path, body, &[])
                        .await
                        .map(|(status, body)| serde_json::json!({ "status": status, "body": body }))
                        .map_err(|e| format!("{e:#}"));
                    em.emit(Event::Api { tag, result });
                });
            }
            Command::Account { tag, method, path, body, mfa } => {
                let (http, em) = (http.clone(), em.clone());
                tokio::spawn(async move {
                    let result = account_request(&http, method, &path, body, mfa).await;
                    em.emit(Event::Api { tag, result });
                });
            }

            Command::FetchNitro => {
                let (http, em) = (http.clone(), em.clone());
                tokio::spawn(async move {
                    em.emit(Event::Nitro(http.subscriptions().await.map_err(|e| format!("{e:#}"))));
                });
            }
            Command::LeaveGuild(guild) => {
                let (http, em) = (http.clone(), em.clone());
                tokio::spawn(async move {
                    if let Err(e) = http.leave_guild(guild).await {
                        em.emit(Event::Error(format!("Couldn't leave the server: {e:#}")));
                    }
                });
            }
            Command::LeaveGroup { channel, silent } => {
                let (http, em) = (http.clone(), em.clone());
                tokio::spawn(async move {
                    match http.leave_group(channel, silent).await {
                        Ok(()) => em.emit(Event::GroupLeft(channel)),
                        Err(e) => em.emit(Event::Error(format!("Couldn't leave the group: {e:#}"))),
                    }
                });
            }
            Command::FetchGuildProfile(guild) => {
                let (http, em) = (http.clone(), em.clone());
                tokio::spawn(async move {
                    let result = http.guild_profile(guild).await.map_err(|e| format!("{e:#}"));
                    em.emit(Event::GuildProfile { guild, result });
                });
            }
            Command::StreamCreate { guild, channel } => {
                if let Some(g) = &gateway {
                    let kind = if guild.is_some() { "guild" } else { "call" };
                    let _ = g.send(GatewayCommand::Send(serde_json::json!({
                        "op": 18,
                        "d": { "type": kind, "guild_id": guild.map(|g| g.to_string()), "channel_id": channel.to_string(), "preferred_region": null }
                    })));
                }
            }
            Command::StreamWatch(key) => {
                if let Some(g) = &gateway {
                    let _ = g.send(GatewayCommand::Send(serde_json::json!({ "op": 20, "d": { "stream_key": key } })));
                }
            }
            Command::StreamDelete(key) => {
                if let Some(g) = &gateway {
                    let _ = g.send(GatewayCommand::Send(serde_json::json!({ "op": 19, "d": { "stream_key": key } })));
                }
            }
            Command::StreamSetPaused { key, paused } => {
                if let Some(g) = &gateway {
                    let _ = g.send(GatewayCommand::Send(serde_json::json!({ "op": 22, "d": { "stream_key": key, "paused": paused } })));
                }
            }
            Command::GoLiveConnect { gen, cfg, source, quality, audio } => {
                let (em2, wake) = (em.clone(), em.waker());
                match &call {
                    Some(c) => {
                        let h = c.start_stream(cfg, source, quality, audio, tokio::runtime::Handle::current(), wake, move |e| em2.emit(Event::Stream(gen, e)));
                        em.emit(Event::StreamHandle(gen, Some(std::sync::Arc::new(h)), None));
                    }
                    None => em.emit(Event::Stream(gen, voice::StreamEvent::Disconnected { reason: Some("you're not connected to voice".into()) })),
                }
            }
            Command::WatchConnect { gen, cfg } => {
                let (em2, wake) = (em.clone(), em.waker());
                match &call {
                    Some(c) => {
                        let h = c.watch_stream(cfg, tokio::runtime::Handle::current(), wake, move |e| em2.emit(Event::Stream(gen, e)));
                        em.emit(Event::StreamHandle(gen, None, Some(std::sync::Arc::new(h))));
                    }
                    None => em.emit(Event::Stream(gen, voice::StreamEvent::Disconnected { reason: Some("you're not connected to voice".into()) })),
                }
            }
            Command::SearchMembers { guild, query } => {
                if let Some(g) = &gateway {
                    let _ = g.send(GatewayCommand::Send(serde_json::json!({
                        "op": 8,
                        "d": { "guild_id": guild.to_string(), "query": query, "limit": 25, "presences": false }
                    })));
                }
            }
            Command::RequestMembers { guild, users } => {
                if let Some(g) = &gateway {
                    let ids: Vec<String> = users.iter().map(|u| u.to_string()).collect();
                    let _ = g.send(GatewayCommand::Send(serde_json::json!({
                        "op": 8,
                        "d": { "guild_id": guild.to_string(), "user_ids": ids, "presences": false }
                    })));
                }
            }
            Command::FetchPins(channel) => {
                let (http, em) = (http.clone(), em.clone());
                tokio::spawn(async move {
                    let result = http.pins(channel).await.map_err(|e| format!("{e:#}"));
                    em.emit(Event::Pins { channel, result });
                });
            }
            Command::Search { guild, channel, query, filters } => {
                let (http, em) = (http.clone(), em.clone());
                tokio::spawn(async move {
                    let result = http.search(guild, channel, &filters).await.map_err(|e| format!("{e:#}"));
                    em.emit(Event::Search { query, result });
                });
            }
            Command::FetchMentions => {
                let (http, em) = (http.clone(), em.clone());
                tokio::spawn(async move {
                    em.emit(Event::Mentions(http.mentions().await.map_err(|e| format!("{e:#}"))));
                });
            }
            Command::FetchGifs(query) => {
                let (http, em) = (http.clone(), em.clone());
                tokio::spawn(async move {
                    let result = http.gifs(query.as_deref()).await.map_err(|e| format!("{e:#}"));
                    em.emit(Event::Gifs { query, result });
                });
            }
            Command::Relationship { user, add, location } => {
                let op = if add { RelOp::Add } else { RelOp::Remove };
                let _ = rel_queue.send(RelJob { http: http.clone(), user, op, location: Some(location) });
            }
            Command::AcceptStranger { user } => {
                let _ = rel_queue.send(RelJob { http: http.clone(), user, op: RelOp::AcceptStranger, location: None });
            }
            Command::AddFriendSolved { user, captcha, stranger } => {
                let _ = rel_queue.send(RelJob { http: http.clone(), user, op: RelOp::Solved { captcha, stranger }, location: None });
            }
            Command::Logout { done } => {
                if let Some(g) = gateway.take() {
                    let _ = g.send(GatewayCommand::Shutdown);
                }
                presence_cache::set_account(None);
                tokio::spawn(end_session(std::mem::replace(&mut http, Http::new(None)), done));
                if let Some(h) = registry.take() {
                    h.abort();
                }
            }
            Command::EndSession { token, done } => {
                tokio::spawn(end_session(Http::new(Some(token)), done));
            }
            Command::FetchMessages { channel, before } => {
                let (http, em) = (http.clone(), em.clone());
                tokio::spawn(async move {
                    let result = http.messages(channel, before, 50).await.map_err(|e| format!("{e:#}"));
                    em.emit(Event::Messages { channel, before, result });
                });
            }
            Command::Send(msg) if !msg.uploads.is_empty() => {
                let (http, em) = (http.clone(), em.clone());
                tokio::spawn(async move { send_message(&http, msg, &em).await });
            }
            Command::Send(msg) => {
                let _ = send_queue.send(SendJob { http: http.clone(), em: em.clone(), kind: SendKind::Message(msg) });
            }
            Command::Edit { channel, id, content } => {
                let (http, em) = (http.clone(), em.clone());
                tokio::spawn(async move {
                    if let Err(e) = http.edit_message(channel, id, &content).await {
                        em.emit(Event::Error(format!("Couldn't edit message: {e:#}")));
                    }
                });
            }
            Command::Delete { channel, id } => {
                let (http, em) = (http.clone(), em.clone());
                tokio::spawn(async move {
                    if let Err(e) = http.delete_message(channel, id).await {
                        em.emit(Event::Error(format!("Couldn't delete message: {e:#}")));
                    }
                });
            }
            Command::Typing(channel) => {
                let http = http.clone();
                tokio::spawn(async move {
                    let _ = http.trigger_typing(channel).await;
                });
            }
            Command::React { channel, msg, emoji, add } => {
                let (http, em) = (http.clone(), em.clone());
                tokio::spawn(async move {
                    if let Err(e) = http.react(channel, msg, &emoji, add).await {
                        em.emit(Event::Error(format!("Couldn't update reaction: {e:#}")));
                    }
                });
            }
            Command::Pin { channel, msg, pinned } => {
                let (http, em) = (http.clone(), em.clone());
                tokio::spawn(async move {
                    if let Err(e) = http.set_pinned(channel, msg, pinned).await {
                        em.emit(Event::PinFailed { channel, msg, pinned, error: format!("{e:#}") });
                    }
                });
            }
            Command::FetchProfile { user, guild } => {
                let (http, em) = (http.clone(), em.clone());
                tokio::spawn(async move {
                    let result = http.user_profile(user, guild).await.map_err(|e| format!("{e:#}"));
                    em.emit(Event::Profile { user, guild, result });
                });
            }
            Command::OpenDm(user) => {
                let (http, em) = (http.clone(), em.clone());
                tokio::spawn(async move {
                    match http.open_dm(user).await {
                        Ok(v) => em.emit(Event::DmOpened(v)),
                        Err(e) => em.emit(Event::Error(format!("Couldn't open DM: {e}"))),
                    }
                });
            }
            Command::FetchBytes(url) => {
                let (client, em) = (http.plain_client().clone(), em.clone());
                tokio::spawn(async move {
                    let result = async {
                        let resp = client.get(&url).send().await?.error_for_status()?;
                        Ok::<_, reqwest::Error>(resp.bytes().await?)
                    }
                    .await
                    .map(|b| std::sync::Arc::<[u8]>::from(b.to_vec()))
                    .map_err(|e| e.without_url().to_string());
                    em.emit(Event::Bytes { url, result });
                });
            }
            Command::FetchTheme(url) => spawn_theme_fetch(http.plain_client().clone(), url, em.clone()),
        }
    }
}

pub fn spawn_theme_fetch(client: reqwest::Client, url: String, em: Emitter) {
    tokio::spawn(async move {
        let result = fetch_theme(&client, &url).await;
        em.emit(Event::Theme { source: url, result });
    });
}

/// GitHub "blob" page URLs → raw file URLs.
fn normalize_theme_url(url: &str) -> String {
    let url = url.trim();
    if let Some(rest) = url.strip_prefix("https://github.com/") {
        let parts: Vec<&str> = rest.splitn(4, '/').collect();
        if parts.len() == 4 && parts[2] == "blob" {
            return format!("https://raw.githubusercontent.com/{}/{}/{}", parts[0], parts[1], parts[3]);
        }
    }
    url.to_string()
}

/// A theme file over this size isn't a theme (and isn't read further).
const THEME_MAX_BYTES: usize = 2 * 1024 * 1024;

async fn fetch_text(client: &reqwest::Client, url: &str) -> Result<String, String> {
    if !url.starts_with("https://") {
        return Err("only https:// links are loaded".into());
    }
    let resp = client.get(url).send().await.map_err(|e| e.without_url().to_string())?;
    let mut resp = resp.error_for_status().map_err(|e| e.without_url().to_string())?;
    let mut body = Vec::new();
    while let Some(chunk) = resp.chunk().await.map_err(|e| e.without_url().to_string())? {
        body.extend_from_slice(&chunk);
        if body.len() > THEME_MAX_BYTES {
            return Err(format!("the file is over {} MB, too big for a theme", THEME_MAX_BYTES / (1024 * 1024)));
        }
    }
    Ok(String::from_utf8_lossy(&body).into_owned())
}

/// Fetch a theme and (up to a few levels of) its `@import`s. Imports come
/// first so the theme's own variables override them.
async fn fetch_theme(client: &reqwest::Client, url: &str) -> Result<String, String> {
    let root = fetch_text(client, &normalize_theme_url(url)).await?;
    let mut queue: VecDeque<(String, u8)> = rencord::theme::extract_imports(&root)
        .into_iter()
        .map(|u| (u, 1))
        .collect();
    let mut imported = Vec::new();
    while let Some((u, depth)) = queue.pop_front() {
        if imported.len() >= 12 || u.contains("fonts.googleapis.com") {
            continue;
        }
        if let Ok(css) = fetch_text(client, &u).await {
            if depth < 3 {
                queue.extend(rencord::theme::extract_imports(&css).into_iter().map(|x| (x, depth + 1)));
            }
            imported.push(css);
        }
    }
    imported.reverse();
    imported.push(root);
    Ok(imported.join("\n"))
}

/// An account change; see [`Command::Account`].
async fn account_request(http: &Http, method: reqwest::Method, path: &str, body: Option<serde_json::Value>, mfa: Option<(String, String, String)>) -> Result<serde_json::Value, String> {
    use serde_json::json;
    let mut extra: Vec<(&str, String)> = Vec::new();
    if let Some((ticket, kind, data)) = mfa {
        let (status, v) = http
            .request_raw(reqwest::Method::POST, "/mfa/finish", Some(json!({ "ticket": ticket, "mfa_type": kind, "data": data })), &[])
            .await
            .map_err(|e| format!("{e:#}"))?;
        match v["token"].as_str() {
            Some(token) if status < 300 => extra.push(("X-Discord-MFA-Authorization", token.to_string())),
            _ => return Err(Http::error_message(&v)),
        }
    }
    let (status, v) = http.request_raw(method, path, body, &extra).await.map_err(|e| format!("{e:#}"))?;
    if status < 300 {
        return Ok(v);
    }
    if v["code"].as_u64() == Some(60003) && v["mfa"]["ticket"].is_string() {
        return Ok(json!({ "__mfa": v["mfa"] }));
    }
    Err(Http::error_message(&v))
}