Skip to content

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

38.4 KB
Raw Blame
//! Server Settings → Integrations (webhooks, followed channels, apps) and
//! Server Template.

use super::expression_pages::{dialog, field, length_ok, new_visit, page_state, release_dialog, with_state, Calls};
use super::{Act, Btn, ChanOpt, Theme};
use crate::app::RustCord;
use crate::store::Store;
use crate::style::{bold, icon, icon_font, overlay};
use discord::model::{channel_kind, Id, User};
use eframe::egui::{self, pos2, vec2, Align, Align2, Color32, CursorIcon, FontId, Frame, Layout, Margin, Rect, RichText, Rounding, Sense, Ui, WidgetText};
use reqwest::Method;
use serde::Deserialize;
use serde_json::{json, Value};
use std::sync::Arc;

// ---- Integrations -----------------------------------------------------------------

/// The names Discord gives new webhooks (one at random).
const WEBHOOK_NAMES: [&str; 2] = ["Captain Hook", "Spidey Bot"];

/// Channels a webhook can post to.
const WEBHOOK_KINDS: [u8; 6] = [
    channel_kind::GUILD_TEXT,
    channel_kind::GUILD_ANNOUNCEMENT,
    channel_kind::GUILD_VOICE,
    channel_kind::GUILD_STAGE_VOICE,
    channel_kind::GUILD_FORUM,
    channel_kind::GUILD_MEDIA,
];

/// Webhook types: posted to by apps and sites, or a followed announcement channel.
const INCOMING: u64 = 1;
const FOLLOWER: u64 = 2;

fn tag_webhooks(g: Id) -> String {
    format!("ss:webhooks:{g}")
}

fn tag_integrations(g: Id) -> String {
    format!("ss:integrations:{g}")
}

fn integrations_id(g: Id) -> egui::Id {
    egui::Id::new(("ss_integrations", g.0))
}

#[derive(Clone, Copy, Default, PartialEq)]
enum View {
    #[default]
    Overview,
    Webhooks,
    Followed,
}

#[derive(Clone, Default)]
struct IntegrationsUi {
    view: View,
    calls: Calls<Call>,
    /// The webhook whose panel is open, with its edits.
    open: Option<WebhookDraft>,
    confirm: Option<Confirm>,
    /// When "Copy Webhook URL" was clicked, and for which webhook.
    copied: Option<(Id, f64)>,
}

#[derive(Clone)]
struct WebhookDraft {
    id: Id,
    name: String,
    channel: Option<Id>,
    avatar: Option<NewAvatar>,
}

impl WebhookDraft {
    fn from_value(v: &Value) -> Option<Self> {
        Some(Self { id: super::vid(v, "id")?, name: super::vstr(v, "name").to_string(), channel: super::vid(v, "channel_id"), avatar: None })
    }

    fn dirty(&self, v: &Value) -> bool {
        self.name.trim() != super::vstr(v, "name") || self.channel != super::vid(v, "channel_id") || self.avatar.is_some()
    }
}

/// A picked avatar: what to send, and the bytes for its preview.
#[derive(Clone)]
struct NewAvatar {
    data_uri: Arc<str>,
    bytes: Arc<[u8]>,
    uri: String,
}

#[derive(Clone)]
enum Confirm {
    DeleteWebhook { id: Id, name: String, followed: bool },
    RemoveApp { id: Id, name: String },
}

#[derive(Clone)]
enum Call {
    Create(Id),
    Save(Id, Id),
    Delete(Id, Id),
    RemoveApp(Id, Id),
}

/// Drop a closed panel's avatar preview from egui's image cache.
fn forget_avatar(ctx: &egui::Context, d: Option<WebhookDraft>) {
    if let Some(a) = d.and_then(|d| d.avatar) {
        ctx.forget_image(&a.uri);
    }
}

fn webhook_avatar(v: &Value, id: Id) -> String {
    match v.get("avatar").and_then(Value::as_str) {
        Some(hash) => format!("https://cdn.discordapp.com/avatars/{id}/{hash}.png?size=80"),
        None => format!("https://cdn.discordapp.com/embed/avatars/{}.png", (id.0 >> 22) % 6),
    }
}

fn plural(n: usize, one: &str) -> String {
    if n == 1 {
        format!("1 {one}")
    } else {
        format!("{n} {one}s")
    }
}

/// One of the overview's cards: glyph, name, count and a button.
fn card(ui: &mut Ui, t: &Theme, glyph: &str, name: &str, sub: &str, button: Option<&str>, enabled: bool) -> bool {
    let mut clicked = false;
    Frame::none().fill(overlay(0.06)).rounding(8.0).inner_margin(Margin::same(16.0)).show(ui, |ui| {
        ui.set_width(ui.available_width());
        ui.horizontal(|ui| {
            let (r, _) = ui.allocate_exact_size(vec2(40.0, 40.0), Sense::hover());
            ui.painter().circle_filled(r.center(), 20.0, overlay(0.12));
            ui.painter().text(r.center(), Align2::CENTER_CENTER, glyph, icon_font(18.0), t.header_primary);
            ui.add_space(8.0);
            ui.vertical(|ui| {
                ui.label(bold(name).size(16.0).color(t.header_primary));
                ui.label(RichText::new(sub).size(14.0).color(t.text_muted));
            });
            if let Some(b) = button {
                ui.with_layout(Layout::right_to_left(Align::Center), |ui| {
                    clicked = super::btn(ui, t, Btn::Secondary, b, enabled).clicked();
                });
            }
        });
    });
    clicked
}

