Skip to content

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

44.6 KB
Raw Blame
//! Server Settings → Access, Enable Community / Community Overview and
//! Server Insights.
//!
//! Community choices save the moment they're made (like Safety Setup);
//! Access and the server description have a Save, like Discord. The server object is
//! the cached GET /guilds/{g} (`tag_guild`), kept fresh by the PATCH
//! helpers in `ss_safety.rs`.

use super::safety_pages::{dialog, features_with, first_frame, has_feature, heading, option_card, patch_guild, release_escape, run};
use super::{btn, chan_job, combo, divider, help, icon_button, input, link, notice, section, tag_guild, tag_roles, title, vbool, vid, vstr, vu64, Act, Btn, ChanOpt, Theme};
use crate::app::RustCord;
use crate::style::{bold, icon, icon_font};
use discord::model::{channel_kind, Id};
use eframe::egui::{
    self, epaint::Shadow, pos2, vec2, Align, Align2, Color32, CursorIcon, FontId, Frame, Layout, Margin, Rect, RichText, Sense, Stroke, Ui,
    UiBuilder, WidgetText,
};
use reqwest::Method;
use serde_json::{json, Value};

/// Stands in for a channel id when "Create one for me" is picked: Discord
/// makes the channel itself.
const CREATE: Id = Id(1);

/// Open this server on discord.com, for what RustCord doesn't show.
fn open_on_web(app: &mut RustCord, g: Id) {
    app.ctx.open_url(egui::OpenUrl::new_tab(format!("https://discord.com/channels/{g}")));
    app.toast("Opened this server on discord.com: RustCord doesn't have that screen yet.", false);
}

// ---- Access ----------------------------------------------------------------------------------------

/// The label Discord gives the rules field of its member verification form.
const RULES_LABEL: &str = "Read and agree to the server rules";
/// Discord: up to 16 rules of 300 characters.
const MAX_RULES: usize = 16;
const RULE_LEN: usize = 300;
const EXAMPLE_RULES: [&str; 4] = ["Be civil and respectful", "No spam or self-promotion", "No age-restricted or obscene content", "Help keep things safe"];
/// Discord: up to 5 application questions.
const MAX_QUESTIONS: usize = 5;
const QUESTION_LEN: usize = 300;
const MAX_CHOICES: usize = 8;
const FIRST_QUESTION: &str = "Why do you want to join our server?";
/// Question kinds: (field_type, Discord's name for it).
const QUESTION_KINDS: [(&str, &str); 3] = [("TEXT_INPUT", "Short Answer"), ("PARAGRAPH", "Paragraph"), ("MULTIPLE_CHOICE", "Multiple Choice")];

/// What GET member-verification gives a server that never had a form.
static NO_FORM: Value = Value::Null;

/// How people join: Discord's three choices.
#[derive(Clone, Copy, PartialEq, Eq)]
enum JoinMode {
    Invite,
    Apply,
    Discoverable,
}

/// One Join Application question.
#[derive(Clone, PartialEq)]
struct Question {
    kind: String,
    label: String,
    required: bool,
    choices: Vec<String>,
    /// The field as Discord sent it: keys RustCord doesn't edit ride along.
    raw: Value,
}

impl Question {
    fn new(label: &str) -> Self {
        Self { kind: "TEXT_INPUT".into(), label: label.into(), required: true, choices: Vec::new(), raw: Value::Null }
    }

    fn from_value(v: &Value) -> Self {
        Self {
            kind: vstr(v, "field_type").to_string(),
            label: vstr(v, "label").to_string(),
            required: v["required"].as_bool().unwrap_or(true),
            choices: v["choices"].as_array().into_iter().flatten().filter_map(Value::as_str).map(String::from).collect(),
            raw: v.clone(),
        }
    }

    fn to_value(&self) -> Value {
        let mut v = if self.raw.is_object() { self.raw.clone() } else { json!({}) };
        v["field_type"] = json!(self.kind);
        v["label"] = json!(self.label.trim());
        v["required"] = json!(self.required);
        if self.kind == "MULTIPLE_CHOICE" {
            v["choices"] = json!(clean(&self.choices));
        } else if let Some(o) = v.as_object_mut() {
            o.remove("choices");
        }
        v
    }
}

/// The page's settings: as saved, or as edited.
#[derive(Clone, PartialEq)]
struct AccessDraft {
    mode: JoinMode,
    /// "Server Rules": members agree to the rules before chatting.
    gate: bool,
    rules: Vec<String>,
    questions: Vec<Question>,
}

impl AccessDraft {
    /// What Discord has: the join mode and gate from the server's features,
    /// rules and questions from its member verification form.
    fn saved(v: &Value, form: &Value) -> Self {
        let mode = if has_feature(v, "MEMBER_VERIFICATION_MANUAL_APPROVAL") {
            JoinMode::Apply
        } else if has_feature(v, "DISCOVERABLE") {
            JoinMode::Discoverable
        } else {
            JoinMode::Invite
        };
        let fields = form["form_fields"].as_array().map(Vec::as_slice).unwrap_or(&[]);
        Self {
            mode,
            gate: has_feature(v, "MEMBER_VERIFICATION_GATE_ENABLED"),
            rules: form_rules(form),
            questions: fields.iter().filter(|f| f["field_type"] != "TERMS").map(Question::from_value).collect(),
        }
    }
}

#[derive(Clone, Default)]
struct AccessUi {
    /// The settings as edited; None until loaded (and after a save).
    draft: Option<AccessDraft>,
    new_rule: String,
    /// The form PATCH that goes once the features PATCH is through.
    queued: Option<Value>,
}

