waifuvault 0.1.4

SDK for interacting with the Waifu Vault API
Documentation
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
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
//! This is the Rust version of the [Waifu Vault SDK](https://waifuvault.moe/) which is used to
//! interact with the file upload service.
//!
//! For Terms of Service and usage policy, please refer to the above website.
//!
//! # Uploading a file
//!
//! ```rust,no_run
//! use waifuvault::{
//!     ApiCaller,
//!     api::{WaifuUploadRequest, WaifuResponse}
//! };
//!
//! #[tokio::main]
//! async fn main() -> anyhow::Result<()> {
//!     let caller = ApiCaller::new();
//!
//!     // Upload a file from disk
//!     let request = WaifuUploadRequest::new()
//!         .file("/some/file/path") // Path to a file
//!         .password("set a password") // Set a password
//!         .one_time_download(true); // Delete after first access
//!     let response = caller.upload_file(request).await?;
//!
//!     // Upload a file from a URL
//!     let request = WaifuUploadRequest::new()
//!         .url("https://some-website/image.jpg"); // URL to content
//!     let response = caller.upload_file(request).await?;
//!
//!     // Upload a file from raw bytes
//!     let data = std::fs::read("some/file/path")?;
//!     let request = WaifuUploadRequest::new()
//!         .bytes(data, "name-to-store.rs"); // Raw file content and name to store on the vault
//!     let response = caller.upload_file(request).await?;
//!
//!     Ok(())
//! }
//! ```
//!
//! # Get File Information
//!
//! ```rust,no_run
//! use waifuvault::{
//!     ApiCaller,
//!     api::WaifuGetRequest
//! };
//!
//! #[tokio::main]
//! async fn main() -> anyhow::Result<()> {
//!     let caller = ApiCaller::new();
//!
//!     let request = WaifuGetRequest::new("some-waifu-vault-token");
//!     let response = caller.file_info(request).await?;
//!
//!     // Do something with the response
//!
//!     Ok(())
//! }
//! ```
//!
//! # Modify Existing File Properties
//!
//! ```rust,no_run
//! use waifuvault::{
//!     ApiCaller,
//!     api::WaifuModificationRequest
//! };
//!
//! #[tokio::main]
//! async fn main() -> anyhow::Result<()> {
//!     let caller = ApiCaller::new();
//!
//!     let request = WaifuModificationRequest::new("some-waifu-vault-token")
//!         .password("new_password") // Set a new password
//!         .previous_password("old_password") // Old password
//!         .custom_expiry("1h") // Set a new expiry
//!         .hide_filename(true); // Hide the filename
//!
//!     let response = caller.update_file(request).await?;
//!
//!     // Do something with the response
//!
//!     Ok(())
//! }
//! ```
//!
//! # Delete a file from Waifu Vault
//!
//! ```rust,no_run
//! use waifuvault::ApiCaller;
//!
//! #[tokio::main]
//! async fn main() -> anyhow::Result<()> {
//!     let caller = ApiCaller::new();
//!     let response = caller.delete_file("some-waifu-token").await?;
//!
//!     Ok(())
//! }
//! ```
//!
//! # Download a file
//!
//! ```rust,no_run
//! use waifuvault::ApiCaller;
//! use std::io::Write;
//!
//! #[tokio::main]
//! async fn main() -> anyhow::Result<()> {
//!     let caller = ApiCaller::new();
//!
//!     // Download a file with no password
//!     let content = caller.download_file("https://waifuvault.moe/f/some-file.ext", None).await?;
//!     let mut f = std::fs::File::create("downloaded_file.txt")?;
//!     f.write_all(&content)?;
//!
//!     // Download a file with no password
//!     let content = caller.download_file("https://waifuvault.moe/f/some-other-file.ext", Some("password".to_string())).await?;
//!     let mut f = std::fs::File::create("downloaded_file2.txt")?;
//!     f.write_all(&content)?;
//!
//!     Ok(())
//! }
//! ```
pub mod api;

use std::path::PathBuf;

use api::*;

use anyhow::Context;
use reqwest::Client;

/// REST endpoint for the service
const API: &str = "https://waifuvault.moe/rest";

/// Api controller which calls the endpoint
#[derive(Debug, Clone, Default)]
pub struct ApiCaller {
    client: Client,
}

