Skip to content

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

13.0 KB
Raw Blame
//! Server Settings → Members: the server's members, newest first (Discord's
//! member search), with a search box, Prune and each member's menu
//! (moderation.rs: roles, timeout, kick, ban).

use super::{bold_font, btn, help, input, link, title, vstr, Act, Btn, Theme, KICK_MEMBERS, MANAGE_GUILD};
use crate::app::RustCord;
use crate::style::{bold, icon, icon_font, overlay};
use crate::ui::moderation::{member_search_tag, unix_of};
use discord::model::{Id, User};
use eframe::egui::{self, pos2, vec2, Align, Align2, Color32, CursorIcon, FontId, Layout, Pos2, Rect, RichText, Sense, Stroke, Ui};
use reqwest::Method;
use serde::Deserialize;
use serde_json::{json, Value};
use std::time::Duration;

/// Members asked for per search; "Load more" asks for this many more, up to
/// Discord's limit of 1000.
const PAGE: usize = 250;
const MAX: usize = 1000;
/// A search waits for typing to pause this long (seconds).
const TYPING_PAUSE: f64 = 0.35;

/// The page's state (egui temp memory, per server).
#[derive(Clone, Default)]
struct MembersUi {
    query: String,
    /// The (query, limit) of the search on screen or on its way.
    sent: Option<(String, usize)>,
    limit: usize,
    /// When the query last changed.
    edited_at: f64,
    /// The frame the page was last drawn (coming back to it searches again).
    drawn: u64,
}

/// Where each column starts in a row `w` wide (Name at 0).
fn columns(left: f32, w: f32) -> [f32; 4] {
    [left + w * 0.31, left + w * 0.47, left + w * 0.63, left + w * 0.78]
}

/// How they joined (`join_source_type`), as (what, detail).
fn join_method(e: &Value) -> (&str, &'static str) {
    let code = vstr(e, "source_invite_code");
    match e["join_source_type"].as_u64().unwrap_or(0) {
        1 => ("Bot", "Added by an app"),
        2 => ("Integration", "Joined through an integration"),
        3 => ("Server Discovery", "Found in Server Discovery"),
        4 => ("Student Hub", "Joined from a Student Hub"),
        5 if !code.is_empty() => (code, "Invite"),
        5 => ("Invite", "Joined with an invite"),
        6 => ("Vanity URL", "The server's custom invite"),
        7 => ("Application", "Approved to join"),
        _ => ("Unknown", "Join method not available"),
    }
}

/// "19 days ago" over "3 Nov 2026, 22:29".
fn when(unix: i64) -> (String, String) {
    let Some(dt) = chrono::DateTime::from_timestamp(unix, 0) else { return (String::new(), String::new()) };
    let local = dt.with_timezone(&chrono::Local);
    let date = format!("{}, {}", local.format("%-d %b %Y"), local.format(crate::ui::time_fmt()));
    (crate::ui::relative_time(unix - chrono::Utc::now().timestamp()), date)
}

/// A two-line cell: `top` in the normal colour over `bottom` muted.
fn cell(ui: &Ui, t: &Theme, clip: Rect, x: f32, y: f32, top: &str, bottom: &str) {
    let p = ui.painter_at(clip);
    p.text(pos2(x, y - 9.0), Align2::LEFT_CENTER, top, FontId::proportional(14.0), t.text_normal);
    p.text(pos2(x, y + 9.0), Align2::LEFT_CENTER, bottom, FontId::proportional(12.0), t.text_muted);
}