impl RustCord {
    pub(super) fn ss_integrations(&self, ui: &mut Ui, t: &Theme, acts: &mut Vec<Act>, g: Id) {
        let id = integrations_id(g);
        let mut s: IntegrationsUi = page_state(ui, id);
        release_dialog(ui);
        let perms = self.store.guild_perms(g);
        let webhooks = perms & super::MANAGE_WEBHOOKS != 0;
        let apps = perms & super::MANAGE_GUILD != 0;
        if new_visit(ui, id) {
            s.view = View::Overview;
            s.confirm = None;
            forget_avatar(ui.ctx(), s.open.take());
            ui.data_mut(|d| d.remove::<Arc<Vec<ChanOpt>>>(id.with("channels")));
            if webhooks {
                acts.push(Act::Refetch(tag_webhooks(g), format!("/guilds/{g}/webhooks")));
            }
            if apps {
                acts.push(Act::Refetch(tag_integrations(g), format!("/guilds/{g}/integrations?include_applications=true")));
            }
        }
        s.calls.poll(self, acts, integration_done);
        match s.view {
            View::Overview => self.integrations_overview(ui, t, acts, g, &mut s, webhooks, apps),
            View::Webhooks | View::Followed => self.webhook_list(ui, t, acts, g, &mut s),
        }
        self.integrations_confirm(ui, t, acts, g, &mut s);
        ui.data_mut(|d| d.insert_temp(id, s));
    }

    #[allow(clippy::too_many_arguments)]
    fn integrations_overview(&self, ui: &mut Ui, t: &Theme, acts: &mut Vec<Act>, g: Id, s: &mut IntegrationsUi, webhooks: bool, apps: bool) {
        super::title(ui, t, "Integrations");
        super::help(
            ui,
            t,
            "Customise your server with integrations. Manage webhooks, followed channels and apps, as well as Twitch and YouTube settings for creators.",
        );
        ui.add_space(20.0);
        if webhooks {
            if let Some(v) = self.ss_loaded(ui, t, &tag_webhooks(g), &format!("/guilds/{g}/webhooks"), acts) {
                let list = v.as_array().map(Vec::as_slice).unwrap_or(&[]);
                let incoming = list.iter().filter(|w| super::vu64(w, "type") == INCOMING).count();
                let followed = list.iter().filter(|w| super::vu64(w, "type") == FOLLOWER).count();
                let creating = s.calls.busy(|c| matches!(c, Call::Create(_)));
                let button = match (incoming, creating) {
                    (_, true) => "Creating…",
                    (0, _) => "Create Webhook",
                    _ => "View Webhooks",
                };
                if card(ui, t, icon::LINK, "Webhooks", &plural(incoming, "webhook"), Some(button), !creating) {
                    if incoming == 0 {
                        self.create_webhook(acts, g, s);
                    } else {
                        s.view = View::Webhooks;
                    }
                }
                ui.add_space(12.0);
                let button = (followed > 0).then_some("View Followed Channels");
                if card(ui, t, icon::ANNOUNCEMENT, "Channels Followed", &plural(followed, "channel"), button, true) {
                    s.view = View::Followed;
                }
            }
            super::divider(ui, t);
        }
        if apps {
            ui.label(bold("Bots and Apps").size(16.0).color(t.header_primary));
            ui.add_space(12.0);
            let path = format!("/guilds/{g}/integrations?include_applications=true");
            if let Some(v) = self.ss_loaded(ui, t, &tag_integrations(g), &path, acts) {
                self.app_rows(ui, t, s, v.as_array().map(Vec::as_slice).unwrap_or(&[]));
            }
        }
    }

    /// "Create Webhook": Discord makes it in the first text channel.
    fn create_webhook(&self, acts: &mut Vec<Act>, g: Id, s: &mut IntegrationsUi) {
        let kinds = [channel_kind::GUILD_TEXT, channel_kind::GUILD_ANNOUNCEMENT];
        let Some(c) = self.ss_guild_channels(g, |k| kinds.contains(&k)).first().map(|c| c.id) else {
            acts.push(Act::Note("Webhooks post to a text channel: create one first."));
            return;
        };
        let name = WEBHOOK_NAMES[(super::next_seq() % 2) as usize];
        s.calls.start(acts, Call::Create(g), move |app, tag| app.api(tag, Method::POST, format!("/channels/{c}/webhooks"), Some(json!({ "name": name }))));
    }