fn access_id(g: Id) -> egui::Id {
    egui::Id::new(("ss_access", g.0))
}
fn tag_verification(g: Id) -> String {
    format!("ss:member-verification:{g}")
}
fn tag_verification_save(g: Id) -> String {
    format!("ss:member-verification-save:{g}")
}
/// The features PATCH (DISCOVERABLE on / off) of an Access save.
fn tag_access_features(g: Id) -> String {
    format!("ss:access-features:{g}")
}
/// The server again after a form save: Discord switches its join
/// features (MEMBER_VERIFICATION_MANUAL_APPROVAL…) from the form itself.
fn tag_access_guild(g: Id) -> String {
    format!("ss:access-guild:{g}")
}

/// Start the page again from what Discord has.
fn access_reload(app: &mut RustCord, g: Id) {
    app.ctx.data_mut(|d| {
        let s = d.get_temp_mut_or_default::<AccessUi>(access_id(g));
        s.draft = None;
        s.queued = None;
    });
}

fn send_form(app: &mut RustCord, g: Id, body: Value) {
    app.api(&tag_verification_save(g), Method::PATCH, format!("/guilds/{g}/member-verification"), Some(body));
}

/// Trimmed, blank ones dropped.
fn clean(list: &[String]) -> Vec<String> {
    list.iter().map(|r| r.trim().to_string()).filter(|r| !r.is_empty()).collect()
}

/// The rules in a member verification form (its TERMS field).
fn form_rules(form: &Value) -> Vec<String> {
    form["form_fields"]
        .as_array()
        .into_iter()
        .flatten()
        .find(|f| f["field_type"] == "TERMS")
        .map(|f| f["values"].as_array().into_iter().flatten().filter_map(Value::as_str).map(String::from).collect())
        .unwrap_or_default()
}

fn terms_field(rules: &[String]) -> Value {
    json!({ "field_type": "TERMS", "label": RULES_LABEL, "values": rules, "required": true })
}

/// What a save sends, like Discord's client: (the new features list if
/// DISCOVERABLE changes, the member-verification PATCH if the form
/// changes), or the reason it can't be saved.
fn access_plan(v: &Value, saved: &AccessDraft, d: &AccessDraft) -> Result<(Option<Value>, Option<Value>), &'static str> {
    let discoverable = has_feature(v, "DISCOVERABLE");
    let rules = clean(&d.rules);
    let features = match d.mode {
        JoinMode::Discoverable if !discoverable => Some(features_with(v, &["DISCOVERABLE"], &[])),
        JoinMode::Invite | JoinMode::Apply if discoverable => Some(features_with(v, &[], &["DISCOVERABLE"])),
        _ => None,
    };
    let form = match d.mode {
        JoinMode::Apply => {
            let questions: Vec<&Question> = d.questions.iter().filter(|q| !q.label.trim().is_empty()).collect();
            if questions.is_empty() {
                return Err("Add a non-server rules question to enable Apply to Join.");
            }
            if questions.iter().any(|q| q.kind == "MULTIPLE_CHOICE" && clean(&q.choices).is_empty()) {
                return Err("Give each multiple choice question at least one choice.");
            }
            let mut fields: Vec<Value> = Vec::new();
            if !rules.is_empty() {
                fields.push(terms_field(&rules));
            }
            fields.extend(questions.iter().map(|q| q.to_value()));
            Some(json!({ "form_fields": fields, "enabled": true }))
        }
        _ => {
            if d.gate && rules.is_empty() {
                return Err("You need to add one or more rules.");
            }
            // Leaving Apply to Join drops the questions.
            let changed = rules != clean(&saved.rules) || d.gate != saved.gate || saved.mode == JoinMode::Apply;
            let fields = if rules.is_empty() { json!([]) } else { json!([terms_field(&rules)]) };
            changed.then(|| json!({ "form_fields": fields, "enabled": d.gate }))
        }
    };
    Ok((features, form))
}

impl RustCord {
    pub(super) fn ss_access(&self, ui: &mut Ui, t: &Theme, acts: &mut Vec<Act>, g: Id) {
        title(ui, t, "Access");
        let sid = access_id(g);
        let mut st: AccessUi = ui.data(|d| d.get_temp(sid)).unwrap_or_default();
        if first_frame(ui, "access", g) {
            st = AccessUi::default();
            acts.push(run(move |app| app.api(&tag_verification(g), Method::GET, format!("/guilds/{g}/member-verification?with_guild=false"), None)));
        }
        let queued = st.queued.clone();
        self.on_answer(acts, tag_access_features(g), move |app, r| {
            match r {
                Ok(v) => {
                    app.ss_guild_changed(g, v);
                    match queued {
                        Some(body) => send_form(app, g, body),
                        None => access_reload(app, g),
                    }
                }
                Err(e) => app.toast(format!("Couldn't change how people join: {e}"), true),
            }
            app.ctx.data_mut(|d| d.get_temp_mut_or_default::<AccessUi>(access_id(g)).queued = None);
        });
        self.on_answer(acts, tag_verification_save(g), move |app, r| match r {
            Ok(form) => {
                app.api_results.insert(tag_verification(g), Ok(form));
                app.api(&tag_access_guild(g), Method::GET, format!("/guilds/{g}"), None);
            }
            Err(e) => app.toast(format!("Couldn't save the join settings: {e}"), true),
        });
        self.on_answer(acts, tag_access_guild(g), move |app, r| {
            if let Ok(v) = r {
                app.ss_guild_changed(g, v);
            }
            access_reload(app, g);
        });
        self.ss_access_body(ui, t, acts, g, &mut st);
        ui.data_mut(|d| d.insert_temp(sid, st));
    }