impl ApiCaller {
    /// Create a new Waifu Vault API Caller
    pub fn new() -> Self {
        Self::default()
    }

    /// Upload a file to Waifu Vault
    ///
    /// Takes an [`api::WaifuUploadRequest`] which details the content to upload and any
    /// necessary options.
    ///
    /// # Example
    ///
    /// ```rust,no_run
    /// use waifuvault::{
    ///     ApiCaller,
    ///     api::{WaifuUploadRequest, WaifuResponse}
    /// };
    /// #[tokio::main]
    /// async fn main() -> anyhow::Result<()> {
    ///     let caller = ApiCaller::new();
    ///     let request = WaifuUploadRequest::new()
    ///         .file("/some/file/to/upload")
    ///         .password("supersecurepassword")
    ///         .expires("1h");
    ///
    ///     let response = caller.upload_file(request).await?;
    ///     // Do something with response
    ///     Ok(())
    /// }
    /// ```
    pub async fn upload_file(&self, request: WaifuUploadRequest) -> anyhow::Result<WaifuResponse> {
        let request = {
            let mut intermediate = self.client.put(API).query(&[
                ("hide_filename", request.one_time_download),
                ("one_time_download", request.one_time_download),
            ]);

            if let Some(expiry) = request.expires {
                intermediate = intermediate.query(&[("expires", expiry)]);
            }

            if let Some(file) = request.file {
                let path = PathBuf::from(&file);
                let f = std::fs::read(&path)
                    .with_context(|| format!("reading file {}", path.display()))?;

                let filename = path.file_name().expect("this should be a valid filename");
                let filename = filename
                    .to_str()
                    .expect("this should be a valid convertion from os string");

                let file_part = reqwest::multipart::Part::bytes(f).file_name(filename.to_owned());
                let mut form = reqwest::multipart::Form::new().part("file", file_part);

                if let Some(password) = request.password {
                    form = form.text("password", password);
                }

                println!("Form data: {form:?}");

                intermediate = intermediate.multipart(form);
            } else if let Some(url) = request.url {
                intermediate = match request.password {
                    Some(password) => intermediate.form(&[("url", url), ("password", password)]),
                    None => intermediate.form(&[("url", url)]),
                };
            } else if let (Some(raw), Some(filename)) = (request.bytes, request.filename) {
                let file_part = reqwest::multipart::Part::bytes(raw).file_name(filename);
                let mut form = reqwest::multipart::Form::new().part("file", file_part);

                if let Some(password) = request.password {
                    form = form.text("password", password);
                }

                println!("Form data: {form:?}");
                intermediate = intermediate.multipart(form);
            } else {
                anyhow::bail!("need either a file, url, or stream");
            }

            intermediate
        };

        // println!("Request: {request:?}");
        let response = request
            .send()
            .await
            .context("sending upload request")?
            .json()
            .await
            .context("converting upload response")?;

        let response = parse_response(response).context("parsing waifu api response")?;

        Ok(response)
    }

    /// Retrieves information about a file stored in Waifu Vault
    ///
    /// # Example
    ///
    /// ```rust,no_run
    /// use waifuvault::{
    ///     ApiCaller,
    ///     api::{WaifuGetRequest, WaifuResponse}
    /// };
    ///
    /// #[tokio::main]
    /// async fn main() -> anyhow::Result<()> {
    ///     let token = "some-file-token-for-waifu-vault";
    ///     let caller = ApiCaller::new();
    ///     let request = WaifuGetRequest::new(token)
    ///         .formatted(true);
    ///
    ///     let response = caller.file_info(request).await?;
    ///     // Do something with response
    ///
    ///     Ok(())
    /// }
    /// ```
    pub async fn file_info(&self, request: WaifuGetRequest) -> anyhow::Result<WaifuResponse> {
        let url = format!("{API}/{}", request.token);
        let request = self
            .client
            .get(url)
            .query(&[("formatted", request.formatted)]);

        let response: WaifuApiResponse = request
            .send()
            .await
            .context("sending file info request")?
            .json()
            .await
            .context("converting response")?;

        let response = parse_response(response).context("parsing waifu api response")?;

        Ok(response)
    }

