Skip to content

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

25.0 KB
Raw Blame
//! Bot interactions the way Discord's client runs them: the wait after a
//! button or select click (three dots on the button, the message's other
//! controls off), "This interaction failed", and the forms (modals) an app
//! opens in answer, which are filled in and sent back.

use crate::app::RustCord;
use crate::style::{icon, icon_font, medium, Theme};
use discord::model::{Component, Id, SelectOption};
use eframe::egui::{self, pos2, vec2, Align2, Color32, CursorIcon, FontId, Frame, Key, Margin, Order, Rect, RichText, Sense, Stroke, Ui};
use serde_json::{json, Value};
use std::time::{Duration, Instant};

const BRAND: Color32 = Color32::from_rgb(0x58, 0x65, 0xf2);
/// A click that got no answer at all (connection trouble) gives up after this.
const GIVE_UP: Duration = Duration::from_secs(15);

/// A click (or form) sent to an app, not answered yet.
pub struct PendingInteraction {
    pub nonce: String,
    /// The message whose control was used (none for a form).
    pub msg: Option<Id>,
    pub custom_id: String,
    pub at: Instant,
}

/// One input of a form.
pub enum Field {
    Text { custom_id: String, id: Option<u64>, label: String, description: Option<String>, paragraph: bool, placeholder: String, min: usize, max: usize, required: bool, value: String, in_label: bool },
    Select { custom_id: String, id: Option<u64>, label: String, description: Option<String>, placeholder: String, options: Vec<SelectOption>, min: usize, max: usize, required: bool, picked: Vec<String>, open: bool },
    /// Plain text between the inputs.
    Display(String),
}

/// A form an app opened (`INTERACTION_MODAL_CREATE`).
pub struct BotModal {
    /// The interaction the form answers.
    id: String,
    custom_id: String,
    title: String,
    application: Id,
    app_name: String,
    app_icon: Option<String>,
    channel: Id,
    fields: Vec<Field>,
    /// Sent, waiting for the app (the nonce).
    submitting: Option<String>,
    error: Option<String>,
    focus: bool,
}

fn new_nonce() -> String {
    let now = std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).map(|d| d.as_millis() as u64).unwrap_or(0);
    Id::from_timestamp_ms(now).0.to_string()
}

fn strong(size: f32) -> FontId {
    FontId::new(size, egui::FontFamily::Name(crate::style::BOLD.into()))
}

/// Discord's three pulsing dots (a button or form waiting for its app).
pub fn loading_dots(ui: &Ui, center: egui::Pos2, color: Color32) {
    let time = ui.input(|i| i.time);
    for k in 0..3 {
        let phase = ((time / 1.4 - k as f64 * 0.14).rem_euclid(1.0)) as f32;
        // Up and back down over the first 60 % of the cycle.
        let pulse = if phase < 0.6 { (phase / 0.6 * std::f32::consts::PI).sin() } else { 0.0 };
        let c = pos2(center.x + (k as f32 - 1.0) * 9.0, center.y);
        ui.painter().circle_filled(c, 2.5 + pulse * 0.8, color.gamma_multiply(0.35 + 0.65 * pulse));
    }
    if super::animating() {
        ui.ctx().request_repaint_after(std::time::Duration::from_millis(33));
    }
}

impl RustCord {
    /// Is this message waiting for its app? `Some(true)` for the control
    /// that was used, `Some(false)` for the message's other controls.
    pub(super) fn interaction_state(&self, msg: Id, custom_id: Option<&str>) -> Option<bool> {
        let p = self.interaction.as_ref().filter(|p| p.msg == Some(msg))?;
        Some(custom_id == Some(p.custom_id.as_str()))
    }

    fn interaction_base(&self, channel: Id, application: Id, nonce: &str) -> Option<Value> {
        let session_id = self.store.session_id.clone()?;
        let guild = self.store.channels.get(&channel).and_then(|c| c.guild_id);
        Some(json!({
            "nonce": nonce,
            "guild_id": guild.map(|g| g.to_string()),
            "channel_id": channel.to_string(),
            "application_id": application.to_string(),
            "session_id": session_id,
        }))
    }