    fn ss_access_body(&self, ui: &mut Ui, t: &Theme, acts: &mut Vec<Act>, g: Id, st: &mut AccessUi) {
        let (gtag, gpath) = (tag_guild(g), format!("/guilds/{g}"));
        self.ss_want(acts, gtag.clone(), gpath.clone());
        let Some(v) = self.ss_loaded(ui, t, &gtag, &gpath, acts) else { return };
        let (vtag, vpath) = (tag_verification(g), format!("/guilds/{g}/member-verification?with_guild=false"));
        // No form yet answers 404: that's an empty one.
        let form = match self.api_result(&vtag) {
            Some(Err(e)) if e.contains("404") => &NO_FORM,
            _ => match self.ss_loaded(ui, t, &vtag, &vpath, acts) {
                Some(form) => form,
                None => return,
            },
        };
        let saved = AccessDraft::saved(v, form);
        let busy = st.queued.is_some()
            || [tag_access_features(g), tag_verification_save(g), tag_access_guild(g)].iter().any(|tag| self.api_busy(tag));
        let community = has_feature(v, "COMMUNITY");
        let d = st.draft.get_or_insert_with(|| saved.clone());
        let new_rule = &mut st.new_rule;
        ui.add_enabled_ui(!busy, |ui| {
            join_mode(ui, t, d, community);
            if d.mode == JoinMode::Apply {
                divider(ui, t);
                questions(ui, t, g, &mut d.questions);
            }
            divider(ui, t);
            rules_editor(ui, t, g, d, new_rule);
        });

        if *d != saved {
            let (save, reset) = save_bar(ui, t, busy);
            if reset {
                *d = saved;
            } else if save {
                match access_plan(v, &saved, d) {
                    Ok((Some(features), form)) => {
                        st.queued = form;
                        let body = json!({ "features": features });
                        acts.push(run(move |app| app.api(&tag_access_features(g), Method::PATCH, format!("/guilds/{g}"), Some(body))));
                    }
                    Ok((None, Some(form))) => acts.push(run(move |app| send_form(app, g, form))),
                    // Only blank lines changed: nothing to send.
                    Ok((None, None)) => *d = saved,
                    Err(why) => acts.push(run(move |app| app.toast(why, true))),
                }
            }
        }
    }
}

/// "How can people join your server?"
fn join_mode(ui: &mut Ui, t: &Theme, d: &mut AccessDraft, community: bool) {
    heading(ui, t, "How can people join your server?");
    help(ui, t, "Keep your server private or open it up for more people to join.");
    ui.add_space(12.0);
    if option_card(ui, t, "Invite Only", "People can join your server directly with an invite", d.mode == JoinMode::Invite, true).clicked() {
        d.mode = JoinMode::Invite;
    }
    if option_card(ui, t, "Apply to Join", "People must submit an application and be approved to join", d.mode == JoinMode::Apply, true).clicked() {
        d.mode = JoinMode::Apply;
        // Discord starts an application with this question.
        if d.questions.is_empty() {
            d.questions.push(Question::new(FIRST_QUESTION));
        }
    }
    let resp = option_card(ui, t, "Discoverable", "Anyone can join your server directly through Server Discovery", d.mode == JoinMode::Discoverable, community);
    if !community {
        resp.on_hover_text("Only Community servers can be discoverable. Enable Community first.");
    } else if resp.clicked() {
        d.mode = JoinMode::Discoverable;
    }
}

/// Apply to Join: the application's questions.
fn questions(ui: &mut Ui, t: &Theme, g: Id, list: &mut Vec<Question>) {
    heading(ui, t, "Join Application");
    help(
        ui,
        t,
        "Add questions to your application. People don't join your server until you approve their application. You'll have the option to DM applicants before approving or denying them.",
    );
    ui.add_space(16.0);
    section(ui, t, &format!("QUESTIONS ({}/{MAX_QUESTIONS})", list.len()));
    let mut remove = None;
    for (i, q) in list.iter_mut().enumerate() {
        Frame::none().fill(t.bg_secondary).rounding(8.0).inner_margin(Margin::same(12.0)).show(ui, |ui| {
            ui.set_width(ui.available_width());
            ui.horizontal(|ui| {
                let kind = QUESTION_KINDS.iter().find(|(k, _)| *k == q.kind).map_or("Short Answer", |(_, name)| *name);
                combo(ui, &format!("ss_question_kind_{i}"), 180.0, WidgetText::from(kind), |ui| {
                    for (k, name) in QUESTION_KINDS {
                        if ui.selectable_label(q.kind == k, name).clicked() {
                            q.kind = k.to_string();
                        }
                    }
                });
                ui.add_space(8.0);
                super::super::toggle_switch(ui, &mut q.required, t);
                ui.label(RichText::new("Required").size(14.0).color(t.text_normal));
                ui.with_layout(Layout::right_to_left(Align::Center), |ui| {
                    if icon_button(ui, t, icon::CLOSE, true).on_hover_text("Remove question").clicked() {
                        remove = Some(i);
                    }
                });
            });
            ui.add_space(8.0);
            let w = ui.available_width();
            input(ui, t, egui::Id::new(("ss_question", g.0, i)), &mut q.label, "Enter a question", 1, QUESTION_LEN, w);
            if q.kind == "MULTIPLE_CHOICE" {
                ui.add_space(8.0);
                let mut drop = None;
                for (j, choice) in q.choices.iter_mut().enumerate() {
                    ui.horizontal(|ui| {
                        input(ui, t, egui::Id::new(("ss_question_choice", g.0, i, j)), choice, "Enter a choice", 1, 100, w - 40.0);
                        if icon_button(ui, t, icon::CLOSE, true).on_hover_text("Remove choice").clicked() {
                            drop = Some(j);
                        }
                    });
                    ui.add_space(6.0);
                }
                if let Some(j) = drop {
                    q.choices.remove(j);
                }
                if q.choices.len() < MAX_CHOICES && link(ui, "Add a choice", t.text_link).clicked() {
                    q.choices.push(String::new());
                }
            }
        });
        ui.add_space(8.0);
    }
    if let Some(i) = remove {
        list.remove(i);
    }
    if list.len() < MAX_QUESTIONS && btn(ui, t, Btn::Secondary, "Add a question", true).clicked() {
        list.push(Question::new(""));
    }
}