    /// Updates options on a stored file in Waifu Vault
    ///
    /// Allows the changing of the password, expiry time, and whether to hide the filename or not
    ///
    /// # Example
    ///
    /// ```rust,no_run
    /// use waifuvault::{
    ///     ApiCaller,
    ///     api::{WaifuModificationRequest, WaifuResponse}
    /// };
    ///
    /// #[tokio::main]
    /// async fn main() -> anyhow::Result<()> {
    ///     let token = "some-token";
    ///     let caller = ApiCaller::new();
    ///     let request = WaifuModificationRequest::new(token)
    ///         .password("banana")
    ///         .previous_password("apple")
    ///         .hide_filename(true);
    ///     let response = caller.update_file(request).await?;
    ///     // Do something with the response
    ///
    ///     Ok(())
    /// }
    /// ```
    pub async fn update_file(
        &self,
        request: WaifuModificationRequest,
    ) -> anyhow::Result<WaifuResponse> {
        let url = format!("{API}/{}", request.token);
        let response: WaifuApiResponse = self
            .client
            .patch(url)
            .header("Content-Type", "application/json")
            .json(&request)
            .send()
            .await
            .context("sending modification request")?
            .json()
            .await
            .context("converting response")?;

        let response = parse_response(response).context("parsing waifu api response")?;
        Ok(response)
    }

    /// Deletes a file from Waifu Vault
    ///
    /// # Example
    ///
    /// ```rust,no_run
    /// use waifuvault::ApiCaller;
    ///
    /// #[tokio::main]
    /// async fn main() -> anyhow::Result<()> {
    ///     let token = "token-to-delete";
    ///     let caller = ApiCaller::new();
    ///     let response = caller.delete_file(token).await?;
    ///     Ok(())
    /// }
    /// ```
    pub async fn delete_file(&self, token: impl AsRef<str>) -> anyhow::Result<bool> {
        let url = format!("{API}/{}", token.as_ref());
        let response: WaifuApiResponse = self
            .client
            .delete(url)
            .send()
            .await
            .context("sending delete request")?
            .json()
            .await
            .context("converting response")?;

        match response {
            WaifuApiResponse::Delete(del) => Ok(del),
            WaifuApiResponse::WaifuError(err) => Err(err.into()),
            _ => anyhow::bail!("received unexpected response from DELETE call"),
        }
    }

    /// Downloads a file from Waifu Vault
    ///
    /// Returns the contents of the file as an array of bytes
    ///
    /// # Example
    ///
    /// ```rust,no_run
    /// use waifuvault::ApiCaller;
    /// use std::io::Write;
    ///
    /// #[tokio::main]
    /// async fn main() -> anyhow::Result<()> {
    ///     let url = "https://waifuvault.moe/f/[some-id]/file.jpg";
    ///     let caller = ApiCaller::new();
    ///     let file_bytes = caller.download_file(url, Some("securepassword".to_string())).await?;
    ///     let mut f = std::fs::File::create("downloaded.jpg")?;
    ///     f.write_all(&file_bytes)?;
    ///
    ///     Ok(())
    /// }
    /// ```
    pub async fn download_file(
        &self,
        url: impl AsRef<str>,
        password: Option<String>,
    ) -> anyhow::Result<Vec<u8>> {
        let request = {
            let mut r = self.client.get(url.as_ref());
            if let Some(password) = &password {
                r = r.header("x-password", password);
            }

            r
        };

        let response = request.send().await.context("sending download request")?;
        let status = response.status();

        match status {
            reqwest::StatusCode::OK => {}
            reqwest::StatusCode::FORBIDDEN => {
                if password.is_some() {
                    anyhow::bail!("supplied password is incorrect");
                } else {
                    anyhow::bail!("this file requires a password to download");
                }
            }
            _ => {
                let api_response: WaifuApiResponse =
                    response.json().await.context("converting error")?;
                match api_response {
                    WaifuApiResponse::WaifuError(err) => return Err(err.into()),
                    _ => anyhow::bail!("something went wrong"),
                }
            }
        }

        let content = response
            .bytes()
            .await
            .context("getting content bytes")?
            .to_vec();

        Ok(content)
    }
}

/// Parses the response from the Waifu Vault API and converts it to
/// a concrete type
pub(crate) fn parse_response(response: WaifuApiResponse) -> anyhow::Result<WaifuResponse> {
    match response {
        WaifuApiResponse::WaifuResponse(resp) => Ok(resp),
        WaifuApiResponse::WaifuError(err) => Err(anyhow::anyhow!(err)),
        WaifuApiResponse::Delete(_) => unreachable!("unused"),
    }
}

