Lightweight native Discord client for Windows, Linux and macOS, written in Rust. No Electron, no browser engine.
Rust desktop-appdiscorddiscord-clienteguielectron-alternativelightweightlinuxmacosnative-apprustwindows
//! A server member's right-click menu (Discord's user context menu) and the
//! moderation dialogs it opens: change nickname, roles, timeout, kick, ban,
//! plus Server Settings → Members' Prune.
//!
//! One menu and at most one dialog are open at a time (`ModState`). Rows show
//! only when you may use them: your permissions, and for the moderator
//! actions the role hierarchy (never yourself or the owner; their highest
//! role must be below yours unless you own the server). What the menu needs
//! to know about the member (roles, timeout) comes from the store, the
//! Members page's search results or, once per member, `GET …/members/{id}`.
use crate::app::RustCord;
use crate::style::{bold, icon, icon_font, medium, overlay, Theme};
use discord::model::{permissions, Id, User};
use eframe::egui::{
self, epaint::Shadow, pos2, vec2, Align, Align2, Color32, CursorIcon, FontFamily, FontId, Frame, Key, Label, Layout, Margin, Modifiers, Order, Pos2, Rect, Response,
RichText, ScrollArea, Sense, Stroke, TextEdit, Ui,
};
use reqwest::Method;
use serde_json::{json, Value};
use std::collections::{HashMap, HashSet};
// Discord's permission bits the menu needs that `permissions` doesn't name.
const KICK_MEMBERS: u64 = 1 << 1;
const BAN_MEMBERS: u64 = 1 << 2;
const MANAGE_NICKNAMES: u64 = 1 << 27;
const MODERATE_MEMBERS: u64 = 1 << 40;
/// Discord's user menu is 220 px wide; the Roles submenu a little narrower.
const MENU_W: f32 = 220.0;
const SUB_W: f32 = 200.0;
/// "Timeout" lengths, as Discord offers them (its maximum is 28 days).
const TIMEOUTS: [(i64, &str); 6] = [(60, "60 secs"), (300, "5 mins"), (600, "10 mins"), (3600, "1 hour"), (86_400, "1 day"), (604_800, "1 week")];
/// "Reason for Ban": the last one ("Other") asks for your own words.
const BAN_REASONS: [&str; 4] = ["Suspicious or spam account", "Compromised or hacked account", "Breaking server rules", "Other"];
/// "Delete Message History": seconds of their messages to remove.
const BAN_HISTORY: [(u32, &str); 7] = [
(0, "Don't Delete Any"),
(3600, "Previous Hour"),
(21_600, "Previous 6 Hours"),
(43_200, "Previous 12 Hours"),
(86_400, "Previous 24 Hours"),
(259_200, "Previous 3 Days"),
(604_800, "Previous 7 Days"),
];
/// Prune: members not seen for this many days.
const PRUNE_DAYS: [u32; 3] = [1, 7, 30];
/// The api tag of the Members page's search for a server (the moderation
/// actions keep that list up to date).
pub fn member_search_tag(guild: Id) -> String {
format!("ss:members:{guild}")
}
/// What the member menu and its dialogs remember between frames.
#[derive(Default)]
pub struct ModState {
menu: Option<Menu>,
dialog: Option<Dialog>,
/// Requests on their way: (api tag, what to do with the answer).
pending: Vec<(String, Op)>,
/// Numbers the api tags.
seq: u64,
/// When a member's timeout ends (unix seconds), by (server, user).
timeouts: HashMap<(Id, Id), i64>,
/// Members already looked up this session.
fetched: HashSet<(Id, Id)>,
}
struct Menu {
guild: Id,
user: User,
pos: Pos2,
/// Frame it opened (the opening click doesn't close it).
opened: u64,
/// The Roles submenu is open, beside the row with this top.
roles: Option<f32>,
}
enum Dialog {
Nickname { guild: Id, user: User, nick: String },
Timeout { guild: Id, user: User, secs: i64, reason: String },
Kick { guild: Id, user: User, reason: String },
/// `reason` indexes `BAN_REASONS`; `error` once Ban was pressed without one.
Ban { guild: Id, user: User, reason: Option<usize>, other: String, history: u32, history_open: bool, error: bool },
/// `count`: how many would go, for `days` (None while counting).
Prune { guild: Id, days: u32, count: Option<Result<u64, String>> },
}
/// A request in flight and what its answer changes.
enum Op {
/// The member's roles and timeout, for the menu.
Fetch { guild: Id },
Nick { guild: Id, user: Id },
/// A role given or taken (already shown; put back if it fails).
Role { guild: Id, user: Id, role: Id, add: bool },
Timeout { guild: Id, user: Id, until: Option<i64>, name: String },
Kick { guild: Id, user: Id, name: String },
Ban { guild: Id, user: Id, name: String },
/// Server mute / deafen / disconnect, block: only failures are told.
Quiet(&'static str),
PruneCount { guild: Id, days: u32 },
Prune { guild: Id, count: u64 },
}
/// A menu row that was clicked (carried out after drawing).
#[derive(Clone, Copy)]
enum Pick {
Profile,
Mention,
Message,
AddNote,
FriendNickname,
Volume(f32, bool),
StreamVolume(f32, bool),
LocalMute,
SelfDeafen,
Nickname,
Block(bool),
Role(Id, bool),
ServerMute(bool),
ServerDeaf(bool),
Disconnect,
Timeout,
RemoveTimeout,
Kick,
Ban,
CopyId,
}
/// The menu's rows in groups, with Discord's separators between the groups
/// that have something in them.
struct Rows<'a> {
t: &'a Theme,
pick: Option<Pick>,
/// A row other than Roles is hovered: its submenu closes.
other_hovered: bool,
any: bool,
new_group: bool,
}
impl Rows<'_> {
fn group(&mut self) {
self.new_group = true;
}
fn begin(&mut self, ui: &mut Ui) {
if self.new_group && self.any {
super::ctx_separator(ui, self.t);
}
self.new_group = false;
self.any = true;
}
fn item(&mut self, ui: &mut Ui, glyph: Option<&str>, label: &str, danger: bool, pick: Pick) {
self.begin(ui);
let r = super::ctx_row(ui, self.t, glyph, label, None, danger, true);
self.other_hovered |= r.hovered();
if r.clicked() {
self.pick = Some(pick);
}
}
fn check(&mut self, ui: &mut Ui, label: &str, on: bool, pick: Pick) {
self.begin(ui);
let r = check_row(ui, self.t, None, label, on, true);
self.other_hovered |= r.hovered();
if r.clicked() {
self.pick = Some(pick);
}
}
}
/// A menu row with Discord's checkbox on the right (and, for roles, the
/// role's colour as a dot before the label).
fn check_row(ui: &mut Ui, t: &Theme, dot: Option<Color32>, label: &str, checked: bool, enabled: bool) -> Response {
let (r, resp) = ui.allocate_exact_size(vec2(ui.available_width(), super::dense(34.0)), if enabled { Sense::click() } else { Sense::hover() });
let hovered = enabled && resp.hovered();
if hovered {
ui.painter().rect_filled(r, 4.0, t.bg_hover);
}
let fg = if enabled { t.header_primary } else { t.text_muted.gamma_multiply(0.6) };
let mut x = r.left() + 8.0;
if let Some(c) = dot {
ui.painter().circle_filled(pos2(x + 5.0, r.center().y), 5.0, if enabled { c } else { c.gamma_multiply(0.5) });
x += 18.0;
}
ui.painter()
.with_clip_rect(r.with_max_x(r.right() - 34.0).intersect(ui.clip_rect()))
.text(pos2(x, r.center().y), Align2::LEFT_CENTER, label, medium(14.0), fg);
let b = Rect::from_center_size(pos2(r.right() - 18.0, r.center().y), vec2(18.0, 18.0));
let blurple = if enabled { super::voice_menu::BLURPLE } else { super::voice_menu::BLURPLE.gamma_multiply(0.5) };
if checked {
ui.painter().rect_filled(b, 4.0, blurple);
ui.painter().text(b.center(), Align2::CENTER_CENTER, icon::CHECK, icon_font(11.0), Color32::WHITE);
} else {
ui.painter().rect_stroke(b.shrink(0.75), 4.0, Stroke::new(1.5_f32, if enabled { t.interactive_normal } else { fg }));
}
if enabled {
resp.on_hover_cursor(CursorIcon::PointingHand)
} else {
resp
}
}
#[derive(Clone, Copy, PartialEq)]
enum Btn {
Primary,
Secondary,
Danger,
}
fn bold_font(size: f32) -> FontId {
FontId::new(size, FontFamily::Name(crate::style::BOLD.into()))
}
/// Discord's modal button: 38 px, 8 px corners, bold label.
fn button(ui: &mut Ui, t: &Theme, kind: Btn, text: &str, enabled: bool) -> Response {
let fg = if kind == Btn::Secondary { t.header_primary } else { Color32::WHITE };
let galley = ui.painter().layout_no_wrap(text.to_string(), bold_font(14.0), fg);
let (r, resp) = ui.allocate_exact_size(vec2((galley.size().x + 32.0).max(96.0), 38.0), if enabled { Sense::click() } else { Sense::hover() });
let hot = enabled && resp.hovered();
let fill = match kind {
Btn::Primary => t.accent,
Btn::Secondary => overlay(if hot { 0.2 } else { 0.12 }),
Btn::Danger => t.danger,
};
let fill = if hot && kind != Btn::Secondary { fill.gamma_multiply(0.85) } else { fill };
ui.painter().rect_filled(r, 8.0, if enabled { fill } else { fill.gamma_multiply(0.5) });
ui.painter().galley(r.center() - galley.size() / 2.0, galley, fg);
if enabled {
resp.on_hover_cursor(CursorIcon::PointingHand)
} else {
resp
}
}
/// A form label above a field ("Reason for Kick").
fn label(ui: &mut Ui, t: &Theme, text: &str) {
ui.label(RichText::new(text).font(medium(15.0)).color(t.header_primary));
ui.add_space(8.0);
}
/// Discord's text field: input fill, hairline border (link blue while typing).
fn text_box(ui: &mut Ui, t: &Theme, id: egui::Id, text: &mut String, hint: &str, rows: usize, limit: usize) -> Response {
let focused = ui.memory(|m| m.has_focus(id));
Frame::none()
.fill(t.input_bg)
.rounding(8.0)
.stroke(Stroke::new(1.0_f32, if focused { t.text_link } else { overlay(0.2) }))
.inner_margin(Margin::symmetric(12.0, 10.0))
.show(ui, |ui| {
let edit = if rows > 1 { TextEdit::multiline(text).desired_rows(rows) } else { TextEdit::singleline(text) };
ui.add(edit.id(id).frame(false).hint_text(hint).char_limit(limit).desired_width(ui.available_width()).font(FontId::proportional(15.0)).text_color(t.text_normal))
})
.inner
}
/// A row of pill choices (timeout lengths, prune days); returns the one clicked.
fn pills<T: Copy + PartialEq>(ui: &mut Ui, t: &Theme, choices: &[(T, &str)], selected: T) -> Option<T> {
let mut picked = None;
ui.horizontal_wrapped(|ui| {
ui.spacing_mut().item_spacing = vec2(8.0, 8.0);
for &(value, text) in choices {
let on = value == selected;
let galley = ui.painter().layout_no_wrap(text.to_string(), medium(14.0), t.header_primary);
let (r, resp) = ui.allocate_exact_size(vec2(galley.size().x + 24.0, 32.0), Sense::click());
let fill = if on {
super::voice_menu::BLURPLE
} else if resp.hovered() {
overlay(0.16)
} else {
overlay(0.08)
};
ui.painter().rect_filled(r, 16.0, fill);
let fg = if on { Color32::WHITE } else { t.header_primary };
ui.painter().galley(r.center() - galley.size() / 2.0, galley, fg);
if resp.on_hover_cursor(CursorIcon::PointingHand).clicked() && !on {
picked = Some(value);
}
}
});
picked
}
/// A radio row (Ban's reasons).
fn radio_row(ui: &mut Ui, t: &Theme, text: &str, on: bool) -> bool {
let (r, resp) = ui.allocate_exact_size(vec2(ui.available_width(), 36.0), Sense::click());
if resp.hovered() {
ui.painter().rect_filled(r, 6.0, overlay(0.06));
}
let c = pos2(r.left() + 14.0, r.center().y);
if on {
ui.painter().circle_filled(c, 9.0, super::voice_menu::BLURPLE);
ui.painter().circle_filled(c, 3.5, Color32::WHITE);
} else {
ui.painter().circle_stroke(c, 8.25, Stroke::new(1.5_f32, t.interactive_normal));
}
ui.painter().text(pos2(r.left() + 34.0, c.y), Align2::LEFT_CENTER, text, FontId::proportional(15.0), if on { t.header_primary } else { t.text_normal });
resp.on_hover_cursor(CursorIcon::PointingHand).clicked()
}
/// What happened in a dialog this frame.
#[derive(Default)]
struct Answer {
/// The action button ("Kick", "Ban"…).
go: bool,
/// Cancel, or a click on the dimmed app.
cancel: bool,
}
/// Discord's modal over a dimmed app: title, body, then Cancel and the
/// action button on the right. Both layers go above Server Settings.
fn modal(ctx: &egui::Context, t: &Theme, title: &str, action: (&str, Btn, bool), body: impl FnOnce(&mut Ui)) -> Answer {
let mut answer = Answer::default();
let screen = ctx.screen_rect();
let dim = egui::Area::new(egui::Id::new("mod_dialog_dim")).order(Order::Tooltip).fixed_pos(screen.min).show(ctx, |ui| {
let (r, resp) = ui.allocate_exact_size(screen.size(), Sense::click());
ui.painter().rect_filled(r, 0.0, Color32::from_black_alpha(170));
resp.clicked()
});
ctx.move_to_top(dim.response.layer_id);
let card = egui::Area::new(egui::Id::new("mod_dialog")).order(Order::Tooltip).anchor(Align2::CENTER_CENTER, vec2(0.0, 0.0)).show(ctx, |ui| {
Frame::none()
.fill(t.surface_high)
.rounding(12.0)
.stroke(Stroke::new(1.0_f32, super::modal_border(t)))
.shadow(Shadow { offset: vec2(0.0, 8.0), blur: 24.0, spread: 0.0, color: Color32::from_black_alpha(140) })
.show(ui, |ui| {
ui.set_width(440.0);
ui.spacing_mut().item_spacing.y = 0.0;
Frame::none().inner_margin(Margin { left: 24.0, right: 24.0, top: 24.0, bottom: 8.0 }).show(ui, |ui| {
ui.set_width(ui.available_width());
ui.add(Label::new(bold(title).size(20.0).color(t.header_primary)).wrap());
ui.add_space(16.0);
body(ui);
});
Frame::none().inner_margin(Margin { left: 24.0, right: 24.0, top: 16.0, bottom: 24.0 }).show(ui, |ui| {
ui.set_width(ui.available_width());
ui.spacing_mut().item_spacing.x = 8.0;
ui.with_layout(Layout::right_to_left(Align::Center), |ui| {
let (text, kind, enabled) = action;
answer.go = button(ui, t, kind, text, enabled).clicked();
answer.cancel = button(ui, t, Btn::Secondary, "Cancel", true).clicked();
});
});
});
});
ctx.move_to_top(card.response.layer_id);
answer.cancel |= dim.inner;
answer
}
/// Unix seconds from Discord's ISO-8601 time (None for null / unparsable).
pub(super) fn unix_of(v: &Value) -> Option<i64> {
v.as_str().and_then(|s| chrono::DateTime::parse_from_rfc3339(s).ok()).map(|d| d.timestamp())
}
fn now_unix() -> i64 {
chrono::Utc::now().timestamp()
}
impl RustCord {
/// Open the member menu for `user` in `guild` at `pos` (a right-click on
/// them in the member list, in chat, in voice or on the Members page).
pub fn open_member_menu(&mut self, guild: Id, user: User, pos: Pos2) {
let key = (guild, user.id);
if !self.moderation.fetched.contains(&key) {
// The Members page may have them already.
let hit = self.member_search_hit(guild, user.id).cloned();
if let Some(m) = hit {
self.mod_remember(guild, &m);
self.moderation.fetched.insert(key);
} else if Some(user.id) != self.store.me_id()
&& self.store.has_perm(guild, MODERATE_MEMBERS | KICK_MEMBERS | BAN_MEMBERS | permissions::MANAGE_ROLES | MANAGE_NICKNAMES)
{
// Their roles decide what you may do; the timeout, which row shows.
self.moderation.fetched.insert(key);
self.mod_send(Op::Fetch { guild }, Method::GET, format!("/guilds/{guild}/members/{}", user.id), None, "");
}
}
self.context_menu = None;
self.voice_ui.menu = None;
self.moderation.menu = Some(Menu { guild, user, pos, opened: self.ctx.cumulative_pass_nr(), roles: None });
}
/// Chat: a right-click on a server message's author (avatar or name)
/// opens the member menu. DMs and webhook authors keep the message menu.
pub(super) fn author_menu(&self, m: &discord::model::Message, guild: Option<Id>, resp: &Response, actions: &mut Vec<super::chat::UiAction>) {
let Some(guild) = guild.filter(|_| resp.secondary_clicked() && m.webhook_id.is_none()) else { return };
let pos = resp.interact_pointer_pos().unwrap_or(resp.rect.right_top());
actions.push(super::chat::UiAction::MemberMenu { guild, user: Box::new(m.author.clone()), pos });
}
/// Server Settings → Members → Prune: the dialog, counting at once.
pub fn open_prune(&mut self, guild: Id) {
let days = 7;
self.moderation.dialog = Some(Dialog::Prune { guild, days, count: None });
self.mod_send(Op::PruneCount { guild, days }, Method::GET, format!("/guilds/{guild}/prune?days={days}"), None, "");
}
/// The member menu and the open dialog (called once per frame).
pub fn moderation_ui(&mut self, ctx: &egui::Context) {
self.mod_poll();
if self.moderation.menu.is_some() {
self.member_menu_ui(ctx);
}
if self.moderation.dialog.is_some() {
self.mod_dialog_ui(ctx);
}
}
// ---- requests ----------------------------------------------------------------------
/// Send a request (with an audit-log reason when there is one) and
/// remember what its answer is for.
fn mod_send(&mut self, op: Op, method: Method, path: String, body: Option<Value>, reason: &str) {
self.moderation.seq += 1;
let tag = format!("mod:{}", self.moderation.seq);
self.api_reason(&tag, method, path, body, reason);
self.moderation.pending.push((tag, op));
}
fn mod_poll(&mut self) {
if self.moderation.pending.is_empty() {
return;
}
for (tag, op) in std::mem::take(&mut self.moderation.pending) {
match self.api_take(&tag) {
None => self.moderation.pending.push((tag, op)),
Some(Ok(v)) => self.mod_done(op, v),
Some(Err(e)) => self.mod_failed(op, e),
}
}
}
fn mod_done(&mut self, op: Op, v: Value) {
match op {
Op::Fetch { guild } => self.mod_remember(guild, &v),
Op::Nick { guild, user } => {
if v.get("user").is_some() {
self.store.remember_member(guild, &v);
}
let nick = v["nick"].clone();
self.mod_edit_search(guild, user, |m| m["nick"] = nick);
self.toast("Nickname changed", false);
}
Op::Role { guild, user, role, add } => {
self.mod_edit_search(guild, user, |m| {
let Some(roles) = m["roles"].as_array_mut() else { return };
roles.retain(|r| Id::from_value(r) != Some(role));
if add {
roles.push(json!(role.to_string()));
}
});
}
Op::Timeout { guild, user, until, name } => {
match until {
Some(t) => self.moderation.timeouts.insert((guild, user), t),
None => self.moderation.timeouts.remove(&(guild, user)),
};
let iso = until.and_then(|t| chrono::DateTime::from_timestamp(t, 0)).map(|d| d.to_rfc3339());
self.mod_edit_search(guild, user, |m| m["communication_disabled_until"] = json!(iso));
let text = if until.is_some() { format!("{name} timed out") } else { format!("Removed timeout from {name}") };
self.toast(text, false);
}
Op::Kick { guild, user, name } => {
self.mod_drop_from_search(guild, user);
self.toast(format!("Kicked {name}"), false);
}
Op::Ban { guild, user, name } => {
self.mod_drop_from_search(guild, user);
// Bans page: fetched again when it next shows.
self.api_results.remove(&format!("ss:bans:{guild}"));
self.toast(format!("Banned {name}"), false);
}
Op::Quiet(_) => {}
Op::PruneCount { guild, days } => {
if let Some(Dialog::Prune { guild: g, days: d, count }) = self.moderation.dialog.as_mut() {
if *g == guild && *d == days {
*count = Some(Ok(v["pruned"].as_u64().unwrap_or(0)));
}
}
}
Op::Prune { guild, count } => {
// The Members page searches again.
self.api_results.remove(&member_search_tag(guild));
self.toast(format!("Pruned {count} member{}", if count == 1 { "" } else { "s" }), false);
}
}
}
fn mod_failed(&mut self, op: Op, e: String) {
let what = match op {
Op::Fetch { .. } => {
log::debug!("member lookup failed: {e}");
return;
}
Op::Nick { .. } => "change the nickname",
Op::Role { guild, user, role, add } => {
// Put the checkbox back.
if let Some(m) = self.store.members.get_mut(&(guild, user)) {
m.roles.retain(|r| *r != role);
if !add {
m.roles.push(role);
}
}
if add {
"give that role"
} else {
"remove that role"
}
}
Op::Timeout { until: Some(_), .. } => "time them out",
Op::Timeout { until: None, .. } => "remove the timeout",
Op::Kick { .. } => "kick them",
Op::Ban { .. } => "ban them",
Op::Quiet(what) => what,
Op::PruneCount { guild, days } => {
if let Some(Dialog::Prune { guild: g, days: d, count }) = self.moderation.dialog.as_mut() {
if *g == guild && *d == days {
*count = Some(Err(e));
}
}
return;
}
Op::Prune { .. } => "prune members",
};
self.toast(format!("Couldn't {what}: {e}"), true);
}
/// Take a member object's roles, nickname and timeout.
fn mod_remember(&mut self, guild: Id, m: &Value) {
let Some(user) = Id::from_value(&m["user"]["id"]) else { return };
self.store.remember_member(guild, m);
match unix_of(&m["communication_disabled_until"]) {
Some(t) => self.moderation.timeouts.insert((guild, user), t),
None => self.moderation.timeouts.remove(&(guild, user)),
};
}
/// Someone's member object in the Members page's search results.
fn member_search_hit(&self, guild: Id, user: Id) -> Option<&Value> {
let Some(Ok(v)) = self.api_result(&member_search_tag(guild)) else { return None };
v["members"].as_array()?.iter().map(|e| &e["member"]).find(|m| Id::from_value(&m["user"]["id"]) == Some(user))
}
/// Change someone's member object in the Members page's search results.
fn mod_edit_search(&mut self, guild: Id, user: Id, edit: impl FnOnce(&mut Value)) {
let Some(Ok(v)) = self.api_results.get_mut(&member_search_tag(guild)) else { return };
let Some(list) = v["members"].as_array_mut() else { return };
if let Some(m) = list.iter_mut().map(|e| &mut e["member"]).find(|m| Id::from_value(&m["user"]["id"]) == Some(user)) {
edit(m);
}
}
/// Someone left (kicked, banned): off the Members page's list.
fn mod_drop_from_search(&mut self, guild: Id, user: Id) {
let Some(Ok(v)) = self.api_results.get_mut(&member_search_tag(guild)) else { return };
let Some(list) = v["members"].as_array_mut() else { return };
let before = list.len();
list.retain(|e| Id::from_value(&e["member"]["user"]["id"]) != Some(user));
if list.len() < before {
if let Some(n) = v["total_result_count"].as_u64() {
v["total_result_count"] = json!(n.saturating_sub(1));
}
}
}
// ---- who may do what ---------------------------------------------------------------
/// Whether the role hierarchy lets you act on `user`: not yourself, never
/// the owner, and their highest role below yours unless you own the server.
fn mod_outranks(&self, guild: Id, user: Id) -> bool {
let (Some(gs), Some(me)) = (self.store.guilds.get(&guild), self.store.me_id()) else { return false };
if user == me || gs.guild.owner_id == Some(user) {
return false;
}
if gs.guild.owner_id == Some(me) {
return true;
}
let theirs = self.store.members.get(&(guild, user)).map(|m| m.roles.as_slice()).unwrap_or(&[]);
let top = gs.guild.roles.iter().filter(|r| theirs.contains(&r.id)).map(|r| r.position as i64).max().unwrap_or(0);
self.store.my_top_role(guild) > top
}
/// Administrators can't be timed out (Discord refuses).
fn mod_is_admin(&self, guild: Id, user: Id) -> bool {
let Some(gs) = self.store.guilds.get(&guild) else { return false };
let theirs = self.store.members.get(&(guild, user)).map(|m| m.roles.as_slice()).unwrap_or(&[]);
gs.guild.roles.iter().filter(|r| theirs.contains(&r.id)).any(|r| r.permission_bits() & permissions::ADMINISTRATOR != 0)
}
/// The voice channel `user` is in on `guild`, if any.
fn mod_voice_channel(&self, guild: Id, user: Id) -> Option<Id> {
self.store
.voice
.iter()
.find(|(ch, users)| users.contains(&user) && self.store.channels.get(ch).and_then(|c| c.guild_id) == Some(guild))
.map(|(ch, _)| *ch)
}
// ---- the menu ------------------------------------------------------------------------
fn member_menu_ui(&mut self, ctx: &egui::Context) {
let Some(menu) = self.moderation.menu.as_ref() else { return };
let (g, user, pos, opened, roles_at) = (menu.guild, menu.user.clone(), menu.pos, menu.opened, menu.roles);
if !self.store.guilds.contains_key(&g) {
self.moderation.menu = None;
return;
}
let t = self.theme.clone();
let uid = user.id;
let me = self.store.me_id();
let is_me = me == Some(uid);
let perms = self.store.guild_perms(g);
let has = |p: u64| perms & p != 0;
let outranks = self.mod_outranks(g, uid);
// Discord's "Kick {user}" / "Ban {user}" rows name the username.
let name = user.username.clone();
let timed_out = self.moderation.timeouts.get(&(g, uid)).is_some_and(|until| *until > now_unix());
let blocked = self.store.relationships.get(&uid).is_some_and(|r| r.kind == 2);
let nickname_row = self.friend_nickname_row(uid);
let can_nick = if is_me { has(permissions::CHANGE_NICKNAME) || has(MANAGE_NICKNAMES) } else { has(MANAGE_NICKNAMES) && outranks };
let can_timeout = has(MODERATE_MEMBERS) && outranks && !self.mod_is_admin(g, uid);
// Voice: moderator rows while they're in one of this server's
// channels; volume and local mute while they're in your call.
let their_voice = self.mod_voice_channel(g, uid);
let my_call = self.voice.as_ref().filter(|v| v.connected).map(|v| v.channel);
let in_my_call = their_voice.is_some() && their_voice == my_call;
let flags = self.store.voice_flags.get(&uid).copied().unwrap_or_default();
let volume = self.voice_ui.user_volume(uid);
let stream_volume = self.watched_stream_volume(uid);
let local_mute = self.voice_ui.locally_muted(uid);
let deaf = self.self_deaf;
let gs = &self.store.guilds[&g];
let has_roles = gs.guild.roles.iter().any(|r| r.id != g);
// The Roles submenu: every role but @everyone, highest first; the ones
// you can't hand out (managed, or not below your top role) greyed.
let role_rows: Vec<(Id, String, u32, bool, bool)> = if roles_at.is_some() {
let mine = self.store.members.get(&(g, uid)).map(|m| m.roles.as_slice()).unwrap_or(&[]);
let top = self.store.my_top_role(g);
let mut v: Vec<_> = gs.guild.roles.iter().filter(|r| r.id != g).collect();
v.sort_by_key(|r| (std::cmp::Reverse(r.position), r.id));
v.into_iter().map(|r| (r.id, r.name.clone(), r.color, mine.contains(&r.id), !r.managed && (r.position as i64) < top)).collect()
} else {
Vec::new()
};
let mut rows = Rows { t: &t, pick: None, other_hovered: false, any: false, new_group: false };
let mut roles_row: Option<Response> = None;
let area = egui::Area::new(egui::Id::new("member_menu")).order(Order::Foreground).fixed_pos(pos).constrain(true).show(ctx, |ui| {
super::ctx_menu_frame(&t).show(ui, |ui| {
ui.set_width(MENU_W - 16.0);
ui.spacing_mut().item_spacing = vec2(0.0, 0.0);
rows.item(ui, None, "Profile", false, Pick::Profile);
rows.item(ui, None, "Mention", false, Pick::Mention);
if !is_me {
rows.item(ui, None, "Message", false, Pick::Message);
rows.item(ui, None, "Add Note", false, Pick::AddNote);
if let Some(label) = nickname_row {
rows.item(ui, None, label, false, Pick::FriendNickname);
}
}
if in_my_call {
rows.group();
if is_me {
rows.check(ui, "Deafen", deaf, Pick::SelfDeafen);
} else {
rows.begin(ui);
let top = ui.cursor().top();
let mut v = volume;
let (changed, done) = super::voice_menu::slider_row(ui, rows.t, egui::Id::new(("member_menu_volume", uid.0)), "User Volume", &mut v, 200.0);
let slider = Rect::from_x_y_ranges(ui.max_rect().x_range(), top..=ui.cursor().top());
rows.other_hovered |= ui.rect_contains_pointer(slider);
if changed || done {
rows.pick = Some(Pick::Volume(v, done));
}
if let Some(mut v) = stream_volume {
let top = ui.cursor().top();
let (changed, done) = super::voice_menu::slider_row(ui, rows.t, egui::Id::new(("member_menu_stream_volume", uid.0)), "Stream Volume", &mut v, 200.0);
let slider = Rect::from_x_y_ranges(ui.max_rect().x_range(), top..=ui.cursor().top());
rows.other_hovered |= ui.rect_contains_pointer(slider);
if changed || done {
rows.pick = Some(Pick::StreamVolume(v, done));
}
}
rows.check(ui, "Mute", local_mute, Pick::LocalMute);
}
}
rows.group();
if can_nick {
rows.item(ui, None, "Change Nickname", false, Pick::Nickname);
}
if !is_me {
rows.item(ui, None, if blocked { "Unblock" } else { "Block" }, false, Pick::Block(!blocked));
}
if has(permissions::MANAGE_ROLES) && has_roles {
rows.group();
rows.begin(ui);
// Highlighted while its submenu is open, like Discord's.
let fill = ui.painter().add(egui::Shape::Noop);
let r = super::ctx_row(ui, rows.t, None, "Roles", Some(icon::CHEVRON), false, true);
if roles_at.is_some() && !r.hovered() {
ui.painter().set(fill, egui::Shape::rect_filled(r.rect, 4.0, rows.t.bg_hover));
}
roles_row = Some(r);
}
if their_voice.is_some() {
rows.group();
if has(permissions::MUTE_MEMBERS) {
rows.check(ui, "Server Mute", flags.server_mute, Pick::ServerMute(!flags.server_mute));
}
if has(permissions::DEAFEN_MEMBERS) {
rows.check(ui, "Server Deafen", flags.server_deaf, Pick::ServerDeaf(!flags.server_deaf));
}
if has(permissions::MOVE_MEMBERS) || is_me {
rows.item(ui, None, "Disconnect", true, Pick::Disconnect);
}
}
rows.group();
if can_timeout {
if timed_out {
rows.item(ui, None, &format!("Remove timeout from {name}"), true, Pick::RemoveTimeout);
} else {
rows.item(ui, None, &format!("Timeout {name}"), true, Pick::Timeout);
}
}
if has(KICK_MEMBERS) && outranks {
rows.item(ui, None, &format!("Kick {name}"), true, Pick::Kick);
}
// Discord: bot accounts can be kicked but not banned.
if has(BAN_MEMBERS) && outranks && !user.bot {
rows.item(ui, None, &format!("Ban {name}"), true, Pick::Ban);
}
rows.group();
rows.item(ui, Some(icon::ID), "Copy User ID", false, Pick::CopyId);
});
});
ctx.move_to_top(area.response.layer_id);
let main_rect = area.response.rect;
let mut pick = rows.pick;
// The Roles submenu opens on hover and stays until another row is.
let mut sub_at = roles_at;
if let Some(r) = &roles_row {
if r.hovered() || r.clicked() {
sub_at = Some(r.rect.top());
}
}
if rows.other_hovered {
sub_at = None;
}
if sub_at.is_some() && roles_at.is_none() {
ctx.request_repaint();
}
// (Drawn from the frame after it opens: the role list is built then.)
let mut sub_rect = None;
if let (Some(top), false) = (sub_at, role_rows.is_empty()) {
let right = main_rect.right() - 4.0 + SUB_W <= ctx.screen_rect().right();
let (pivot, at) = if right { (Align2::LEFT_TOP, pos2(main_rect.right() - 4.0, top - 9.0)) } else { (Align2::RIGHT_TOP, pos2(main_rect.left() + 4.0, top - 9.0)) };
let sub = egui::Area::new(egui::Id::new("member_menu_roles")).order(Order::Foreground).pivot(pivot).fixed_pos(at).constrain(true).show(ctx, |ui| {
super::ctx_menu_frame(&t).show(ui, |ui| {
ui.set_width(SUB_W - 16.0);
ui.spacing_mut().item_spacing = vec2(0.0, 0.0);
ScrollArea::vertical().max_height(360.0).show(ui, |ui| {
for (id, role_name, color, on, enabled) in &role_rows {
let dot = if *color == 0 { t.interactive_normal } else { Color32::from_rgb((color >> 16) as u8, (color >> 8) as u8, *color as u8) };
let r = check_row(ui, &t, Some(dot), role_name, *on, *enabled);
if r.clicked() {
pick = Some(Pick::Role(*id, !on));
}
}
});
});
});
ctx.move_to_top(sub.response.layer_id);
sub_rect = Some(sub.response.rect);
}
// Click elsewhere or Escape closes it.
let frame = ctx.cumulative_pass_nr();
let inside = |p: Pos2| main_rect.contains(p) || sub_rect.is_some_and(|r| r.contains(p));
let outside = frame > opened && ctx.input(|i| i.pointer.any_pressed() && i.pointer.interact_pos().is_some_and(|p| !inside(p)));
let escape = ctx.input_mut(|i| i.consume_key(Modifiers::NONE, Key::Escape));
if let Some(m) = self.moderation.menu.as_mut() {
m.roles = sub_at;
}
// Volume, mute and role ticks keep the menu open, like Discord's.
let keep = matches!(pick, Some(Pick::Volume(..) | Pick::StreamVolume(..) | Pick::LocalMute | Pick::Role(..) | Pick::ServerMute(_) | Pick::ServerDeaf(_) | Pick::SelfDeafen));
if outside || escape || (pick.is_some() && !keep) {
self.moderation.menu = None;
}
if let Some(p) = pick {
self.mod_pick(p, g, user, pos);
}
}
/// Block `user`, or unblock them.
pub(crate) fn set_blocked(&mut self, user: Id, on: bool) {
let path = format!("/users/@me/relationships/{user}");
if on {
self.mod_send(Op::Quiet("block them"), Method::PUT, path, Some(json!({ "type": 2 })), "");
} else {
self.mod_send(Op::Quiet("unblock them"), Method::DELETE, path, None, "");
}
}
/// Carry out a menu row.
fn mod_pick(&mut self, pick: Pick, g: Id, user: User, pos: Pos2) {
let uid = user.id;
let member = format!("/guilds/{g}/members/{uid}");
match pick {
Pick::Profile => self.open_profile(user, Some(g), pos),
Pick::Mention => {
// Into the chat you're looking at, like the voice menu's.
if let Some(ch) = self.current_channel {
let draft = self.drafts.entry(ch).or_default();
if !draft.is_empty() && !draft.ends_with(' ') {
draft.push(' ');
}
draft.push_str(&format!("<@{uid}> "));
self.compose.focus_composer = true;
}
}
Pick::Message => self.open_dm_with(uid, String::new()),
// The full profile holds the note ("Only visible to you").
Pick::AddNote => self.open_full_profile(user, Some(g)),
Pick::FriendNickname => self.open_friend_nickname(uid),
Pick::Volume(v, done) => self.set_user_volume(uid, v, done),
Pick::StreamVolume(v, done) => self.set_watch_volume(uid, v / 100.0, done),
Pick::LocalMute => self.toggle_local_mute(uid),
Pick::SelfDeafen => self.toggle_self_deaf(),
Pick::Nickname => {
let nick = self.store.members.get(&(g, uid)).and_then(|m| m.nick.clone()).unwrap_or_default();
self.moderation.dialog = Some(Dialog::Nickname { guild: g, user, nick });
}
Pick::Block(on) => self.set_blocked(uid, on),
Pick::Role(role, add) => {
// Shown at once; put back if Discord says no.
let m = self.store.members.entry((g, uid)).or_default();
m.roles.retain(|r| *r != role);
if add {
m.roles.push(role);
}
let method = if add { Method::PUT } else { Method::DELETE };
self.mod_send(Op::Role { guild: g, user: uid, role, add }, method, format!("{member}/roles/{role}"), None, "");
}
Pick::ServerMute(on) => self.mod_send(Op::Quiet("change their server mute"), Method::PATCH, member, Some(json!({ "mute": on })), ""),
Pick::ServerDeaf(on) => self.mod_send(Op::Quiet("change their server deafen"), Method::PATCH, member, Some(json!({ "deaf": on })), ""),
Pick::Disconnect => {
if Some(uid) == self.store.me_id() {
self.leave_voice();
} else {
self.mod_send(Op::Quiet("disconnect them"), Method::PATCH, member, Some(json!({ "channel_id": null })), "");
}
}
Pick::Timeout => self.moderation.dialog = Some(Dialog::Timeout { guild: g, user, secs: 60, reason: String::new() }),
Pick::RemoveTimeout => {
let name = user.display_name().to_string();
let op = Op::Timeout { guild: g, user: uid, until: None, name };
self.mod_send(op, Method::PATCH, member, Some(json!({ "communication_disabled_until": null })), "");
}
Pick::Kick => self.moderation.dialog = Some(Dialog::Kick { guild: g, user, reason: String::new() }),
Pick::Ban => self.moderation.dialog = Some(Dialog::Ban { guild: g, user, reason: None, other: String::new(), history: 3600, history_open: false, error: false }),
Pick::CopyId => self.ctx.copy_text(uid.to_string()),
}
}
// ---- the dialogs ---------------------------------------------------------------------
fn mod_dialog_ui(&mut self, ctx: &egui::Context) {
let Some(mut dialog) = self.moderation.dialog.take() else { return };
let t = self.theme.clone();
// Escape is the dialog's while one is up (Server Settings would close too).
let mut close = ctx.input_mut(|i| i.consume_key(Modifiers::NONE, Key::Escape));
// What the action button sends: (op, method, path, body, audit-log reason).
let mut send: Option<(Op, Method, String, Option<Value>, String)> = None;
let mut recount: Option<(Id, u32)> = None;
match &mut dialog {
Dialog::Nickname { guild, user, nick } => {
let (g, uid) = (*guild, user.id);
let mut enter = false;
let a = modal(ctx, &t, "Change Nickname", ("Save", Btn::Primary, true), |ui| {
label(ui, &t, "Nickname");
let r = text_box(ui, &t, egui::Id::new(("mod_nick", uid.0)), nick, user.display_name(), 1, 32);
if ui.memory(|m| m.focused().is_none()) {
r.request_focus();
}
enter = r.lost_focus() && ui.input(|i| i.key_pressed(Key::Enter));
ui.add_space(8.0);
let reset = ui.add(Label::new(RichText::new("Reset Nickname").size(14.0).color(t.text_link)).sense(Sense::click()));
if reset.on_hover_cursor(CursorIcon::PointingHand).clicked() {
nick.clear();
}
});
close |= a.cancel;
if a.go || enter {
let n = nick.trim();
let value = if n.is_empty() { Value::Null } else { json!(n) };
// Yours goes through @me (Change Nickname); others' need Manage Nicknames.
let who = if Some(uid) == self.store.me_id() { "@me".to_string() } else { uid.to_string() };
send = Some((Op::Nick { guild: g, user: uid }, Method::PATCH, format!("/guilds/{g}/members/{who}"), Some(json!({ "nick": value })), String::new()));
}
}
Dialog::Timeout { guild, user, secs, reason } => {
let (g, uid) = (*guild, user.id);
let name = user.display_name().to_string();
let a = modal(ctx, &t, &format!("Timeout {name}"), ("Timeout", Btn::Danger, true), |ui| {
let text = "Members in timeout can't send messages, react or join voice and Stage channels until it ends.";
ui.add(Label::new(RichText::new(text).size(15.0).color(t.text_normal)).wrap());
ui.add_space(20.0);
label(ui, &t, "Duration");
if let Some(s) = pills(ui, &t, &TIMEOUTS, *secs) {
*secs = s;
}
ui.add_space(20.0);
label(ui, &t, "Reason");
text_box(ui, &t, egui::Id::new(("mod_timeout_reason", uid.0)), reason, "", 3, 512);
});
close |= a.cancel;
if a.go {
let until = now_unix() + *secs;
let iso = chrono::DateTime::from_timestamp(until, 0).map(|d| d.to_rfc3339()).unwrap_or_default();
let op = Op::Timeout { guild: g, user: uid, until: Some(until), name };
send = Some((op, Method::PATCH, format!("/guilds/{g}/members/{uid}"), Some(json!({ "communication_disabled_until": iso })), reason.clone()));
}
}
Dialog::Kick { guild, user, reason } => {
let (g, uid) = (*guild, user.id);
let name = user.display_name().to_string();
let a = modal(ctx, &t, &format!("Kick {name} from Server"), ("Kick", Btn::Danger, true), |ui| {
let text = format!("Are you sure you want to kick {name} from the server? They will be able to re-join again with a new invite.");
ui.add(Label::new(RichText::new(text).size(15.0).color(t.text_normal)).wrap());
ui.add_space(20.0);
label(ui, &t, "Reason for Kick");
text_box(ui, &t, egui::Id::new(("mod_kick_reason", uid.0)), reason, "", 3, 512);
});
close |= a.cancel;
if a.go {
send = Some((Op::Kick { guild: g, user: uid, name }, Method::DELETE, format!("/guilds/{g}/members/{uid}"), None, reason.clone()));
}
}
Dialog::Ban { guild, user, reason, other, history, history_open, error } => {
let (g, uid) = (*guild, user.id);
let mut field: Option<Rect> = None;
let a = modal(ctx, &t, &format!("Ban @{}?", user.username), ("Ban", Btn::Danger, true), |ui| {
label(ui, &t, "Reason for Ban");
for (i, text) in BAN_REASONS.iter().enumerate() {
if radio_row(ui, &t, text, *reason == Some(i)) {
*reason = Some(i);
*error = false;
}
}
// "Other": in your own words.
if *reason == Some(BAN_REASONS.len() - 1) {
ui.add_space(8.0);
if text_box(ui, &t, egui::Id::new(("mod_ban_reason", uid.0)), other, "", 3, 512).changed() {
*error = false;
}
}
if *error {
ui.add_space(6.0);
ui.label(RichText::new("Ban reason must be provided").size(13.0).color(t.danger));
}
ui.add_space(20.0);
label(ui, &t, "Delete Message History");
// Discord's select: the choice and a chevron; its list opens below.
let current = BAN_HISTORY.iter().find(|(s, _)| s == history).map_or("", |(_, l)| *l);
let (r, resp) = ui.allocate_exact_size(vec2(ui.available_width(), 42.0), Sense::click());
ui.painter().rect(r, 8.0, t.input_bg, Stroke::new(1.0_f32, if *history_open { t.text_link } else { overlay(0.2) }));
ui.painter().text(pos2(r.left() + 12.0, r.center().y), Align2::LEFT_CENTER, current, FontId::proportional(15.0), t.text_normal);
let chevron = if *history_open { super::voice_menu::CHEVRON_UP } else { icon::CHEVRON_DOWN };
ui.painter().text(pos2(r.right() - 16.0, r.center().y), Align2::CENTER_CENTER, chevron, icon_font(12.0), t.interactive_normal);
if resp.on_hover_cursor(CursorIcon::PointingHand).clicked() {
*history_open = !*history_open;
}
field = Some(r);
});
// The open select's list, over the dialog.
if let (Some(field), true) = (field, *history_open) {
let list = egui::Area::new(egui::Id::new("mod_ban_history")).order(Order::Tooltip).fixed_pos(field.left_bottom() + vec2(0.0, 4.0)).constrain(true).show(ctx, |ui| {
super::ctx_menu_frame(&t).show(ui, |ui| {
ui.set_width(field.width() - 16.0);
ui.spacing_mut().item_spacing = vec2(0.0, 0.0);
for (s, text) in BAN_HISTORY {
if super::ctx_row(ui, &t, None, text, (s == *history).then_some(icon::CHECK), false, true).clicked() {
*history = s;
*history_open = false;
}
}
});
});
ctx.move_to_top(list.response.layer_id);
if ctx.input(|i| i.pointer.any_pressed() && i.pointer.interact_pos().is_some_and(|p| !list.response.rect.contains(p) && !field.contains(p))) {
*history_open = false;
}
}
close |= a.cancel;
if a.go {
let why = match *reason {
Some(i) if i + 1 < BAN_REASONS.len() => Some(BAN_REASONS[i].to_string()),
Some(_) => Some(other.trim().to_string()).filter(|s| !s.is_empty()),
None => None,
};
match why {
Some(why) => {
let op = Op::Ban { guild: g, user: uid, name: user.display_name().to_string() };
send = Some((op, Method::PUT, format!("/guilds/{g}/bans/{uid}"), Some(json!({ "delete_message_seconds": *history })), why));
}
None => *error = true,
}
}
}
Dialog::Prune { guild, days, count } => {
let g = *guild;
let n = match count {
Some(Ok(n)) => Some(*n),
_ => None,
};
let a = modal(ctx, &t, "Prune Members", ("Prune", Btn::Danger, n.is_some_and(|n| n > 0)), |ui| {
label(ui, &t, "Last seen");
let choices = PRUNE_DAYS.map(|d| (d, if d == 1 { "1 day" } else if d == 7 { "7 days" } else { "30 days" }));
if let Some(d) = pills(ui, &t, &choices, *days) {
*days = d;
*count = None;
recount = Some((g, d));
}
ui.add_space(20.0);
let plural = |n: u64| if n == 1 { "" } else { "s" };
let text = match count {
None => "Counting members…".to_string(),
Some(Err(e)) => format!("Couldn't count them: {e}"),
Some(Ok(n)) => format!(
"{n} member{} not seen for {days} day{} and without a role will be kicked. They can join again with a new invite.",
plural(*n),
plural(u64::from(*days)),
),
};
ui.add(Label::new(RichText::new(text).size(15.0).color(t.text_normal)).wrap());
});
close |= a.cancel;
if let (true, Some(n)) = (a.go, n) {
let body = json!({ "days": *days, "compute_prune_count": false, "include_roles": [] });
send = Some((Op::Prune { guild: g, count: n }, Method::POST, format!("/guilds/{g}/prune"), Some(body), String::new()));
}
}
}
if let Some((g, days)) = recount {
self.mod_send(Op::PruneCount { guild: g, days }, Method::GET, format!("/guilds/{g}/prune?days={days}"), None, "");
}
if let Some((op, method, path, body, reason)) = send {
self.mod_send(op, method, path, body, &reason);
close = true;
}
if !close {
self.moderation.dialog = Some(dialog);
}
}
}