/// "Server Rules": the switch (not for Apply to Join, where the rules are
/// part of the application) and the rules.
fn rules_editor(ui: &mut Ui, t: &Theme, g: Id, d: &mut AccessDraft, new_rule: &mut String) {
    let desc = "Members must agree to rules before they can chat or interact in the server.";
    if d.mode == JoinMode::Apply {
        heading(ui, t, "Server Rules");
        help(ui, t, desc);
        ui.add_space(12.0);
    } else {
        super::switch_row(ui, t, "Server Rules", Some(desc), &mut d.gate);
    }
    let rules = &mut d.rules;
    let w = ui.available_width();
    let mut remove = None;
    for (i, rule) in rules.iter_mut().enumerate() {
        ui.horizontal(|ui| {
            let (r, _) = ui.allocate_exact_size(vec2(24.0, 36.0), Sense::hover());
            ui.painter().text(r.center(), Align2::CENTER_CENTER, format!("{}", i + 1), super::bold_font(15.0), t.header_primary);
            input(ui, t, egui::Id::new(("ss_rule", g.0, i)), rule, "Enter a rule", 1, RULE_LEN, w - 70.0);
            if icon_button(ui, t, icon::CLOSE, true).on_hover_text("Remove").clicked() {
                remove = Some(i);
            }
        });
        ui.add_space(6.0);
    }
    if let Some(i) = remove {
        rules.remove(i);
    }
    if rules.len() < MAX_RULES {
        ui.horizontal(|ui| {
            ui.add_space(24.0 + ui.spacing().item_spacing.x);
            let resp = input(ui, t, egui::Id::new(("ss_new_rule", g.0)), new_rule, "Enter a rule", 1, RULE_LEN, w - 160.0);
            let typed = !new_rule.trim().is_empty();
            let enter = resp.lost_focus() && ui.input(|i| i.key_pressed(egui::Key::Enter));
            if (btn(ui, t, Btn::Secondary, "Add a rule", typed).clicked() || enter) && typed {
                rules.push(new_rule.trim().to_string());
                new_rule.clear();
            }
        });
    }
    if rules.is_empty() {
        ui.add_space(16.0);
        section(ui, t, "EXAMPLE RULES");
        ui.horizontal_wrapped(|ui| {
            for example in EXAMPLE_RULES {
                if btn(ui, t, Btn::Secondary, example, true).on_hover_text("Add this rule").clicked() {
                    rules.push(example.to_string());
                }
            }
        });
    }
}

/// Discord's "Careful — you have unsaved changes!" bar, floating at the
/// bottom of the page. Returns (Save Changes, Reset) clicks.
fn save_bar(ui: &mut Ui, t: &Theme, saving: bool) -> (bool, bool) {
    let x = ui.max_rect().x_range();
    let bottom = ui.clip_rect().bottom();
    let bar = Rect::from_min_max(pos2(x.min - 10.0, bottom - 72.0), pos2(x.max + 10.0, bottom - 20.0));
    let shadow = Shadow { offset: vec2(0.0, 6.0), blur: 20.0, spread: 0.0, color: Color32::from_black_alpha(120) };
    ui.painter().add(shadow.as_shape(bar, 8.0));
    ui.painter().rect(bar, 8.0, t.bg_secondary, Stroke::new(1.0_f32, t.border_subtle));
    // Clicks on the bar don't reach the page under it.
    ui.interact(bar, egui::Id::new("ss_access_save_bar"), Sense::click());
    ui.painter_at(bar.shrink(4.0)).text(pos2(bar.left() + 16.0, bar.center().y), Align2::LEFT_CENTER, "Careful — you have unsaved changes!", super::bold_font(15.0), t.header_primary);
    let mut bui = ui.new_child(UiBuilder::new().max_rect(bar.shrink2(vec2(10.0, 8.0))).layout(Layout::right_to_left(Align::Center)));
    let save = btn(&mut bui, t, Btn::Success, if saving { "Saving…" } else { "Save Changes" }, !saving).clicked();
    bui.add_space(4.0);
    let reset = link(&mut bui, "Reset", t.text_normal).clicked() && !saving;
    (save, reset)
}

// ---- Enable Community / Community Overview ---------------------------------------------------------

/// Permissions "Remove moderation permissions from @everyone" takes away:
/// Administrator, Kick, Ban, Manage Channels / Server / Messages /
/// Nicknames / Roles / Webhooks / Expressions / Events / Threads,
/// Mention @everyone and Timeout Members.
const MOD_PERMS: u64 = 1 << 1
    | 1 << 2
    | 1 << 3
    | 1 << 4
    | 1 << 5
    | 1 << 13
    | 1 << 17
    | 1 << 27
    | 1 << 28
    | 1 << 29
    | 1 << 30
    | 1 << 33
    | 1 << 34
    | 1 << 40;

/// Discord's server languages: (locale, name).
const LOCALES: &[(&str, &str)] = &[
    ("id", "Indonesian"),
    ("da", "Danish"),
    ("de", "German"),
    ("en-GB", "English, UK"),
    ("en-US", "English, US"),
    ("es-ES", "Spanish"),
    ("es-419", "Spanish, LATAM"),
    ("fr", "French"),
    ("hr", "Croatian"),
    ("it", "Italian"),
    ("lt", "Lithuanian"),
    ("hu", "Hungarian"),
    ("nl", "Dutch"),
    ("no", "Norwegian"),
    ("pl", "Polish"),
    ("pt-BR", "Portuguese, Brazilian"),
    ("ro", "Romanian, Romania"),
    ("fi", "Finnish"),
    ("sv-SE", "Swedish"),
    ("vi", "Vietnamese"),
    ("tr", "Turkish"),
    ("cs", "Czech"),
    ("el", "Greek"),
    ("bg", "Bulgarian"),
    ("ru", "Russian"),
    ("uk", "Ukrainian"),
    ("hi", "Hindi"),
    ("th", "Thai"),
    ("zh-CN", "Chinese, China"),
    ("ja", "Japanese"),
    ("zh-TW", "Chinese, Taiwan"),
    ("ko", "Korean"),
];

