concord 1.3.0

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
417
418
419
420
use std::collections::BTreeMap;

use chrono::{DateTime, Utc};

use crate::discord::ids::{
    Id,
    marker::{ChannelMarker, GuildMarker, MessageMarker, UserMarker},
};
use crate::discord::{
    AppEvent, ChannelNotificationOverrideInfo, GuildNotificationSettingsInfo, MentionInfo,
    NotificationLevel,
};

use super::{DiscordState, MessageState};

#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum ChannelUnreadState {
    Seen,
    Unread,
    Mentioned(u32),
    Notified(u32),
}

#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub(super) enum MessageNotificationKind {
    None,
    Mention,
    Notify,
}

#[derive(Clone, Debug, Eq, PartialEq)]
struct ChannelNotificationSettingsState {
    message_notifications: Option<NotificationLevel>,
    muted: bool,
    mute_end_time: Option<String>,
}

#[derive(Clone, Debug, Eq, PartialEq)]
pub(super) struct GuildNotificationSettingsState {
    message_notifications: Option<NotificationLevel>,
    muted: bool,
    mute_end_time: Option<String>,
    suppress_everyone: bool,
    suppress_roles: bool,
    channel_overrides: BTreeMap<Id<ChannelMarker>, ChannelNotificationSettingsState>,
}

impl DiscordState {
    pub fn channel_unread(&self, channel_id: Id<ChannelMarker>) -> ChannelUnreadState {
        let latest = self
            .channels
            .get(&channel_id)
            .and_then(|channel| channel.last_message_id);
        let Some(latest) = latest else {
            return ChannelUnreadState::Seen;
        };
        let read = self
            .read_states
            .get(&channel_id)
            .copied()
            .unwrap_or_default();
        if read.mention_count > 0 {
            return ChannelUnreadState::Mentioned(read.mention_count);
        }
        if read.notification_count > 0 {
            return ChannelUnreadState::Notified(read.notification_count);
        }

        let (loaded_mentions, loaded_notifications) =
            self.loaded_unread_notification_counts(channel_id);
        if loaded_mentions > 0 {
            return ChannelUnreadState::Mentioned(saturating_u32_count(loaded_mentions));
        }
        if loaded_notifications > 0 {
            return ChannelUnreadState::Notified(saturating_u32_count(loaded_notifications));
        }

        if read
            .last_acked_message_id
            .is_none_or(|acked| acked < latest)
        {
            return ChannelUnreadState::Unread;
        }

        ChannelUnreadState::Seen
    }

    pub fn guild_unread(&self, guild_id: Id<GuildMarker>) -> ChannelUnreadState {
        let mut mention_count = 0u32;
        let mut notification_count = 0u32;
        let mut has_unread = false;
        for channel in self.viewable_channels_for_guild(Some(guild_id)) {
            match self.channel_unread(channel.id) {
                ChannelUnreadState::Mentioned(count) => {
                    mention_count = mention_count.saturating_add(count);
                }
                ChannelUnreadState::Notified(count) => {
                    notification_count = notification_count.saturating_add(count);
                }
                ChannelUnreadState::Unread => has_unread = true,
                ChannelUnreadState::Seen => {}
            }
        }

        if mention_count > 0 {
            ChannelUnreadState::Mentioned(mention_count)
        } else if notification_count > 0 {
            ChannelUnreadState::Notified(notification_count)
        } else if has_unread {
            ChannelUnreadState::Unread
        } else {
            ChannelUnreadState::Seen
        }
    }

    pub fn direct_message_unread_count(&self) -> usize {
        self.channels_for_guild(None)
            .into_iter()
            .filter(|channel| self.channel_unread(channel.id) != ChannelUnreadState::Seen)
            .count()
    }

    pub fn channel_unread_message_count(&self, channel_id: Id<ChannelMarker>) -> usize {
        let (mentions, notifications) = self.loaded_unread_notification_counts(channel_id);
        mentions.saturating_add(notifications)
    }

    pub fn message_event_triggers_notification(&self, event: &AppEvent) -> bool {
        let AppEvent::MessageCreate {
            guild_id,
            channel_id,
            message_id,
            author_id,
            content,
            mentions,
            ..
        } = event
        else {
            return false;
        };

        let guild_id = guild_id.or_else(|| self.channel_guild_id(*channel_id));
        self.message_create_notification_kind(
            guild_id,
            *channel_id,
            *message_id,
            *author_id,
            content.as_deref(),
            mentions,
        ) != MessageNotificationKind::None
    }

