concord 2.5.0

A terminal user interface client for Discord
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
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
use std::time::Duration;

use reqwest::StatusCode;
use serde_json::Value;
use serde_json::json;

use crate::discord::ids::{
    Id,
    marker::{ChannelMarker, ForumTagMarker, GuildMarker},
};
use crate::{
    AppError, Result,
    discord::{
        ChannelInfo, ForumPostArchiveState, ForumPostCreate, MessageAttachmentUpload, MessageInfo,
        gateway::{parse_channel_info, parse_message_info},
    },
};

use super::messages::{message_multipart_form, validate_message_payload};
use super::{DiscordRest, clone_array, extra_fields};

const FORUM_POST_SEARCH_PAGE_LIMIT: u16 = 25;
const FORUM_POST_SEARCH_MAX_ATTEMPTS: usize = 3;
const FORUM_POST_SEARCH_DEFAULT_RETRY: Duration = Duration::from_secs(5);

#[derive(Clone, Debug, Eq, PartialEq)]
pub struct ForumPostPage {
    pub threads: Vec<ChannelInfo>,
    pub first_messages: Vec<MessageInfo>,
    pub has_more: bool,
    pub next_offset: usize,
}

#[derive(Clone, Debug, Eq, PartialEq)]
pub struct CreatedForumPost {
    pub thread: ChannelInfo,
    pub first_message: Option<MessageInfo>,
}

impl DiscordRest {
    /// Follow a forum post by joining its thread, so the current user receives
    /// notifications (and can then mute it).
    pub async fn follow_thread(&self, thread_id: Id<ChannelMarker>) -> Result<()> {
        self.send_unit(
            self.raw_http.put(format!(
                "https://discord.com/api/v9/channels/{}/thread-members/@me",
                thread_id.get()
            )),
            "follow post",
        )
        .await
    }

    /// Unfollow a forum post by leaving its thread.
    pub async fn unfollow_thread(&self, thread_id: Id<ChannelMarker>) -> Result<()> {
        self.send_unit(
            self.raw_http.delete(format!(
                "https://discord.com/api/v9/channels/{}/thread-members/@me",
                thread_id.get()
            )),
            "unfollow post",
        )
        .await
    }

    /// Archive ("close") or unarchive a thread (regular thread or forum post).
    pub async fn set_thread_archived(
        &self,
        thread_id: Id<ChannelMarker>,
        archived: bool,
    ) -> Result<()> {
        self.edit_thread(thread_id, &json!({ "archived": archived }))
            .await
    }

    /// Lock or unlock a thread. While locked, members without manage permissions
    /// can no longer reply.
    pub async fn set_thread_locked(
        &self,
        thread_id: Id<ChannelMarker>,
        locked: bool,
    ) -> Result<()> {
        self.edit_thread(thread_id, &json!({ "locked": locked }))
            .await
    }

    /// Pin or unpin a forum post within its parent forum. The pin lives in the
    /// channel `flags` bitfield, so we flip only the PINNED bit and preserve the
    /// other flags (for example REQUIRE_TAG).
    pub async fn set_thread_pinned(
        &self,
        thread_id: Id<ChannelMarker>,
        pinned: bool,
        current_flags: u64,
    ) -> Result<()> {
        const THREAD_FLAG_PINNED: u64 = 1 << 1;
        let flags = if pinned {
            current_flags | THREAD_FLAG_PINNED
        } else {
            current_flags & !THREAD_FLAG_PINNED
        };
        self.edit_thread(thread_id, &json!({ "flags": flags }))
            .await
    }

    /// Edit a thread's general settings in one `PATCH` call: the title, applied
    /// tags (forum posts only), slow-mode cooldown, and auto-archive duration.
    /// This is the popup-driven counterpart to the single-field archive/lock/pin
    /// helpers above.
    pub async fn edit_thread_settings(
        &self,
        thread_id: Id<ChannelMarker>,
        name: &str,
        applied_tags: &[Id<ForumTagMarker>],
        rate_limit_per_user: Option<u64>,
        auto_archive_duration: u64,
    ) -> Result<()> {
        let mut body = json!({
            "name": name,
            "applied_tags": applied_tags
                .iter()
                .map(|tag_id| Value::String(tag_id.to_string()))
                .collect::<Vec<_>>(),
            "auto_archive_duration": auto_archive_duration,
        });
        if let Some(rate_limit_per_user) = rate_limit_per_user {
            body.as_object_mut()
                .expect("thread edit body is an object")
                .insert(
                    "rate_limit_per_user".to_owned(),
                    Value::from(rate_limit_per_user),
                );
        }
        self.edit_thread(thread_id, &body).await
    }