/// The "Enable Community" dialog's answers.
#[derive(Clone)]
struct Setup {
    /// 0 safety checks, 1 basics, 2 finishing touches.
    step: u8,
    email: bool,
    scan: bool,
    rules: Option<Id>,
    updates: Option<Id>,
    mentions_only: bool,
    strip_perms: bool,
    agree: bool,
}

#[derive(Clone, Default)]
struct CommunityUi {
    setup: Option<Setup>,
    confirm_disable: bool,
    /// The server description as edited; None until shown.
    description: Option<String>,
}

fn community_id(g: Id) -> egui::Id {
    egui::Id::new(("ss_community", g.0))
}
fn tag_everyone_perms(g: Id) -> String {
    format!("ss:community-perms:{g}")
}

impl RustCord {
    pub(super) fn ss_community(&self, ui: &mut Ui, t: &Theme, acts: &mut Vec<Act>, g: Id) {
        let sid = community_id(g);
        let mut st: CommunityUi = ui.data(|d| d.get_temp(sid)).unwrap_or_default();
        if first_frame(ui, "community", g) {
            st = CommunityUi::default();
        }
        self.poll_guild_patch(acts, g);
        self.on_answer(acts, tag_everyone_perms(g), move |app, r| match r {
            Ok(role) => {
                app.ss_list_upsert(&tag_roles(g), &role);
                app.store.upsert_role(&json!({ "guild_id": g.to_string(), "role": role }));
            }
            Err(e) => app.toast(format!("Couldn't change @everyone's permissions: {e}"), true),
        });
        let (gtag, gpath) = (tag_guild(g), format!("/guilds/{g}"));
        self.ss_want(acts, gtag.clone(), gpath.clone());
        let community = self.api_result(&gtag).and_then(|r| r.as_ref().ok()).is_some_and(|v| has_feature(v, "COMMUNITY"));
        title(ui, t, if community { "Community Overview" } else { "Enable Community" });
        if let Some(v) = self.ss_loaded(ui, t, &gtag, &gpath, acts) {
            if community {
                // Set up just now: the dialog has done its job.
                st.setup = None;
                self.ss_community_overview(ui, t, acts, g, v, &mut st);
            } else {
                st.confirm_disable = false;
                self.ss_community_intro(ui, t, acts, g, v, &mut st);
            }
        }
        if st.setup.is_none() && !st.confirm_disable {
            release_escape(ui, "community_setup");
            release_escape(ui, "community_disable");
        }
        ui.data_mut(|d| d.insert_temp(sid, st));
    }

    /// Discord's "Are you building a Community?" page.
    fn ss_community_intro(&self, ui: &mut Ui, t: &Theme, acts: &mut Vec<Act>, g: Id, v: &Value, st: &mut CommunityUi) {
        ui.vertical_centered(|ui| {
            ui.add_space(12.0);
            ui.label(bold("Are you building a Community?").size(24.0).color(t.header_primary));
            ui.add_space(8.0);
            ui.label(
                RichText::new("Convert to a Community Server to access additional administrative tools that help you moderate and grow your server.").size(15.0).color(t.text_muted),
            );
            ui.add_space(20.0);
            if btn(ui, t, Btn::Primary, "Enable Community", st.setup.is_none()).clicked() {
                st.setup = Some(Setup {
                    step: 0,
                    email: vu64(v, "verification_level") >= 1,
                    scan: vu64(v, "explicit_content_filter") == 2,
                    rules: vid(v, "rules_channel_id"),
                    updates: vid(v, "public_updates_channel_id"),
                    mentions_only: true,
                    strip_perms: true,
                    agree: false,
                });
            }
        });
        divider(ui, t);
        help(ui, t, "Community Servers are larger spaces where people with shared interests can come together.");
        ui.add_space(16.0);
        for (glyph, name, desc) in [
            (icon::SEARCH, "Grow your community", "Apply to be in Server Discovery so more people can find your server directly on Discord."),
            (icon::PEOPLE, "Keep members engaged", "Access tools like Server Insights that can better help you moderate and keep your server engaged."),
            (icon::BELL, "Stay informed", "Get direct updates about new features built for communities from Discord."),
        ] {
            Frame::none().fill(t.bg_secondary).rounding(8.0).inner_margin(Margin::same(16.0)).show(ui, |ui| {
                ui.set_width(ui.available_width());
                ui.horizontal_top(|ui| {
                    let (r, _) = ui.allocate_exact_size(vec2(40.0, 40.0), Sense::hover());
                    ui.painter().circle_filled(r.center(), 20.0, t.accent);
                    ui.painter().text(r.center(), Align2::CENTER_CENTER, glyph, icon_font(18.0), egui::Color32::WHITE);
                    ui.add_space(8.0);
                    ui.vertical(|ui| {
                        ui.label(bold(name).size(16.0).color(t.header_primary));
                        ui.add_space(4.0);
                        ui.label(RichText::new(desc).size(14.0).color(t.text_muted));
                    });
                });
            });
            ui.add_space(8.0);
        }
        ui.add_space(8.0);
        help(ui, t, "Enabling Community does not make your server visible on Server Discovery.");
        if st.setup.is_some() {
            self.ss_community_setup(ui, t, acts, g, v, st);
        }
    }