    fn webhook_list(&self, ui: &mut Ui, t: &Theme, acts: &mut Vec<Act>, g: Id, s: &mut IntegrationsUi) {
        let followed = s.view == View::Followed;
        if super::back_link(ui, t).clicked() {
            s.view = View::Overview;
            forget_avatar(ui.ctx(), s.open.take());
        }
        ui.add_space(12.0);
        if followed {
            super::title(ui, t, "Channels Followed");
            super::help(ui, t, "Announcement channels this server follows post their updates to the channel you pick for each.");
        } else {
            super::title(ui, t, "Webhooks");
            super::help(ui, t, "Webhooks are a simple way to post messages from other apps and websites into Discord using internet magic.");
            ui.add_space(16.0);
            let creating = s.calls.busy(|c| matches!(c, Call::Create(_)));
            if super::btn(ui, t, Btn::Primary, if creating { "Creating…" } else { "New Webhook" }, !creating).clicked() {
                self.create_webhook(acts, g, s);
            }
        }
        ui.add_space(20.0);
        let Some(v) = self.ss_loaded(ui, t, &tag_webhooks(g), &format!("/guilds/{g}/webhooks"), acts) else { return };
        let kind = if followed { FOLLOWER } else { INCOMING };
        let mut any = false;
        for w in v.as_array().into_iter().flatten().filter(|w| super::vu64(w, "type") == kind) {
            any = true;
            self.webhook_row(ui, t, acts, g, s, w, followed);
        }
        if !any {
            let (heading, text) = if followed {
                ("No Followed Channels", "Follow an announcement channel from another server to have its updates posted here.")
            } else {
                ("No Webhooks", "Create a webhook to let apps and websites post messages to this server.")
            };
            super::empty_state(ui, t, heading, text);
        }
    }

    /// A webhook: avatar, name, who made it; click to open its panel.
    #[allow(clippy::too_many_arguments)]
    fn webhook_row(&self, ui: &mut Ui, t: &Theme, acts: &mut Vec<Act>, g: Id, s: &mut IntegrationsUi, w: &Value, followed: bool) {
        let Some(id) = super::vid(w, "id") else { return };
        let open = s.open.as_ref().is_some_and(|d| d.id == id);
        let (r, resp) = ui.allocate_exact_size(vec2(ui.available_width(), 68.0), Sense::click());
        let resp = resp.on_hover_cursor(CursorIcon::PointingHand);
        if ui.is_rect_visible(r) {
            let rounding = if open { Rounding { nw: 8.0, ne: 8.0, sw: 0.0, se: 0.0 } } else { Rounding::same(8.0) };
            ui.painter().rect_filled(r, rounding, overlay(if resp.hovered() { 0.1 } else { 0.06 }));
            let (name, sub, avatar) = if followed {
                let source = &w["source_guild"];
                let name = format!("{} #{}", super::vstr(source, "name"), super::vstr(&w["source_channel"], "name"));
                let to = super::vid(w, "channel_id").and_then(|c| self.store.channels.get(&c)).map(Store::channel_label).unwrap_or_default();
                let avatar = match (super::vid(source, "id"), source.get("icon").and_then(Value::as_str)) {
                    (Some(sg), Some(hash)) => format!("https://cdn.discordapp.com/icons/{sg}/{hash}.png?size=80"),
                    _ => webhook_avatar(w, id),
                };
                (name, format!("Posts to #{to}"), avatar)
            } else {
                let date = super::super::popups::long_date(id.timestamp_ms());
                let sub = match w.get("user").and_then(|u| User::deserialize(u).ok()) {
                    Some(u) => format!("Created on {date} by {}", u.display_name()),
                    None => format!("Created on {date}"),
                };
                (super::vstr(w, "name").to_string(), sub, webhook_avatar(w, id))
            };
            let av = Rect::from_center_size(pos2(r.left() + 36.0, r.center().y), vec2(40.0, 40.0));
            super::super::paint_avatar(ui, av, Some(avatar), &name);
            let p = ui.painter_at(Rect::from_min_max(r.min, pos2(r.right() - 44.0, r.bottom())));
            p.text(pos2(av.right() + 12.0, r.center().y - 10.0), Align2::LEFT_CENTER, &name, super::bold_font(16.0), t.header_primary);
            p.text(pos2(av.right() + 12.0, r.center().y + 11.0), Align2::LEFT_CENTER, sub, FontId::proportional(13.0), t.text_muted);
            let chevron = if open { icon::CHEVRON_DOWN } else { icon::CHEVRON };
            ui.painter().text(pos2(r.right() - 22.0, r.center().y), Align2::CENTER_CENTER, chevron, icon_font(12.0), t.interactive_normal);
        }
        if resp.clicked() {
            forget_avatar(ui.ctx(), s.open.take());
            if !open {
                s.open = WebhookDraft::from_value(w);
            }
        }
        if open {
            self.webhook_panel(ui, t, acts, g, s, w, followed);
        }
        ui.add_space(8.0);
    }