    /// Permanently delete a thread by deleting its underlying channel.
    pub async fn delete_thread(&self, thread_id: Id<ChannelMarker>) -> Result<()> {
        self.send_unit(
            self.raw_http.delete(format!(
                "https://discord.com/api/v9/channels/{}",
                thread_id.get()
            )),
            "delete thread",
        )
        .await
    }

    /// Apply a partial `PATCH /channels/{id}` edit to a thread. Shared by the
    /// archive/lock/pin actions, which each send one field.
    async fn edit_thread(&self, thread_id: Id<ChannelMarker>, body: &Value) -> Result<()> {
        self.send_unit(
            self.raw_http
                .patch(format!(
                    "https://discord.com/api/v9/channels/{}",
                    thread_id.get()
                ))
                .json(body),
            "edit thread",
        )
        .await
    }

    pub async fn create_forum_post(
        &self,
        post: &ForumPostCreate,
        upload_limit: u64,
        slow_mode: Option<Duration>,
    ) -> Result<CreatedForumPost> {
        let _channel_guard = self.message_sends.acquire(post.channel_id).await;
        self.message_sends
            .ensure_cooldown_elapsed(post.channel_id)?;
        let body = create_forum_post_request_body(
            &post.title,
            &post.content,
            &post.applied_tags,
            &post.attachments,
            upload_limit,
        )?;
        let request = self.raw_http.post(format!(
            "https://discord.com/api/v9/channels/{}/threads",
            post.channel_id.get()
        ));
        let request = if post.attachments.is_empty() {
            request.json(&body)
        } else {
            request.multipart(message_multipart_form(body, &post.attachments, upload_limit).await?)
        };

        let result = self
            .send_json(request, "create forum post")
            .await
            .and_then(|raw: Value| parse_create_forum_post_response(&raw, Some(post.channel_id)));
        match &result {
            Ok(_) => {
                if let Some(slow_mode) = slow_mode {
                    self.message_sends
                        .record_cooldown(post.channel_id, slow_mode);
                }
            }
            Err(AppError::DiscordRateLimited {
                retry_after_millis, ..
            }) => self
                .message_sends
                .record_cooldown(post.channel_id, Duration::from_millis(*retry_after_millis)),
            Err(_) => {}
        }
        result
    }

    pub async fn load_forum_posts(
        &self,
        guild_id: Id<GuildMarker>,
        channel_id: Id<ChannelMarker>,
        archive_state: ForumPostArchiveState,
        offset: usize,
    ) -> Result<ForumPostPage> {
        // The `last_message_time` index excludes posts where nobody has
        // replied yet (`message_count == 0`), and the `creation_time` index
        // doesn't surface old-but-active threads in its first page. Discord's
        // own client gets the union by querying both, so on the very first
        // page we issue both calls in parallel and merge. Subsequent pages
        // only need `last_message_time` because zero-reply posts are almost
        // always recent and already covered by the first response.
        if offset == 0 {
            // `relevance` is the only sort that lifts pinned posts to the top.
            // The activity/creation sorts bury an inactive pin below page 0, so
            // we also harvest pins from a relevance page (active only, since
            // archiving clears the pin flag). Best-effort, so a failed relevance
            // call cannot break the list.
            let harvest_pins = archive_state == ForumPostArchiveState::Active;
            let (activity, recent, pins) = tokio::join!(
                self.load_forum_post_search_page(
                    guild_id,
                    channel_id,
                    archive_state,
                    offset,
                    ForumSearchSort::LastMessageTime,
                ),
                self.load_forum_post_search_page(
                    guild_id,
                    channel_id,
                    archive_state,
                    offset,
                    ForumSearchSort::CreationTime,
                ),
                async {
                    if harvest_pins {
                        self.load_forum_post_search_page(
                            guild_id,
                            channel_id,
                            archive_state,
                            offset,
                            ForumSearchSort::Relevance,
                        )
                        .await
                        .ok()
                    } else {
                        None
                    }
                },
            );
            let page = merge_forum_pages(activity?, recent?);
            return Ok(match pins {
                Some(pins) => merge_pinned_forum_posts(page, pins),
                None => page,
            });
        }

        self.load_forum_post_search_page(
            guild_id,
            channel_id,
            archive_state,
            offset,
            ForumSearchSort::LastMessageTime,
        )
        .await
    }