    /// Click a bot's button or pick from its select menu (`values`): an
    /// interaction of type 3, like the official client sends.
    pub(super) fn start_interaction(&mut self, channel: Id, msg: Id, component_type: u8, custom_id: String, values: Option<Vec<String>>) {
        self.open_select = None;
        // One at a time, as in Discord (the controls are off meanwhile).
        if self.interaction.is_some() {
            return;
        }
        let Some(m) = self.store.message(channel, msg) else { return };
        let (application, flags) = (m.application_id.unwrap_or(m.author.id), m.flags);
        let nonce = new_nonce();
        let Some(mut body) = self.interaction_base(channel, application, &nonce) else {
            self.toast("Not connected yet, try again in a moment.", true);
            return;
        };
        let mut data = json!({ "component_type": component_type, "custom_id": custom_id });
        if let Some(v) = values {
            data["type"] = json!(component_type);
            data["values"] = json!(v);
        }
        body["type"] = json!(3);
        body["message_flags"] = json!(flags);
        body["message_id"] = json!(msg.to_string());
        body["data"] = data;
        self.interaction_failed = None;
        self.interaction = Some(PendingInteraction { nonce: nonce.clone(), msg: Some(msg), custom_id, at: Instant::now() });
        self.api(&format!("interact:{nonce}"), reqwest::Method::POST, "/interactions", Some(body));
    }

    /// The app answered (`ok`) or failed to. True when `nonce` was one of
    /// RustCord's (a button, select or form; slash commands report on their own).
    pub fn interaction_done(&mut self, nonce: &str, ok: bool) -> bool {
        let mut ours = false;
        if self.interaction.as_ref().is_some_and(|p| p.nonce == nonce) {
            let p = self.interaction.take();
            if !ok {
                self.interaction_failed = p.and_then(|p| p.msg);
            }
            ours = true;
        }
        if self.bot_modal.as_ref().is_some_and(|m| m.submitting.as_deref() == Some(nonce)) {
            if ok {
                self.bot_modal = None;
            } else if let Some(m) = &mut self.bot_modal {
                m.submitting = None;
                m.error = Some("Something went wrong. Try again.".into());
            }
            ours = true;
        }
        ours
    }

    /// `INTERACTION_MODAL_CREATE`: an app answered with a form.
    pub fn open_bot_modal(&mut self, d: &Value) {
        let Some(channel) = Id::from_value(&d["channel_id"]) else { return };
        // The click that led here is answered.
        if let Some(nonce) = d["nonce"].as_str() {
            self.interaction_done(nonce, true);
        }
        let app = &d["application"];
        let Some(application) = Id::from_value(&app["id"]) else { return };
        let comps: Vec<Component> = serde_json::from_value(d["components"].clone()).unwrap_or_default();
        let raw = d["components"].as_array().cloned().unwrap_or_default();
        let id_of = |v: &Value| v["id"].as_u64();
        let mut fields = Vec::new();
        for (c, v) in comps.iter().zip(&raw) {
            match c.kind {
                // The classic form: one text input per action row.
                1 => {
                    for (child, cv) in c.components.iter().zip(v["components"].as_array().into_iter().flatten()) {
                        if child.kind == 4 {
                            fields.push(text_field(child, id_of(cv), child.label.clone().unwrap_or_default(), None, false));
                        }
                    }
                }
                // A label around a text input or a select.
                18 => {
                    let (label, description) = (c.label.clone().unwrap_or_default(), c.description.clone());
                    match c.component.as_deref() {
                        Some(child) if child.kind == 4 => fields.push(text_field(child, id_of(&v["component"]), label, description, true)),
                        Some(child) if child.kind == 3 => fields.push(Field::Select {
                            custom_id: child.custom_id.clone().unwrap_or_default(),
                            id: id_of(&v["component"]),
                            label,
                            description,
                            placeholder: child.placeholder.clone().unwrap_or_else(|| "Make a selection".into()),
                            options: child.options.clone(),
                            min: child.min_values.unwrap_or(1) as usize,
                            max: child.max_values.unwrap_or(1).max(1) as usize,
                            required: child.required.unwrap_or(true),
                            picked: child.options.iter().filter(|o| o.default).map(|o| o.value.clone()).collect(),
                            open: false,
                        }),
                        _ => {}
                    }
                }
                10 => fields.push(Field::Display(c.content.clone().unwrap_or_default())),
                _ => {}
            }
        }
        let app_icon = app["icon"].as_str().map(|h| format!("https://cdn.discordapp.com/app-icons/{application}/{h}.png?size=64"));
        self.bot_modal = Some(BotModal {
            id: d["id"].as_str().unwrap_or_default().to_string(),
            custom_id: d["custom_id"].as_str().unwrap_or_default().to_string(),
            title: d["title"].as_str().unwrap_or("Form").to_string(),
            application,
            app_name: app["name"].as_str().unwrap_or("this app").to_string(),
            app_icon,
            channel,
            fields,
            submitting: None,
            error: None,
            focus: true,
        });
    }

