Skip to main content

twilight_model/http/
message_search.rs

1//! Data types for performing a message search.
2
3use serde::{Deserialize, Serialize};
4use std::fmt::{Display, Error as FmtError, Formatter};
5
6mod sealed {
7    use super::{AuthorType, SearchHasType};
8
9    pub trait Sealed {}
10
11    impl Sealed for AuthorType {}
12    impl Sealed for SearchHasType {}
13}
14
15/// Denotes whether a field value can be negated, excluding results with the
16/// field instead of including results.
17// # Development implementation note
18//
19// When implementing this trait for a new type be sure to make a note on the
20// relevant HTTP request builder method that the value can be negated.
21pub trait Negate: Display + sealed::Sealed {}
22
23impl Negate for AuthorType {}
24
25impl Negate for SearchHasType {}
26
27/// Mark whether a field is being marked for inclusion or exclusion.
28#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)]
29pub enum SearchFilter<T: Negate> {
30    /// Results must include this value.
31    Include(T),
32    /// Results must exclude this value.
33    Exclude(T),
34}
35
36impl<T: Negate> Display for SearchFilter<T> {
37    fn fmt(&self, f: &mut Formatter<'_>) -> Result<(), FmtError> {
38        match self {
39            SearchFilter::Include(value) => Display::fmt(value, f),
40            SearchFilter::Exclude(value) => {
41                f.write_str("-")?;
42
43                Display::fmt(value, f)
44            }
45        }
46    }
47}
48
49/// Filter messages by the type of author.
50///
51/// All types can be negated, which means results will not include messages that
52/// match the type.
53#[derive(Clone, Copy, Debug, Deserialize, Eq, Hash, PartialEq, Serialize)]
54#[serde(rename_all = "snake_case")]
55pub enum AuthorType {
56    /// Return messages sent by bot accounts.
57    Bot,
58    /// Return messages sent by user accounts.
59    User,
60    /// Return messages sent by webhooks.
61    Webhook,
62}
63
64impl Display for AuthorType {
65    fn fmt(&self, f: &mut Formatter<'_>) -> Result<(), FmtError> {
66        match self {
67            Self::Bot => f.write_str("bot"),
68            Self::User => f.write_str("user"),
69            Self::Webhook => f.write_str("webhook"),
70        }
71    }
72}
73
74/// Filter messages by whether they have a particular type of data.
75///
76/// All types can be negated, which means results will not include messages that
77/// match the type.
78#[derive(Clone, Copy, Debug, Deserialize, Eq, Hash, PartialEq, Serialize)]
79#[serde(rename_all = "snake_case")]
80pub enum SearchHasType {
81    /// Return messages that have an embed.
82    Embed,
83    /// Return messages that have an attachment.
84    File,
85    /// Return messages that have an image.
86    Image,
87    /// Return messages that have a link.
88    Link,
89    /// Return messages that have a poll.
90    Poll,
91    /// Return messages that have a forwarded message.
92    Snapshot,
93    /// Return messages that have a sound attachment.
94    Sound,
95    /// Return messages that have a sent sticker.
96    Sticker,
97    /// Return messages that have a video.
98    Video,
99}
100
101impl Display for SearchHasType {
102    fn fmt(&self, f: &mut Formatter<'_>) -> Result<(), FmtError> {
103        match self {
104            Self::Embed => f.write_str("embed"),
105            Self::File => f.write_str("file"),
106            Self::Image => f.write_str("image"),
107            Self::Link => f.write_str("link"),
108            Self::Poll => f.write_str("poll"),
109            Self::Snapshot => f.write_str("snapshot"),
110            Self::Sound => f.write_str("sound"),
111            Self::Sticker => f.write_str("sticker"),
112            Self::Video => f.write_str("video"),
113        }
114    }
115}
116
117/// Embed types to filter results by.
118///
119/// These do not correspond 1:1 to actual embed types and encompass a wider
120/// range of actual types.
121#[derive(Clone, Copy, Debug, Deserialize, Eq, Hash, PartialEq, Serialize)]
122#[serde(rename_all = "snake_case")]
123pub enum SearchEmbedType {
124    /// Return messages that have an article embed.
125    Article,
126    /// Return messages that have a gifv embed.
127    ///
128    /// Messages sent before February 24, 2026 may not be properly indexed under
129    /// the gif embed type.
130    Gif,
131    /// Return messages that have an image embed.
132    Image,
133    /// Return messages that have a sound embed.
134    Sound,
135    /// Return messages that have a video embed.
136    Video,
137}
138
139impl Display for SearchEmbedType {
140    fn fmt(&self, f: &mut Formatter<'_>) -> Result<(), FmtError> {
141        match self {
142            Self::Article => f.write_str("article"),
143            Self::Gif => f.write_str("gif"),
144            Self::Image => f.write_str("image"),
145            Self::Sound => f.write_str("sound"),
146            Self::Video => f.write_str("video"),
147        }
148    }
149}
150
151/// Sorting algorithm to use.
152#[derive(Clone, Copy, Debug, Deserialize, Eq, Hash, PartialEq, Serialize)]
153#[serde(rename_all = "snake_case")]
154pub enum SearchSortMode {
155    /// Sort by the relevance of the message to the search query.
156    Relevance,
157    /// Sort by the message creation time.
158    ///
159    /// This is the default sort mode Discord uses.
160    Timestamp,
161}
162
163impl Display for SearchSortMode {
164    fn fmt(&self, f: &mut Formatter<'_>) -> Result<(), FmtError> {
165        match self {
166            Self::Relevance => f.write_str("relevance"),
167            Self::Timestamp => f.write_str("timestamp"),
168        }
169    }
170}
171
172/// Sorting order to use.
173#[derive(Clone, Copy, Debug, Deserialize, Eq, Hash, PartialEq, Serialize)]
174pub enum SearchSortOrder {
175    /// Results will be in ascending order.
176    #[serde(rename = "asc")]
177    Ascending,
178    /// Results will be in descending order.
179    #[serde(rename = "desc")]
180    Descending,
181}
182
183impl Display for SearchSortOrder {
184    fn fmt(&self, f: &mut Formatter<'_>) -> Result<(), FmtError> {
185        match self {
186            Self::Ascending => f.write_str("asc"),
187            Self::Descending => f.write_str("desc"),
188        }
189    }
190}
191
192#[cfg(test)]
193mod tests {
194    use super::{
195        AuthorType, Negate, SearchEmbedType, SearchFilter, SearchHasType, SearchSortMode,
196        SearchSortOrder,
197    };
198    use serde::{Deserialize, Serialize};
199    use static_assertions::assert_impl_all;
200    use std::{fmt::Debug, hash::Hash};
201
202    assert_impl_all!(AuthorType: Clone, Copy, Debug, Deserialize<'static>, Eq, Hash, Negate, PartialEq, Send, Serialize, Sync);
203    assert_impl_all!(SearchEmbedType: Clone, Copy, Debug, Deserialize<'static>, Eq, Hash, PartialEq, Send, Serialize, Sync);
204    assert_impl_all!(SearchHasType: Clone, Copy, Debug, Deserialize<'static>, Eq, Hash, Negate, PartialEq, Send, Serialize, Sync);
205    assert_impl_all!(SearchSortMode: Clone, Copy, Debug, Deserialize<'static>, Eq, Hash, PartialEq, Send, Serialize, Sync);
206    assert_impl_all!(SearchSortOrder: Clone, Copy, Debug, Deserialize<'static>, Eq, Hash, PartialEq, Send, Serialize, Sync);
207
208    #[test]
209    fn filter_display() {
210        assert_eq!(
211            "file",
212            SearchFilter::Include(SearchHasType::File).to_string()
213        );
214        assert_eq!(
215            "-file",
216            SearchFilter::Exclude(SearchHasType::File).to_string()
217        );
218    }
219
220    #[test]
221    fn author_type_display() {
222        assert_eq!("bot", AuthorType::Bot.to_string());
223        assert_eq!("user", AuthorType::User.to_string());
224        assert_eq!("webhook", AuthorType::Webhook.to_string());
225    }
226
227    #[test]
228    fn search_has_types_display() {
229        assert_eq!("embed", SearchHasType::Embed.to_string());
230        assert_eq!("file", SearchHasType::File.to_string());
231        assert_eq!("image", SearchHasType::Image.to_string());
232        assert_eq!("link", SearchHasType::Link.to_string());
233        assert_eq!("poll", SearchHasType::Poll.to_string());
234        assert_eq!("snapshot", SearchHasType::Snapshot.to_string());
235        assert_eq!("sound", SearchHasType::Sound.to_string());
236        assert_eq!("sticker", SearchHasType::Sticker.to_string());
237        assert_eq!("video", SearchHasType::Video.to_string());
238    }
239
240    #[test]
241    fn search_embed_types_display() {
242        assert_eq!("article", SearchEmbedType::Article.to_string());
243        assert_eq!("gif", SearchEmbedType::Gif.to_string());
244        assert_eq!("image", SearchEmbedType::Image.to_string());
245        assert_eq!("sound", SearchEmbedType::Sound.to_string());
246        assert_eq!("video", SearchEmbedType::Video.to_string());
247    }
248
249    #[test]
250    fn search_sort_modes_display() {
251        assert_eq!("relevance", SearchSortMode::Relevance.to_string());
252        assert_eq!("timestamp", SearchSortMode::Timestamp.to_string());
253    }
254
255    #[test]
256    fn search_sort_order_display() {
257        assert_eq!("asc", SearchSortOrder::Ascending.to_string());
258        assert_eq!("desc", SearchSortOrder::Descending.to_string());
259    }
260}