    async fn load_forum_post_search_page(
        &self,
        guild_id: Id<GuildMarker>,
        channel_id: Id<ChannelMarker>,
        archive_state: ForumPostArchiveState,
        offset: usize,
        sort_by: ForumSearchSort,
    ) -> Result<ForumPostPage> {
        // `/threads/search` is the only Discord endpoint that ships
        // `first_messages` alongside thread metadata, so we never want to
        // fall back to the active or archived endpoints. They cannot supply
        // previews and routinely 403 on user-account tokens. Instead retry
        // according to Discord's response when the search index is warming up.
        for attempt in 0..FORUM_POST_SEARCH_MAX_ATTEMPTS {
            match self
                .request_forum_post_search_page(
                    guild_id,
                    channel_id,
                    archive_state,
                    offset,
                    sort_by,
                )
                .await
            {
                Ok(page) => return Ok(page),
                Err(error) => {
                    let Some(delay) = forum_search_retry_after(&error) else {
                        return Err(error);
                    };
                    if attempt + 1 == FORUM_POST_SEARCH_MAX_ATTEMPTS {
                        return Err(error);
                    }
                    tokio::time::sleep(delay).await;
                }
            }
        }
        unreachable!("forum search attempt loop always returns")
    }

    async fn request_forum_post_search_page(
        &self,
        guild_id: Id<GuildMarker>,
        channel_id: Id<ChannelMarker>,
        archive_state: ForumPostArchiveState,
        offset: usize,
        sort_by: ForumSearchSort,
    ) -> Result<ForumPostPage> {
        let request = self
            .raw_http
            .get(format!(
                "https://discord.com/api/v9/channels/{}/threads/search",
                channel_id.get()
            ))
            .query(&[
                ("archived", archive_state.as_query_value().to_owned()),
                ("sort_by", sort_by.as_str().to_owned()),
                ("sort_order", "desc".to_owned()),
                ("limit", FORUM_POST_SEARCH_PAGE_LIMIT.to_string()),
                ("tag_setting", "match_some".to_owned()),
                ("offset", offset.to_string()),
            ]);
        let response = self
            .execute_authenticated(request, "forum post search")
            .await?;
        if response.status() == StatusCode::ACCEPTED {
            let raw = response.json::<Value>().await.unwrap_or(Value::Null);
            let delay = raw
                .get("retry_after")
                .and_then(Value::as_f64)
                .and_then(super::rate_limit_delay)
                .filter(|delay| !delay.is_zero())
                .unwrap_or(FORUM_POST_SEARCH_DEFAULT_RETRY);
            return Err(AppError::ForumSearchIndexWarming {
                retry_after_millis: super::duration_millis_ceil(delay),
            });
        }
        if let Err(error) = response.error_for_status_ref() {
            return Err(super::request_error(error, response, "forum post search").await);
        }
        let raw: Value = response.json().await.map_err(|error| {
            AppError::DiscordRequest(format!("forum post search decode failed: {error}"))
        })?;

        let response = parse_forum_thread_search_response(&raw, Some(guild_id), channel_id, true);
        let has_more = forum_search_has_more(&response);

        Ok(ForumPostPage {
            // Advance by Discord's raw result count. Local filtering can drop
            // malformed or unrelated threads and must not make the cursor
            // repeat those same server-side rows.
            next_offset: forum_search_next_offset(offset, &response),
            threads: response.threads,
            first_messages: response.first_messages,
            has_more,
        })
    }
}

pub(super) fn forum_search_next_offset(
    offset: usize,
    response: &ForumThreadSearchResponse,
) -> usize {
    offset.saturating_add(response.raw_threads.len())
}

pub(super) fn forum_search_has_more(response: &ForumThreadSearchResponse) -> bool {
    response.has_more && !response.raw_threads.is_empty()
}

