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
use std::{collections::HashMap, ops::FnOnce};

use crate::{
    builders::*,
    structs::{response::MyustResponse, *},
    traits::*,
    utils::*,
};

use async_trait::async_trait;
use reqwest::Method;
use serde_json::{json, Value};

/// A client to interact with the API.
///
/// Use this if you're not doing anything users-related endpoints.
#[derive(Default)]
pub struct Client {
    inner: reqwest::Client,
    token: Option<String>,
}

impl Client {
    async fn check_token(client: reqwest::Client, token: String) -> u16 {
        client
            .get(SELF_ENDPOINT)
            .header("Authorization", format!("Bearer {}", token))
            .send()
            .await
            .unwrap()
            .status()
            .as_u16()
    }

    /// Instantiate a new Client.
    pub fn new() -> Self {
        Client {
            inner: reqwest::Client::new(),
            ..Default::default()
        }
    }

    pub async fn auth(mut self, token: impl Into<String>) -> Self {
        let token_str = token.into();
        let code = Self::check_token(self.inner.clone(), token_str.clone()).await;
        match code {
            200 => {
                self.token = Some(format!("Bearer {}", token_str));
                self
            }
            _ => panic!("The provided token is invalid."),
        }
    }

    async fn request(&self, method: &str, url: &str, json: Value) -> MyustResponse {
        let methods = HashMap::from([
            ("GET", Method::GET),
            ("PUT", Method::PUT),
            ("DELETE", Method::DELETE),
        ]);
        let response = if let Some(token) = &self.token {
            self.inner
                .request(methods[method].clone(), url.clone())
                .header("Authorization", token)
                .json(&json)
                .send()
                .await
                .unwrap()
        } else {
            self.inner
                .request(methods[method].clone(), url.clone())
                .json(&json)
                .send()
                .await
                .unwrap()
        };
        let status_code = response.status().as_u16();
        let json_value = response.json::<Value>().await.ok();
        MyustResponse {
            json: json_value,
            status_code,
        }
    }

    /// Create a paste.
    pub async fn create_paste<F>(&self, paste: F) -> Result<PasteResult, MystbinError>
    where
        F: FnOnce(&mut PasteBuilder) -> &mut PasteBuilder,
    {
        let mut builder = PasteBuilder {
            ..Default::default()
        };
        let data = paste(&mut builder);
        let expires = data.expires.as_ref().map(|dt| dt.to_rfc3339());
        let files = vec![File {
            filename: data.filename.to_string(),
            content: data.content.to_string(),
        }];
        let json = json!({
            "files": files,
            "password": data.password,
            "expires": expires
        });
        let response = self.request_create_paste(json).await;

        match response.status_code {
            200 | 201 | 204 => {
                let paste_result = response.json.unwrap();
                Ok(PasteResult {
                    created_at: paste_result["created_at"].as_str().unwrap().to_string(),
                    expires: paste_result["expires"].as_str().map(|d| d.to_string()),
                    files,
                    id: paste_result["id"].as_str().unwrap().to_string(),
                })
            }
            _ => {
                let data = response.json.unwrap();
                Err(MystbinError {
                    code: response.status_code,
                    error: data["error"].as_str().map(|s| s.to_string()),
                    notice: data["notice"].as_str().map(|s| s.to_string()),
                    detail: data["detail"]
                        .as_object()
                        .map(|m| m.clone().into_iter().collect()),
                })
            }
        }
    }

    /// Create a paste with multiple files.
    ///
    /// If you want to provide `expires` and `password`,
    /// put it in the first file.
    pub async fn create_multifile_paste<F>(&self, pastes: F) -> Result<PasteResult, MystbinError>
    where
        F: FnOnce(&mut PastesBuilder) -> &mut PastesBuilder,
    {
        let mut builder = PastesBuilder::default();
        let data = &pastes(&mut builder).files;
        let expires = data[0].expires.as_ref().map(|dt| dt.to_rfc3339());
        let first_paste = &data[0];
        let files = data
            .iter()
            .map(|file| File {
                filename: file.filename.clone(),
                content: file.content.clone(),
            })
            .collect();

        let json = json!({
            "files": files,
            "password": first_paste.password,
            "expires": expires
        });
        let response = self.request_create_paste(json).await;

        match response.status_code {
            200 | 201 | 204 => {
                let paste_result = response.json.unwrap();
                Ok(PasteResult {
                    created_at: paste_result["created_at"].as_str().unwrap().to_string(),
                    expires: paste_result["expires"].as_str().map(|d| d.to_string()),
                    files,
                    id: paste_result["id"].as_str().unwrap().to_string(),
                })
            }
            _ => {
                let data = response.json.unwrap();
                Err(MystbinError {
                    code: response.status_code,
                    error: data["error"].as_str().map(|s| s.to_string()),
                    notice: data["notice"].as_str().map(|s| s.to_string()),
                    detail: data["detail"]
                        .as_object()
                        .map(|m| m.clone().into_iter().collect()),
                })
            }
        }
    }

