concord 2.4.8

A terminal user interface client for Discord
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
use std::collections::BTreeMap;

use crate::discord::ids::{
    Id,
    marker::{ChannelMarker, GuildMarker, UserMarker},
};
use crate::discord::{MicrophoneSensitivityDb, VoiceVolumePercent};
use crate::discord::{VoiceScope, VoiceSoundKind, VoiceStateInfo};

use crate::discord::state::DiscordState;

#[derive(Clone, Debug, Eq, PartialEq)]
pub struct VoiceParticipantState {
    pub user_id: Id<UserMarker>,
    pub display_name: String,
    pub deaf: bool,
    pub mute: bool,
    pub self_deaf: bool,
    pub self_mute: bool,
    pub self_stream: bool,
    pub speaking: bool,
}

#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub struct CurrentVoiceConnectionState {
    pub scope: VoiceScope,
    pub channel_id: Id<ChannelMarker>,
    pub self_mute: bool,
    pub self_deaf: bool,
    pub allow_microphone_transmit: bool,
    pub noise_suppression: bool,
    pub microphone_sensitivity: MicrophoneSensitivityDb,
    pub microphone_volume: VoiceVolumePercent,
    pub voice_output_volume: VoiceVolumePercent,
}

/// Audio settings applied together to an active voice connection.
#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
#[non_exhaustive]
pub struct VoiceAudioSettings {
    pub allow_microphone_transmit: bool,
    pub noise_suppression: bool,
    pub microphone_sensitivity: MicrophoneSensitivityDb,
    pub microphone_volume: VoiceVolumePercent,
    pub voice_output_volume: VoiceVolumePercent,
}

impl CurrentVoiceConnectionState {
    /// The guild this connection belongs to, or `None` for a DM/group-DM call.
    pub fn guild_id(&self) -> Option<Id<GuildMarker>> {
        self.scope.guild_id()
    }

    pub(crate) fn audio_settings(self) -> VoiceAudioSettings {
        VoiceAudioSettings {
            allow_microphone_transmit: self.allow_microphone_transmit,
            noise_suppression: self.noise_suppression,
            microphone_sensitivity: self.microphone_sensitivity,
            microphone_volume: self.microphone_volume,
            voice_output_volume: self.voice_output_volume,
        }
    }

    pub(crate) fn set_audio_settings(&mut self, settings: VoiceAudioSettings) {
        self.allow_microphone_transmit = settings.allow_microphone_transmit;
        self.noise_suppression = settings.noise_suppression;
        self.microphone_sensitivity = settings.microphone_sensitivity;
        self.microphone_volume = settings.microphone_volume;
        self.voice_output_volume = settings.voice_output_volume;
    }
}

#[cfg(test)]
#[allow(dead_code)]
impl CurrentVoiceConnectionState {
    pub(crate) fn test(guild_id: Id<GuildMarker>, channel_id: Id<ChannelMarker>) -> Self {
        Self {
            scope: VoiceScope::Guild(guild_id),
            channel_id,
            self_mute: false,
            self_deaf: false,
            allow_microphone_transmit: false,
            noise_suppression: false,
            microphone_sensitivity: MicrophoneSensitivityDb::default(),
            microphone_volume: VoiceVolumePercent::default(),
            voice_output_volume: VoiceVolumePercent::default(),
        }
    }
}

#[derive(Clone, Debug, Eq, PartialEq)]
pub(in crate::discord) struct VoiceState {
    channel_id: Id<ChannelMarker>,
    user_id: Id<UserMarker>,
    deaf: bool,
    mute: bool,
    self_deaf: bool,
    self_mute: bool,
    self_stream: bool,
    speaking: bool,
}

impl DiscordState {
    pub fn current_user_voice_connection(&self) -> Option<CurrentVoiceConnectionState> {
        let current_user_id = self.session.current_user_id?;
        self.voice
            .states
            .iter()
            .find_map(|((scope, user_id), state)| {
                (*user_id == current_user_id).then_some(CurrentVoiceConnectionState {
                    scope: *scope,
                    channel_id: state.channel_id,
                    self_mute: state.self_mute,
                    self_deaf: state.self_deaf,
                    allow_microphone_transmit: false,
                    noise_suppression: false,
                    microphone_sensitivity: MicrophoneSensitivityDb::default(),
                    microphone_volume: VoiceVolumePercent::default(),
                    voice_output_volume: VoiceVolumePercent::default(),
                })
            })
    }

    pub fn voice_participants_for_channel(
        &self,
        guild_id: Id<GuildMarker>,
        channel_id: Id<ChannelMarker>,
    ) -> Vec<VoiceParticipantState> {
        self.voice_participants_for_scope(VoiceScope::Guild(guild_id), channel_id)
    }