    /// The open webhook: avatar, name and channel, its URL, Delete.
    #[allow(clippy::too_many_arguments)]
    fn webhook_panel(&self, ui: &mut Ui, t: &Theme, acts: &mut Vec<Act>, g: Id, s: &mut IntegrationsUi, w: &Value, followed: bool) {
        let IntegrationsUi { open, calls, confirm, copied, .. } = s;
        let Some(d) = open.as_mut() else { return };
        let id = d.id;
        let now = ui.input(|i| i.time);
        // The channel picker's options, kept for the visit.
        let key = integrations_id(g).with("channels");
        let channels = ui.data(|m| m.get_temp::<Arc<Vec<ChanOpt>>>(key)).unwrap_or_else(|| {
            let list = Arc::new(self.ss_guild_channels(g, |k| WEBHOOK_KINDS.contains(&k)));
            ui.data_mut(|m| m.insert_temp(key, list.clone()));
            list
        });
        Frame::none()
            .fill(overlay(0.03))
            .rounding(Rounding { nw: 0.0, ne: 0.0, sw: 8.0, se: 8.0 })
            .inner_margin(Margin::same(16.0))
            .show(ui, |ui| {
                ui.set_width(ui.available_width());
                ui.horizontal_top(|ui| {
                    if !followed {
                        ui.vertical(|ui| {
                            ui.set_width(96.0);
                            let (r, resp) = ui.allocate_exact_size(vec2(80.0, 80.0), Sense::click());
                            let resp = resp.on_hover_cursor(CursorIcon::PointingHand);
                            match &d.avatar {
                                Some(a) => egui::Image::from_bytes(a.uri.clone(), a.bytes.clone()).rounding(40.0).paint_at(ui, r),
                                None => super::super::paint_avatar(ui, r, Some(webhook_avatar(w, id)), &d.name),
                            }
                            if resp.hovered() {
                                ui.painter().circle_filled(r.center(), 40.0, Color32::from_black_alpha(150));
                                ui.painter().text(r.center(), Align2::CENTER_CENTER, "CHANGE\nAVATAR", super::bold_font(10.0), Color32::WHITE);
                            }
                            if resp.clicked() {
                                acts.push(Act::Run(Box::new(move |app: &mut RustCord| pick_avatar(app, g, id))));
                            }
                            ui.add_space(6.0);
                            ui.label(RichText::new("Minimum Size: 128x128").size(12.0).color(t.text_muted));
                        });
                        ui.add_space(12.0);
                    }
                    ui.vertical(|ui| {
                        if !followed {
                            field(ui, t, "NAME", egui::Id::new(("ss_webhook_name", id.0)), &mut d.name, "", 1, 80);
                        }
                        super::section(ui, t, "CHANNEL");
                        let selected = match d.channel.and_then(|c| channels.iter().find(|o| o.id == c)) {
                            Some(o) => WidgetText::from(super::chan_job(t, o, false)),
                            None => WidgetText::from(RichText::new("Pick a channel").color(t.text_muted)),
                        };
                        let width = ui.available_width();
                        super::combo(ui, &format!("ss_webhook_channel_{}", id.0), width, selected, |ui| {
                            for o in channels.iter() {
                                if ui.selectable_label(d.channel == Some(o.id), super::chan_job(t, o, false)).clicked() {
                                    d.channel = Some(o.id);
                                }
                            }
                        });
                    });
                });
                super::thin_rule(ui, t);
                ui.horizontal(|ui| {
                    if !followed {
                        let token = super::vstr(w, "token");
                        let just_copied = copied.is_some_and(|(c, at)| c == id && now - at < 1.5);
                        let label = if just_copied { "Copied!" } else { "Copy Webhook URL" };
                        if super::btn(ui, t, Btn::Secondary, label, !token.is_empty()).clicked() {
                            ui.ctx().copy_text(format!("https://discord.com/api/webhooks/{id}/{token}"));
                            *copied = Some((id, now));
                        }
                        if just_copied {
                            ui.ctx().request_repaint_after(std::time::Duration::from_millis(300));
                        }
                        ui.add_space(8.0);
                    }
                    let delete = if followed { "Unfollow" } else { "Delete Webhook" };
                    if super::link(ui, delete, t.danger).clicked() {
                        *confirm = Some(Confirm::DeleteWebhook { id, name: d.name.clone(), followed });
                    }
                    if !d.dirty(w) {
                        return;
                    }
                    ui.with_layout(Layout::right_to_left(Align::Center), |ui| {
                        let saving = calls.busy(|c| matches!(c, Call::Save(_, s) if *s == id));
                        let valid = length_ok(&d.name, 1, 80) && d.channel.is_some();
                        if super::btn(ui, t, Btn::Success, if saving { "Saving…" } else { "Save Changes" }, valid && !saving).clicked() {
                            let mut body = serde_json::Map::new();
                            if d.name.trim() != super::vstr(w, "name") {
                                body.insert("name".into(), json!(d.name.trim()));
                            }
                            if d.channel != super::vid(w, "channel_id") {
                                body.insert("channel_id".into(), super::opt_id(d.channel));
                            }
                            if let Some(a) = &d.avatar {
                                body.insert("avatar".into(), json!(&*a.data_uri));
                            }
                            calls.start(acts, Call::Save(g, id), move |app, tag| app.api(tag, Method::PATCH, format!("/webhooks/{id}"), Some(Value::Object(body))));
                        }
                        ui.add_space(8.0);
                        if super::link(ui, "Reset", t.text_normal).clicked() {
                            if let Some(a) = d.avatar.take() {
                                ui.ctx().forget_image(&a.uri);
                            }
                            d.name = super::vstr(w, "name").to_string();
                            d.channel = super::vid(w, "channel_id");
                        }
                    });
                });
            });
    }