    /// Get a paste.
    pub async fn get_paste<F>(&self, paste: F) -> Result<PasteResult, MystbinError>
    where
        F: FnOnce(&mut GetPasteBuilder) -> &mut GetPasteBuilder,
    {
        let mut builder = GetPasteBuilder::default();
        let data = paste(&mut builder);
        let response = self
            .request_get_paste(data.id.clone(), data.password.clone())
            .await;
        match response.status_code {
            200 => {
                let paste_result = response.json.unwrap();
                let files = paste_result["files"]
                    .as_array()
                    .unwrap()
                    .iter()
                    .map(|x| File {
                        filename: x.get("filename").unwrap().to_string(),
                        content: x.get("content").unwrap().to_string(),
                    })
                    .collect::<Vec<File>>();
                Ok(PasteResult {
                    created_at: paste_result["created_at"].as_str().unwrap().to_string(),
                    expires: paste_result["expires"].as_str().map(|d| d.to_string()),
                    files,
                    id: data.id.clone(),
                })
            }
            _ => {
                let data = response.json.unwrap();
                Err(MystbinError {
                    code: response.status_code,
                    error: data["error"].as_str().map(|s| s.to_string()),
                    notice: data["notice"].as_str().map(|s| s.to_string()),
                    detail: data["detail"]
                        .as_object()
                        .map(|m| m.clone().into_iter().collect()),
                })
            }
        }
    }

    /// Delete a paste.
    pub async fn delete_paste(&self, paste_id: &str) -> Result<DeleteResult, MystbinError> {
        let response = self.request_delete_paste(paste_id).await;
        match response.status_code {
            200 => Ok(DeleteResult {
                succeeded: Some(vec![paste_id.to_string()]),
                ..Default::default()
            }),
            _ => {
                let data = response.json.unwrap();
                Err(MystbinError {
                    code: response.status_code,
                    error: data["error"].as_str().map(|s| s.to_string()),
                    notice: data["notice"].as_str().map(|s| s.to_string()),
                    detail: data["detail"]
                        .as_object()
                        .map(|m| m.clone().into_iter().collect()),
                })
            }
        }
    }

    /// Delete pastes.
    pub async fn delete_pastes(&self, paste_ids: Vec<&str>) -> Result<DeleteResult, MystbinError> {
        let json = json!({ "pastes": paste_ids });
        let response = self.request_delete_pastes(json).await;
        match response.status_code {
            200 => {
                let data = response.json.unwrap();
                Ok(DeleteResult {
                    succeeded: Some(
                        data["succeeded"]
                            .as_array()
                            .unwrap()
                            .iter()
                            .map(|p| p.to_string())
                            .collect(),
                    ),
                    failed: Some(
                        data["failed"]
                            .as_array()
                            .unwrap()
                            .iter()
                            .map(|p| p.to_string())
                            .collect(),
                    ),
                })
            }
            _ => {
                let data = response.json.unwrap();
                Err(MystbinError {
                    code: response.status_code,
                    error: data["error"].as_str().map(|s| s.to_string()),
                    notice: data["notice"].as_str().map(|s| s.to_string()),
                    detail: data["detail"]
                        .as_object()
                        .map(|m| m.clone().into_iter().collect()),
                })
            }
        }
    }

    /// Get the authenticated user pastes.
    pub async fn get_user_pastes<F>(&self, options: F) -> Result<Vec<UserPaste>, MystbinError>
    where
        F: FnOnce(&mut UserPastesOptions) -> &mut UserPastesOptions,
    {
        let mut builder = UserPastesOptions::default();
        let data = options(&mut builder);
        let json = json!({
            "limit": data.limit,
            "page": data.page
        });
        let response = self.request_get_user_pastes(json).await;
        match response.status_code {
            200 => {
                let results = response.json.unwrap();
                let pastes = results["pastes"]
                    .as_array()
                    .unwrap()
                    .iter()
                    .map(|result| UserPaste {
                        created_at: result["created_at"].as_str().unwrap().to_string(),
                        expires: result["expires"].as_str().map(|d| d.to_string()),
                        id: result["id"].as_str().unwrap().to_string(),
                    })
                    .collect();
                Ok(pastes)
            }
            _ => {
                let data = response.json.unwrap();
                Err(MystbinError {
                    code: response.status_code,
                    error: data["error"].as_str().map(|s| s.to_string()),
                    notice: data["notice"].as_str().map(|s| s.to_string()),
                    detail: data["detail"]
                        .as_object()
                        .map(|m| m.clone().into_iter().collect()),
                })
            }
        }
    }