    pub(super) fn upsert_notification_settings(
        &mut self,
        settings: &GuildNotificationSettingsInfo,
    ) {
        let state = GuildNotificationSettingsState {
            message_notifications: settings.message_notifications,
            muted: settings.muted,
            mute_end_time: settings.mute_end_time.clone(),
            suppress_everyone: settings.suppress_everyone,
            suppress_roles: settings.suppress_roles,
            channel_overrides: notification_override_map(&settings.channel_overrides),
        };
        if let Some(guild_id) = settings.guild_id {
            self.notification_settings.insert(guild_id, state);
        } else {
            self.private_notification_settings = Some(state);
        }
    }

    fn message_state_notification_kind(&self, message: &MessageState) -> MessageNotificationKind {
        self.message_create_notification_kind(
            message.guild_id,
            message.channel_id,
            message.id,
            message.author_id,
            message.content.as_deref(),
            &message.mentions,
        )
    }

    pub(super) fn message_create_notification_kind(
        &self,
        guild_id: Option<Id<GuildMarker>>,
        channel_id: Id<ChannelMarker>,
        message_id: Id<MessageMarker>,
        author_id: Id<UserMarker>,
        content: Option<&str>,
        mentions: &[MentionInfo],
    ) -> MessageNotificationKind {
        if self.current_user_id == Some(author_id) {
            return MessageNotificationKind::None;
        }
        if self
            .read_states
            .get(&channel_id)
            .and_then(|state| state.last_acked_message_id)
            .is_some_and(|acked| acked >= message_id)
        {
            return MessageNotificationKind::None;
        }
        let Some(guild_id) = guild_id else {
            return self.private_message_notification_kind(channel_id, mentions);
        };
        let mentions_current_user = |settings: &GuildNotificationSettingsState| {
            self.message_mentions_current_user(
                guild_id,
                content,
                mentions,
                settings.suppress_everyone,
                settings.suppress_roles,
            )
        };
        let Some(settings) = self.notification_settings.get(&guild_id) else {
            return if self.message_mentions_current_user(guild_id, content, mentions, false, false)
            {
                MessageNotificationKind::Mention
            } else {
                MessageNotificationKind::None
            };
        };
        if notification_setting_muted(settings.muted, settings.mute_end_time.as_deref())
            || self.channel_notification_muted(settings, channel_id)
        {
            return MessageNotificationKind::None;
        }

        match self.channel_notification_level(settings, channel_id) {
            NotificationLevel::AllMessages if mentions_current_user(settings) => {
                MessageNotificationKind::Mention
            }
            NotificationLevel::AllMessages => MessageNotificationKind::Notify,
            NotificationLevel::OnlyMentions | NotificationLevel::ParentDefault => {
                if mentions_current_user(settings) {
                    MessageNotificationKind::Mention
                } else {
                    MessageNotificationKind::None
                }
            }
            NotificationLevel::NoMessages => MessageNotificationKind::None,
        }
    }

    fn private_message_notification_kind(
        &self,
        channel_id: Id<ChannelMarker>,
        mentions: &[MentionInfo],
    ) -> MessageNotificationKind {
        let Some(settings) = self.private_notification_settings.as_ref() else {
            return MessageNotificationKind::Notify;
        };
        if notification_setting_muted(settings.muted, settings.mute_end_time.as_deref())
            || self.channel_notification_muted(settings, channel_id)
        {
            return MessageNotificationKind::None;
        }
        let mentions_current_user = self
            .current_user_id
            .is_some_and(|self_id| mentions.iter().any(|mention| mention.user_id == self_id));
        match self.channel_notification_level(settings, channel_id) {
            NotificationLevel::AllMessages if mentions_current_user => {
                MessageNotificationKind::Mention
            }
            NotificationLevel::AllMessages => MessageNotificationKind::Notify,
            NotificationLevel::OnlyMentions | NotificationLevel::ParentDefault => {
                if mentions_current_user {
                    MessageNotificationKind::Mention
                } else {
                    MessageNotificationKind::None
                }
            }
            NotificationLevel::NoMessages => MessageNotificationKind::None,
        }
    }