    /// The three-step "Enable Community" dialog.
    fn ss_community_setup(&self, ui: &mut Ui, t: &Theme, acts: &mut Vec<Act>, g: Id, v: &Value, st: &mut CommunityUi) {
        let Some(s) = st.setup.as_mut() else { return };
        let text = self.ss_guild_channels(g, |k| k == channel_kind::GUILD_TEXT);
        let saving = self.guild_saving(g);
        let step = s.step;
        let ready = match step {
            0 => s.email && s.scan,
            1 => s.rules.is_some() && s.updates.is_some(),
            _ => s.agree,
        };
        let level = vu64(v, "verification_level");
        let filter = vu64(v, "explicit_content_filter");
        let (mut back, mut next) = (false, false);
        let close = dialog(
            ui,
            t,
            "community_setup",
            480.0,
            |ui| {
                ui.label(bold(format!("STEP {} OF 3", step + 1)).size(12.0).color(t.text_muted));
                ui.add_space(6.0);
                match step {
                    0 => {
                        ui.label(bold("Safety checks").size(20.0).color(t.header_primary));
                        ui.add_space(6.0);
                        help(ui, t, "Community servers need these settings to help keep members safe.");
                        ui.add_space(16.0);
                        check_row(ui, t, "Verified email required", "Members of the server must have a verified email on their Discord account before they can send messages or direct message anyone in this server.", &mut s.email, level < 1);
                        check_row(ui, t, "Scan media content from all members", "Discord will automatically scan and delete media sent in this server that contains explicit content.", &mut s.scan, filter < 2);
                    }
                    1 => {
                        ui.label(bold("Set up basics").size(20.0).color(t.header_primary));
                        ui.add_space(16.0);
                        section(ui, t, "RULES OR GUIDELINES CHANNEL");
                        help(ui, t, "Post the rules or guidelines of your server here.");
                        ui.add_space(8.0);
                        setup_channel(ui, t, "ss_setup_rules", &mut s.rules, &text);
                        ui.add_space(16.0);
                        section(ui, t, "COMMUNITY UPDATES CHANNEL");
                        help(ui, t, "Discord sends updates for moderators of Community servers here.");
                        ui.add_space(8.0);
                        setup_channel(ui, t, "ss_setup_updates", &mut s.updates, &text);
                    }
                    _ => {
                        ui.label(bold("Finishing touches").size(20.0).color(t.header_primary));
                        ui.add_space(16.0);
                        check_row(ui, t, "Default notifications to only @mentions", "Members who haven't set their own notification settings are only notified when they're @mentioned.", &mut s.mentions_only, true);
                        check_row(ui, t, "Remove moderation permissions from @everyone", "Permissions like Administrator, Manage Server, Kick and Ban Members are taken away from @everyone.", &mut s.strip_perms, true);
                        check_row(ui, t, "I agree and understand", "Community servers must follow Discord's Community Guidelines.", &mut s.agree, true);
                        if link(ui, "Community Guidelines", t.text_link).clicked() {
                            acts.push(Act::OpenUrl("https://discord.com/guidelines"));
                        }
                    }
                }
            },
            |ui| {
                let label = match (step, saving) {
                    (2, true) => "Saving…",
                    (2, false) => "Finish Setup",
                    _ => "Next",
                };
                if btn(ui, t, Btn::Primary, label, ready && !saving).clicked() {
                    next = true;
                }
                if step > 0 {
                    ui.add_space(8.0);
                    if link(ui, "Back", t.text_normal).clicked() && !saving {
                        back = true;
                    }
                }
            },
        );
        if back {
            s.step -= 1;
        } else if next && step < 2 {
            s.step += 1;
        } else if next {
            let s = s.clone();
            self.ss_enable_community(acts, g, v, &s);
        }
        if close && !saving {
            st.setup = None;
        }
    }

    /// "Finish Setup": the server becomes a Community server.
    fn ss_enable_community(&self, acts: &mut Vec<Act>, g: Id, v: &Value, s: &Setup) {
        let (Some(rules), Some(updates)) = (s.rules, s.updates) else { return };
        let mut body = json!({
            "features": features_with(v, &["COMMUNITY"], &[]),
            "rules_channel_id": rules.to_string(),
            "public_updates_channel_id": updates.to_string(),
            "verification_level": vu64(v, "verification_level").max(1),
            "explicit_content_filter": 2,
        });
        if s.mentions_only {
            body["default_message_notifications"] = json!(1);
        }
        patch_guild(acts, g, body);
        let everyone = self.store.guilds.get(&g).and_then(|gs| gs.guild.roles.iter().find(|r| r.id == g)).map(|r| r.permission_bits());
        if let Some(perms) = everyone.filter(|p| s.strip_perms && p & MOD_PERMS != 0) {
            let body = json!({ "permissions": (perms & !MOD_PERMS).to_string() });
            acts.push(run(move |app| app.api(&tag_everyone_perms(g), Method::PATCH, format!("/guilds/{g}/roles/{g}"), Some(body))));
        }
    }