    /// Add a paste to the authenticated user's bookmark.
    pub async fn create_bookmark(&self, paste_id: &str) -> Result<(), MystbinError> {
        let json = json!({ "paste_id": paste_id });
        let response = self.request_create_bookmark(json).await;
        match response.status_code {
            201 => Ok(()),
            _ => {
                let data = response.json.unwrap();
                Err(MystbinError {
                    code: response.status_code,
                    error: data["error"].as_str().map(|s| s.to_string()),
                    notice: data["notice"].as_str().map(|s| s.to_string()),
                    detail: data["detail"]
                        .as_object()
                        .map(|m| m.clone().into_iter().collect()),
                })
            }
        }
    }

    /// Delete a paste from the authenticated user's bookmark.
    pub async fn delete_bookmark(&self, paste_id: &str) -> Result<(), MystbinError> {
        let json = json!({ "paste_id": paste_id });
        let response = self.request_delete_bookmark(json).await;
        match response.status_code {
            204 => Ok(()),
            _ => {
                let data = response.json.unwrap();
                Err(MystbinError {
                    code: response.status_code,
                    error: data["error"].as_str().map(|s| s.to_string()),
                    notice: data["notice"].as_str().map(|s| s.to_string()),
                    detail: data["detail"]
                        .as_object()
                        .map(|m| m.clone().into_iter().collect()),
                })
            }
        }
    }

    /// Get the authenticated user's bookmarks.
    pub async fn get_user_bookmarks(&self) -> Result<Vec<UserPaste>, MystbinError> {
        let response = self.request_get_user_bookmarks().await;
        match response.status_code {
            200 => {
                let data = response.json.unwrap();
                let bookmarks = data["bookmarks"]
                    .as_array()
                    .unwrap()
                    .iter()
                    .map(|paste| UserPaste {
                        created_at: paste["created_at"].as_str().unwrap().to_string(),
                        expires: paste["expires"].as_str().map(|d| d.to_string()),
                        id: paste["id"].as_str().unwrap().to_string(),
                    })
                    .collect();
                Ok(bookmarks)
            }
            _ => {
                let data = response.json.unwrap();
                Err(MystbinError {
                    code: response.status_code,
                    error: data["error"].as_str().map(|s| s.to_string()),
                    notice: data["notice"].as_str().map(|s| s.to_string()),
                    detail: data["detail"]
                        .as_object()
                        .map(|m| m.clone().into_iter().collect()),
                })
            }
        }
    }
}

#[async_trait]
impl ClientPaste for Client {
    async fn request_create_paste(&self, json: Value) -> MyustResponse {
        self.request("PUT", PASTE_ENDPOINT, json).await
    }

    async fn request_delete_paste(&self, paste_id: &str) -> MyustResponse {
        self.request(
            "DELETE",
            &format!("{}/{}", PASTE_ENDPOINT, paste_id),
            json!({}),
        )
        .await
    }

    async fn request_delete_pastes(&self, json: Value) -> MyustResponse {
        self.request("DELETE", PASTE_ENDPOINT, json).await
    }

    async fn request_get_paste(&self, paste_id: String, password: Option<String>) -> MyustResponse {
        let url = if password.is_some() {
            format!(
                "{}/{}?password={}",
                PASTE_ENDPOINT,
                paste_id,
                password.unwrap()
            )
        } else {
            format!("{}/{}", PASTE_ENDPOINT, paste_id)
        };
        self.request("GET", &url, json!({})).await
    }

    async fn request_get_user_pastes(&self, json: Value) -> MyustResponse {
        self.request("GET", USER_PASTES_ENDPOINT, json).await
    }
}

#[async_trait]
impl ClientBookmark for Client {
    async fn request_create_bookmark(&self, json: Value) -> MyustResponse {
        self.request("PUT", BOOKMARK_ENDPOINT, json).await
    }

    async fn request_delete_bookmark(&self, json: Value) -> MyustResponse {
        self.request("DELETE", BOOKMARK_ENDPOINT, json).await
    }

    async fn request_get_user_bookmarks(&self) -> MyustResponse {
        self.request("GET", BOOKMARK_ENDPOINT, json!({})).await
    }
}