    fn loaded_unread_notification_counts(&self, channel_id: Id<ChannelMarker>) -> (usize, usize) {
        let Some(messages) = self.messages.get(&channel_id) else {
            return (0, 0);
        };
        let last_acked = self
            .read_states
            .get(&channel_id)
            .and_then(|state| state.last_acked_message_id);
        let mut mentions = 0usize;
        let mut notifications = 0usize;
        for message in messages
            .iter()
            .filter(|message| last_acked.is_none_or(|last_acked| message.id > last_acked))
        {
            match self.message_state_notification_kind(message) {
                MessageNotificationKind::Mention => mentions = mentions.saturating_add(1),
                MessageNotificationKind::Notify => notifications = notifications.saturating_add(1),
                MessageNotificationKind::None => {}
            }
        }
        (mentions, notifications)
    }

    fn channel_notification_level(
        &self,
        settings: &GuildNotificationSettingsState,
        channel_id: Id<ChannelMarker>,
    ) -> NotificationLevel {
        if let Some(level) = settings
            .channel_overrides
            .get(&channel_id)
            .and_then(|setting| setting.message_notifications)
            .filter(|level| *level != NotificationLevel::ParentDefault)
        {
            return level;
        }
        if let Some(parent_id) = self
            .channels
            .get(&channel_id)
            .and_then(|channel| channel.parent_id)
            && let Some(level) = settings
                .channel_overrides
                .get(&parent_id)
                .and_then(|setting| setting.message_notifications)
                .filter(|level| *level != NotificationLevel::ParentDefault)
        {
            return level;
        }

        settings
            .message_notifications
            .filter(|level| *level != NotificationLevel::ParentDefault)
            .unwrap_or(NotificationLevel::OnlyMentions)
    }

    fn channel_notification_muted(
        &self,
        settings: &GuildNotificationSettingsState,
        channel_id: Id<ChannelMarker>,
    ) -> bool {
        let direct_muted = settings
            .channel_overrides
            .get(&channel_id)
            .is_some_and(|setting| {
                notification_setting_muted(setting.muted, setting.mute_end_time.as_deref())
            });
        if direct_muted {
            return true;
        }
        self.channels
            .get(&channel_id)
            .and_then(|channel| channel.parent_id)
            .and_then(|parent_id| settings.channel_overrides.get(&parent_id))
            .is_some_and(|setting| {
                notification_setting_muted(setting.muted, setting.mute_end_time.as_deref())
            })
    }

    fn message_mentions_current_user(
        &self,
        guild_id: Id<GuildMarker>,
        content: Option<&str>,
        mentions: &[MentionInfo],
        suppress_everyone: bool,
        suppress_roles: bool,
    ) -> bool {
        let Some(self_id) = self.current_user_id else {
            return false;
        };
        if mentions.iter().any(|mention| mention.user_id == self_id) {
            return true;
        }
        let content = content.unwrap_or_default();
        if !suppress_everyone && (content.contains("@everyone") || content.contains("@here")) {
            return true;
        }
        if suppress_roles {
            return false;
        }
        self.members
            .get(&guild_id)
            .and_then(|members| members.get(&self_id))
            .is_some_and(|member| {
                member
                    .role_ids
                    .iter()
                    .any(|role_id| content.contains(&format!("<@&{}>", role_id.get())))
            })
    }
}

fn notification_override_map(
    overrides: &[ChannelNotificationOverrideInfo],
) -> BTreeMap<Id<ChannelMarker>, ChannelNotificationSettingsState> {
    overrides
        .iter()
        .map(|override_info| {
            (
                override_info.channel_id,
                ChannelNotificationSettingsState {
                    message_notifications: override_info.message_notifications,
                    muted: override_info.muted,
                    mute_end_time: override_info.mute_end_time.clone(),
                },
            )
        })
        .collect()
}

fn notification_setting_muted(muted: bool, end_time: Option<&str>) -> bool {
    if !muted {
        return false;
    }
    let Some(end_time) = end_time else {
        return true;
    };
    DateTime::parse_from_rfc3339(end_time)
        .map(|end_time| end_time.with_timezone(&Utc) > Utc::now())
        .unwrap_or(true)
}

fn saturating_u32_count(count: usize) -> u32 {
    u32::try_from(count).unwrap_or(u32::MAX)
}