    /// A Community server's channels, language, description, and the way out.
    fn ss_community_overview(&self, ui: &mut Ui, t: &Theme, acts: &mut Vec<Act>, g: Id, v: &Value, st: &mut CommunityUi) {
        help(ui, t, "Community servers get tools that help moderate the server and keep members informed.");
        ui.add_space(20.0);
        let busy = self.guild_saving(g);
        let text = self.ss_guild_channels(g, |k| k == channel_kind::GUILD_TEXT);
        for (key, label, desc, combo_id) in [
            ("rules_channel_id", "RULES OR GUIDELINES CHANNEL", "Members see this channel's rules or guidelines.", "ss_community_rules"),
            ("public_updates_channel_id", "COMMUNITY UPDATES CHANNEL", "Discord sends updates for moderators of Community servers here.", "ss_community_updates"),
        ] {
            section(ui, t, label);
            help(ui, t, desc);
            ui.add_space(8.0);
            let current = vid(v, key);
            let mut pick = current;
            ui.add_enabled_ui(!busy, |ui| pick_channel(ui, t, combo_id, &mut pick, &text, None));
            if pick != current {
                patch_guild(acts, g, json!({ key: super::opt_id(pick) }));
            }
            ui.add_space(20.0);
        }

        divider(ui, t);
        self.ss_activity_alerts(ui, t, acts, g, v);

        divider(ui, t);
        heading(ui, t, "Primary Language");
        help(ui, t, "Server Discovery and Discord's messages to this server use this language.");
        ui.add_space(8.0);
        let locale = vstr(v, "preferred_locale");
        let shown = LOCALES.iter().find(|(l, _)| *l == locale).map_or(locale, |(_, n)| *n);
        ui.add_enabled_ui(!busy, |ui| {
            combo(ui, "ss_community_locale", 320.0, WidgetText::from(shown), |ui| {
                for &(l, name) in LOCALES {
                    if ui.selectable_label(l == locale, name).clicked() && l != locale {
                        patch_guild(acts, g, json!({ "preferred_locale": l }));
                    }
                }
            });
        });

        divider(ui, t);
        heading(ui, t, "Server Description");
        help(ui, t, "How did your server get started? Why should people join? Shown in Server Discovery and invites.");
        ui.add_space(8.0);
        let saved = vstr(v, "description");
        let draft = st.description.get_or_insert_with(|| saved.to_string());
        let w = ui.available_width();
        input(ui, t, egui::Id::new(("ss_community_description", g.0)), draft, "Tell people what your server is about", 3, 120, w);
        if draft.trim() != saved {
            ui.add_space(8.0);
            ui.horizontal(|ui| {
                if btn(ui, t, Btn::Success, if busy { "Saving…" } else { "Save Changes" }, !busy).clicked() {
                    let d = draft.trim();
                    patch_guild(acts, g, json!({ "description": if d.is_empty() { Value::Null } else { json!(d) } }));
                }
                if link(ui, "Reset", t.text_normal).clicked() {
                    *draft = saved.to_string();
                }
            });
        }

        divider(ui, t);
        heading(ui, t, "Disable Community");
        help(ui, t, "Turns off Community features like Server Insights and Server Discovery. Your channels and settings stay.");
        ui.add_space(12.0);
        if btn(ui, t, Btn::Danger, "Disable Community", !busy).clicked() {
            st.confirm_disable = true;
        }
        if st.confirm_disable {
            let mut confirm = false;
            let close = dialog(
                ui,
                t,
                "community_disable",
                440.0,
                |ui| {
                    ui.label(bold("Disable Community?").size(20.0).color(t.header_primary));
                    ui.add_space(14.0);
                    ui.label(
                        RichText::new("Server Insights, Server Discovery and the other Community features will be turned off. You can enable Community again at any time.")
                            .size(15.0)
                            .color(t.text_normal),
                    );
                },
                |ui| {
                    if btn(ui, t, Btn::Danger, "Disable Community", !busy).clicked() {
                        confirm = true;
                    }
                    ui.add_space(8.0);
                    if link(ui, "Cancel", t.text_normal).clicked() {
                        st.confirm_disable = false;
                    }
                },
            );
            if confirm {
                patch_guild(acts, g, json!({ "features": features_with(v, &[], &["COMMUNITY", "DISCOVERABLE"]) }));
            }
            if close || confirm {
                st.confirm_disable = false;
            }
        }
    }
}

/// A checkbox with a description under it (the Community setup's checks).
fn check_row(ui: &mut Ui, t: &Theme, label: &str, desc: &str, on: &mut bool, enabled: bool) {
    let w = ui.available_width();
    let desc = ui.painter().layout(desc.to_string(), FontId::proportional(13.0), t.text_muted, (w - 36.0).max(80.0));
    let (r, resp) = ui.allocate_exact_size(vec2(w, 26.0 + desc.size().y), if enabled { Sense::click() } else { Sense::hover() });
    let bx = egui::Rect::from_min_size(r.min + vec2(0.0, 1.0), vec2(22.0, 22.0));
    if *on {
        ui.painter().rect_filled(bx, 4.0, if enabled { t.accent } else { t.accent.gamma_multiply(0.5) });
        ui.painter().text(bx.center(), Align2::CENTER_CENTER, icon::CHECK, icon_font(13.0), egui::Color32::WHITE);
    } else {
        ui.painter().rect_stroke(bx, 4.0, Stroke::new(2.0_f32, if resp.hovered() { t.interactive_hover } else { t.interactive_normal }));
    }
    ui.painter().text(pos2(r.left() + 34.0, r.top() + 12.0), Align2::LEFT_CENTER, label, super::bold_font(15.0), t.header_primary);
    ui.painter().galley(pos2(r.left() + 34.0, r.top() + 26.0), desc, t.text_muted);
    if enabled && resp.on_hover_cursor(CursorIcon::PointingHand).clicked() {
        *on = !*on;
    }
    ui.add_space(14.0);
}

/// A text channel dropdown with no "none"; `create` adds "Create one for me".
fn pick_channel(ui: &mut Ui, t: &Theme, id: &str, value: &mut Option<Id>, options: &[ChanOpt], create: Option<&str>) {
    let w = ui.available_width();
    let selected = match (*value, create) {
        (Some(CREATE), Some(label)) => WidgetText::from(label),
        (Some(v), _) => match options.iter().find(|o| o.id == v) {
            Some(o) => WidgetText::from(chan_job(t, o, false)),
            None => WidgetText::from("Unknown channel"),
        },
        (None, _) => WidgetText::from(RichText::new("Select a channel").color(t.text_muted)),
    };
    combo(ui, id, w, selected, |ui| {
        if let Some(label) = create {
            if ui.selectable_label(*value == Some(CREATE), label).clicked() {
                *value = Some(CREATE);
            }
        }
        for o in options {
            if ui.selectable_label(*value == Some(o.id), chan_job(t, o, false)).clicked() {
                *value = Some(o.id);
            }
        }
    });
}