    /// Bots and Apps: each app's icon, name, when and by whom it was added,
    /// and Remove.
    fn app_rows(&self, ui: &mut Ui, t: &Theme, s: &mut IntegrationsUi, list: &[Value]) {
        let mut any = false;
        for i in list {
            let (Some(id), Some(app)) = (super::vid(i, "id"), i.get("application").filter(|a| a.is_object())) else { continue };
            any = true;
            let name = super::vstr(app, "name");
            let (r, _) = ui.allocate_exact_size(vec2(ui.available_width(), 64.0), Sense::hover());
            if !ui.is_rect_visible(r) {
                continue;
            }
            let bot = app.get("bot").and_then(|b| User::deserialize(b).ok());
            let icon_url = match (super::vid(app, "id"), app.get("icon").and_then(Value::as_str)) {
                (Some(a), Some(hash)) => Some(format!("https://cdn.discordapp.com/app-icons/{a}/{hash}.png?size=80")),
                _ => bot.as_ref().map(|b| b.avatar_or_default(80)),
            };
            let av = Rect::from_center_size(pos2(r.left() + 20.0, r.center().y), vec2(40.0, 40.0));
            super::super::paint_avatar(ui, av, icon_url, name);
            let p = ui.painter_at(Rect::from_min_max(r.min, pos2(r.right() - 110.0, r.bottom())));
            let x = av.right() + 12.0;
            let title = p.text(pos2(x, r.center().y - 10.0), Align2::LEFT_CENTER, name, super::bold_font(15.0), t.header_primary);
            if bot.is_some() {
                let tag = Rect::from_min_size(pos2(title.right() + 6.0, title.center().y - 8.0), vec2(30.0, 16.0));
                p.rect_filled(tag, 4.0, t.accent);
                p.text(tag.center(), Align2::CENTER_CENTER, "Bot", super::bold_font(10.0), Color32::WHITE);
            }
            let date = super::super::popups::long_date(id.timestamp_ms());
            let sub = match i.get("user").and_then(|u| User::deserialize(u).ok()) {
                Some(u) => format!("Added on {date} by {}", u.username),
                None => format!("Added on {date}"),
            };
            p.text(pos2(x, r.center().y + 11.0), Align2::LEFT_CENTER, sub, FontId::proportional(13.0), t.text_muted);

            let button = Rect::from_min_max(pos2(r.right() - 100.0, r.center().y - 18.0), pos2(r.right(), r.center().y + 18.0));
            if s.calls.busy(|c| matches!(c, Call::RemoveApp(_, a) if *a == id)) {
                ui.put(button, egui::Spinner::new().size(16.0));
            } else if ui.put(button, |ui: &mut Ui| super::btn(ui, t, Btn::Danger, "Remove", true)).clicked() {
                s.confirm = Some(Confirm::RemoveApp { id, name: name.to_string() });
            }
            ui.painter().hline(r.x_range(), r.bottom(), egui::Stroke::new(1.0_f32, t.border_subtle));
        }
        if !any {
            super::help(ui, t, "No apps have been added to this server yet.");
        }
    }

    fn integrations_confirm(&self, ui: &Ui, t: &Theme, acts: &mut Vec<Act>, g: Id, s: &mut IntegrationsUi) {
        let Some(c) = s.confirm.clone() else { return };
        let server = self.store.guilds.get(&g).map(|gs| gs.guild.name.as_str()).unwrap_or("this server");
        let out = match &c {
            Confirm::DeleteWebhook { name, followed: false, .. } => dialog(ui, t, "Delete Webhook", "Delete", Btn::Danger, true, |ui| {
                ui.label(RichText::new(format!("Are you sure you want to delete {name}? This action cannot be undone.")).size(15.0).color(t.text_normal));
            }),
            Confirm::DeleteWebhook { name, followed: true, .. } => dialog(ui, t, "Unfollow Channel", "Unfollow", Btn::Danger, true, |ui| {
                ui.label(RichText::new(format!("Stop posting updates from {name} in {server}?")).size(15.0).color(t.text_normal));
            }),
            Confirm::RemoveApp { name, .. } => dialog(ui, t, &format!("Remove {name}"), "Remove", Btn::Danger, true, |ui| {
                ui.label(
                    RichText::new(format!("Are you sure you want to remove {name} from {server}? It won't be able to use this server until someone adds it again."))
                        .size(15.0)
                        .color(t.text_normal),
                );
            }),
        };
        if out == Some(true) {
            match c {
                Confirm::DeleteWebhook { id, .. } => {
                    s.calls.start(acts, Call::Delete(g, id), move |app, tag| app.api(tag, Method::DELETE, format!("/webhooks/{id}"), None));
                }
                Confirm::RemoveApp { id, .. } => {
                    let path = format!("/guilds/{g}/integrations/{id}");
                    s.calls.start(acts, Call::RemoveApp(g, id), move |app, tag| app.api(tag, Method::DELETE, path, None));
                }
            }
        }
        if out.is_some() {
            s.confirm = None;
        }
    }
}

