refluxer 0.1.0

Rust API wrapper for Fluxer
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
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
use crate::error::HttpError;
use crate::http::client::HttpClient;
use crate::http::routing::Route;
use crate::model::id::{AttachmentId, ChannelId, MessageId};
use crate::model::message::{
    Embed, EmbedAuthor, EmbedField, EmbedFooter, EmbedMedia, Message, MessageReference,
};

impl HttpClient {
    /// Convenience wrapper around [`list_messages`](Self::list_messages) that
    /// returns the most recent messages with no filters.
    pub async fn get_messages(&self, channel_id: ChannelId) -> Result<Vec<Message>, HttpError> {
        self.list_messages(channel_id, &ListMessagesParams::default())
            .await
    }

    /// List messages in a channel with optional `before`/`after`/`around`
    /// cursors and `limit` (1..=100, default 50 server-side).
    pub async fn list_messages(
        &self,
        channel_id: ChannelId,
        params: &ListMessagesParams,
    ) -> Result<Vec<Message>, HttpError> {
        self.request_no_body(Route::GetMessages {
            channel_id,
            query: params.to_query(),
        })
        .await
    }

    /// Search messages across channels/guilds. Returns the raw JSON response
    /// because it is a `oneOf` of a results payload and an "indexing in
    /// progress" marker — consumers should match on the top-level `messages`
    /// key to decide which shape they got. A future revision may introduce
    /// typed variants.
    pub async fn search_messages(
        &self,
        params: &SearchMessagesRequest,
    ) -> Result<serde_json::Value, HttpError> {
        self.request(Route::SearchMessages, Some(params)).await
    }
    pub async fn get_message(
        &self,
        channel_id: ChannelId,
        message_id: MessageId,
    ) -> Result<Message, HttpError> {
        self.request_no_body(Route::GetMessage {
            channel_id,
            message_id,
        })
        .await
    }
    pub async fn create_message(
        &self,
        channel_id: ChannelId,
        params: &CreateMessage,
    ) -> Result<Message, HttpError> {
        self.request(Route::CreateMessage { channel_id }, Some(params))
            .await
    }

    /// Send a message with one or more file attachments as multipart/form-data.
    ///
    /// Each file is added as a `files[i]` part; `params.attachments` should
    /// already contain an `Attachment` entry with `id = i` and the matching
    /// `filename`. Embeds can reference uploaded files via `attachment://<name>`.
    pub async fn create_message_with_files(
        &self,
        channel_id: ChannelId,
        params: &CreateMessage,
        files: Vec<(String, Vec<u8>)>,
    ) -> Result<Message, HttpError> {
        let payload_json = serde_json::to_string(params)?;
        let mut form = reqwest::multipart::Form::new().part(
            "payload_json",
            reqwest::multipart::Part::text(payload_json).mime_str("application/json")?,
        );
        for (i, (filename, bytes)) in files.into_iter().enumerate() {
            let part = reqwest::multipart::Part::bytes(bytes)
                .file_name(filename)
                .mime_str("application/octet-stream")?;
            form = form.part(format!("files[{i}]"), part);
        }
        self.fire_multipart(Route::CreateMessage { channel_id }, form)
            .await
    }
    pub async fn edit_message(
        &self,
        channel_id: ChannelId,
        message_id: MessageId,
        params: &EditMessage,
    ) -> Result<Message, HttpError> {
        self.request(
            Route::EditMessage {
                channel_id,
                message_id,
            },
            Some(params),
        )
        .await
    }
    pub async fn delete_message(
        &self,
        channel_id: ChannelId,
        message_id: MessageId,
    ) -> Result<(), HttpError> {
        self.request_empty(
            Route::DeleteMessage {
                channel_id,
                message_id,
            },
            None::<&()>,
        )
        .await
    }

    /// Remove a single attachment from an existing message without deleting
    /// the message itself.
    pub async fn delete_message_attachment(
        &self,
        channel_id: ChannelId,
        message_id: MessageId,
        attachment_id: AttachmentId,
    ) -> Result<(), HttpError> {
        self.request_empty(
            Route::DeleteMessageAttachment {
                channel_id,
                message_id,
                attachment_id,
            },
            None::<&()>,
        )
        .await
    }