fn setup_channel(ui: &mut Ui, t: &Theme, id: &str, value: &mut Option<Id>, options: &[ChanOpt]) {
    pick_channel(ui, t, id, value, options, Some("Create one for me"));
}

// ---- Server Insights -------------------------------------------------------------------------------

/// 12345 → "12,345".
fn grouped(n: u64) -> String {
    let digits = n.to_string();
    let mut out = String::with_capacity(digits.len() + digits.len() / 3);
    for (i, c) in digits.chars().enumerate() {
        if i > 0 && (digits.len() - i) % 3 == 0 {
            out.push(',');
        }
        out.push(c);
    }
    out
}

impl RustCord {
    /// What's certain without Discord's analytics endpoints (which aren't
    /// public): member and online counts, Boosts, the server's age; the
    /// charts stay on discord.com.
    pub(super) fn ss_insights(&self, ui: &mut Ui, t: &Theme, acts: &mut Vec<Act>, g: Id) {
        title(ui, t, "Server Insights");
        let (tag, path) = (format!("ss:insights:{g}"), format!("/guilds/{g}?with_counts=true"));
        if first_frame(ui, "insights", g) {
            let (tag, path) = (tag.clone(), path.clone());
            acts.push(run(move |app| app.api(&tag, Method::GET, path, None)));
        }
        let Some(v) = self.ss_loaded(ui, t, &tag, &path, acts) else { return };
        let boosts = vu64(v, "premium_subscription_count");
        let created = chrono::DateTime::from_timestamp((g.timestamp_ms() / 1000) as i64, 0)
            .map(|d| d.with_timezone(&chrono::Local).format("%-d %b %Y").to_string())
            .unwrap_or_default();
        let tiles = [
            ("MEMBERS", grouped(vu64(v, "approximate_member_count"))),
            ("ONLINE", grouped(vu64(v, "approximate_presence_count"))),
            ("BOOSTS", format!("{} (Level {})", grouped(boosts), vu64(v, "premium_tier"))),
            ("CREATED", created),
        ];
        ui.columns(tiles.len(), |cols| {
            for (ui, (label, value)) in cols.iter_mut().zip(tiles) {
                Frame::none().fill(t.bg_secondary).rounding(8.0).inner_margin(Margin::same(14.0)).show(ui, |ui| {
                    ui.set_width(ui.available_width());
                    ui.label(bold(label).size(12.0).color(t.header_secondary));
                    ui.add_space(6.0);
                    ui.label(bold(value).size(20.0).color(t.header_primary));
                });
            }
        });
        ui.add_space(20.0);
        let partnered = vbool(v, "partnered") || has_feature(v, "PARTNERED");
        notice(
            ui,
            t,
            if partnered {
                "Growth, engagement and audience charts come from Discord's analytics, which RustCord doesn't show yet. Partner program stats are there too."
            } else {
                "Growth, engagement and audience charts come from Discord's analytics, which RustCord doesn't show yet."
            },
        );
        ui.add_space(16.0);
        ui.with_layout(Layout::left_to_right(Align::Min), |ui| {
            if btn(ui, t, Btn::Primary, "Open full Insights on discord.com", true).clicked() {
                acts.push(run(move |app| open_on_web(app, g)));
            }
        });
    }
}

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

    #[test]
    fn numbers_group_by_thousands() {
        assert_eq!(grouped(0), "0");
        assert_eq!(grouped(999), "999");
        assert_eq!(grouped(1000), "1,000");
        assert_eq!(grouped(1234567), "1,234,567");
    }

    #[test]
    fn saves_send_what_discord_sends() {
        let v = json!({ "features": ["DISCOVERABLE", "COMMUNITY"] });
        let form = json!({ "form_fields": [{ "field_type": "TERMS", "label": RULES_LABEL, "values": ["Old"], "required": true }] });
        let saved = AccessDraft::saved(&v, &form);
        assert!(saved.mode == JoinMode::Discoverable && saved.rules == ["Old"]);

        // Apply to Join: DISCOVERABLE goes, the rules stay, questions follow.
        let mut d = saved.clone();
        d.mode = JoinMode::Apply;
        assert_eq!(access_plan(&v, &saved, &d), Err("Add a non-server rules question to enable Apply to Join."));
        d.questions.push(Question::new(FIRST_QUESTION));
        let (features, body) = access_plan(&v, &saved, &d).unwrap();
        assert_eq!(features, Some(json!(["COMMUNITY"])));
        let body = body.unwrap();
        assert_eq!(body["enabled"], true);
        assert_eq!(body["form_fields"][0]["field_type"], "TERMS");
        assert_eq!(body["form_fields"][1], json!({ "field_type": "TEXT_INPUT", "label": FIRST_QUESTION, "required": true }));

        // Invite Only with the gate on needs a rule; with rules it sends only them.
        let mut d = saved.clone();
        d.mode = JoinMode::Invite;
        d.gate = true;
        d.rules.clear();
        assert_eq!(access_plan(&v, &saved, &d), Err("You need to add one or more rules."));
        d.rules = vec!["Be kind ".into(), " ".into()];
        let (_, body) = access_plan(&v, &saved, &d).unwrap();
        assert_eq!(body.unwrap(), json!({ "form_fields": [terms_field(&["Be kind".to_string()])], "enabled": true }));
    }
}