/// The webhook avatar picker (after the frame: the file dialog blocks).
fn pick_avatar(app: &mut RustCord, g: Id, webhook: Id) {
    let Some(path) = rfd::FileDialog::new().set_title("Choose an avatar").add_filter("Images", &super::IMAGE_EXTS).pick_file() else {
        return;
    };
    let img = match super::prepare_image(&path, 512, 2 << 20) {
        Ok(img) => img,
        Err(e) => return app.toast(e, true),
    };
    let avatar = NewAvatar { data_uri: img.data_uri.into(), bytes: img.bytes, uri: format!("bytes://ss-webhook-{}.png", super::next_seq()) };
    let mut old = None;
    with_state::<IntegrationsUi>(app, integrations_id(g), |s| {
        if let Some(d) = s.open.as_mut().filter(|d| d.id == webhook) {
            old = d.avatar.replace(avatar);
        }
    });
    if let Some(a) = old {
        app.ctx.forget_image(&a.uri);
    }
}

fn integration_done(app: &mut RustCord, call: Call, r: Result<Value, String>) {
    let mut v = match r {
        Ok(v) => v,
        Err(e) => {
            let what = match call {
                Call::Create(_) => "Couldn't create the webhook",
                Call::Save(..) => "Couldn't save the webhook",
                Call::Delete(..) => "Couldn't delete the webhook",
                Call::RemoveApp(..) => "Couldn't remove the app",
            };
            app.toast(format!("{what}: {e}"), true);
            return;
        }
    };
    let mut closed = None;
    match call {
        Call::Create(g) => {
            app.ss_list_upsert(&tag_webhooks(g), &v);
            let draft = WebhookDraft::from_value(&v);
            with_state::<IntegrationsUi>(app, integrations_id(g), |s| {
                s.view = View::Webhooks;
                closed = std::mem::replace(&mut s.open, draft);
            });
        }
        Call::Save(g, id) => {
            // Keep the token if the answer leaves it out (the URL needs it).
            let tag = tag_webhooks(g);
            if v.get("token").is_none() {
                let old = app.ss_list_mut(&tag).and_then(|l| l.iter().find(|w| super::vid(w, "id") == Some(id))).and_then(|w| w.get("token")).cloned();
                if let Some(token) = old {
                    v["token"] = token;
                }
            }
            app.ss_list_upsert(&tag, &v);
            with_state::<IntegrationsUi>(app, integrations_id(g), |s| {
                if s.open.as_ref().is_some_and(|d| d.id == id) {
                    closed = std::mem::replace(&mut s.open, WebhookDraft::from_value(&v));
                }
            });
        }
        Call::Delete(g, id) => {
            app.ss_list_remove(&tag_webhooks(g), |w| super::vid(w, "id") == Some(id));
            with_state::<IntegrationsUi>(app, integrations_id(g), |s| {
                if s.open.as_ref().is_some_and(|d| d.id == id) {
                    closed = s.open.take();
                }
            });
        }
        Call::RemoveApp(g, id) => app.ss_list_remove(&tag_integrations(g), |i| super::vid(i, "id") == Some(id)),
    }
    forget_avatar(&app.ctx, closed);
}

// ---- Server Template --------------------------------------------------------------

fn tag_templates(g: Id) -> String {
    format!("ss:templates:{g}")
}

fn template_id(g: Id) -> egui::Id {
    egui::Id::new(("ss_template", g.0))
}

#[derive(Clone, Default)]
struct TemplateUi {
    calls: Calls<TemplateCall>,
    /// The title and description being edited, and the template they came
    /// from ("" before there is one).
    form: Option<TemplateForm>,
    confirm_delete: bool,
    /// When "Copy" was clicked.
    copied: Option<f64>,
}

#[derive(Clone, Default, PartialEq)]
struct TemplateForm {
    code: String,
    title: String,
    description: String,
}

impl TemplateForm {
    fn from_value(v: Option<&Value>) -> Self {
        match v {
            Some(v) => Self {
                code: super::vstr(v, "code").to_string(),
                title: super::vstr(v, "name").to_string(),
                description: super::vstr(v, "description").to_string(),
            },
            None => Self::default(),
        }
    }

