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
/// The paste namespace which contains
/// every method and struct to
/// `GET` and `POST` (send) a paste
/// to [pastemyst](https://paste.myst.rs).
/// 
/// ### [API Docs](https://paste.myst.rs/api-docs/index)
#[allow(dead_code, unused_variables)]
pub mod paste {
    use serde::Deserialize;
    use serde::Serialize;

    /// The PasteResult type provided
    /// by this library for ease. It
    /// has a return value and error.
    ///
    /// ## Examples
    /// ```rust
    /// use pastemyst::paste::PasteResult;
    ///
    /// fn main() -> PasteResult<()> {
    ///     Ok(())
    /// }
    /// ```
    pub type PasteResult<T, E = Box<dyn std::error::Error>> = std::result::Result<T, E>;

    const ENDPOINT: &str = "https://paste.myst.rs/";
    const BASE_ENDPOINT: &str = "https://paste.myst.rs/api/v2/";
    /// This endpoint is temporarily here due to a bug in pastemyst
    /// which does not allow the paste to be end when the last
    /// slash is present.
    const SEND_ENDPOINT: &str = "https://paste.myst.rs/api/v2/paste";
    const PASTE_ENDPOINT: &str = "https://paste.myst.rs/api/v2/paste/";

    /// Gets a paste's data in json format
    /// from [pastemyst](https://paste.myst.rs)
    /// synchronously. It returns a `Result`
    /// with a `PasteObject` and error.
    ///
    /// ## Examples
    ///
    /// ```rust
    /// use pastemyst::paste::get_paste;
    /// use pastemyst::paste::PasteResult;
    /// 
    /// fn main() -> PasteResult<()> {
    ///     let foo = get_paste("hipfqanx");
    ///     println!("{:?}", foo.title);
    ///     Ok(())
    /// }
    /// ```
    /// 
    pub fn get_paste(id: &str) -> Result<PasteObject, reqwest::Error> {
        let info: PasteObject = reqwest::blocking::get(&parse_url(id))?.json()?;
        Ok(info)
    }

    /// Gets a paste's data in json format
    /// from [pastemyst](https://paste.myst.rs)
    /// asynchronously. It returns a `Result`
    /// with a `PasteObject` and error.
    /// 
    /// ## Examples
    /// 
    /// ```rust
    /// use pastemyst::paste::get_paste_async;
    /// use pastemyst::paste::PasteResult;
    /// 
    /// #[tokio::main]
    /// async fn main() -> PasteResult<()> {
    ///     let foo = get_paste_async("hipfqanx").await?;
    ///     println!("{:?}", foo._id);
    ///     Ok(())
    /// }
    /// ```
    pub async fn get_paste_async(id: &str) -> Result<PasteObject, reqwest::Error> {
        let info: PasteObject = reqwest::get(&parse_url(id)).await?.json().await?;
        Ok(info)
    }

    /// Gets a private paste's data in json format
    /// from [pastemyst](https://paste.myst.rs)
    /// synchronously. It returns a `Result`
    /// with a `PasteObject` and error.
    /// 
    /// ## Examples
    /// 
    /// ```rust
    /// use pastemyst::paste::get_private_paste;
    /// use pastemyst::paste::PasteResult;
    /// 
    /// fn main() -> PasteResult<()> {
    ///     let foo = get_private_paste("pasteID", "Your PasteMyst Token. Get it from: https://paste.myst.rs/user/settings");
    ///     println!("{:?}", foo._id);
    ///     Ok(())
    /// }
    /// ```
    pub fn get_private_paste(id: &str, auth_token: &str) -> Result<PasteObject, reqwest::Error> {
        let info: PasteObject = reqwest::blocking::Client::builder()
            .build()?
            .get(&parse_url(id))
            .header("Authorization", auth_token)
            .send()?
            .json()?;
        Ok(info)
    }

    /// Gets a private paste's data in json format
    /// from [pastemyst](https://paste.myst.rs)
    /// asynchronously. It returns a `Result`
    /// with a `PasteObject` and error.
    /// 
    /// ## Examples
    /// 
    /// ```rust
    /// use pastemyst::paste::get_private_paste_async;
    /// use pastemyst::paste::PasteResult;
    /// 
    /// #[tokio::main]
    /// async fn main() -> Result<()> {
    ///     let foo = paste::get_private_paste_async("pasteID", "Your PasteMyst Token. Get it from: https://paste.myst.rs/user/settings").await?;
    ///     println!("{}", paste.isPrivate);
    ///     Ok(())
    /// }
    /// ```
    pub async fn get_private_paste_async(
        id: &str,
        auth_token: &str,
    ) -> Result<PasteObject, reqwest::Error> {
        let info: PasteObject = reqwest::Client::builder()
            .build()?
            .get(&parse_url(&id))
            .header("Authorization", auth_token)
            .send()
            .await?
            .json()
            .await?;
        Ok(info)
    }

