Skip to content

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

36.6 KB
Raw Blame
//! Settings → Connected Apps → Connections, as Discord draws it: the "Add a
//! new connection" grid (Discord's own platform icons, in its order) and one
//! card per linked account.
//!
//! Linking works the way Discord's desktop app does it: RustCord asks Discord
//! for the platform's sign-in address (`GET /connections/{type}/authorize`)
//! and opens it in your browser. Once you've signed in there, Discord's page
//! hands the result back to this session over the gateway
//! (`USER_CONNECTIONS_CALLBACK`), and RustCord finishes the link with
//! `POST /connections/{type}/callback` — only for sign-ins it started itself.
//! Bluesky asks for your handle first; a domain is verified with a DNS record
//! or a file on the site; Riot Games and Battle.net link from their own sites.

use super::settings::switch;
use crate::app::RustCord;
use crate::style::{icon, icon_font, overlay, Theme};
use eframe::egui::{self, load::Bytes, pos2, vec2, Align2, Color32, CursorIcon, FontId, Rect, Sense, Stroke, TextEdit, Ui};
use reqwest::Method;
use serde_json::{json, Value};
use std::collections::HashSet;
use std::sync::Mutex;

/// How a platform links.
#[derive(Clone, Copy, PartialEq)]
enum Flow {
    /// Sign in on the platform's site (opened in the browser).
    Browser,
    /// Asks for your handle first (Bluesky).
    Federated,
    /// Proves you own a domain.
    Domain,
    /// Links from the platform's own site (an app on Discord).
    App(&'static str),
}

/// Discord's "Add a new connection" grid, in its order: (type, name, flow).
const PLATFORMS: &[(&str, &str, Flow)] = &[
    ("riotgames", "Riot Games", Flow::App("1443033465766281327")),
    ("battlenet", "Battle.net", Flow::App("1356665549089800303")),
    ("bluesky", "Bluesky", Flow::Federated),
    ("letterboxd", "Letterboxd", Flow::Browser),
    ("paypal", "PayPal", Flow::Browser),
    ("reddit", "Reddit", Flow::Browser),
    ("ebay", "eBay", Flow::Browser),
    ("crunchyroll", "Crunchyroll", Flow::Browser),
    ("playstation", "PlayStation Network", Flow::Browser),
    ("xbox", "Xbox", Flow::Browser),
    ("amazon-music", "Amazon Music", Flow::Browser),
    ("bungie", "Bungie.net", Flow::Browser),
    ("domain", "Domain", Flow::Domain),
    ("epicgames", "Epic Games", Flow::Browser),
    ("facebook", "Facebook", Flow::Browser),
    ("github", "GitHub", Flow::Browser),
    ("steam", "Steam", Flow::Browser),
    ("twitter", "X", Flow::Browser),
    ("spotify", "Spotify", Flow::Browser),
    ("roblox", "Roblox", Flow::Browser),
    ("twitch", "Twitch", Flow::Browser),
    ("youtube", "YouTube", Flow::Browser),
];

/// Discord's platform icons (from its web client), as the grid shows them.
fn add_icon(kind: &str) -> Option<egui::ImageSource<'static>> {
    let (bytes, ext): (&'static [u8], &str) = match kind {
        "riotgames" => (include_bytes!("../../assets/connections/add/riotgames.png"), "png"),
        "battlenet" => (include_bytes!("../../assets/connections/add/battlenet.png"), "png"),
        "amazon-music" => (include_bytes!("../../assets/connections/add/amazon-music.png"), "png"),
        "bluesky" => (include_bytes!("../../assets/connections/add/bluesky.svg"), "svg"),
        "letterboxd" => (include_bytes!("../../assets/connections/add/letterboxd.svg"), "svg"),
        "paypal" => (include_bytes!("../../assets/connections/add/paypal.svg"), "svg"),
        "reddit" => (include_bytes!("../../assets/connections/add/reddit.svg"), "svg"),
        "ebay" => (include_bytes!("../../assets/connections/add/ebay.svg"), "svg"),
        "crunchyroll" => (include_bytes!("../../assets/connections/add/crunchyroll.svg"), "svg"),
        "playstation" => (include_bytes!("../../assets/connections/add/playstation.svg"), "svg"),
        "xbox" => (include_bytes!("../../assets/connections/add/xbox.svg"), "svg"),
        "bungie" => (include_bytes!("../../assets/connections/add/bungie.svg"), "svg"),
        "domain" => (include_bytes!("../../assets/connections/add/domain.svg"), "svg"),
        "epicgames" => (include_bytes!("../../assets/connections/add/epicgames.svg"), "svg"),
        "facebook" => (include_bytes!("../../assets/connections/add/facebook.svg"), "svg"),
        "github" => (include_bytes!("../../assets/connections/add/github.svg"), "svg"),
        "steam" => (include_bytes!("../../assets/connections/add/steam.svg"), "svg"),
        "twitter" | "x" => (include_bytes!("../../assets/connections/add/twitter.svg"), "svg"),
        "spotify" => (include_bytes!("../../assets/connections/add/spotify.svg"), "svg"),
        "roblox" => (include_bytes!("../../assets/connections/add/roblox.svg"), "svg"),
        "twitch" => (include_bytes!("../../assets/connections/add/twitch.svg"), "svg"),
        "youtube" => (include_bytes!("../../assets/connections/add/youtube.svg"), "svg"),
        _ => return None,
    };
    Some(egui::ImageSource::Bytes { uri: format!("bytes://conn-add-{kind}.{ext}").into(), bytes: Bytes::Static(bytes) })
}