pub(super) fn create_forum_post_request_body(
    title: &str,
    content: &str,
    applied_tags: &[Id<ForumTagMarker>],
    attachments: &[MessageAttachmentUpload],
    upload_limit: u64,
) -> Result<Value> {
    let title = validate_forum_post_title(title)?;
    validate_message_payload(content, attachments, upload_limit)?;

    let mut body = json!({
        "name": title,
        "message": {
            "content": content,
        },
    });
    if !applied_tags.is_empty() {
        body["applied_tags"] = Value::Array(
            applied_tags
                .iter()
                .map(|tag_id| Value::String(tag_id.to_string()))
                .collect(),
        );
    }
    if !attachments.is_empty() {
        body["message"]["attachments"] = Value::Array(
            attachments
                .iter()
                .enumerate()
                .map(|(index, attachment)| {
                    json!({
                        "id": index,
                        "filename": attachment.filename,
                    })
                })
                .collect(),
        );
    }
    Ok(body)
}

fn validate_forum_post_title(title: &str) -> Result<&str> {
    let title = title.trim();
    let len = title.chars().count();
    if len == 0 {
        return Err(AppError::DiscordRequest(
            "forum post title cannot be empty".to_owned(),
        ));
    }
    if len > 100 {
        return Err(AppError::DiscordRequest(format!(
            "forum post title is too long: {len}/100"
        )));
    }
    Ok(title)
}

pub(super) fn parse_create_forum_post_response(
    raw: &Value,
    parent_channel_id: Option<Id<ChannelMarker>>,
) -> Result<CreatedForumPost> {
    let mut thread = parse_channel_info(raw, None).ok_or_else(|| {
        AppError::DiscordRequest("create forum post response was missing thread".to_owned())
    })?;
    if thread.parent_id.is_none() {
        thread.parent_id = parent_channel_id;
    }
    let first_message = raw.get("message").and_then(parse_message_info);
    Ok(CreatedForumPost {
        thread,
        first_message,
    })
}

#[derive(Clone, Debug, PartialEq)]
pub(super) struct ForumThreadSearchResponse {
    pub(super) threads: Vec<ChannelInfo>,
    pub(super) first_messages: Vec<MessageInfo>,
    pub(super) has_more: bool,
    pub(super) raw_threads: Vec<Value>,
    pub(super) raw_first_messages: Vec<Value>,
    pub(super) extra_fields: std::collections::BTreeMap<String, Value>,
}

pub(super) fn parse_forum_thread_search_response(
    raw: &Value,
    guild_id: Option<Id<GuildMarker>>,
    parent_channel_id: Id<ChannelMarker>,
    fill_missing_parent: bool,
) -> ForumThreadSearchResponse {
    let threads = parse_forum_threads(raw, guild_id, parent_channel_id, fill_missing_parent);
    let first_messages = parse_forum_first_messages(raw, &threads);
    ForumThreadSearchResponse {
        threads,
        first_messages,
        has_more: raw
            .get("has_more")
            .and_then(Value::as_bool)
            .unwrap_or(false),
        raw_threads: clone_array(raw.get("threads")),
        raw_first_messages: clone_array(raw.get("first_messages")),
        extra_fields: extra_fields(raw, &["threads", "first_messages", "has_more"]),
    }
}

pub(super) fn parse_forum_threads(
    raw: &Value,
    guild_id: Option<Id<GuildMarker>>,
    parent_channel_id: Id<ChannelMarker>,
    fill_missing_parent: bool,
) -> Vec<ChannelInfo> {
    raw.get("threads")
        .and_then(Value::as_array)
        .map(|threads| {
            threads
                .iter()
                .filter_map(|thread| {
                    let mut channel = parse_channel_info(thread, guild_id)?;
                    if fill_missing_parent && channel.parent_id.is_none() {
                        channel.parent_id = Some(parent_channel_id);
                    }
                    if channel.parent_id != Some(parent_channel_id) {
                        return None;
                    }
                    Some(channel)
                })
                .collect()
        })
        .unwrap_or_default()
}