    /// Bulk delete messages (2-100 messages, not older than 14 days).
    pub async fn bulk_delete_messages(
        &self,
        channel_id: ChannelId,
        message_ids: &[MessageId],
    ) -> Result<(), HttpError> {
        #[derive(serde::Serialize)]
        struct Body<'a> {
            messages: &'a [MessageId],
        }
        self.request_empty(
            Route::BulkDeleteMessages { channel_id },
            Some(&Body {
                messages: message_ids,
            }),
        )
        .await
    }

    /// Schedule a message for future delivery. The body is accepted as a
    /// serializable body because the Fluxer OpenAPI spec does not document
    /// the request schema; at minimum it should include `scheduled_at` (ISO
    /// 8601 UTC) and a message payload (content and/or embeds).
    pub async fn schedule_message(
        &self,
        channel_id: ChannelId,
        body: &impl serde::Serialize,
    ) -> Result<serde_json::Value, HttpError> {
        self.request(Route::ScheduleMessage { channel_id }, Some(body))
            .await
    }

    /// List the current user's pending scheduled messages.
    pub async fn list_scheduled_messages(&self) -> Result<Vec<serde_json::Value>, HttpError> {
        self.request_no_body(Route::ListScheduledMessages).await
    }

    pub async fn get_scheduled_message(
        &self,
        scheduled_message_id: crate::model::id::Snowflake,
    ) -> Result<serde_json::Value, HttpError> {
        self.request_no_body(Route::GetScheduledMessage {
            scheduled_message_id,
        })
        .await
    }

    pub async fn update_scheduled_message(
        &self,
        scheduled_message_id: crate::model::id::Snowflake,
        body: &impl serde::Serialize,
    ) -> Result<serde_json::Value, HttpError> {
        self.request(
            Route::UpdateScheduledMessage {
                scheduled_message_id,
            },
            Some(body),
        )
        .await
    }

    pub async fn cancel_scheduled_message(
        &self,
        scheduled_message_id: crate::model::id::Snowflake,
    ) -> Result<(), HttpError> {
        self.request_empty(
            Route::CancelScheduledMessage {
                scheduled_message_id,
            },
            None::<&()>,
        )
        .await
    }

    // --- Read states ---

    /// Mark a single message as read, updating the channel read state.
    pub async fn acknowledge_message(
        &self,
        channel_id: ChannelId,
        message_id: MessageId,
        mention_count: Option<i32>,
        manual: bool,
    ) -> Result<(), HttpError> {
        #[derive(serde::Serialize)]
        struct Body {
            #[serde(skip_serializing_if = "Option::is_none")]
            mention_count: Option<i32>,
            manual: bool,
        }
        self.request_empty(
            Route::AcknowledgeMessage {
                channel_id,
                message_id,
            },
            Some(&Body {
                mention_count,
                manual,
            }),
        )
        .await
    }

    /// Mark all pinned messages in a channel as seen.
    pub async fn acknowledge_pins(&self, channel_id: ChannelId) -> Result<(), HttpError> {
        #[derive(serde::Serialize)]
        struct Body {}

        self.request_empty(Route::AcknowledgePins { channel_id }, Some(&Body {}))
            .await
    }

    /// Clear a channel's entire read state.
    pub async fn clear_channel_read_state(&self, channel_id: ChannelId) -> Result<(), HttpError> {
        self.request_empty(Route::ClearChannelReadState { channel_id }, None::<&()>)
            .await
    }

    /// Bulk-acknowledge up to 100 channel/message pairs in a single request.
    pub async fn ack_bulk_messages(&self, read_states: &[ReadStateAck]) -> Result<(), HttpError> {
        #[derive(serde::Serialize)]
        struct Body<'a> {
            read_states: &'a [ReadStateAck],
        }
        self.request_empty(Route::AckBulkMessages, Some(&Body { read_states }))
            .await
    }
}

#[derive(Debug, Clone, serde::Serialize)]
pub struct ReadStateAck {
    pub channel_id: ChannelId,
    pub message_id: MessageId,
}

// ---------------------------------------------------------------------------
// ListMessagesParams
// ---------------------------------------------------------------------------

#[derive(Debug, Default, Clone)]
pub struct ListMessagesParams {
    pub before: Option<MessageId>,
    pub after: Option<MessageId>,
    pub around: Option<MessageId>,
    pub limit: Option<u32>,
}

impl ListMessagesParams {
    pub fn before(mut self, id: MessageId) -> Self {
        self.before = Some(id);
        self
    }
    pub fn after(mut self, id: MessageId) -> Self {
        self.after = Some(id);
        self
    }
    pub fn around(mut self, id: MessageId) -> Self {
        self.around = Some(id);
        self
    }
    pub fn limit(mut self, n: u32) -> Self {
        self.limit = Some(n);
        self
    }