/// A connection's logo: Discord's icon, else the profile one.
pub fn logo(kind: &str) -> Option<egui::ImageSource<'static>> {
    add_icon(kind).or_else(|| super::brand_icons::connection(kind))
}

/// Sign-ins this session started (their `state`), so only those are finished
/// here when Discord hands a code back.
fn pending() -> &'static Mutex<HashSet<String>> {
    static P: std::sync::OnceLock<Mutex<HashSet<String>>> = std::sync::OnceLock::new();
    P.get_or_init(Default::default)
}

/// Platforms that sync your friends list when linked (Discord's list).
fn friend_sync(kind: &str) -> bool {
    matches!(kind, "facebook" | "contacts")
}

/// Open dialogs on this page (kept in egui's memory between frames).
#[derive(Clone, Default)]
struct Dialogs {
    /// Bluesky: the handle typed, an error, waiting.
    handle: Option<(String, Option<String>, bool)>,
    domain: Option<DomainDialog>,
    /// "Unlink {platform}": (type, id).
    unlink: Option<(String, String)>,
}

#[derive(Clone, Default)]
struct DomainDialog {
    domain: String,
    /// Shown once Discord asks for proof.
    proof: Option<String>,
    https: bool,
    error: Option<String>,
    busy: bool,
}

fn dialogs_id() -> egui::Id {
    egui::Id::new("settings_connections_dialogs")
}

/// One of this page's dialogs is open (Settings then leaves Escape and
/// clicks outside to it).
pub(super) fn dialog_open(ctx: &egui::Context) -> bool {
    ctx.data(|d| d.get_temp::<Dialogs>(dialogs_id())).is_some_and(|d| d.handle.is_some() || d.domain.is_some() || d.unlink.is_some())
}

/// Discord's dialog over the settings window: a dimmed screen and the card.
/// (Above Settings, which lifts itself to the top of its layer every frame.)
/// Returns whether the dim was clicked.
fn modal_frame(ctx: &egui::Context, t: &Theme, id: &str, width: f32, body: impl FnOnce(&mut Ui)) -> bool {
    let screen = ctx.screen_rect();
    let dim = egui::Area::new(egui::Id::new((id, "dim"))).order(egui::Order::Tooltip).fixed_pos(screen.min).show(ctx, |ui| {
        let (_, r) = ui.allocate_exact_size(screen.size(), Sense::click());
        ui.painter().rect_filled(screen, 0.0, Color32::from_black_alpha(140));
        r.clicked()
    });
    let area = egui::Area::new(egui::Id::new(id)).order(egui::Order::Tooltip).anchor(Align2::CENTER_CENTER, vec2(0.0, 0.0)).show(ctx, |ui| {
        egui::Frame::none()
            .fill(t.surface_high)
            .rounding(12.0)
            .stroke(Stroke::new(1.0_f32, crate::style::rgba(143, 143, 152, 51)))
            .shadow(egui::Shadow { offset: vec2(0.0, 4.0), blur: 8.0, spread: 0.0, color: Color32::from_black_alpha(41) })
            .show(ui, |ui| {
                ui.set_width(width);
                ui.spacing_mut().item_spacing.y = 0.0;
                body(ui);
            });
    });
    ctx.move_to_top(dim.response.layer_id);
    ctx.move_to_top(area.response.layer_id);
    dim.inner
}

fn query_param(url: &str, key: &str) -> Option<String> {
    url::Url::parse(url).ok()?.query_pairs().find(|(k, _)| k == key).map(|(_, v)| v.into_owned())
}

