summaryrefslogtreecommitdiffstats
path: root/src/status_builder.rs
blob: e1ce182e0a168b0f4491953f4131af4f58438a4d (plain)
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
use isolang::Language;

/// A builder pattern struct for constructing a status.
///
/// # Example
///
/// ```
/// # extern crate elefren;
/// # use elefren::{Language, StatusBuilder};
///
/// # fn main() -> Result<(), elefren::Error> {
/// let status = StatusBuilder::new()
///     .status("a status")
///     .sensitive(true)
///     .spoiler_text("a CW")
///     .language(Language::Eng)
///     .build()?;
/// # Ok(())
/// # }
/// ```
#[derive(Debug, Default, Clone, PartialEq)]
pub struct StatusBuilder {
    status: Option<String>,
    in_reply_to_id: Option<String>,
    media_ids: Option<Vec<String>>,
    sensitive: Option<bool>,
    spoiler_text: Option<String>,
    visibility: Option<Visibility>,
    language: Option<Language>,
}

impl StatusBuilder {
    /// Create a StatusBuilder object
    ///
    /// # Example
    ///
    /// ```rust,no_run
    /// # use elefren::prelude::*;
    /// # use elefren::status_builder::Visibility;
    /// # fn main() -> Result<(), elefren::Error> {
    /// # let data = Data {
    /// #     base: "".into(),
    /// #     client_id: "".into(),
    /// #     client_secret: "".into(),
    /// #     redirect: "".into(),
    /// #     token: "".into(),
    /// # };
    /// # let client = Mastodon::from(data);
    /// let status = StatusBuilder::new()
    ///     .status("a status")
    ///     .visibility(Visibility::Public)
    ///     .build()?;
    /// client.new_status(status)?;
    /// #   Ok(())
    /// # }
    /// ```
    pub fn new() -> StatusBuilder {
        StatusBuilder::default()
    }

    /// Set the text for the post
    ///
    /// # Example
    ///
    /// ```rust
    /// # use elefren::prelude::*;
    /// # fn main() -> Result<(), elefren::Error> {
    /// let status = StatusBuilder::new().status("awoooooo").build()?;
    /// #   Ok(())
    /// # }
    /// ```
    pub fn status<I: Into<String>>(&mut self, status: I) -> &mut Self {
        self.status = Some(status.into());
        self
    }

    /// Set the in_reply_to_id for the post
    ///
    /// # Example
    ///
    /// ```rust
    /// # use elefren::prelude::*;
    /// # fn main() -> Result<(), elefren::Error> {
    /// let status = StatusBuilder::new()
    ///     .status("awooooo")
    ///     .in_reply_to("12345")
    ///     .build()?;
    /// #   Ok(())
    /// # }
    /// ```
    pub fn in_reply_to<I: Into<String>>(&mut self, id: I) -> &mut Self {
        self.in_reply_to_id = Some(id.into());
        self
    }

    /// Set the media_ids for the post
    ///
    /// # Example
    ///
    /// ```rust
    /// # use elefren::prelude::*;
    /// # fn main() -> Result<(), elefren::Error> {
    /// let status = StatusBuilder::new().media_ids(&["foo", "bar"]).build()?;
    /// #   Ok(())
    /// # }
    /// ```
    pub fn media_ids<S: std::fmt::Display, I: IntoIterator<Item = S>>(
        &mut self,
        ids: I,
    ) -> &mut Self {
        self.media_ids = Some(ids.into_iter().map(|s| s.to_string()).collect::<Vec<_>>());
        self
    }

    /// Set the sensitive attribute for the post
    ///
    /// # Example
    ///
    /// ```rust
    /// # use elefren::prelude::*;
    /// # fn main() -> Result<(), elefren::Error> {
    /// let status = StatusBuilder::new()
    ///     .media_ids(&["foo", "bar"])
    ///     .sensitive(true)
    ///     .build()?;
    /// #   Ok(())
    /// # }
    /// ```
    pub fn sensitive(&mut self, sensitive: bool) -> &mut Self {
        self.sensitive = Some(sensitive);
        self
    }

    /// Set the spoiler text/CW for the post
    ///
    /// # Example
    ///
    /// ```rust
    /// # use elefren::prelude::*;
    /// # fn main() -> Result<(), elefren::Error> {
    /// let status = StatusBuilder::new()
    ///     .status("awoooo!!")
    ///     .spoiler_text("awoo inside")
    ///     .build()?;
    /// #   Ok(())
    /// # }
    /// ```
    pub fn spoiler_text<I: Into<String>>(&mut self, spoiler_text: I) -> &mut Self {
        self.spoiler_text = Some(spoiler_text.into());
        self
    }