#[cfg(test)]
mod tests {
    // These tests run against the actual API endpoint because i dont know how to mock these calls
    // Each test has a `be_nice()` call which adds a small delay for requests
    // Until mocking is easier, test liberally
    use super::*;
    use anyhow::Result;
    use rand::RngCore;
    use sha1::{Digest, Sha1};
    use std::path::PathBuf;
    use tokio::{fs, io::AsyncWriteExt};

    // I know I could use `tempfile` here but scope issues made it awkward
    // at least with this i can control when to delete the temp file
    struct TempFileCreator {
        file: PathBuf,
    }

    impl TempFileCreator {
        pub async fn new(filename: &str) -> Result<Self> {
            let tmp = std::env::temp_dir();

            let mut data = Vec::with_capacity(16_384);
            rand::thread_rng().fill_bytes(&mut data);

            let test_file = tmp.join(filename);
            let mut f = tokio::fs::File::create(&test_file).await?;
            f.write_all(&mut data).await?;

            return Ok(Self { file: test_file });
        }
    }

    impl Drop for TempFileCreator {
        fn drop(&mut self) {
            let _ = std::fs::remove_file(&self.file);
        }
    }

    async fn cleanup(caller: &ApiCaller, token: &str) -> Result<()> {
        caller.delete_file(token).await?;

        Ok(())
    }

    #[tokio::test]
    async fn upload_file() -> Result<()> {
        let tmp = TempFileCreator::new("upload_basic.bin").await?;
        assert!(tmp.file.exists());
        let caller = ApiCaller::new();
        let upload_request = api::WaifuUploadRequest::new().file(&tmp.file);

        let response = caller
            .upload_file(upload_request)
            .await
            .context("upload file - basic");

        assert!(response.is_ok());

        let response = response?;
        let options = response
            .options
            .expect("expected options when there are none");

        assert!(!options.hide_filename);
        assert!(!options.protected);
        assert!(!options.one_time_download);

        cleanup(&caller, &response.token).await?;
        be_nice().await;

        Ok(())
    }

    #[tokio::test]
    async fn upload_file_with_options() -> Result<()> {
        let tmp = TempFileCreator::new("upload_with_options.bin").await?;
        let caller = ApiCaller::new();
        let upload_request = api::WaifuUploadRequest::new()
            .file(&tmp.file)
            .expires("1h")
            .password("apple")
            .one_time_download(true)
            .hide_filename(true);

        let response = caller
            .upload_file(upload_request)
            .await
            .context("upload file with options")?;
        let options = response
            .options
            .expect("expected options when there are none");

        assert!(options.hide_filename);
        assert!(options.protected);
        assert!(options.one_time_download);

        cleanup(&caller, &response.token).await?;
        be_nice().await;

        Ok(())
    }

    #[tokio::test]
    async fn upload_file_from_url() -> Result<()> {
        let url = "https://waifuvault.moe/assets/custom/images/08.png";
        let caller = ApiCaller::new();
        let request = WaifuUploadRequest::new().url(url).expires("1h");

        let response = caller
            .upload_file(request)
            .await
            .context("upload from url")?;
        let options = response
            .options
            .expect("expected options when there are none");

        assert!(!options.hide_filename);
        assert!(!options.protected);
        assert!(!options.one_time_download);

        cleanup(&caller, &response.token).await?;
        be_nice().await;

        Ok(())
    }

    #[tokio::test]
    async fn upload_file_bytes() -> Result<()> {
        let tmp = TempFileCreator::new("upload_from_raw_bytes.bin").await?;
        let caller = ApiCaller::new();
        let content = fs::read(&tmp.file).await?;
        let request = WaifuUploadRequest::new()
            .bytes(content, "test_raw_bytes.bin")
            .expires("1h");

        let response = caller.upload_file(request).await?;
        cleanup(&caller, &response.token).await?;
        be_nice().await;

        Ok(())
    }

    #[tokio::test]
    async fn get_file_info() -> Result<()> {
        let tmp = TempFileCreator::new("get_file_info_basic.bin").await?;
        let caller = ApiCaller::new();
        let upload = WaifuUploadRequest::new().file(&tmp.file);
        let response = caller.upload_file(upload).await?;

        let token = response.token;
        let options = response
            .options
            .expect("options expected but there are none");
        let get_req = WaifuGetRequest::new(&token);
        let response = caller.file_info(get_req).await?;

        assert_eq!(&token, &response.token);
        assert_eq!(
            &options,
            &response
                .options
                .expect("expected options but there are none")
        );
        cleanup(&caller, &response.token).await?;
        be_nice().await;

        Ok(())
    }