    /// Uses the `CreateObject` struct as a parameter for paste data
    /// to be contructed and sent to [pastemyst](https://paste.myst.rs).
    /// in a synchronous manner.
    ///
    /// ## Examples
    ///
    /// ```rust
    /// use pastemyst::paste::PastyObject;
    /// use pastemyst::paste::*;
    /// 
    /// fn main() -> PasteResult<()> {
    ///     let pasties: Vec<PastyObject> = vec![
    ///             PastyObject {
    ///             _id: None,
    ///             language: Some(String::from("autodetect")),
    ///             title: Some(String::from("Pasty1")),
    ///             code: Some(String::from("Code")),
    ///         },
    ///         PastyObject {
    ///             _id: None,
    ///             language: Some(String::from("autodetect")),
    ///             title: Some(String::from("Pasty2")),
    ///             code: Some(String::from("Code")),
    ///         },
    ///     ];
    ///     let data: CreateObject = CreateObject {
    ///         title: String::from("This is a title"),
    ///         expiresIn: String::from("1d"),
    ///         isPrivate: false,
    ///         isPublic: false,
    ///         tags: String::from(""),
    ///         pasties: pasties,
    ///     };
    ///     let foo = create_paste(data);
    ///     println!("{:?}", foo._id);
    ///     Ok(())
    /// }
    /// ```
    pub fn create_paste(contents: CreateObject) -> Result<reqwest::blocking::Response, reqwest::Error> {
        let content_type = reqwest::header::HeaderValue::from_static("application/json");
        let result =
            reqwest::blocking::Client::builder()
                .build()?
                .post(SEND_ENDPOINT)
                .header(reqwest::header::CONTENT_TYPE, content_type)
                .body(serde_json::to_string(&contents).unwrap())
                .send().unwrap();
        Ok(result)
    }

    /// Uses the `CreateObject` struct as a parameter for paste
    /// data to be contructed and sent to [pastemyst](https://paste.myst.rs)
    /// in an asynchronous manner.
    ///
    /// ## Examples
    ///
    /// ```rust
    /// use pastemyst::paste::PastyObject;
    /// use pastemyst::paste::*;
    /// 
    /// #[tokio::main]
    /// async fn main() -> PasteResult<()> {
    ///     let pasties: Vec<PastyObject> = vec![
    ///             PastyObject {
    ///             _id: None,
    ///             language: Some(String::from("autodetect")),
    ///             title: Some(String::from("Pasty1")),
    ///             code: Some(String::from("Code")),
    ///         },
    ///         PastyObject {
    ///             _id: None,
    ///             language: Some(String::from("autodetect")),
    ///             title: Some(String::from("Pasty2")),
    ///             code: Some(String::from("Code")),
    ///         },
    ///     ];
    ///     let data: CreateObject = CreateObject {
    ///         title: String::from("This is a title"),
    ///         expiresIn: String::from("1d"),
    ///         isPrivate: false,
    ///         isPublic: false,
    ///         tags: String::from(""),
    ///         pasties: pasties,
    ///     };
    ///     let foo = create_paste(data);
    ///     println!("{:?}", foo.tags);
    ///     Ok(())
    /// }
    /// ```
    pub async fn create_paste_async(contents: CreateObject) -> Result<reqwest::Response, reqwest::Error> {
        let content_type = reqwest::header::HeaderValue::from_static("application/json");
        let result =
            reqwest::Client::builder()
                .build()?
                .post(SEND_ENDPOINT)
                .header(reqwest::header::CONTENT_TYPE, content_type)
                .body(serde_json::to_string(&contents).unwrap())
                .send().await?;
        Ok(result)
    }

    /// Parses the url by combining
    /// the `PASTE_ENDPOINT` with a
    /// provided id.
    fn parse_url(id: &str) -> String { return PASTE_ENDPOINT.to_owned() + &id }