    pub(crate) fn to_query(&self) -> String {
        let mut parts: Vec<String> = Vec::new();
        if let Some(v) = self.before {
            parts.push(format!("before={v}"));
        }
        if let Some(v) = self.after {
            parts.push(format!("after={v}"));
        }
        if let Some(v) = self.around {
            parts.push(format!("around={v}"));
        }
        if let Some(v) = self.limit {
            parts.push(format!("limit={v}"));
        }
        if parts.is_empty() {
            String::new()
        } else {
            format!("?{}", parts.join("&"))
        }
    }
}

// ---------------------------------------------------------------------------
// SearchMessagesRequest
// ---------------------------------------------------------------------------

/// Request body for [`HttpClient::search_messages`]. Mirrors the
/// `GlobalSearchMessagesRequest` schema but exposes only the most common
/// fields; add more as needed.
#[derive(Debug, Default, serde::Serialize)]
pub struct SearchMessagesRequest {
    #[serde(skip_serializing_if = "Option::is_none")]
    pub content: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub hits_per_page: Option<u32>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub page: Option<u64>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub max_id: Option<MessageId>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub min_id: Option<MessageId>,
    #[serde(skip_serializing_if = "Vec::is_empty")]
    pub channel_id: Vec<ChannelId>,
    #[serde(skip_serializing_if = "Vec::is_empty")]
    pub exclude_channel_id: Vec<ChannelId>,
    #[serde(skip_serializing_if = "Vec::is_empty")]
    pub exact_phrases: Vec<String>,
}

// ---------------------------------------------------------------------------
// CreateMessage
// ---------------------------------------------------------------------------

/// Metadata entry for an uploaded file. Paired with a `files[N]` part in the
/// multipart form; the `id` field equals the zero-based index of the matching
/// file part. Embeds can reference these via `attachment://<filename>`.
#[derive(Debug, Clone, serde::Serialize)]
pub struct Attachment {
    pub id: u32,
    pub filename: String,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub description: Option<String>,
}

#[derive(Debug, Default, serde::Serialize)]
pub struct CreateMessage {
    #[serde(skip_serializing_if = "Option::is_none")]
    pub content: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub tts: Option<bool>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub embeds: Option<Vec<Embed>>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub message_reference: Option<MessageReference>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub nonce: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub attachments: Option<Vec<Attachment>>,
}

impl CreateMessage {
    pub fn new() -> Self {
        Self::default()
    }

    pub fn text(content: impl Into<String>) -> Self {
        Self {
            content: Some(content.into()),
            ..Default::default()
        }
    }

    pub fn content(mut self, content: impl Into<String>) -> Self {
        self.content = Some(content.into());
        self
    }

    pub fn tts(mut self, tts: bool) -> Self {
        self.tts = Some(tts);
        self
    }

    pub fn embed(mut self, build: impl FnOnce(EmbedBuilder) -> EmbedBuilder) -> Self {
        let embed = build(EmbedBuilder::new()).build();
        self.embeds.get_or_insert_with(Vec::new).push(embed);
        self
    }

    pub fn reply(mut self, message_id: MessageId) -> Self {
        self.message_reference = Some(MessageReference {
            message_id: Some(message_id),
            channel_id: None,
        });
        self
    }

    pub fn nonce(mut self, nonce: impl Into<String>) -> Self {
        self.nonce = Some(nonce.into());
        self
    }
}

// ---------------------------------------------------------------------------
// EditMessage
// ---------------------------------------------------------------------------

#[derive(Debug, Default, serde::Serialize)]
pub struct EditMessage {
    #[serde(skip_serializing_if = "Option::is_none")]
    pub content: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub embeds: Option<Vec<Embed>>,
}

impl EditMessage {
    pub fn new() -> Self {
        Self::default()
    }

    pub fn content(mut self, content: impl Into<String>) -> Self {
        self.content = Some(content.into());
        self
    }

    pub fn embed(mut self, build: impl FnOnce(EmbedBuilder) -> EmbedBuilder) -> Self {
        let embed = build(EmbedBuilder::new()).build();
        self.embeds.get_or_insert_with(Vec::new).push(embed);
        self
    }
}

// ---------------------------------------------------------------------------
// EmbedBuilder
// ---------------------------------------------------------------------------

#[derive(Debug, Default)]
pub struct EmbedBuilder {
    title: Option<String>,
    description: Option<String>,
    url: Option<String>,
    timestamp: Option<String>,
    color: Option<i32>,
    footer_text: Option<String>,
    footer_icon_url: Option<String>,
    image_url: Option<String>,
    thumbnail_url: Option<String>,
    author_name: Option<String>,
    author_url: Option<String>,
    author_icon_url: Option<String>,
    fields: Vec<EmbedField>,
}