    fn body(&self) -> Value {
        json!({ "name": self.title.trim(), "description": self.description.trim() })
    }
}

#[derive(Clone)]
enum TemplateCall {
    Create(Id),
    Save(Id),
    Sync(Id),
    Delete(Id),
}

impl RustCord {
    pub(super) fn ss_template(&self, ui: &mut Ui, t: &Theme, acts: &mut Vec<Act>, g: Id) {
        super::title(ui, t, "Server Template");
        let id = template_id(g);
        let (tag, path) = (tag_templates(g), format!("/guilds/{g}/templates"));
        let mut s: TemplateUi = page_state(ui, id);
        release_dialog(ui);
        if new_visit(ui, id) {
            s.form = None;
            s.confirm_delete = false;
            acts.push(Act::Refetch(tag.clone(), path.clone()));
        }
        s.calls.poll(self, acts, template_done);

        super::help(ui, t, "A server template is an easy way to share your server setup and help anyone create a server instantly.");
        ui.add_space(8.0);
        super::help(
            ui,
            t,
            "When someone uses your server template link, they create a new server pre-filled with the same channels, roles, permissions and settings as yours.",
        );
        ui.add_space(20.0);
        ui.columns(2, |cols| {
            copies(&mut cols[0], t, "Templates will copy:", &["Channels and channel topics", "Roles and permissions", "Default server settings"], true);
            copies(
                &mut cols[1],
                t,
                "Templates will not copy:",
                &["Messages or any content", "Members or bots", "Your server icon, Boosts or other perks"],
                false,
            );
        });
        super::divider(ui, t);

        if let Some(v) = self.ss_loaded(ui, t, &tag, &path, acts) {
            let template = v.as_array().and_then(|a| a.first());
            // (Re)fill the form when the template changes.
            let code = template.map_or("", |tp| super::vstr(tp, "code"));
            if s.form.as_ref().map(|f| f.code.as_str()) != Some(code) {
                s.form = Some(TemplateForm::from_value(template));
            }
            match template {
                None => self.template_new(ui, t, acts, g, &mut s),
                Some(tp) => self.template_existing(ui, t, acts, g, &mut s, tp),
            }
        }
        if s.confirm_delete {
            let code = s.form.as_ref().map(|f| f.code.clone()).unwrap_or_default();
            let out = dialog(ui, t, "Delete Template", "Delete Template", Btn::Danger, true, |ui| {
                ui.label(
                    RichText::new("Are you sure you want to delete this template? Its link will stop working, and servers already made from it won't change.")
                        .size(15.0)
                        .color(t.text_normal),
                );
            });
            if out == Some(true) && !code.is_empty() {
                s.calls.start(acts, TemplateCall::Delete(g), move |app, tag| app.api(tag, Method::DELETE, format!("/guilds/{g}/templates/{code}"), None));
            }
            if out.is_some() {
                s.confirm_delete = false;
            }
        }
        ui.data_mut(|d| d.insert_temp(id, s));
    }

    fn template_new(&self, ui: &mut Ui, t: &Theme, acts: &mut Vec<Act>, g: Id, s: &mut TemplateUi) {
        let Some(form) = s.form.as_mut() else { return };
        template_fields(ui, t, form);
        let creating = s.calls.busy(|c| matches!(c, TemplateCall::Create(_)));
        let label = if creating { "Generating…" } else { "Generate Template" };
        if super::btn(ui, t, Btn::Primary, label, length_ok(&form.title, 1, 100) && !creating).clicked() {
            let body = form.body();
            s.calls.start(acts, TemplateCall::Create(g), move |app, tag| app.api(tag, Method::POST, format!("/guilds/{g}/templates"), Some(body)));
        }
    }

