Skip to main content

sew_proto/api/
messages.rs

1//! Messages, reactions, references and threads.
2
3use schemars::JsonSchema;
4use serde::{Deserialize, Serialize};
5
6use crate::api::extras::{Poll, PollInput};
7use crate::api::media::{CustomEmojiRef, LinkPreview};
8use crate::error::{Validate, ValidationError};
9use crate::http::Nonce;
10use crate::id::{Id, IdList};
11use crate::limits::{
12    FORWARD_BODY_MAX_BYTES, MESSAGE_BODY_MAX_BYTES, PAGE_LIMIT_DEFAULT, PAGE_LIMIT_MAX,
13};
14use crate::time::Timestamp;
15
16/// Longest Unicode emoji value in bytes.
17pub const EMOJI_VALUE_MAX_BYTES: usize = 64;
18/// Longest custom emoji name in bytes.
19pub const EMOJI_NAME_MAX_BYTES: usize = 64;
20
21/// An emoji on a reaction: Unicode or a custom emoji.
22#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize, JsonSchema)]
23#[serde(tag = "kind", rename_all = "snake_case")]
24pub enum Emoji {
25    /// A Unicode emoji.
26    Unicode {
27        /// The emoji text, for example `👍`.
28        value: String,
29    },
30    /// A custom emoji.
31    Custom {
32        /// The emoji id.
33        id: Id,
34        /// The emoji name, for example `party`.
35        name: String,
36        /// An animated GIF.
37        #[serde(default)]
38        animated: bool,
39        /// Signed image URL; absent when not available.
40        #[serde(default, skip_serializing_if = "Option::is_none")]
41        url: Option<String>,
42        /// `false` once the emoji is deleted. Old payloads read as `true`.
43        #[serde(default = "yes")]
44        available: bool,
45    },
46    /// A kind this build does not know.
47    #[serde(other)]
48    #[schemars(skip)]
49    Unknown,
50}
51
52fn yes() -> bool {
53    true
54}
55
56fn is_false(b: &bool) -> bool {
57    !*b
58}
59
60/// An emoji in a request: Unicode or a custom emoji.
61#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize, JsonSchema)]
62#[serde(tag = "kind", rename_all = "snake_case", deny_unknown_fields)]
63pub enum EmojiInput {
64    /// A Unicode emoji.
65    Unicode {
66        /// The emoji text.
67        value: String,
68    },
69    /// A custom emoji.
70    Custom {
71        /// The emoji id.
72        id: Id,
73        /// The emoji name.
74        name: String,
75    },
76}
77
78impl Validate for EmojiInput {
79    fn validate(&self) -> Result<(), ValidationError> {
80        match self {
81            EmojiInput::Unicode { value } => {
82                if value.is_empty() || value.len() > EMOJI_VALUE_MAX_BYTES {
83                    return Err(ValidationError::invalid(
84                        "value",
85                        format!("value must be 1–{EMOJI_VALUE_MAX_BYTES} bytes"),
86                    ));
87                }
88            }
89            EmojiInput::Custom { name, .. } => {
90                if name.is_empty() || name.len() > EMOJI_NAME_MAX_BYTES {
91                    return Err(ValidationError::invalid(
92                        "name",
93                        format!("name must be 1–{EMOJI_NAME_MAX_BYTES} bytes"),
94                    ));
95                }
96            }
97        }
98        Ok(())
99    }
100}
101
102/// One emoji's reaction count on a message.
103#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
104pub struct ReactionSummary {
105    /// The emoji.
106    pub emoji: Emoji,
107    /// How many members reacted with it.
108    pub count: u32,
109    /// Whether the viewer reacted with it.
110    pub me: bool,
111}
112
113/// Who a message mentions, after expansion rules.
114#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
115pub struct MentionTargets {
116    /// Mentioned members.
117    pub members: Vec<Id>,
118    /// Mentioned roles.
119    pub roles: Vec<Id>,
120    /// Mentioned user groups.
121    pub groups: Vec<Id>,
122    /// `@channel` (or an alias).
123    pub channel: bool,
124    /// `@here`.
125    pub here: bool,
126}
127
128unit_enum! {
129    /// How a message refers to another.
130    #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize, JsonSchema)]
131    pub enum ReferenceKind {
132        /// An inline reply.
133        Reply = "reply",
134        /// A quote.
135        Quote = "quote",
136        /// A forward.
137        Forward = "forward",
138    }
139}
140
141unit_enum! {
142    /// Why a tombstone is one, when it is not the usual delete (`Message.deleted_reason`).
143    #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize, JsonSchema)]
144    pub enum DeletedReason {
145        /// Deleted with its author's account (an account erase). Clients may show "Deleted
146        /// with the account".
147        Erased = "erased",
148    }
149}
150
151/// A message's reference to another message.
152#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
153pub struct MessageReference {
154    /// Reply, quote or forward.
155    pub kind: ReferenceKind,
156    /// The referenced message.
157    pub message_id: Id,
158    /// Its channel.
159    pub channel_id: Id,
160}
161
162/// A file attached to a message.
163///
164/// `id` = the upload id = the attachment id. URLs are signed, path-absolute and valid for
165/// 55–60 minutes (`url_expires_at`); every render inside one 5-minute window gives the same
166/// strings. `width`/`height` are the displayed size (after EXIF orientation) of an image or the
167/// poster frame of a video.
168#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
169#[non_exhaustive]
170pub struct Attachment {
171    /// The attachment id.
172    pub id: Id,
173    /// The file name.
174    pub filename: String,
175    /// The stored (sniffed) MIME type, not the served one.
176    pub content_type: String,
177    /// Size in bytes.
178    pub size: u64,
179    /// Signed download URL.
180    pub url: String,
181    /// Signed thumbnail URL (images, and video posters).
182    #[serde(default, skip_serializing_if = "Option::is_none")]
183    pub thumbnail_url: Option<String>,
184    /// Image or video width in pixels.
185    #[serde(default, skip_serializing_if = "Option::is_none")]
186    pub width: Option<u32>,
187    /// Image or video height in pixels.
188    #[serde(default, skip_serializing_if = "Option::is_none")]
189    pub height: Option<u32>,
190    /// The kind (older payloads without it read as `other`).
191    #[serde(default)]
192    pub kind: crate::api::files::FileKind,
193    /// Served `inline` (only sniffed image, video and audio types).
194    #[serde(default)]
195    pub inline: bool,
196    /// An animated GIF or WebP.
197    #[serde(default)]
198    pub animated: bool,
199    /// A thumbnail or poster is still being made; `attachments_updated` follows.
200    #[serde(default)]
201    pub media_pending: bool,
202    /// Signed large-preview URL (images wider than 1,920 px, BMP, TIFF).
203    #[serde(default, skip_serializing_if = "Option::is_none")]
204    pub preview_url: Option<String>,
205    /// Signed poster-frame URL (videos, when the server has `ffmpeg`).
206    #[serde(default, skip_serializing_if = "Option::is_none")]
207    pub poster_url: Option<String>,
208    /// When the signed URLs stop working (absent in older payloads).
209    #[serde(default, skip_serializing_if = "Option::is_none")]
210    pub url_expires_at: Option<Timestamp>,
211}
212
213impl Attachment {
214    /// An `Attachment` with its required fields: every count 0, every flag `false`, the
215    /// other fields at their serde defaults and every optional field unset.
216    pub fn new(
217        id: Id,
218        filename: impl Into<String>,
219        content_type: impl Into<String>,
220        url: impl Into<String>,
221    ) -> Self {
222        Attachment {
223            id,
224            filename: filename.into(),
225            content_type: content_type.into(),
226            size: 0,
227            url: url.into(),
228            thumbnail_url: None,
229            width: None,
230            height: None,
231            kind: Default::default(),
232            inline: false,
233            animated: false,
234            media_pending: false,
235            preview_url: None,
236            poster_url: None,
237            url_expires_at: None,
238        }
239    }
240}
241
242/// A thread's summary, carried on its root message and in `thread_updated`.
243#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
244pub struct ThreadSummary {
245    // Where the thread is.
246    /// Its channel.
247    pub channel_id: Id,
248    /// The root message.
249    pub root_id: Id,
250    // The viewer's relation to it.
251    /// Whether the viewer follows the thread.
252    pub following: bool,
253    // Its activity.
254    /// When the newest reply was posted.
255    #[serde(default, skip_serializing_if = "Option::is_none")]
256    pub last_reply_at: Option<Timestamp>,
257    /// The newest reply.
258    #[serde(default, skip_serializing_if = "Option::is_none")]
259    pub last_reply_id: Option<Id>,
260    /// Number of replies.
261    pub reply_count: u32,
262    // How current this summary is.
263    /// The channel seq this summary is current as of; set in `thread_updated` events.
264    #[serde(default, skip_serializing_if = "Option::is_none")]
265    pub seq: Option<u64>,
266}
267
268/// The snapshot a forward copies: the origin's text at forward time, sealed under
269/// the target channel's key. Source edits and deletes never change it.
270#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
271pub struct ForwardedMessage {
272    /// The origin message.
273    pub message_id: Id,
274    /// Its channel.
275    pub channel_id: Id,
276    /// Its author.
277    pub author_id: Id,
278    /// Its body at forward time.
279    pub body: String,
280    /// When the origin was posted.
281    pub created_at: Timestamp,
282}
283
284unit_enum! {
285    /// Where an assistant's on-behalf post stands with its person.
286    #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize, JsonSchema)]
287    pub enum OnBehalfApprovalState {
288        /// Not answered yet (every new on-behalf post).
289        Pending = "pending",
290        /// The person approved it.
291        Approved = "approved",
292        /// The person declined it.
293        Declined = "declined",
294    }
295}
296
297/// The approval state of an assistant's on-behalf post. Additive: the post shows at
298/// once whatever the state, and old clients ignore the field.
299#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
300pub struct OnBehalfApproval {
301    /// `pending`, `approved` or `declined`.
302    pub state: OnBehalfApprovalState,
303    /// Who set it (the person in `on_behalf_of`); absent while pending.
304    #[serde(default, skip_serializing_if = "Option::is_none")]
305    pub by: Option<Id>,
306    /// When it was last set; absent while pending.
307    #[serde(default, skip_serializing_if = "Option::is_none")]
308    pub at: Option<Timestamp>,
309}
310
311/// Body of `POST /api/v1/messages/{id}/on-behalf-approval`: the person named in
312/// `on_behalf_of`, from their own session, approves or declines the post. `pending` cannot be
313/// set again.
314#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
315#[serde(deny_unknown_fields)]
316pub struct SetOnBehalfApprovalRequest {
317    /// `approved` or `declined`.
318    pub state: OnBehalfApprovalState,
319}
320
321impl Validate for SetOnBehalfApprovalRequest {
322    fn validate(&self) -> Result<(), ValidationError> {
323        match self.state {
324            OnBehalfApprovalState::Approved | OnBehalfApprovalState::Declined => Ok(()),
325            _ => Err(ValidationError::invalid(
326                "state",
327                "state is approved or declined",
328            )),
329        }
330    }
331}
332
333/// A message.
334#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
335#[non_exhaustive]
336// `transcript_failure` is deprecated; the derives still read and write it.
337#[allow(deprecated)]
338pub struct Message {
339    /// The message id.
340    pub id: Id,
341    /// Its channel.
342    pub channel_id: Id,
343    /// The author.
344    pub author_id: Id,
345    /// For assistant posts, the person the assistant acts for.
346    #[serde(default, skip_serializing_if = "Option::is_none")]
347    pub on_behalf_of: Option<Id>,
348    /// For assistant posts (exactly when `on_behalf_of` is set): whether that person approved
349    /// the post. Never holds the post back; edits keep it.
350    #[serde(default, skip_serializing_if = "Option::is_none")]
351    pub on_behalf_approval: Option<OnBehalfApproval>,
352    /// The body; empty when deleted.
353    pub body: String,
354    /// The sender's nonce, echoed back.
355    #[serde(default, skip_serializing_if = "Option::is_none")]
356    pub nonce: Option<Nonce>,
357    /// The thread root, for replies.
358    #[serde(default, skip_serializing_if = "Option::is_none")]
359    pub thread_root_id: Option<Id>,
360    /// Whether a thread reply was also sent to the channel.
361    pub also_in_channel: bool,
362    /// A reply, quote or forward reference.
363    #[serde(default, skip_serializing_if = "Option::is_none")]
364    pub reference: Option<MessageReference>,
365    /// For a forward: the snapshot of the origin.
366    #[serde(default, skip_serializing_if = "Option::is_none")]
367    pub forwarded: Option<ForwardedMessage>,
368    /// Who the message mentions.
369    pub mentions: MentionTargets,
370    /// Reaction counts.
371    pub reactions: Vec<ReactionSummary>,
372    /// Attachments.
373    pub attachments: Vec<Attachment>,
374    /// Whether it is pinned.
375    pub pinned: bool,
376    /// Thread summary, on thread roots.
377    #[serde(default, skip_serializing_if = "Option::is_none")]
378    pub thread: Option<ThreadSummary>,
379    /// The channel seq this message is current as of.
380    pub seq: u64,
381    /// When it was posted.
382    pub created_at: Timestamp,
383    /// When it was last edited.
384    #[serde(default, skip_serializing_if = "Option::is_none")]
385    pub edited_at: Option<Timestamp>,
386    /// When it was deleted.
387    #[serde(default, skip_serializing_if = "Option::is_none")]
388    pub deleted_at: Option<Timestamp>,
389    /// Why the tombstone is one: `erased` when it went with its author's account; absent for
390    /// every other delete and on live messages.
391    #[serde(default, skip_serializing_if = "Option::is_none")]
392    pub deleted_reason: Option<DeletedReason>,
393    /// Link previews in body order; `[]` on tombstones and until the preview job lands.
394    #[serde(default)]
395    pub previews: Vec<LinkPreview>,
396    /// The author (or a moderator) turned previews off for this message.
397    #[serde(default)]
398    pub previews_suppressed: bool,
399    /// The usable custom emoji of the body, ascending id; `[]` on tombstones.
400    #[serde(default)]
401    pub emojis: Vec<CustomEmojiRef>,
402    /// The poll posted with the message; absent on tombstones.
403    #[serde(default, skip_serializing_if = "Option::is_none")]
404    pub poll: Option<Poll>,
405    /// The message mentions the viewer directly (per viewer; v1 counts direct member
406    /// mentions only). Present only when true.
407    #[serde(default, skip_serializing_if = "std::ops::Not::not")]
408    pub mentions_me: bool,
409    /// The DM call this message records; absent on tombstones and forwards.
410    #[serde(default, skip_serializing_if = "Option::is_none")]
411    pub call: Option<crate::calls::CallSummary>,
412    /// The recording this message records; absent on tombstones and forwards.
413    #[serde(default, skip_serializing_if = "Option::is_none")]
414    pub recording: Option<crate::recording::RecordingSummary>,
415    /// The transcript turn this message is: numbers only, the text is the body;
416    /// absent on tombstones.
417    #[serde(default, skip_serializing_if = "Option::is_none")]
418    pub transcript: Option<crate::recording::TranscriptTurn>,
419    /// What this system message records (a group DM renamed); absent on ordinary messages and
420    /// on tombstones. A system message's `body` is empty, and it cannot be edited.
421    #[serde(default, skip_serializing_if = "Option::is_none")]
422    pub system: Option<MessageKind>,
423    /// Deprecated: moves into `recording.transcript.failure`
424    /// ([`SummaryTranscript::failure`](crate::recording::SummaryTranscript::failure)); kept for
425    /// at least one more release, then removed in a later breaking release. Until then the server
426    /// writes both, with the same value: on a record message (`recording` set) whose transcript
427    /// is `failed` or `partial`, why, as a stable code and plain words for the person
428    /// (`{"code": "transcriber_error", "message": "..."}`). Absent otherwise, when no cause is
429    /// known, and from servers that predate it.
430    #[deprecated(
431        note = "moves into `recording.transcript.failure`; kept for at least one more release, then removed in a later breaking release"
432    )]
433    #[serde(default, skip_serializing_if = "Option::is_none")]
434    pub transcript_failure: Option<crate::recording::TranscriptFailure>,
435}
436
437/// What a system message records (`Message.system`), tagged by `kind`. A client shows a kind
438/// it does not know ([`MessageKind::Unknown`]) as nothing, or as a plain notice.
439#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize, JsonSchema)]
440#[serde(tag = "kind", rename_all = "snake_case")]
441#[non_exhaustive]
442pub enum MessageKind {
443    /// The author renamed the group DM, or cleared its name.
444    GroupDmRenamed {
445        /// The new name; absent when the name was cleared (clients show the members again).
446        #[serde(default, skip_serializing_if = "Option::is_none")]
447        name: Option<String>,
448    },
449    /// A kind this build does not know.
450    #[serde(other)]
451    #[schemars(skip)]
452    Unknown,
453}
454
455/// `details.reason` values of message refusals.
456pub mod reasons {
457    /// `422 invalid_state`: a system message (`Message.system`) cannot be edited.
458    pub const SYSTEM_MESSAGE_IMMUTABLE: &str = "system_message_immutable";
459}
460
461impl Message {
462    /// A message with its required fields: an empty body, no mentions, reactions or
463    /// attachments, not pinned, every optional field unset.
464    #[allow(deprecated)]
465    pub fn new(id: Id, channel_id: Id, author_id: Id, seq: u64, created_at: Timestamp) -> Message {
466        Message {
467            id,
468            channel_id,
469            author_id,
470            on_behalf_of: None,
471            on_behalf_approval: None,
472            body: String::new(),
473            nonce: None,
474            thread_root_id: None,
475            also_in_channel: false,
476            reference: None,
477            forwarded: None,
478            mentions: MentionTargets::default(),
479            reactions: Vec::new(),
480            attachments: Vec::new(),
481            pinned: false,
482            thread: None,
483            seq,
484            created_at,
485            edited_at: None,
486            deleted_at: None,
487            deleted_reason: None,
488            previews: Vec::new(),
489            previews_suppressed: false,
490            emojis: Vec::new(),
491            poll: None,
492            mentions_me: false,
493            call: None,
494            recording: None,
495            transcript: None,
496            system: None,
497            transcript_failure: None,
498        }
499    }
500}
501
502/// Query of `GET /api/v1/channels/{id}/messages` and `GET /api/v1/messages/{root_id}/replies`:
503/// a [`PageQuery`](crate::http::PageQuery) plus an optional long-poll.
504/// With `after` and `wait_ms`, an empty page waits up to `wait_ms` (0–25,000) for a new
505/// message and reads again.
506#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
507#[serde(deny_unknown_fields)]
508pub struct TimelineQuery {
509    /// Items older than this id.
510    #[serde(default, skip_serializing_if = "Option::is_none")]
511    pub before: Option<Id>,
512    /// Items newer than this id.
513    #[serde(default, skip_serializing_if = "Option::is_none")]
514    pub after: Option<Id>,
515    /// Items around this id.
516    #[serde(default, skip_serializing_if = "Option::is_none")]
517    pub around: Option<Id>,
518    /// Page size, 1–100 (default 50).
519    #[serde(default, skip_serializing_if = "Option::is_none")]
520    pub limit: Option<u32>,
521    /// Long-poll: wait up to this long for a message when the `after` page is empty.
522    #[serde(default, skip_serializing_if = "Option::is_none")]
523    pub wait_ms: Option<u32>,
524}
525
526impl TimelineQuery {
527    /// The page part.
528    pub fn page(&self) -> crate::http::PageQuery {
529        crate::http::PageQuery {
530            before: self.before,
531            after: self.after,
532            around: self.around,
533            limit: self.limit,
534        }
535    }
536}
537
538impl From<crate::http::PageQuery> for TimelineQuery {
539    fn from(q: crate::http::PageQuery) -> Self {
540        TimelineQuery {
541            before: q.before,
542            after: q.after,
543            around: q.around,
544            limit: q.limit,
545            wait_ms: None,
546        }
547    }
548}
549
550impl Validate for TimelineQuery {
551    fn validate(&self) -> Result<(), ValidationError> {
552        self.page().validate()?;
553        if let Some(w) = self.wait_ms {
554            if w > crate::limits::MESSAGES_WAIT_MAX_MS {
555                return Err(ValidationError::invalid(
556                    "wait_ms",
557                    format!("wait_ms must be 0–{}", crate::limits::MESSAGES_WAIT_MAX_MS),
558                ));
559            }
560            if self.after.is_none() {
561                return Err(ValidationError::invalid("wait_ms", "wait_ms needs after"));
562            }
563        }
564        Ok(())
565    }
566}
567
568/// One row of a message's edit history.
569#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
570pub struct MessageVersion {
571    /// The revision id (optional on the wire so frozen v1 payloads still parse).
572    #[serde(default, skip_serializing_if = "Option::is_none")]
573    pub id: Option<Id>,
574    /// The message.
575    pub message_id: Id,
576    /// The version this body was: 0 at create, +1 per edit.
577    #[serde(default)]
578    pub version: u32,
579    /// The body of this version.
580    pub body: String,
581    /// When this version was written.
582    pub created_at: Timestamp,
583    /// When the next version replaced it.
584    #[serde(default, skip_serializing_if = "Option::is_none")]
585    pub replaced_at: Option<Timestamp>,
586}
587
588/// A reply or quote reference in a create request.
589#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
590#[serde(deny_unknown_fields)]
591pub struct ReferenceInput {
592    /// The referenced message.
593    pub message_id: Id,
594    /// `reply` or `quote`.
595    pub kind: ReferenceKind,
596}
597
598impl Validate for ReferenceInput {
599    fn validate(&self) -> Result<(), ValidationError> {
600        match self.kind {
601            ReferenceKind::Reply | ReferenceKind::Quote => Ok(()),
602            _ => Err(ValidationError::invalid(
603                "kind",
604                "kind must be reply or quote; forwards use the forward route",
605            )),
606        }
607    }
608}
609
610fn check_body(field: &str, body: &str, max: usize) -> Result<(), ValidationError> {
611    if body.len() > max {
612        return Err(ValidationError::too_large(
613            field,
614            format!("{field} is {} bytes; at most {max}", body.len()),
615        ));
616    }
617    Ok(())
618}
619
620/// Body of `POST /api/v1/channels/{id}/messages`.
621#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
622#[serde(deny_unknown_fields)]
623pub struct CreateMessageRequest {
624    /// The body: 1 byte to 16 KiB of UTF-8. Larger is `413 too_large`.
625    pub body: String,
626    /// A client nonce, 1–64 characters, echoed back.
627    #[serde(default, skip_serializing_if = "Option::is_none")]
628    pub nonce: Option<Nonce>,
629    /// Post as a reply in this thread.
630    #[serde(default, skip_serializing_if = "Option::is_none")]
631    pub thread_root_id: Option<Id>,
632    /// For thread replies, also show it in the channel.
633    #[serde(default)]
634    pub also_send_to_channel: bool,
635    /// Reply to or quote a message.
636    #[serde(default, skip_serializing_if = "Option::is_none")]
637    pub reference: Option<ReferenceInput>,
638    /// Finished uploads of the caller in this channel to attach, 0–10, in display order.
639    /// With at least one, the body may be empty.
640    #[serde(default, skip_serializing_if = "Vec::is_empty")]
641    pub upload_ids: Vec<Id>,
642    /// Build no link previews for this message.
643    #[serde(default, skip_serializing_if = "is_false")]
644    pub suppress_previews: bool,
645    /// Post a poll with the message (needs CREATE_POLLS). The body may then be empty.
646    #[serde(default, skip_serializing_if = "Option::is_none")]
647    pub poll: Option<PollInput>,
648    /// Delete the author's draft for this channel and thread in the same write.
649    #[serde(default, skip_serializing_if = "is_false")]
650    pub clear_draft: bool,
651}
652
653impl Validate for CreateMessageRequest {
654    fn validate(&self) -> Result<(), ValidationError> {
655        // An empty body is the server's `blank_body` unless the post attaches files; the count
656        // and duplicate rules of `upload_ids` carry reasons and run in the server too.
657        check_body("body", &self.body, MESSAGE_BODY_MAX_BYTES)?;
658        if let Some(n) = &self.nonce {
659            n.check("nonce")?;
660        }
661        if let Some(r) = &self.reference {
662            r.validate().map_err(|e| e.nested("reference"))?;
663        }
664        Ok(())
665    }
666}
667
668/// Body of `POST /api/v1/messages/{id}/edit`.
669#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
670#[serde(deny_unknown_fields)]
671pub struct EditMessageRequest {
672    /// The new body (same rules as create).
673    pub body: String,
674}
675
676impl Validate for EditMessageRequest {
677    fn validate(&self) -> Result<(), ValidationError> {
678        // A blank body is the server's `blank_body`, except on a message with live files.
679        check_body("body", &self.body, MESSAGE_BODY_MAX_BYTES)
680    }
681}
682
683/// Body of the forward route: copy a message into another channel or thread.
684#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
685#[serde(deny_unknown_fields)]
686pub struct ForwardMessageRequest {
687    /// The destination channel.
688    pub channel_id: Id,
689    /// The destination thread.
690    #[serde(default, skip_serializing_if = "Option::is_none")]
691    pub thread_root_id: Option<Id>,
692    /// An optional comment, at most 16 KiB.
693    #[serde(default, skip_serializing_if = "Option::is_none")]
694    pub body: Option<String>,
695    /// A client nonce, 1–64 characters, echoed back.
696    #[serde(default, skip_serializing_if = "Option::is_none")]
697    pub nonce: Option<Nonce>,
698    /// Copy the source's files too (default `true`). `false` forwards the text only.
699    #[serde(default = "default_true")]
700    pub attachments: bool,
701    /// Build no link previews for the forward's comment.
702    #[serde(default, skip_serializing_if = "is_false")]
703    pub suppress_previews: bool,
704}
705
706fn default_true() -> bool {
707    true
708}
709
710impl Validate for ForwardMessageRequest {
711    fn validate(&self) -> Result<(), ValidationError> {
712        if let Some(b) = &self.body {
713            check_body("body", b, FORWARD_BODY_MAX_BYTES)?;
714        }
715        if let Some(n) = &self.nonce {
716            n.check("nonce")?;
717        }
718        Ok(())
719    }
720}
721
722/// Body of the add-reaction route.
723#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
724#[serde(deny_unknown_fields)]
725pub struct ReactionRequest {
726    /// The emoji.
727    pub emoji: EmojiInput,
728}
729
730impl Validate for ReactionRequest {
731    fn validate(&self) -> Result<(), ValidationError> {
732        self.emoji.validate().map_err(|e| e.nested("emoji"))
733    }
734}
735
736/// Body of `POST /api/v1/messages/{id}/reactions/remove`. No `member_id`, or the
737/// caller's own id, removes the caller's reaction; another id needs MANAGE_MESSAGES.
738#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
739#[serde(deny_unknown_fields)]
740pub struct RemoveReactionRequest {
741    /// The emoji.
742    pub emoji: EmojiInput,
743    /// Whose reaction; absent = the caller's.
744    #[serde(default, skip_serializing_if = "Option::is_none")]
745    pub member_id: Option<Id>,
746}
747
748impl Validate for RemoveReactionRequest {
749    fn validate(&self) -> Result<(), ValidationError> {
750        self.emoji.validate().map_err(|e| e.nested("emoji"))
751    }
752}
753
754/// Query of `GET /api/v1/messages?ids=`.
755#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
756#[serde(deny_unknown_fields)]
757pub struct MessagesByIdsQuery {
758    /// 1–100 distinct message ids, comma-separated.
759    pub ids: IdList,
760}
761
762impl Validate for MessagesByIdsQuery {
763    fn validate(&self) -> Result<(), ValidationError> {
764        Ok(())
765    }
766}
767
768/// Longest emoji key in a [`ReactorsQuery`] (`u:` + a 64-byte emoji, or `c:` + an id).
769pub const EMOJI_KEY_MAX_BYTES: usize = 2 + EMOJI_VALUE_MAX_BYTES;
770
771/// Query of `GET /api/v1/messages/{id}/reactors`.
772#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
773#[serde(deny_unknown_fields)]
774pub struct ReactorsQuery {
775    /// The emoji in key form: `u:<emoji>` or `c:<custom emoji id>`.
776    pub emoji: String,
777    /// Members after this id (ascending).
778    #[serde(default, skip_serializing_if = "Option::is_none")]
779    pub after: Option<Id>,
780    /// Page size, 1–100 (default 50).
781    #[serde(default, skip_serializing_if = "Option::is_none")]
782    pub limit: Option<u32>,
783}
784
785impl ReactorsQuery {
786    /// The page size.
787    pub fn limit(&self) -> u32 {
788        self.limit.unwrap_or(PAGE_LIMIT_DEFAULT)
789    }
790}
791
792impl Validate for ReactorsQuery {
793    fn validate(&self) -> Result<(), ValidationError> {
794        let shape_ok = match (self.emoji.strip_prefix("u:"), self.emoji.strip_prefix("c:")) {
795            (Some(v), _) => !v.is_empty(),
796            (_, Some(v)) => crate::id::parse_id_str(v).is_some(),
797            _ => false,
798        };
799        if !shape_ok || self.emoji.len() > EMOJI_KEY_MAX_BYTES {
800            return Err(ValidationError::invalid(
801                "emoji",
802                "emoji must be u:<emoji> or c:<custom emoji id>",
803            ));
804        }
805        if let Some(l) = self.limit
806            && !(1..=PAGE_LIMIT_MAX).contains(&l)
807        {
808            return Err(ValidationError::invalid(
809                "limit",
810                format!("limit must be 1–{PAGE_LIMIT_MAX}"),
811            ));
812        }
813        Ok(())
814    }
815}
816
817/// One member who reacted with an emoji.
818#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
819pub struct Reactor {
820    /// The member.
821    pub member_id: Id,
822    /// When they reacted.
823    pub created_at: Timestamp,
824}
825
826/// A page of reactors.
827pub type ReactorPage = crate::http::Page<Reactor>;