impl RustCord {
    /// The Connections section of Settings → Connected Apps.
    pub(super) fn connections_section(&mut self, ui: &mut Ui, t: &Theme) {
        let mut dialogs: Dialogs = ui.data(|d| d.get_temp(dialogs_id())).unwrap_or_default();
        self.connection_answers(ui, &mut dialogs);

        // Title and what connections are (Discord: 24/32 500, then 14/18).
        // (The settings sidebar jumps here as this page's first section.)
        super::settings::section(ui, t, 0, "Connections");
        ui.add_space(4.0 - 16.0);
        ui.add(egui::Label::new(egui::RichText::new("These are accounts from other platforms. Connecting them here can unlock new features on Discord, like the ability to share what you're currently listening to, get paid safely and securely, and more.").size(14.0).color(t.text_muted)).wrap());
        ui.add_space(29.0);

        // "Add a new connection": 44 px tiles, 8 apart, wrapping.
        ui.label(egui::RichText::new("Add a new connection").font(crate::style::medium(16.0)).color(t.header_primary));
        ui.add_space(16.0);
        let width = ui.available_width();
        let per_row = (((width + 8.0) / 52.0).floor() as usize).max(1);
        let rows = PLATFORMS.len().div_ceil(per_row);
        let (grid, _) = ui.allocate_exact_size(vec2(width, rows as f32 * 53.0 - 9.0), Sense::hover());
        let mut clicked = None;
        for (i, (kind, name, flow)) in PLATFORMS.iter().enumerate() {
            let tile = Rect::from_min_size(pos2(grid.left() + (i % per_row) as f32 * 52.0, grid.top() + (i / per_row) as f32 * 53.0), vec2(44.0, 44.0));
            let resp = ui.interact(tile, egui::Id::new(("conn_add", *kind)), Sense::click());
            ui.painter().rect_filled(tile, 8.0, overlay(if resp.hovered() { 0.2 } else { 0.12 }));
            ui.painter().rect_stroke(tile.shrink(0.5), 8.0, Stroke::new(1.0_f32, overlay(0.04)));
            if let Some(src) = add_icon(kind) {
                egui::Image::new(src).paint_at(ui, Rect::from_center_size(tile.center(), vec2(28.0, 28.0)));
            }
            if resp.on_hover_cursor(CursorIcon::PointingHand).on_hover_text(*name).clicked() {
                clicked = Some((*kind, *flow));
            }
        }
        if let Some((kind, flow)) = clicked {
            match flow {
                Flow::Browser => self.start_connection(kind, None),
                Flow::Federated => dialogs.handle = Some((String::new(), None, false)),
                Flow::Domain => dialogs.domain = Some(DomainDialog::default()),
                Flow::App(app) => self.open_app_connection(ui, kind, app),
            }
        }
        // Riot Games and Battle.net link from their own sites: where, Discord
        // says in their app's details.
        if !self.demo {
            let ids: Vec<&str> = PLATFORMS.iter().filter_map(|p| if let Flow::App(a) = p.2 { Some(a) } else { None }).collect();
            self.api_get_once("conn:apps", format!("/applications/public?{}", ids.iter().map(|a| format!("application_ids={a}")).collect::<Vec<_>>().join("&")));
        }

        // Your connections.
        let list = match self.api_results.get("us:connections") {
            Some(Ok(Value::Array(a))) => a.clone(),
            Some(Err(e)) => {
                ui.add_space(32.0);
                ui.label(egui::RichText::new(format!("Couldn't load your connections: {e}")).color(t.danger));
                Vec::new()
            }
            _ => {
                ui.add_space(32.0);
                ui.spinner();
                Vec::new()
            }
        };
        let hide = self.prefs.streaming_hides(|p| p.streamer_hide_personal);
        if !list.is_empty() {
            ui.add_space(32.0);
            ui.label(egui::RichText::new(format!("{} connection{}", list.len(), if list.len() == 1 { "" } else { "s" })).font(egui::FontId::new(16.0, egui::FontFamily::Name(crate::style::BOLD.into()))).color(t.header_primary));
            ui.add_space(24.0);
            if hide {
                ui.label(egui::RichText::new("Hidden while Streamer Mode is on.").size(14.0).color(t.text_muted));
            }
        }
        let mut patch: Option<(String, String, Value)> = None;
        for c in list.iter().filter(|_| !hide) {
            if let Some(p) = self.connection_card(ui, t, c, &mut dialogs) {
                patch = Some(p);
            }
            ui.add_space(24.0);
        }
        if let Some((kind, id, body)) = patch {
            if let Some(Ok(Value::Array(a))) = self.api_results.get_mut("us:connections") {
                for c in a.iter_mut().filter(|c| c["id"].as_str() == Some(id.as_str()) && c["type"].as_str() == Some(kind.as_str())) {
                    if let (Some(c), Some(b)) = (c.as_object_mut(), body.as_object()) {
                        for (k, v) in b {
                            c.insert(k.clone(), v.clone());
                        }
                    }
                }
            }
            self.api("us:conn-patch", Method::PATCH, format!("/users/@me/connections/{kind}/{}", urlencoding(&id)), Some(body));
        }

        self.connection_dialogs(ui, t, &mut dialogs);
        ui.data_mut(|d| d.insert_temp(dialogs_id(), dialogs));
    }