    /// The paste object recieved when
    /// getting a paste. It contains
    /// both the `PastyObject` and
    /// `EditObject` in an array.
    /// 
    /// ### [API Docs](https://paste.myst.rs/api-docs/objects)
    ///
    /// ## Examples
    ///
    /// ```rust
    /// 
    /// ```
    #[derive(Deserialize)]
    #[allow(non_snake_case, dead_code)]
    pub struct PasteObject {
        /// Id of the paste.
        pub _id: String,
        /// Id of the owner, if it doesn't
        ///  have an owner it's set to "".
        pub ownerId: String,
        /// Title of the paste.
        pub title: String,
        /// Unix time of when
        /// the paste is created.
        pub createdAt: u64,
        /// When the paste will expire,
        /// possible values are
        /// `never`, `1h`, `2h`, `10h`,
        /// `1d`, `2d`, `1w`, `1m`, `1y`.
        pub expiresIn: String,
        /// When the paste will be deleted, if
        /// it has no expiry time it's set to 0.
        pub deletesAt: u64,
        /// Number of stars the paste received.
        pub stars: u64,
        /// If it's private it's only
        /// accessible by the owner.
        pub isPrivate: bool,
        /// Is it displayed on the
        /// owner's public profile.
        pub isPublic: bool,
        /// List of tags.
        pub tags: Vec<String>,
        /// List of pasties/files in
        /// the paste, can't be empty.
        pub pasties: Vec<PastyObject>,
        /// List of edits.
        pub edits: Vec<EditObject>,
    }

    /// Information about a specific pasty in a paste.
    /// 
    /// ### [API Docs](https://paste.myst.rs/api-docs/objects)
    ///
    /// ## Examples
    ///
    /// ```rust
    /// let pasty: PastyObject = PastyObject {
    ///     _id: None,
    ///     language: Some(String::from("autodetect")),
    ///     title: Some(String::from("This is a pasty title")),
    ///     code: Some(String::from("{\"This_Is\": \"JSON_Code\"}")),
    /// };
    /// ```
    #[derive(Serialize, Deserialize)]
    #[allow(non_snake_case, dead_code)]
    pub struct PastyObject {
        /// Id of the pasty.
        pub _id: Option<String>,
        /// Language of the pasty.
        pub language: Option<String>,
        /// title of the pasty.
        pub title: Option<String>,
        /// contents of the pasty.
        pub code: Option<String>,
    }

    /// Infomation about edits in a pasty in a paste.
    /// 
    /// ### [API Docs](https://paste.myst.rs/api-docs/objects)
    ///
    /// ## Examples
    ///
    /// ```rust
    /// // Get paste from pastemyst
    /// let edits: EditObject = paste.edits;
    /// ```
    #[derive(Deserialize)]
    #[allow(non_snake_case, dead_code)]
    pub struct EditObject {
        /// Unique id of the edit.
        pub _id: String,
        /// Id of the edit, multiple edits can
        /// share the same id showing that multiple
        /// fields were changed at the same time.
        pub editId: String,
        /// Type of edit, possible values are
        /// title(0), pastyTitle(1), pastyLanguage(2),
        /// pastyContent(3), pastyAdded(4), pastyRemoved(5).
        pub editType: i32,
        /// Various metadata used internally,
        /// biggest usecase is storing exactly which
        /// pasty was edited.
        pub metadata: Vec<String>,
        /// Actual paste edit, it stores old data
        /// before the edit as the current paste
        /// stores the new data
        pub edit: String,
        /// Unix time of when the edit was made
        pub editedAt: i32,
    }

    /// The structure object that holds
    /// the base to create a paste. This
    /// is then sent to pastemyst. All
    /// fields are optional *except* the
    /// `pasties` array which uses `PastyObject`.
    /// 
    /// ### [API Docs](https://paste.myst.rs/api-docs/paste)
    ///
    /// ## Examples
    /// 
    /// ```rust
    /// let _data: CreateObject = CreateObject {
    ///     title: String::from("This is a title"),
    ///     expiresIn: String::from("1d"),
    ///     isPrivate: false,
    ///     isPublic: false,
    ///     tags: String::from(""),
    ///     pasties: var_pasties,
    /// };
    /// ```
    #[derive(Serialize)]
    #[allow(non_snake_case, dead_code)]
    pub struct CreateObject {
        /// Title of the paste.
        pub title: String,
        /// When the paste will expire,
        /// possible values are never, 1h,
        /// 2h, 10h, 1d, 2d, 1w, 1m, 1y.
        pub expiresIn: String,
        /// If it's private it's only
        /// accessible by the owner.
        pub isPrivate: bool,
        /// Is it displayed on the
        /// owner's public profile.
        pub isPublic: bool,
        /// List of tags, comma separated.
        pub tags: String,
        /// List of pasties.
        pub pasties: Vec<PastyObject>,
    }
}