    /// The open form, and each frame the check for a click nobody answered.
    pub fn bot_modal_ui(&mut self, ctx: &egui::Context) {
        if self.interaction.as_ref().is_some_and(|p| p.at.elapsed() > GIVE_UP) {
            let nonce = self.interaction.as_ref().map(|p| p.nonce.clone()).unwrap_or_default();
            self.interaction_done(&nonce, false);
        }
        let Some(mut modal) = self.bot_modal.take() else { return };
        let t = self.theme.clone();
        let busy = modal.submitting.is_some();
        let mut close = ctx.input(|i| i.key_pressed(Key::Escape));
        let mut submit = false;
        let screen = ctx.screen_rect();
        egui::Area::new(egui::Id::new("bot_modal_dim")).order(Order::Foreground).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(178));
            close |= r.clicked();
        });
        egui::Area::new(egui::Id::new("bot_modal")).order(Order::Foreground).anchor(Align2::CENTER_CENTER, vec2(0.0, 0.0)).show(ctx, |ui| {
            ui.ctx().move_to_top(ui.layer_id());
            Frame::none()
                .fill(t.bg_secondary)
                .rounding(12.0)
                .stroke(Stroke::new(1.0_f32, t.border_subtle))
                .shadow(egui::epaint::Shadow { offset: vec2(0.0, 12.0), blur: 24.0, spread: 0.0, color: Color32::from_black_alpha(61) })
                .inner_margin(Margin { left: 24.0, right: 24.0, top: 24.0, bottom: 24.0 })
                .show(ui, |ui| {
                    let w = 432.0;
                    ui.set_width(w);
                    ui.spacing_mut().item_spacing = vec2(0.0, 0.0);
                    // Header: the app's icon, the title, close.
                    let (head, _) = ui.allocate_exact_size(vec2(w, 32.0), Sense::hover());
                    let mut x = head.left();
                    if let Some(url) = &modal.app_icon {
                        egui::Image::new(url.as_str()).rounding(12.0).paint_at(ui, Rect::from_min_size(pos2(x, head.center().y - 12.0), vec2(24.0, 24.0)));
                        x += 36.0;
                    }
                    let p = ui.painter_at(Rect::from_min_max(pos2(x, head.top()), pos2(head.right() - 44.0, head.bottom())));
                    super::paint_text_emoji(ui, &p, pos2(x, head.center().y), &modal.title, strong(24.0), t.header_primary);
                    let xr = Rect::from_center_size(pos2(head.right() - 4.0, head.top() + 4.0), vec2(40.0, 40.0));
                    let xb = ui.interact(xr, egui::Id::new("bot_modal_close"), Sense::click());
                    if xb.hovered() {
                        ui.painter().rect_filled(xr, 8.0, t.bg_hover);
                    }
                    ui.painter().text(xr.center(), Align2::CENTER_CENTER, icon::CLOSE, icon_font(16.0), if xb.hovered() { t.header_primary } else { t.interactive_normal });
                    close |= xb.on_hover_cursor(CursorIcon::PointingHand).clicked();
                    ui.add_space(24.0);

                    egui::ScrollArea::vertical().max_height((screen.height() - 280.0).max(160.0)).show(ui, |ui| {
                        ui.set_width(w);
                        warning(ui, &t, &modal.app_name);
                        let mut focus = std::mem::take(&mut modal.focus);
                        for (i, f) in modal.fields.iter_mut().enumerate() {
                            ui.add_space(if i == 0 { 16.0 } else { 24.0 });
                            submit |= field_ui(ui, &t, i, f, &mut focus, busy);
                        }
                        if let Some(e) = &modal.error {
                            ui.add_space(12.0);
                            ui.label(RichText::new(e).size(14.0).color(t.danger));
                        }
                    });

                    // Footer: two equal buttons.
                    ui.add_space(24.0);
                    let ready = modal.fields.iter().all(field_ready);
                    ui.horizontal(|ui| {
                        ui.spacing_mut().item_spacing.x = 8.0;
                        let bw = (w - 8.0) / 2.0;
                        let (r, b) = ui.allocate_exact_size(vec2(bw, 40.0), Sense::click());
                        ui.painter().rect(r, 8.0, crate::style::rgba(151, 151, 159, if b.hovered() { 51 } else { 31 }), Stroke::new(1.0_f32, crate::style::overlay(0.04)));
                        ui.painter().text(r.center(), Align2::CENTER_CENTER, "Cancel", medium(16.0), Color32::from_rgb(251, 251, 251));
                        close |= b.on_hover_cursor(CursorIcon::PointingHand).clicked();
                        let on = ready && !busy;
                        let (r, b) = ui.allocate_exact_size(vec2(bw, 40.0), if on { Sense::click() } else { Sense::hover() });
                        let fill = if b.hovered() && on { Color32::from_rgb(0x47, 0x52, 0xc4) } else { BRAND };
                        ui.painter().rect(r, 8.0, fill.gamma_multiply(if on || busy { 1.0 } else { 0.5 }), Stroke::new(1.0_f32, crate::style::rgba(255, 255, 255, 20)));
                        if busy {
                            loading_dots(ui, r.center(), Color32::WHITE);
                        } else {
                            ui.painter().text(r.center(), Align2::CENTER_CENTER, "Submit", medium(16.0), Color32::WHITE.gamma_multiply(if on { 1.0 } else { 0.6 }));
                        }
                        submit |= b.on_hover_cursor(if on { CursorIcon::PointingHand } else { CursorIcon::NotAllowed }).clicked();
                        submit &= on;
                    });
                });
        });
        if submit {
            self.submit_bot_modal(&mut modal);
        }
        // A form being sent stays up until the app has answered.
        if !close || busy {
            self.bot_modal = Some(modal);
        }
    }

    fn submit_bot_modal(&mut self, modal: &mut BotModal) {
        let nonce = new_nonce();
        let Some(mut body) = self.interaction_base(modal.channel, modal.application, &nonce) else {
            modal.error = Some("Not connected yet, try again in a moment.".into());
            return;
        };
        let with_id = |mut v: Value, id: &Option<u64>| {
            if let Some(id) = id {
                v["id"] = json!(id);
            }
            v
        };
        let components: Vec<Value> = modal
            .fields
            .iter()
            .filter_map(|f| match f {
                Field::Text { custom_id, id, value, in_label, .. } => {
                    let input = with_id(json!({ "type": 4, "custom_id": custom_id, "value": value }), id);
                    Some(if *in_label { json!({ "type": 18, "component": input }) } else { json!({ "type": 1, "components": [input] }) })
                }
                Field::Select { custom_id, id, picked, .. } => Some(json!({ "type": 18, "component": with_id(json!({ "type": 3, "custom_id": custom_id, "values": picked }), id) })),
                Field::Display(_) => None,
            })
            .collect();
        body["type"] = json!(5);
        body["data"] = json!({ "id": modal.id, "custom_id": modal.custom_id, "components": components });
        modal.error = None;
        modal.submitting = Some(nonce.clone());
        self.api(&format!("interact:{nonce}"), reqwest::Method::POST, "/interactions", Some(body));
    }
}