    /// Answers to this page's requests.
    fn connection_answers(&mut self, ui: &Ui, dialogs: &mut Dialogs) {
        if let Some(Err(e)) = self.api_take("us:conn-patch") {
            self.toast(format!("Couldn't change that connection: {e}"), true);
        }
        for (kind, name, _) in PLATFORMS {
            let Some(result) = self.api_take(&format!("conn:auth:{kind}")) else { continue };
            match result {
                Ok(v) => {
                    let Some(url) = v["url"].as_str().filter(|u| u.starts_with("https://")) else {
                        self.toast(format!("Discord didn't say where to sign in to {name}."), true);
                        continue;
                    };
                    if let (Some(state), Ok(mut p)) = (query_param(url, "state"), pending().lock()) {
                        p.insert(state);
                    }
                    ui.ctx().open_url(egui::OpenUrl::new_tab(url));
                    if *kind == "bluesky" {
                        dialogs.handle = None;
                    }
                }
                Err(e) if *kind == "bluesky" => {
                    log::info!("connections: bluesky authorize failed: {e}");
                    if let Some(h) = dialogs.handle.as_mut() {
                        h.1 = Some("An unknown error occurred. Maybe check your handle?".into());
                        h.2 = false;
                    }
                }
                Err(e) => self.toast(format!("Couldn't connect {name}: {e}"), true),
            }
        }
        if let Some(Err(e)) = self.api_take("conn:callback") {
            self.toast(format!("Couldn't finish linking that account: {e}"), true);
        }
        if let Some(Err(e)) = self.api_take("conn:delete") {
            self.toast(format!("Couldn't unlink that account: {e}"), true);
            self.api_results.remove("us:connections");
        }
        if let Some(Err(e)) = self.api_take("conn:refresh") {
            self.toast(format!("Couldn't refresh that connection: {e}"), true);
        }
        if let Some(result) = self.api_take("conn:domain") {
            if let Some(d) = dialogs.domain.as_mut() {
                d.busy = false;
                match result {
                    Ok(v) => {
                        let status = v["status"].as_u64().unwrap_or(0);
                        if (200..300).contains(&status) {
                            dialogs.domain = None;
                            self.api_results.remove("us:connections");
                        } else if let (None, Some(proof)) = (&d.proof, v["body"]["proof"].as_str()) {
                            d.proof = Some(proof.to_string());
                            d.error = None;
                        } else {
                            let body = &v["body"];
                            let msg = body["errors"]["domain"]["_errors"][0]["message"].as_str().map(String::from).unwrap_or_else(|| discord::http::Http::error_message(body));
                            d.error = Some(msg);
                        }
                    }
                    Err(e) => d.error = Some(e),
                }
            }
        }
    }

    /// Ask Discord where to sign in, then open it (see the module notes).
    fn start_connection(&mut self, kind: &str, handle: Option<&str>) {
        let mut path = format!("/connections/{kind}/authorize");
        if let Some(h) = handle {
            path.push_str(&format!("?handle={}", urlencoding(h)));
        }
        self.api(&format!("conn:auth:{kind}"), Method::GET, path, None);
    }

    /// Riot Games / Battle.net: their own linking page, from their app's details.
    fn open_app_connection(&mut self, ui: &Ui, kind: &str, app: &str) {
        let url = match self.api_results.get("conn:apps") {
            Some(Ok(Value::Array(apps))) => apps.iter().find(|a| a["id"].as_str() == Some(app)).and_then(|a| a["connection_entrypoint_url"].as_str()).map(String::from),
            _ => None,
        };
        match url.filter(|u| u.starts_with("https://")) {
            Some(u) => ui.ctx().open_url(egui::OpenUrl::new_tab(u)),
            // Not known (yet): the classic connection sign-in.
            None => self.start_connection(kind, None),
        }
    }

    /// Discord handed back a finished sign-in (gateway USER_CONNECTIONS_CALLBACK).
    pub fn connection_callback(&mut self, d: &Value) {
        let (Some(provider), Some(state)) = (d["provider"].as_str(), d["state"].as_str()) else { return };
        // Only sign-ins started here (another client finishes its own).
        if !pending().lock().is_ok_and(|mut p| p.remove(state)) {
            return;
        }
        if !provider.chars().all(|c| c.is_ascii_alphanumeric() || c == '-') {
            return;
        }
        let body = json!({
            "code": d["code"],
            "state": state,
            "openid_params": d["openid_params"],
            "insecure": false,
            "friend_sync": friend_sync(provider),
        });
        self.api("conn:callback", Method::POST, format!("/connections/{provider}/callback"), Some(body));
    }