    /// Voice participants currently in a DM or group-DM call.
    pub fn voice_participants_for_private_channel(
        &self,
        channel_id: Id<ChannelMarker>,
    ) -> Vec<VoiceParticipantState> {
        self.voice_participants_for_scope(VoiceScope::Private(channel_id), channel_id)
    }

    fn voice_participants_for_scope(
        &self,
        scope: VoiceScope,
        channel_id: Id<ChannelMarker>,
    ) -> Vec<VoiceParticipantState> {
        let mut participants = Vec::new();
        for ((state_scope, _), state) in &self.voice.states {
            if *state_scope == scope && state.channel_id == channel_id {
                participants.push(self.voice_participant_state(scope, state));
            }
        }
        sort_voice_participants(&mut participants);
        participants
    }

    pub fn current_user_voice_speaking(&self) -> bool {
        let Some(current_user_id) = self.session.current_user_id else {
            return false;
        };
        self.user_voice_speaking(current_user_id)
    }

    pub fn user_voice_speaking_in_guild(
        &self,
        guild_id: Id<GuildMarker>,
        user_id: Id<UserMarker>,
    ) -> bool {
        self.voice
            .states
            .get(&(VoiceScope::Guild(guild_id), user_id))
            .map(|state| state.speaking)
            .unwrap_or(false)
    }

    pub(crate) fn voice_sound_for_state_update(
        &self,
        state: &VoiceStateInfo,
    ) -> Option<VoiceSoundKind> {
        // Look the user up by id, not scope: a DM leave carries no location, so
        // their cached entry is the only way to know which call they left.
        let before = self
            .voice
            .states
            .iter()
            .find(|((_, user_id), _)| *user_id == state.user_id)
            .map(|(_, current)| current.channel_id);
        let after = state.channel_id;
        if before == after {
            return None;
        }

        if self.session.current_user_id == Some(state.user_id) {
            return match (before, after) {
                (None, Some(_)) | (Some(_), Some(_)) => Some(VoiceSoundKind::Join),
                (Some(_), None) => Some(VoiceSoundKind::Leave),
                (None, None) => None,
            };
        }

        // For other users, only chime for the channel the current user is in.
        let active_voice_channel = self.current_user_voice_connection()?.channel_id;
        match (
            before == Some(active_voice_channel),
            after == Some(active_voice_channel),
        ) {
            (false, true) => Some(VoiceSoundKind::Join),
            (true, false) => Some(VoiceSoundKind::Leave),
            _ => None,
        }
    }

    fn user_voice_speaking(&self, user_id: Id<UserMarker>) -> bool {
        self.voice
            .states
            .iter()
            .find_map(|((_, state_user_id), state)| {
                (*state_user_id == user_id).then_some(state.speaking)
            })
            .unwrap_or(false)
    }

    pub fn voice_participants_by_channel_for_guild(
        &self,
        guild_id: Id<GuildMarker>,
    ) -> BTreeMap<Id<ChannelMarker>, Vec<VoiceParticipantState>> {
        let scope = VoiceScope::Guild(guild_id);
        let mut participants_by_channel: BTreeMap<Id<ChannelMarker>, Vec<VoiceParticipantState>> =
            BTreeMap::new();
        for ((state_scope, _), state) in &self.voice.states {
            if *state_scope != scope {
                continue;
            }
            participants_by_channel
                .entry(state.channel_id)
                .or_default()
                .push(self.voice_participant_state(scope, state));
        }
        for participants in participants_by_channel.values_mut() {
            sort_voice_participants(participants);
        }
        participants_by_channel
    }

    fn voice_participant_state(
        &self,
        scope: VoiceScope,
        state: &VoiceState,
    ) -> VoiceParticipantState {
        VoiceParticipantState {
            user_id: state.user_id,
            display_name: self
                .voice_participant_display_name(scope, state.user_id)
                .unwrap_or_else(|| format!("user-{}", state.user_id.get())),
            deaf: state.deaf,
            mute: state.mute,
            self_deaf: state.self_deaf,
            self_mute: state.self_mute,
            self_stream: state.self_stream,
            speaking: state.speaking,
        }
    }