fn text_field(c: &Component, id: Option<u64>, label: String, description: Option<String>, in_label: bool) -> Field {
    Field::Text {
        custom_id: c.custom_id.clone().unwrap_or_default(),
        id,
        label,
        description,
        paragraph: c.style == Some(2),
        placeholder: c.placeholder.clone().unwrap_or_default(),
        min: c.min_length.unwrap_or(0) as usize,
        max: c.max_length.unwrap_or(4000).clamp(1, 4000) as usize,
        required: c.required.unwrap_or(true),
        value: c.value.clone().unwrap_or_default(),
        in_label,
    }
}

/// Can the form be sent as far as this input goes?
fn field_ready(f: &Field) -> bool {
    match f {
        Field::Text { min, required, value, .. } => {
            let n = value.chars().count();
            if n == 0 {
                !*required
            } else {
                n >= *min
            }
        }
        Field::Select { min, required, picked, .. } => {
            if picked.is_empty() {
                !*required
            } else {
                picked.len() >= *min
            }
        }
        Field::Display(_) => true,
    }
}

/// Discord's notice at the top of every app form.
fn warning(ui: &mut Ui, t: &Theme, app: &str) {
    Frame::none()
        .fill(crate::style::rgba(240, 178, 50, 20))
        .stroke(Stroke::new(1.0_f32, crate::style::rgba(240, 178, 50, 82)))
        .rounding(8.0)
        .inner_margin(12.0)
        .show(ui, |ui| {
            ui.set_width(ui.available_width());
            ui.horizontal_top(|ui| {
                ui.spacing_mut().item_spacing.x = 0.0;
                // A warning triangle.
                let (r, _) = ui.allocate_exact_size(vec2(24.0, 18.0), Sense::hover());
                let c = pos2(r.left() + 8.0, r.center().y);
                let tri = vec![pos2(c.x, c.y - 7.0), pos2(c.x + 8.0, c.y + 6.5), pos2(c.x - 8.0, c.y + 6.5)];
                ui.painter().add(egui::Shape::convex_polygon(tri, Color32::from_rgb(240, 178, 50), Stroke::NONE));
                ui.painter().text(pos2(c.x, c.y + 1.5), Align2::CENTER_CENTER, "!", strong(10.0), Color32::from_rgb(40, 30, 0));
                ui.horizontal_wrapped(|ui| {
                    ui.spacing_mut().item_spacing = vec2(0.0, 0.0);
                    let text = |s: &str| RichText::new(s).size(14.0).line_height(Some(18.0)).color(t.header_primary);
                    ui.label(text("This form will be submitted to "));
                    ui.label(text(app).family(egui::FontFamily::Name(crate::style::BOLD.into())));
                    ui.label(text(". Do not share passwords or other sensitive information."));
                });
            });
        });
}