    /// One linked account: Discord's card. Returns a setting changed on it.
    fn connection_card(&mut self, ui: &mut Ui, t: &Theme, c: &Value, dialogs: &mut Dialogs) -> Option<(String, String, Value)> {
        let kind = c["type"].as_str().unwrap_or("").to_string();
        let id = c["id"].as_str().unwrap_or("").to_string();
        let name = c["name"].as_str().unwrap_or("").to_string();
        let platform = super::brand_icons::platform_name(&kind);
        let meta_lines = if c["revoked"].as_bool() == Some(true) { Vec::new() } else { super::brand_icons::metadata_lines(c.get("metadata")) };
        let mut changed = None;
        egui::Frame::none().fill(overlay(0.12)).stroke(Stroke::new(1.0_f32, t.border_subtle)).rounding(8.0).inner_margin(egui::Margin::same(17.0)).show(ui, |ui| {
            ui.set_width(ui.available_width());
            ui.spacing_mut().item_spacing.y = 0.0;
            // Header: logo 32, name 16/20 600, platform 12/16, the unlink ✕.
            let (head, _) = ui.allocate_exact_size(vec2(ui.available_width(), 36.0), Sense::hover());
            if let Some(src) = logo(&kind) {
                egui::Image::new(src).paint_at(ui, Rect::from_min_size(pos2(head.left(), head.top() + 2.0), vec2(32.0, 32.0)));
            }
            let text_w = head.width() - 48.0 - 32.0;
            let painter = ui.painter_at(Rect::from_min_size(pos2(head.left() + 48.0, head.top()), vec2(text_w, 36.0)));
            painter.text(pos2(head.left() + 48.0, head.top() + 10.0), Align2::LEFT_CENTER, &name, FontId::new(16.0, egui::FontFamily::Name(crate::style::BOLD.into())), t.header_primary);
            painter.text(pos2(head.left() + 48.0, head.top() + 28.0), Align2::LEFT_CENTER, &platform, FontId::proportional(12.0), t.text_normal);
            let x = Rect::from_min_size(pos2(head.right() - 24.0, head.top() + 9.0), vec2(16.0, 16.0));
            let xr = ui.interact(x.expand(4.0), egui::Id::new(("conn_unlink", &kind, &id)), Sense::click());
            ui.painter().text(x.center(), Align2::CENTER_CENTER, icon::CLOSE, icon_font(12.0), if xr.hovered() { t.header_primary } else { t.text_muted });
            if xr.on_hover_cursor(CursorIcon::PointingHand).on_hover_text("Disconnect").clicked() {
                dialogs.unlink = Some((kind.clone(), id.clone()));
            }
            ui.add_space(20.0);

            // What Discord knows about the account, with "Refresh".
            if !meta_lines.is_empty() {
                egui::Frame::none().fill(overlay(0.08)).stroke(Stroke::new(1.0_f32, overlay(0.04))).rounding(8.0).inner_margin(egui::Margin::same(8.0)).show(ui, |ui| {
                    ui.set_width(ui.available_width());
                    ui.horizontal(|ui| {
                        ui.set_height(32.0);
                        ui.add_space(4.0);
                        let stats = meta_lines.iter().rev().cloned().collect::<Vec<_>>().join("    ");
                        ui.label(egui::RichText::new(stats).size(12.0).color(t.text_muted));
                        ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| {
                            let b = ui.add(egui::Button::new(egui::RichText::new("Refresh").font(crate::style::medium(14.0)).color(t.header_primary)).fill(overlay(0.12)).rounding(8.0).min_size(vec2(60.0, 32.0)));
                            if b.clicked() {
                                self.api("conn:refresh", Method::POST, format!("/users/@me/connections/{kind}/{}/refresh", urlencoding(&id)), None);
                            }
                        });
                    });
                });
                ui.add_space(20.0);
            }

            // Switches: 24 tall rows, 20 apart.
            let mut rows: Vec<(&str, String, bool, Value)> = Vec::new();
            let visible = c["visibility"].as_u64().unwrap_or(0) == 1;
            rows.push(("visibility", "Display on profile".into(), visible, json!(if visible { 0 } else { 1 })));
            if kind == "spotify" {
                let on = c["show_activity"].as_bool().unwrap_or(false);
                rows.push(("show_activity", "Display Spotify as your status".into(), on, json!(!on)));
            }
            if !meta_lines.is_empty() || c.get("metadata_visibility").is_some_and(|v| !v.is_null()) && !c["metadata"].is_null() {
                let on = c["metadata_visibility"].as_u64().unwrap_or(0) == 1;
                rows.push(("metadata_visibility", "Display details on profile".into(), on, json!(if on { 0 } else { 1 })));
            }
            let n = rows.len();
            for (i, (key, label, on, flipped)) in rows.into_iter().enumerate() {
                ui.horizontal(|ui| {
                    ui.set_height(24.0);
                    ui.label(egui::RichText::new(label).font(crate::style::medium(16.0)).color(t.header_primary));
                    ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| {
                        let mut v = on;
                        if switch(ui, t, &mut v).changed() {
                            changed = Some((kind.clone(), id.clone(), json!({ key: flipped })));
                        }
                    });
                });
                if i + 1 < n {
                    ui.add_space(20.0);
                }
            }
        });
        changed
    }

    /// Bluesky's handle, the domain proof and "Unlink" dialogs.
    fn connection_dialogs(&mut self, ui: &mut Ui, t: &Theme, dialogs: &mut Dialogs) {
        let ctx = ui.ctx().clone();
        // Unlink {platform}?
        if let Some((kind, id)) = dialogs.unlink.clone() {
            let platform = super::brand_icons::platform_name(&kind);
            let (mut cancel, mut unlink) = (false, false);
            let dim = modal_frame(&ctx, t, "conn_unlink_modal", 440.0, |ui| {
                egui::Frame::none().inner_margin(egui::Margin::same(24.0)).show(ui, |ui| {
                    ui.label(egui::RichText::new(format!("Unlink {platform}")).font(FontId::new(20.0, egui::FontFamily::Name(crate::style::BOLD.into()))).color(t.header_primary));
                    ui.add_space(8.0);
                    ui.add(egui::Label::new(egui::RichText::new(format!("You will no longer be able to access features of the \"{platform}\" connection on your Discord account. You will also be removed from servers that require it.")).size(16.0).color(t.text_muted)).wrap());
                    ui.add_space(24.0);
                    let (c, u) = dialog_buttons(ui, t, "Cancel", "Unlink", true, false);
                    cancel = c;
                    unlink = u;
                });
            });
            if unlink {
                self.api("conn:delete", Method::DELETE, format!("/users/@me/connections/{kind}/{}", urlencoding(&id)), None);
                if let Some(Ok(Value::Array(a))) = self.api_results.get_mut("us:connections") {
                    a.retain(|c| !(c["type"].as_str() == Some(kind.as_str()) && c["id"].as_str() == Some(id.as_str())));
                }
            }
            if cancel || unlink || dim || ctx.input(|i| i.key_pressed(egui::Key::Escape)) {
                dialogs.unlink = None;
            }
        }

        // Connect your Bluesky Account.
        if let Some((mut handle, error, busy)) = dialogs.handle.clone() {
            let (mut cancel, mut next) = (false, false);
            let valid = handle_ok(&handle);
            let dim = modal_frame(&ctx, t, "conn_handle_modal", 440.0, |ui| {
                egui::Frame::none().inner_margin(egui::Margin::same(24.0)).show(ui, |ui| {
                    dialog_title(ui, t, "Connect your Bluesky Account", Some("Verify your Bluesky account and show it off on your profile!"));
                    ui.add_space(20.0);
                    let enter = field(ui, t, "Handle", &mut handle, "example.bsky.social", error.as_deref(), !busy);
                    ui.add_space(24.0);
                    let (c, n) = dialog_buttons(ui, t, "Cancel", "Next", valid && !busy, busy);
                    cancel = c;
                    next = n || (enter && valid && !busy);
                });
            });
            if next {
                self.start_connection("bluesky", Some(handle.trim()));
                dialogs.handle = Some((handle, None, true));
            } else if cancel || dim || ctx.input(|i| i.key_pressed(egui::Key::Escape)) {
                dialogs.handle = None;
            } else {
                dialogs.handle = Some((handle, error, busy));
            }
        }

        // Connect your Domain: the domain, then the proof to put on it.
        if let Some(mut d) = dialogs.domain.clone() {
            let (mut cancel, mut next, mut switch_way) = (false, false, false);
            let dim = modal_frame(&ctx, t, "conn_domain_modal", 440.0, |ui| {
                egui::Frame::none().inner_margin(egui::Margin::same(24.0)).show(ui, |ui| {
                    match d.proof.clone() {
                        None => {
                            dialog_title(ui, t, "Connect your Domain", Some("Verify ownership of your domain and show it off on your profile!"));
                            ui.add_space(20.0);
                            let enter = field(ui, t, "Domain", &mut d.domain, "example.com", d.error.as_deref(), !d.busy);
                            ui.add_space(24.0);
                            let (c, n) = dialog_buttons(ui, t, "Cancel", "Next", !d.busy, d.busy);
                            cancel = c;
                            next = n || (enter && !d.busy);
                        }
                        Some(proof) => {
                            dialog_title(ui, t, "Connect your Domain", None);
                            if let Some(e) = &d.error {
                                ui.add_space(12.0);
                                notice(ui, t, e, true);
                            }
                            ui.add_space(20.0);
                            let domain = d.domain.trim().to_string();
                            if d.https {
                                ui.label(egui::RichText::new("Create a new file on your website:").size(16.0).color(t.text_normal));
                                ui.add_space(12.0);
                                copy_field(ui, t, "Name", &format!("https://{domain}/.well-known/discord"));
                                ui.add_space(12.0);
                                copy_field(ui, t, "Content", &proof);
                            } else {
                                ui.label(egui::RichText::new("1.  Sign in to your domain name provider").size(16.0).color(t.text_normal));
                                ui.add_space(8.0);
                                ui.label(egui::RichText::new("2.  Create a new DNS record:").size(16.0).color(t.text_normal));
                                ui.add_space(12.0);
                                copy_field(ui, t, "Name", &format!("_discord.{domain}"));
                                ui.add_space(12.0);
                                copy_field(ui, t, "Type", "TXT");
                                ui.add_space(12.0);
                                copy_field(ui, t, "Content", &proof);
                                ui.add_space(16.0);
                                notice(ui, t, "It may take a few minutes for the DNS record to propagate.", false);
                            }
                            ui.add_space(24.0);
                            ui.horizontal(|ui| {
                                let other = if d.https { "Verify using DNS" } else { "Verify using HTTPS" };
                                if ui.add(egui::Button::new(egui::RichText::new(other).font(crate::style::medium(14.0)).color(t.text_link)).frame(false)).on_hover_cursor(egui::CursorIcon::PointingHand).clicked() {
                                    switch_way = true;
                                }
                                ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| {
                                    if primary(ui, "Verify", !d.busy, d.busy).clicked() {
                                        next = true;
                                    }
                                });
                            });
                        }
                    }
                });
            });
            if switch_way {
                d.https = !d.https;
                d.error = None;
            }
            if next {
                let domain = d.domain.trim().trim_end_matches('/').to_lowercase();
                if domain.is_empty() {
                    d.error = Some("This field is required.".into());
                } else {
                    d.busy = true;
                    d.error = None;
                    self.api_raw("conn:domain", Method::POST, format!("/users/@me/connections/domain/{}", urlencoding(&domain)), Some(json!({})));
                }
            }
            dialogs.domain = if cancel || dim || ctx.input(|i| i.key_pressed(egui::Key::Escape)) { None } else { Some(d) };
        }
    }
}