pub(super) fn parse_forum_first_messages(raw: &Value, threads: &[ChannelInfo]) -> Vec<MessageInfo> {
    let mut seen = std::collections::HashSet::new();
    parse_forum_messages_from_field(raw, threads, "first_messages")
        .into_iter()
        .filter(|message| seen.insert(message.message_id))
        .collect()
}

fn parse_forum_messages_from_field(
    raw: &Value,
    threads: &[ChannelInfo],
    field: &str,
) -> Vec<MessageInfo> {
    raw.get(field)
        .and_then(Value::as_array)
        .map(|messages| {
            messages
                .iter()
                .filter_map(parse_message_info)
                .filter(|message| {
                    threads
                        .iter()
                        .any(|thread| thread.channel_id == message.channel_id)
                })
                .collect()
        })
        .unwrap_or_default()
}

pub(super) fn forum_search_retry_after(error: &AppError) -> Option<Duration> {
    match error {
        AppError::ForumSearchIndexWarming { retry_after_millis } => {
            Some(Duration::from_millis(*retry_after_millis))
        }
        _ => None,
    }
}

#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub(super) enum ForumSearchSort {
    LastMessageTime,
    CreationTime,
    /// Only used to harvest pinned posts: it is the one sort under which
    /// Discord lifts pins to the top of the results.
    Relevance,
}

impl ForumSearchSort {
    pub(super) fn as_str(self) -> &'static str {
        match self {
            Self::LastMessageTime => "last_message_time",
            Self::CreationTime => "creation_time",
            Self::Relevance => "relevance",
        }
    }
}

/// Combine the two first-page responses Discord uses to build the "Recent
/// activity" view. `active` (last_message_time) carries threads with replies.
/// `recent` (creation_time) carries the freshly-created zero-reply ones. We
/// dedupe by `channel_id`. The order does not matter because the display layer
/// re-sorts by `last_message_id` snowflake. `has_more` only follows the
/// `last_message_time` cursor since subsequent pages use that sort alone.
pub(super) fn merge_forum_pages(active: ForumPostPage, recent: ForumPostPage) -> ForumPostPage {
    let mut seen_threads = std::collections::HashSet::new();
    let mut threads = Vec::with_capacity(active.threads.len() + recent.threads.len());
    for thread in active.threads.into_iter().chain(recent.threads) {
        if seen_threads.insert(thread.channel_id) {
            threads.push(thread);
        }
    }
    let mut seen_first_messages = std::collections::HashSet::new();
    let mut first_messages =
        Vec::with_capacity(active.first_messages.len() + recent.first_messages.len());
    for message in active
        .first_messages
        .into_iter()
        .chain(recent.first_messages)
    {
        if seen_first_messages.insert(message.message_id) {
            first_messages.push(message);
        }
    }
    ForumPostPage {
        next_offset: active.next_offset,
        threads,
        first_messages,
        has_more: active.has_more,
    }
}

/// Fold only the pinned posts from a `relevance`-sorted page into `page`,
/// discarding relevance's reshuffle of everything else. The display layer
/// re-sorts pinned-first, so the pins just need to be present. `next_offset`
/// and `has_more` stay from `page` so pagination keeps following the activity
/// sort.
pub(super) fn merge_pinned_forum_posts(
    mut page: ForumPostPage,
    pins: ForumPostPage,
) -> ForumPostPage {
    let mut seen_threads = page
        .threads
        .iter()
        .map(|thread| thread.channel_id)
        .collect::<std::collections::HashSet<_>>();
    let mut new_pin_ids = std::collections::HashSet::new();
    let mut pinned_threads = Vec::new();
    for thread in pins.threads {
        if !thread.thread_pinned().unwrap_or(false) {
            continue;
        }
        if seen_threads.insert(thread.channel_id) {
            new_pin_ids.insert(thread.channel_id);
            pinned_threads.push(thread);
        }
    }
    if pinned_threads.is_empty() {
        return page;
    }

    let mut seen_messages = page
        .first_messages
        .iter()
        .map(|message| message.message_id)
        .collect::<std::collections::HashSet<_>>();
    for message in pins.first_messages {
        if new_pin_ids.contains(&message.channel_id) && seen_messages.insert(message.message_id) {
            page.first_messages.push(message);
        }
    }

    pinned_threads.extend(page.threads);
    page.threads = pinned_threads;
    page
}