    #[tokio::test]
    async fn invalid_token() -> Result<()> {
        let caller = ApiCaller::new();
        let request = WaifuGetRequest::new("hithere");
        let response = caller.file_info(request).await;
        assert!(response.is_err());
        be_nice().await;

        Ok(())
    }

    #[tokio::test]
    async fn patch_entry() -> Result<()> {
        let tmp = TempFileCreator::new("some_entry_to_be_patched.bin").await?;
        let caller = ApiCaller::new();

        let init = WaifuUploadRequest::new().file(&tmp.file).expires("1h");
        let response = caller.upload_file(init).await?;
        let token = response.token;
        let original_exp = response.retention_period;
        let original_opts = response.options.unwrap();
        be_nice().await;

        // Add a password
        let mod_request = WaifuModificationRequest::new(&token).password("banana");
        let response = caller.update_file(mod_request).await?;
        let options = response.options.unwrap();
        assert!(options.protected);
        assert_ne!(options.protected, original_opts.protected);
        be_nice().await;

        // Add an expiry
        let mod_request = WaifuModificationRequest::new(&token).custom_expiry("5m");
        let response = caller.update_file(mod_request).await?;
        assert_ne!(response.retention_period, original_exp);
        be_nice().await;

        // Hide the filename
        let mod_request = WaifuModificationRequest::new(&token).hide_filename(true);
        let response = caller.update_file(mod_request).await?;
        let options = response.options.unwrap();
        assert!(options.hide_filename);
        assert_ne!(options.hide_filename, original_opts.hide_filename);
        be_nice().await;

        // Update password
        let mod_request = WaifuModificationRequest::new(&token)
            .password("apple")
            .previous_password("banana");
        let response = caller.update_file(mod_request).await?;
        let options = response.options.unwrap();
        assert!(options.protected);
        be_nice().await;

        cleanup(&caller, &token).await?;
        be_nice().await;
        Ok(())
    }

    #[tokio::test]
    async fn delete_file() -> Result<()> {
        let tmp = TempFileCreator::new("something_to_delete.bin").await?;
        let caller = ApiCaller::new();
        let request = WaifuUploadRequest::new().file(&tmp.file);
        let response = caller.upload_file(request).await?;
        let token = response.token;
        let success = caller.delete_file(token).await?;

        assert!(success);
        be_nice().await;

        Ok(())
    }

    #[tokio::test]
    async fn download_file() -> Result<()> {
        let url = "https://waifuvault.moe/assets/custom/images/08.png";
        let original = reqwest::get(url).await?.bytes().await?.to_vec();
        let og_hash = hash_item(&original);

        let caller = ApiCaller::new();
        let request = WaifuUploadRequest::new().url(url).expires("1h");
        let response = caller.upload_file(request).await?;
        let url = response.url;

        let response = caller.download_file(url, None).await?;
        let result = hash_item(&response);

        assert_eq!(og_hash, result);
        be_nice().await;
        Ok(())
    }

    #[tokio::test]
    async fn download_file_with_password() -> Result<()> {
        let url = "https://waifuvault.moe/assets/custom/images/08.png";
        let original = reqwest::get(url).await?.bytes().await?.to_vec();
        let og_hash = hash_item(&original);

        let caller = ApiCaller::new();
        let request = WaifuUploadRequest::new()
            .url(url)
            .expires("1h")
            .password("banana");
        let response = caller
            .upload_file(request)
            .await
            .context("uploading protected file to download")?;
        let url = response.url;

        let response = caller
            .download_file(url, Some("banana".to_string()))
            .await?;
        let result = hash_item(&response);

        assert_eq!(og_hash, result);
        be_nice().await;
        Ok(())
    }

    fn hash_item(content: &Vec<u8>) -> String {
        let mut hasher = Sha1::new();
        hasher.update(content);
        let raw = hasher.finalize();

        hex::encode(raw)
    }

    async fn be_nice() {
        tokio::time::sleep(tokio::time::Duration::from_secs(2)).await;
    }
}