/// Discord's check before it lets you go on with a handle.
fn handle_ok(h: &str) -> bool {
    let h = h.trim();
    match h.rsplit_once('.') {
        Some((head, tld)) => !head.is_empty() && tld.chars().count() >= 2 && !tld.contains('@'),
        None => false,
    }
}

fn urlencoding(s: &str) -> String {
    url::form_urlencoded::byte_serialize(s.as_bytes()).collect()
}

fn dialog_title(ui: &mut Ui, t: &Theme, title: &str, subtitle: Option<&str>) {
    ui.label(egui::RichText::new(title).font(FontId::new(20.0, egui::FontFamily::Name(crate::style::BOLD.into()))).color(t.header_primary));
    if let Some(s) = subtitle {
        ui.add_space(8.0);
        ui.add(egui::Label::new(egui::RichText::new(s).size(16.0).color(t.text_muted)).wrap());
    }
}

/// A labelled text box. True when Enter was pressed in it.
fn field(ui: &mut Ui, t: &Theme, label: &str, value: &mut String, hint: &str, error: Option<&str>, enabled: bool) -> bool {
    ui.label(egui::RichText::new(label).font(crate::style::medium(16.0)).color(t.header_primary));
    ui.add_space(8.0);
    let stroke = if error.is_some() { t.danger } else { t.border_subtle };
    let mut enter = false;
    egui::Frame::none().fill(t.input_bg).stroke(Stroke::new(1.0_f32, stroke)).rounding(8.0).inner_margin(egui::Margin::symmetric(12.0, 11.0)).show(ui, |ui| {
        let r = ui.add_enabled(
            enabled,
            TextEdit::singleline(value).hint_text(egui::RichText::new(hint).color(t.text_muted)).frame(false).font(FontId::proportional(16.0)).desired_width(f32::INFINITY),
        );
        if !r.has_focus() && value.is_empty() && enabled {
            r.request_focus();
        }
        enter = r.lost_focus() && ui.input(|i| i.key_pressed(egui::Key::Enter));
    });
    if let Some(e) = error {
        ui.add_space(8.0);
        ui.label(egui::RichText::new(e).size(14.0).color(t.danger));
    }
    enter
}