impl EmbedBuilder {
    pub fn new() -> Self {
        Self::default()
    }

    pub fn title(mut self, title: impl Into<String>) -> Self {
        self.title = Some(title.into());
        self
    }

    pub fn description(mut self, description: impl Into<String>) -> Self {
        self.description = Some(description.into());
        self
    }

    pub fn url(mut self, url: impl Into<String>) -> Self {
        self.url = Some(url.into());
        self
    }

    pub fn timestamp(mut self, timestamp: impl Into<String>) -> Self {
        self.timestamp = Some(timestamp.into());
        self
    }

    pub fn timestamp_now(mut self) -> Self {
        use std::time::{SystemTime, UNIX_EPOCH};
        let secs = SystemTime::now()
            .duration_since(UNIX_EPOCH)
            .unwrap_or_default()
            .as_secs();
        // ISO 8601 format (approximate — no chrono dependency)
        let s = secs;
        let days = s / 86400;
        let time_of_day = s % 86400;
        let hours = time_of_day / 3600;
        let minutes = (time_of_day % 3600) / 60;
        let seconds = time_of_day % 60;

        // Days since 1970-01-01
        let mut y = 1970i64;
        let mut remaining_days = days as i64;
        loop {
            let days_in_year = if y % 4 == 0 && (y % 100 != 0 || y % 400 == 0) {
                366
            } else {
                365
            };
            if remaining_days < days_in_year {
                break;
            }
            remaining_days -= days_in_year;
            y += 1;
        }
        let leap = y % 4 == 0 && (y % 100 != 0 || y % 400 == 0);
        let month_days: [i64; 12] = [
            31,
            if leap { 29 } else { 28 },
            31,
            30,
            31,
            30,
            31,
            31,
            30,
            31,
            30,
            31,
        ];
        let mut m = 0usize;
        for (i, &md) in month_days.iter().enumerate() {
            if remaining_days < md {
                m = i;
                break;
            }
            remaining_days -= md;
        }
        let d = remaining_days + 1;

        self.timestamp = Some(format!(
            "{y:04}-{:02}-{d:02}T{hours:02}:{minutes:02}:{seconds:02}Z",
            m + 1,
        ));
        self
    }

    pub fn color(mut self, color: i32) -> Self {
        self.color = Some(color);
        self
    }

    pub fn footer(mut self, text: impl Into<String>) -> Self {
        self.footer_text = Some(text.into());
        self
    }

    pub fn footer_icon(mut self, icon_url: impl Into<String>) -> Self {
        self.footer_icon_url = Some(icon_url.into());
        self
    }

    pub fn image(mut self, url: impl Into<String>) -> Self {
        self.image_url = Some(url.into());
        self
    }

    pub fn thumbnail(mut self, url: impl Into<String>) -> Self {
        self.thumbnail_url = Some(url.into());
        self
    }

    pub fn author(mut self, name: impl Into<String>) -> Self {
        self.author_name = Some(name.into());
        self
    }

    pub fn author_url(mut self, url: impl Into<String>) -> Self {
        self.author_url = Some(url.into());
        self
    }

    pub fn author_icon(mut self, icon_url: impl Into<String>) -> Self {
        self.author_icon_url = Some(icon_url.into());
        self
    }

    pub fn field(
        mut self,
        name: impl Into<String>,
        value: impl Into<String>,
        inline: bool,
    ) -> Self {
        self.fields.push(EmbedField {
            name: name.into(),
            value: value.into(),
            inline: Some(inline),
        });
        self
    }

    pub fn build(self) -> Embed {
        Embed {
            kind: Some("rich".to_string()),
            title: self.title,
            description: self.description,
            url: self.url,
            timestamp: self.timestamp,
            color: self.color,
            footer: self.footer_text.map(|text| EmbedFooter {
                text,
                icon_url: self.footer_icon_url,
            }),
            image: self.image_url.map(|url| EmbedMedia {
                url,
                proxy_url: None,
                height: None,
                width: None,
            }),
            thumbnail: self.thumbnail_url.map(|url| EmbedMedia {
                url,
                proxy_url: None,
                height: None,
                width: None,
            }),
            video: None,
            author: self.author_name.map(|name| EmbedAuthor {
                name,
                url: self.author_url,
                icon_url: self.author_icon_url,
            }),
            fields: if self.fields.is_empty() {
                None
            } else {
                Some(self.fields)
            },
        }
    }
}