    fn template_existing(&self, ui: &mut Ui, t: &Theme, acts: &mut Vec<Act>, g: Id, s: &mut TemplateUi, tp: &Value) {
        let TemplateUi { calls, form, confirm_delete, copied } = s;
        let Some(form) = form.as_mut() else { return };
        let code = super::vstr(tp, "code").to_string();
        let now = ui.input(|i| i.time);

        // The link, in a box with Copy.
        super::section(ui, t, "Template Link");
        let url = format!("https://discord.new/{code}");
        Frame::none()
            .fill(Color32::from_black_alpha(31))
            .rounding(8.0)
            .stroke(egui::Stroke::new(1.0_f32, overlay(0.2)))
            .inner_margin(Margin { left: 12.0, right: 4.0, top: 4.0, bottom: 4.0 })
            .show(ui, |ui| {
                ui.set_width(ui.available_width());
                ui.horizontal(|ui| {
                    ui.label(RichText::new(&url).size(15.0).color(t.text_normal));
                    ui.with_layout(Layout::right_to_left(Align::Center), |ui| {
                        let just_copied = copied.is_some_and(|at| now - at < 1.5);
                        let kind = if just_copied { Btn::Success } else { Btn::Primary };
                        if super::btn(ui, t, kind, if just_copied { "Copied" } else { "Copy" }, true).clicked() {
                            ui.ctx().copy_text(url.clone());
                            *copied = Some(now);
                        }
                        if just_copied {
                            ui.ctx().request_repaint_after(std::time::Duration::from_millis(300));
                        }
                    });
                });
            });
        ui.add_space(8.0);
        let synced = chrono::DateTime::parse_from_rfc3339(super::vstr(tp, "updated_at"))
            .map(|d| d.with_timezone(&chrono::Local).format("%-d %b %Y").to_string())
            .unwrap_or_default();
        let uses = super::vu64(tp, "usage_count");
        super::help(ui, t, &format!("Used {uses} {}. Last synced {synced}.", if uses == 1 { "time" } else { "times" }));
        ui.add_space(16.0);

        // Discord: the server changed since the template was last synced.
        if super::vbool(tp, "is_dirty") {
            Frame::none().fill(overlay(0.08)).rounding(8.0).inner_margin(Margin::symmetric(14.0, 10.0)).show(ui, |ui| {
                ui.set_width(ui.available_width());
                ui.horizontal(|ui| {
                    ui.label(RichText::new("This template has unsynced changes.").size(14.0).color(t.text_normal));
                    ui.with_layout(Layout::right_to_left(Align::Center), |ui| {
                        let syncing = calls.busy(|c| matches!(c, TemplateCall::Sync(_)));
                        if super::btn(ui, t, Btn::Primary, if syncing { "Syncing…" } else { "Sync Template" }, !syncing).clicked() {
                            let code = code.clone();
                            calls.start(acts, TemplateCall::Sync(g), move |app, tag| app.api(tag, Method::PUT, format!("/guilds/{g}/templates/{code}"), None));
                        }
                    });
                });
            });
            ui.add_space(16.0);
        }

        super::thin_rule(ui, t);
        template_fields(ui, t, form);
        let orig = TemplateForm::from_value(Some(tp));
        if *form != orig {
            ui.horizontal(|ui| {
                let saving = calls.busy(|c| matches!(c, TemplateCall::Save(_)));
                if super::btn(ui, t, Btn::Success, if saving { "Saving…" } else { "Save Changes" }, length_ok(&form.title, 1, 100) && !saving).clicked() {
                    let (code, body) = (code.clone(), form.body());
                    calls.start(acts, TemplateCall::Save(g), move |app, tag| app.api(tag, Method::PATCH, format!("/guilds/{g}/templates/{code}"), Some(body)));
                }
                ui.add_space(8.0);
                if super::link(ui, "Reset", t.text_normal).clicked() {
                    *form = orig;
                }
            });
        }
        super::divider(ui, t);
        let deleting = calls.busy(|c| matches!(c, TemplateCall::Delete(_)));
        if super::btn(ui, t, Btn::Danger, if deleting { "Deleting…" } else { "Delete Template" }, !deleting).clicked() {
            *confirm_delete = true;
        }
    }
}

/// "Templates will copy:" and its list, each item with a tick or a cross.
fn copies(ui: &mut Ui, t: &Theme, heading: &str, items: &[&str], yes: bool) {
    ui.label(bold(heading).size(14.0).color(t.header_primary));
    ui.add_space(8.0);
    let (glyph, color) = if yes { (icon::CHECK, Color32::from_rgb(0x24, 0x80, 0x46)) } else { (icon::CLOSE, t.danger) };
    for item in items {
        ui.horizontal(|ui| {
            ui.label(RichText::new(glyph).font(icon_font(11.0)).color(color));
            ui.label(RichText::new(*item).size(14.0).color(t.text_normal));
        });
    }
}

fn template_fields(ui: &mut Ui, t: &Theme, form: &mut TemplateForm) {
    field(ui, t, "Template Title*", egui::Id::new("ss_template_title"), &mut form.title, "", 1, 100);
    field(ui, t, "Template Description", egui::Id::new("ss_template_description"), &mut form.description, "", 3, 120);
}

fn template_done(app: &mut RustCord, call: TemplateCall, r: Result<Value, String>) {
    let (g, what) = match call {
        TemplateCall::Create(g) => (g, "Couldn't generate the template"),
        TemplateCall::Save(g) => (g, "Couldn't save the template"),
        TemplateCall::Sync(g) => (g, "Couldn't sync the template"),
        TemplateCall::Delete(g) => (g, "Couldn't delete the template"),
    };
    let v = match r {
        Ok(v) => v,
        Err(e) => return app.toast(format!("{what}: {e}"), true),
    };
    // A server has at most one template: the answer is the whole list.
    let list = if matches!(call, TemplateCall::Delete(_)) { json!([]) } else { json!([v]) };
    app.api_results.insert(tag_templates(g), Ok(list));
    with_state::<TemplateUi>(app, template_id(g), |s| s.form = None);
}