    /// Resolve a participant's display name: guild voice via the member list, a
    /// DM via the channel recipients. The current user is special-cased because
    /// Discord omits self from a group DM's recipient list.
    fn voice_participant_display_name(
        &self,
        scope: VoiceScope,
        user_id: Id<UserMarker>,
    ) -> Option<String> {
        match scope {
            VoiceScope::Guild(guild_id) => self
                .member_display_name(guild_id, user_id)
                .map(str::to_owned),
            VoiceScope::Private(channel_id) => {
                if self.session.current_user_id == Some(user_id)
                    && let Some(name) = self.session.current_user.clone()
                {
                    return Some(name);
                }
                self.channel(channel_id)?
                    .recipients
                    .iter()
                    .find(|recipient| recipient.user_id == user_id)
                    .map(|recipient| recipient.display_name.clone())
            }
        }
    }

    pub(in crate::discord) fn update_voice_state(&mut self, state: &VoiceStateInfo) {
        let user_id = state.user_id;
        let is_current_user = self.session.current_user_id == Some(user_id);

        // `None` only for a DM leave (null guild and channel), handled by the
        // user-id removal in the leave branch below.
        let scope = state.scope();

        // When the current user moves or leaves, clear stale speaking flags in
        // the channel they were in. Found by user id, not scope, so it also
        // covers cross-scope moves (DM A -> DM B) and DM leaves (no scope).
        if is_current_user
            && let Some((previous_scope, previous_channel_id)) = self
                .voice
                .states
                .iter()
                .find(|((_, state_user_id), _)| *state_user_id == user_id)
                .map(|((scope, _), current)| (*scope, current.channel_id))
            && state.channel_id != Some(previous_channel_id)
        {
            self.clear_voice_speaking_for_channel(previous_scope, previous_channel_id);
        }

        if let Some(channel_id) = state.channel_id {
            let scope = scope.expect("a voice state with a channel always has a scope");
            let key = (scope, user_id);
            let speaking = self
                .voice
                .states
                .get(&key)
                .is_some_and(|current| current.channel_id == channel_id && current.speaking);
            // Moving across scopes (DM A -> DM B, guild -> DM) changes the key,
            // and Discord sends only the new location, so drop any stale entry
            // this user still holds under a different scope.
            self.voice_mut()
                .states
                .retain(|(state_scope, state_user_id), _| {
                    *state_user_id != user_id || *state_scope == scope
                });
            self.voice_mut().states.insert(
                key,
                VoiceState {
                    channel_id,
                    user_id,
                    deaf: state.deaf,
                    mute: state.mute,
                    self_deaf: state.self_deaf,
                    self_mute: state.self_mute,
                    self_stream: state.self_stream,
                    speaking,
                },
            );
        } else {
            // A leave: a guild leave names its guild, a DM leave names nothing
            // so we drop every private entry this user holds.
            match state.guild_id {
                Some(guild_id) => {
                    self.voice_mut()
                        .states
                        .remove(&(VoiceScope::Guild(guild_id), user_id));
                }
                None => {
                    self.voice_mut().states.retain(|(scope, state_user_id), _| {
                        !(matches!(scope, VoiceScope::Private(_)) && *state_user_id == user_id)
                    });
                }
            }
        }
    }

    pub(in crate::discord) fn update_voice_speaking(
        &mut self,
        scope: VoiceScope,
        channel_id: Id<ChannelMarker>,
        user_id: Id<UserMarker>,
        speaking: bool,
    ) {
        let Some(state) = self.voice_mut().states.get_mut(&(scope, user_id)) else {
            return;
        };
        if state.channel_id == channel_id {
            state.speaking = speaking;
        }
    }

    pub(in crate::discord) fn remove_voice_state(
        &mut self,
        guild_id: Id<GuildMarker>,
        user_id: Id<UserMarker>,
    ) {
        self.voice_mut()
            .states
            .remove(&(VoiceScope::Guild(guild_id), user_id));
    }

    pub(in crate::discord) fn remove_voice_states_for_guild(&mut self, guild_id: Id<GuildMarker>) {
        self.voice_mut()
            .states
            .retain(|(scope, _), _| *scope != VoiceScope::Guild(guild_id));
    }

    pub(in crate::discord) fn remove_voice_states_for_channel(
        &mut self,
        channel_id: Id<ChannelMarker>,
    ) {
        self.voice_mut()
            .states
            .retain(|_, state| state.channel_id != channel_id);
    }

    fn clear_voice_speaking_for_channel(
        &mut self,
        scope: VoiceScope,
        channel_id: Id<ChannelMarker>,
    ) {
        for ((state_scope, _), state) in &mut self.voice_mut().states {
            if *state_scope == scope && state.channel_id == channel_id {
                state.speaking = false;
            }
        }
    }
}

fn sort_voice_participants(participants: &mut [VoiceParticipantState]) {
    participants.sort_by_cached_key(|participant| {
        (participant.display_name.to_lowercase(), participant.user_id)
    });
}