impl RustCord {
    pub(super) fn ss_members(&self, ui: &mut Ui, t: &Theme, acts: &mut Vec<Act>, g: Id) {
        let id = egui::Id::new(("ss_members", g.0));
        let mut st: MembersUi = ui.data(|d| d.get_temp(id)).unwrap_or_default();
        let frame = ui.ctx().cumulative_pass_nr();
        let now = ui.input(|i| i.time);
        let returning = st.drawn + 1 < frame;
        st.drawn = frame;
        if st.limit == 0 {
            st.limit = PAGE;
        }

        title(ui, t, "Server Members");
        // "Recent Members", Prune on the right (Discord: Kick Members and Manage Server).
        let can_prune = self.store.has_perm(g, KICK_MEMBERS) && self.store.has_perm(g, MANAGE_GUILD);
        ui.horizontal(|ui| {
            ui.label(bold("Recent Members").size(16.0).color(t.header_primary));
            if can_prune {
                ui.with_layout(Layout::right_to_left(Align::Center), |ui| {
                    if btn(ui, t, Btn::Secondary, "Prune", true).clicked() {
                        acts.push(Act::Run(Box::new(move |app: &mut RustCord| app.open_prune(g))));
                    }
                });
            }
        });
        ui.add_space(12.0);
        let w = ui.available_width();
        if input(ui, t, egui::Id::new(("ss_members_search", g.0)), &mut st.query, "Search by username", 1, 100, w).changed() {
            st.edited_at = now;
            st.limit = PAGE;
        }
        ui.add_space(16.0);

        // Search when the page shows, when typing pauses and for "Load more".
        let tag = member_search_tag(g);
        let want = (st.query.trim().to_string(), st.limit);
        let changed = st.sent.as_ref() != Some(&want);
        let settled = now - st.edited_at >= TYPING_PAUSE;
        let mut search = !self.api_busy(&tag) && (returning || self.api_result(&tag).is_none() || (changed && settled));
        if changed && !settled {
            ui.ctx().request_repaint_after(Duration::from_secs_f64(TYPING_PAUSE));
        }

        match self.api_result(&tag) {
            None => {
                ui.horizontal(|ui| {
                    ui.spinner();
                    ui.label(RichText::new("Loading…").color(t.text_muted));
                });
            }
            Some(Err(e)) => {
                ui.label(RichText::new(format!("Couldn't load the members: {e}")).color(t.danger));
                ui.add_space(8.0);
                search |= btn(ui, t, Btn::Secondary, "Try Again", true).clicked();
            }
            Some(Ok(v)) => match v["members"].as_array() {
                // Discord answers without a list while it indexes a server's members.
                None => {
                    help(ui, t, "Discord is still getting this server's member list ready. Try again in a moment.");
                    ui.add_space(8.0);
                    search |= btn(ui, t, Btn::Secondary, "Try Again", true).clicked();
                }
                Some(list) => {
                    self.ss_member_table(ui, t, acts, g, list);
                    ui.add_space(16.0);
                    let n = list.len();
                    help(ui, t, &format!("Showing {n} member{}", if n == 1 { "" } else { "s" }));
                    let total = v["total_result_count"].as_u64().unwrap_or(0) as usize;
                    if total > n && st.limit < MAX {
                        ui.add_space(4.0);
                        if link(ui, "Load more", t.text_link).clicked() {
                            st.limit = (st.limit + PAGE).min(MAX);
                        }
                    }
                }
            },
        }

        if search {
            let (query, limit) = (st.query.trim().to_string(), st.limit);
            st.sent = Some((query.clone(), limit));
            acts.push(Act::Run(Box::new(move |app: &mut RustCord| app.ss_member_search(g, &query, limit))));
        }
        ui.data_mut(|d| d.insert_temp(id, st));
    }