/// A value to copy (the domain proof): its label, the text, "Copy".
fn copy_field(ui: &mut Ui, t: &Theme, label: &str, value: &str) {
    ui.label(egui::RichText::new(label).font(crate::style::medium(14.0)).color(t.header_primary));
    ui.add_space(8.0);
    egui::Frame::none().fill(t.input_bg).stroke(Stroke::new(1.0_f32, t.border_subtle)).rounding(8.0).inner_margin(egui::Margin::symmetric(12.0, 4.0)).show(ui, |ui| {
        ui.set_width(ui.available_width());
        ui.horizontal(|ui| {
            ui.set_height(32.0);
            let copied_id = egui::Id::new(("conn_copied", label));
            ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| {
                let copied = ui.data(|d| d.get_temp::<f64>(copied_id)).is_some_and(|at| ui.input(|i| i.time) - at < 2.0);
                let fill = if copied { Color32::from_rgb(0x24, 0x80, 0x46) } else { crate::style::rgba(0x58, 0x65, 0xf2, 255) };
                let b = ui.add(egui::Button::new(egui::RichText::new(if copied { "Copied" } else { "Copy" }).font(crate::style::medium(14.0)).color(Color32::WHITE)).fill(fill).rounding(8.0).min_size(vec2(64.0, 32.0)));
                if b.clicked() {
                    ui.ctx().copy_text(value.to_string());
                    let now = ui.input(|i| i.time);
                    ui.data_mut(|d| d.insert_temp(copied_id, now));
                }
                ui.with_layout(egui::Layout::left_to_right(egui::Align::Center), |ui| {
                    ui.add(egui::Label::new(egui::RichText::new(value).size(16.0).color(t.text_normal)).truncate());
                });
            });
        });
    });
}