/// One input with its label. True when Enter asked to send the form.
fn field_ui(ui: &mut Ui, t: &Theme, index: usize, f: &mut Field, focus: &mut bool, busy: bool) -> bool {
    let label_row = |ui: &mut Ui, label: &str, description: &Option<String>, required: bool| {
        ui.horizontal(|ui| {
            ui.spacing_mut().item_spacing.x = 4.0;
            ui.label(RichText::new(label).font(medium(16.0)).color(t.header_primary));
            if required {
                ui.label(RichText::new("*").font(medium(16.0)).color(t.danger));
            }
        });
        if let Some(d) = description.as_ref().filter(|d| !d.is_empty()) {
            ui.add_space(4.0);
            ui.label(RichText::new(d).size(14.0).color(t.text_muted));
        }
        ui.add_space(8.0);
    };
    match f {
        Field::Display(text) => {
            ui.label(RichText::new(text.as_str()).size(16.0).color(t.text_normal));
            false
        }
        Field::Text { label, description, paragraph, placeholder, max, required, value, .. } => {
            label_row(ui, label, description, *required);
            let id = egui::Id::new(("bot_modal_field", index));
            let focused = ui.memory(|m| m.has_focus(id));
            let out = Frame::none()
                .fill(Color32::from_black_alpha(31))
                .stroke(Stroke::new(1.0_f32, if focused { BRAND } else { crate::style::overlay(0.2) }))
                .rounding(8.0)
                .inner_margin(Margin::symmetric(12.0, 9.0))
                .show(ui, |ui| {
                    let edit = if *paragraph { egui::TextEdit::multiline(value).desired_rows(4) } else { egui::TextEdit::singleline(value) };
                    ui.add_enabled(
                        !busy,
                        edit.id(id).frame(false).desired_width(f32::INFINITY).font(FontId::proportional(16.0)).text_color(t.text_normal).hint_text(RichText::new(placeholder.as_str()).color(t.text_muted)).char_limit(*max),
                    )
                });
            if std::mem::take(focus) {
                out.inner.request_focus();
            }
            // Enter sends from a one-line input.
            !*paragraph && out.inner.lost_focus() && ui.input(|i| i.key_pressed(Key::Enter))
        }
        Field::Select { label, description, placeholder, options, max, required, picked, open, .. } => {
            label_row(ui, label, description, *required);
            let shown: Vec<&str> = options.iter().filter(|o| picked.contains(&o.value)).map(|o| o.label.as_str()).collect();
            let text = if shown.is_empty() { placeholder.clone() } else { shown.join(", ") };
            let (rect, resp) = ui.allocate_exact_size(vec2(ui.available_width(), 40.0), if busy { Sense::hover() } else { Sense::click() });
            ui.painter().rect(rect, 8.0, Color32::from_black_alpha(31), Stroke::new(1.0_f32, if *open { BRAND } else { crate::style::overlay(0.2) }));
            let p = ui.painter_at(rect.shrink2(vec2(12.0, 0.0)));
            super::paint_text_emoji(ui, &p, pos2(rect.left() + 12.0, rect.center().y), &text, medium(16.0), if shown.is_empty() { t.text_muted } else { t.text_normal });
            ui.painter().text(pos2(rect.right() - 17.0, rect.center().y), Align2::CENTER_CENTER, icon::CHEVRON_DOWN, icon_font(11.0), t.interactive_normal);
            if resp.on_hover_cursor(CursorIcon::PointingHand).clicked() {
                *open = !*open;
            }
            if *open {
                ui.add_space(4.0);
                Frame::none().fill(t.bg_floating).stroke(Stroke::new(1.0_f32, t.border_subtle)).rounding(8.0).show(ui, |ui| {
                    ui.set_width(ui.available_width());
                    egui::ScrollArea::vertical().id_salt(("bot_modal_options", index)).max_height(200.0).show(ui, |ui| {
                        for o in options.iter() {
                            let on = picked.contains(&o.value);
                            let (r, b) = ui.allocate_exact_size(vec2(ui.available_width(), if o.description.is_some() { 56.0 } else { 40.0 }), Sense::click());
                            if b.hovered() || on {
                                ui.painter().rect_filled(r.shrink(2.0), 6.0, t.bg_hover);
                            }
                            let p = ui.painter_at(r.shrink2(vec2(8.0, 0.0)));
                            let y = if o.description.is_some() { r.top() + 17.0 } else { r.center().y };
                            super::paint_text_emoji(ui, &p, pos2(r.left() + 10.0, y), &o.label, strong(14.0), t.header_primary);
                            if let Some(d) = &o.description {
                                super::paint_text_emoji(ui, &p, pos2(r.left() + 10.0, r.top() + 39.0), d, FontId::proportional(14.0), t.text_muted);
                            }
                            if on {
                                ui.painter().text(pos2(r.right() - 18.0, r.center().y), Align2::CENTER_CENTER, icon::CHECK, icon_font(12.0), BRAND);
                            }
                            if b.on_hover_cursor(CursorIcon::PointingHand).clicked() {
                                if on {
                                    picked.retain(|v| v != &o.value);
                                } else if *max <= 1 {
                                    *picked = vec![o.value.clone()];
                                    *open = false;
                                } else if picked.len() < *max {
                                    picked.push(o.value.clone());
                                }
                            }
                        }
                    });
                });
            }
            false
        }
    }
}