    /// Set the visibility for the post
    ///
    /// # Example
    ///
    /// ```rust
    /// # use elefren::prelude::*;
    /// # use elefren::status_builder::Visibility;
    /// # fn main() -> Result<(), elefren::Error> {
    /// let status = StatusBuilder::new()
    ///     .status("awooooooo")
    ///     .visibility(Visibility::Public)
    ///     .build()?;
    /// #   Ok(())
    /// # }
    /// ```
    pub fn visibility(&mut self, visibility: Visibility) -> &mut Self {
        self.visibility = Some(visibility);
        self
    }

    /// Set the language for the post
    ///
    /// # Example
    ///
    /// ```rust
    /// # use elefren::prelude::*;
    /// # use elefren::Language;
    /// # fn main() -> Result<(), elefren::Error> {
    /// let status = StatusBuilder::new()
    ///     .status("awoo!!!!")
    ///     .language(Language::Eng)
    ///     .build()?;
    /// #   Ok(())
    /// # }
    /// ```
    pub fn language(&mut self, language: Language) -> &mut Self {
        self.language = Some(language);
        self
    }

    /// Constructs a NewStatus
    ///
    /// # Example
    ///
    /// ```rust
    /// # use elefren::prelude::*;
    /// # fn main() -> Result<(), elefren::Error> {
    /// let status = StatusBuilder::new().status("awoo!").build()?;
    /// #   Ok(())
    /// # }
    /// ```
    pub fn build(&self) -> Result<NewStatus, crate::Error> {
        if self.status.is_none() && self.media_ids.is_none() {
            return Err(crate::Error::Other(
                "status text or media ids are required in order to post a status".to_string(),
            ));
        }
        Ok(NewStatus {
            status: self.status.clone(),
            in_reply_to_id: self.in_reply_to_id.clone(),
            media_ids: self.media_ids.clone(),
            sensitive: self.sensitive.clone(),
            spoiler_text: self.spoiler_text.clone(),
            visibility: self.visibility.clone(),
            language: self.language.clone(),
        })
    }
}

/// Represents a post that can be sent to the POST /api/v1/status endpoint
#[derive(Debug, Default, Clone, Serialize, PartialEq)]
pub struct NewStatus {
    #[serde(skip_serializing_if = "Option::is_none")]
    status: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    in_reply_to_id: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    media_ids: Option<Vec<String>>,
    #[serde(skip_serializing_if = "Option::is_none")]
    sensitive: Option<bool>,
    #[serde(skip_serializing_if = "Option::is_none")]
    spoiler_text: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    visibility: Option<Visibility>,
    #[serde(skip_serializing_if = "Option::is_none")]
    language: Option<Language>,
}

/// The visibility of a status.
#[derive(Clone, Copy, Debug, Deserialize, Serialize, PartialEq)]
#[serde(rename_all = "lowercase")]
pub enum Visibility {
    /// A Direct message to a user
    Direct,
    /// Only available to followers
    Private,
    /// Not shown in public timelines
    Unlisted,
    /// Posted to public timelines
    Public,
}

impl Default for Visibility {
    fn default() -> Self {
        Visibility::Public
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use isolang::Language;
    use serde_json;

    #[test]
    fn test_new() {
        let s = StatusBuilder::new()
            .status("a status")
            .build()
            .expect("Couldn't build status");
        let expected = NewStatus {
            status: Some("a status".to_string()),
            in_reply_to_id: None,
            media_ids: None,
            sensitive: None,
            spoiler_text: None,
            visibility: None,
            language: None,
        };
        assert_eq!(s, expected);
    }

    #[test]
    fn test_default_visibility() {
        let v: Visibility = Default::default();
        assert_eq!(v, Visibility::Public);
    }

    #[test]
    fn test_serialize_visibility() {
        assert_eq!(
            serde_json::to_string(&Visibility::Direct).expect("couldn't serialize visibility"),
            "\"direct\"".to_string()
        );
        assert_eq!(
            serde_json::to_string(&Visibility::Private).expect("couldn't serialize visibility"),
            "\"private\"".to_string()
        );
        assert_eq!(
            serde_json::to_string(&Visibility::Unlisted).expect("couldn't serialize visibility"),
            "\"unlisted\"".to_string()
        );
        assert_eq!(
            serde_json::to_string(&Visibility::Public).expect("couldn't serialize visibility"),
            "\"public\"".to_string()
        );
    }

    #[test]
    fn test_serialize_status() {
        let status = StatusBuilder::new()
            .status("a status")
            .build()
            .expect("Couldn't build status");
        assert_eq!(
            serde_json::to_string(&status).expect("Couldn't serialize status"),
            "{\"status\":\"a status\"}".to_string()
        );

        let status = StatusBuilder::new()
            .status("a status")
            .language(Language::Eng)
            .build()
            .expect("Couldn't build status");
        assert_eq!(
            serde_json::to_string(&status).expect("Couldn't serialize status"),
            "{\"status\":\"a status\",\"language\":\"eng\"}"
        );
    }
}