/// Discord's inline notice (info, or critical in red).
fn notice(ui: &mut Ui, t: &Theme, text: &str, critical: bool) {
    let (fill, line) = if critical { (crate::style::rgba(218, 62, 68, 26), t.danger) } else { (crate::style::rgba(88, 101, 242, 26), crate::style::rgba(0x58, 0x65, 0xf2, 255)) };
    egui::Frame::none().fill(fill).stroke(Stroke::new(1.0_f32, line)).rounding(8.0).inner_margin(egui::Margin::symmetric(12.0, 10.0)).show(ui, |ui| {
        ui.set_width(ui.available_width());
        ui.add(egui::Label::new(egui::RichText::new(text).size(14.0).color(t.text_normal)).wrap());
    });
}

fn primary(ui: &mut Ui, label: &str, enabled: bool, busy: bool) -> egui::Response {
    let brand = crate::style::rgba(0x58, 0x65, 0xf2, 255);
    let text = if busy { "…" } else { label };
    ui.add_enabled(enabled, egui::Button::new(egui::RichText::new(text).font(crate::style::medium(14.0)).color(Color32::WHITE)).fill(brand).rounding(8.0).min_size(vec2(96.0, 38.0))).on_hover_cursor(egui::CursorIcon::PointingHand)
}

/// Cancel (secondary) and the action, on the right. (cancelled, confirmed)
fn dialog_buttons(ui: &mut Ui, t: &Theme, cancel: &str, action: &str, enabled: bool, busy: bool) -> (bool, bool) {
    let (mut c, mut a) = (false, false);
    ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| {
        a = primary(ui, action, enabled, busy).clicked();
        ui.add_space(8.0);
        c = ui.add(egui::Button::new(egui::RichText::new(cancel).font(crate::style::medium(14.0)).color(t.header_primary)).fill(overlay(0.12)).rounding(8.0).min_size(vec2(96.0, 38.0))).on_hover_cursor(egui::CursorIcon::PointingHand).clicked();
    });
    (c, a)
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn handles_like_discord_accepts() {
        assert!(handle_ok("example.bsky.social"));
        assert!(handle_ok("me.com"));
        assert!(!handle_ok("example"));
        assert!(!handle_ok("example.c"));
        assert!(!handle_ok(".com"));
    }

    #[test]
    fn state_is_read_from_the_sign_in_address() {
        assert_eq!(query_param("https://github.com/login/oauth/authorize?client_id=1&state=abc%3D&scope=x", "state").as_deref(), Some("abc="));
        assert_eq!(query_param("not a url", "state"), None);
    }

    #[test]
    fn every_grid_platform_has_its_icon() {
        for (kind, _, _) in PLATFORMS {
            assert!(add_icon(kind).is_some(), "{kind}");
        }
    }
}