    /// The members table: Name, Member Since, Joined Discord, Join Method,
    /// Roles, and the "More Options" button (right-click a row for the same menu).
    fn ss_member_table(&self, ui: &mut Ui, t: &Theme, acts: &mut Vec<Act>, g: Id, list: &[Value]) {
        let Some(gs) = self.store.guilds.get(&g) else { return };
        let w = ui.available_width();
        let now = chrono::Utc::now().timestamp();

        let (head, _) = ui.allocate_exact_size(vec2(w, 28.0), Sense::hover());
        let cols = columns(head.left(), w);
        for (x, text) in [(head.left() + 8.0, "NAME"), (cols[0], "MEMBER SINCE"), (cols[1], "JOINED DISCORD"), (cols[2], "JOIN METHOD"), (cols[3], "ROLES")] {
            ui.painter().text(pos2(x, head.center().y), Align2::LEFT_CENTER, text, bold_font(12.0), t.text_muted);
        }
        ui.painter().hline(head.x_range(), head.bottom(), Stroke::new(1.0_f32, t.border_subtle));

        let mut menu: Option<(User, Pos2)> = None;
        for e in list {
            let (row, resp) = ui.allocate_exact_size(vec2(w, 60.0), Sense::click());
            let resp = resp.on_hover_cursor(egui::CursorIcon::PointingHand);
            // Parsed only when on screen: the list can be a thousand long.
            if !ui.is_rect_visible(row) {
                continue;
            }
            let m = &e["member"];
            let Ok(user) = User::deserialize(&m["user"]) else { continue };
            if resp.hovered() {
                ui.painter().rect_filled(row, 6.0, overlay(0.04));
            }
            ui.painter().hline(row.x_range(), row.bottom(), Stroke::new(1.0_f32, t.border_subtle));
            let y = row.center().y;
            let col = |i: usize| Rect::from_min_max(pos2(cols[i], row.top()), pos2(cols.get(i + 1).map_or(row.right() - 40.0, |x| *x) - 8.0, row.bottom()));

            // Name: avatar, server nickname (or display name), username.
            let nick = vstr(m, "nick");
            let name = if nick.is_empty() { user.display_name() } else { nick };
            let av = Rect::from_center_size(pos2(row.left() + 24.0, y), vec2(32.0, 32.0));
            crate::ui::paint_avatar(ui, av, Some(user.avatar_or_default(64)), name);
            let p = ui.painter_at(Rect::from_min_max(row.min, pos2(cols[0] - 8.0, row.bottom())));
            p.text(pos2(av.right() + 12.0, y - 9.0), Align2::LEFT_CENTER, name, bold_font(14.0), t.header_primary);
            let under = p.text(pos2(av.right() + 12.0, y + 9.0), Align2::LEFT_CENTER, &user.username, FontId::proportional(12.0), t.text_muted);
            if unix_of(&m["communication_disabled_until"]).is_some_and(|until| until > now) {
                p.text(pos2(under.right() + 6.0, y + 9.0), Align2::LEFT_CENTER, "Timed out", FontId::proportional(12.0), t.danger);
            }

            // Member Since / Joined Discord (from the account's ID).
            if let Some(joined) = unix_of(&m["joined_at"]) {
                let (ago, date) = when(joined);
                cell(ui, t, col(0), cols[0], y, &ago, &date);
            }
            let (ago, date) = when((user.id.timestamp_ms() / 1000) as i64);
            cell(ui, t, col(1), cols[1], y, &ago, &date);
            let (what, detail) = join_method(e);
            cell(ui, t, col(2), cols[2], y, what, detail);

            // Roles, highest first, as Discord's chips; "+N" for what doesn't fit.
            let ids: Vec<Id> = m["roles"].as_array().into_iter().flatten().filter_map(Id::from_value).collect();
            let mut roles: Vec<_> = gs.guild.roles.iter().filter(|r| ids.contains(&r.id)).collect();
            roles.sort_by_key(|r| std::cmp::Reverse(r.position));
            let area = col(3);
            let p = ui.painter_at(area);
            let mut x = area.left();
            for (i, r) in roles.iter().enumerate() {
                let galley = p.layout_no_wrap(r.name.clone(), FontId::proportional(12.0), t.header_primary);
                let chip_w = galley.size().x + 26.0;
                let left = roles.len() - i;
                if x + chip_w > area.right() - if left > 1 { 30.0 } else { 0.0 } {
                    p.text(pos2(x + 2.0, y), Align2::LEFT_CENTER, format!("+{left}"), FontId::proportional(12.0), t.text_muted);
                    break;
                }
                let chip = Rect::from_min_size(pos2(x, y - 11.0), vec2(chip_w, 22.0));
                p.rect_filled(chip, 6.0, overlay(0.08));
                let dot = if r.color == 0 { t.interactive_normal } else { Color32::from_rgb((r.color >> 16) as u8, (r.color >> 8) as u8, r.color as u8) };
                p.circle_filled(pos2(chip.left() + 11.0, y), 4.0, dot);
                p.galley(pos2(chip.left() + 19.0, y - galley.size().y / 2.0), galley, t.header_primary);
                x += chip_w + 4.0;
            }

            // More Options (…): the member menu.
            let more = Rect::from_center_size(pos2(row.right() - 20.0, y), vec2(32.0, 32.0));
            let b = ui.interact(more, egui::Id::new(("ss_member_more", g.0, user.id.0)), Sense::click()).on_hover_cursor(CursorIcon::PointingHand).on_hover_text("More Options");
            if b.hovered() {
                ui.painter().rect_filled(more, 6.0, overlay(0.12));
            }
            ui.painter().text(more.center(), Align2::CENTER_CENTER, icon::MORE, icon_font(16.0), if b.hovered() { t.interactive_hover } else { t.interactive_normal });
            if b.clicked() {
                menu = Some((user, pos2(more.right() - 220.0, more.bottom() + 4.0)));
            } else if resp.secondary_clicked() {
                menu = Some((user, resp.interact_pointer_pos().unwrap_or(more.left_bottom())));
            }
        }
        if let Some((user, at)) = menu {
            acts.push(Act::Run(Box::new(move |app: &mut RustCord| app.open_member_menu(g, user, at))));
        }
    }

    /// Discord's member search, newest first; `query` matches usernames.
    fn ss_member_search(&mut self, g: Id, query: &str, limit: usize) {
        let and_query = if query.is_empty() { json!({}) } else { json!({ "usernames": { "or_query": [query] } }) };
        let body = json!({ "limit": limit, "sort": 1, "or_query": {}, "and_query": and_query });
        self.api(&member_search_tag(g), Method::POST, format!("/guilds/{g}/members-search"), Some(body));
    }
}