rustnao 0.3.4

A Rust implementation of a wrapper for the SauceNAO 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
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
//! Handler module of rustnao.  The handler for the SauceNAO API calls.

mod error;
pub use error::{ErrType, Error, Result};

mod constants;

mod sauce;
pub use sauce::Sauce;

mod deserialize;
use deserialize::SauceResult;

use std::cell::Cell;
use url::Url;

/// A builder to create a Handler for RustNAO usage.
/// ## Example
/// ```
/// use rustnao::HandlerBuilder;
/// let handle = HandlerBuilder::default().api_key("your_api_key").num_results(999).db(999).build();
/// ```
#[derive(Default, Debug, Clone)]
pub struct HandlerBuilder {
    api_key: Option<String>,
    testmode: Option<bool>,
    db_mask: Option<Vec<u32>>,
    db_mask_i: Option<Vec<u32>>,
    db: Option<u32>,
    num_results: Option<u32>,
    min_similarity: Option<f64>,
    empty_filter_enabled: Option<bool>,
}

impl HandlerBuilder {
    /// Sets the API key used for searches for the Handler.  If this is not set then a blank API key is used, instead of your personal one.
    ///
    /// ### Arguments
    /// * api_key - A string reference representing your API key.
    ///
    /// ### Examples
    /// ```
    /// use rustnao::HandlerBuilder;
    /// let handle = HandlerBuilder::default().api_key("your_api_key").build();
    /// ```
    pub fn api_key(&mut self, api_key: &str) -> &mut HandlerBuilder {
        self.api_key = Some(api_key.to_string());
        self
    }

    /// Sets whether testmode should be enabled on searches for the Handler.  If this is on, then each index will output at most one result.  If this is unset then it is set to off by default.
    ///
    /// ### Arguments
    /// * testmode - A boolean representing whether you want testmode to be set to on (true) or off (false).
    ///
    /// ### Examples
    /// ```
    /// use rustnao::HandlerBuilder;
    /// let handle = HandlerBuilder::default().testmode(true).build();
    /// ```
    pub fn testmode(&mut self, testmode: bool) -> &mut HandlerBuilder {
        self.testmode = Some(testmode);
        self
    }

    /// Sets which database indices you want included on search for the Handler.  If both db and db_mask are not set, then every index is checked (db_mask_i will still apply).
    ///
    /// ### Arguments
    /// * db_mask - A vector of u32s representing the database indices you wish to have included in your search.
    ///
    /// ### Examples
    /// ```
    /// use rustnao::{Handler, HandlerBuilder};
    /// let handle = HandlerBuilder::default().db_mask([1, 2, Handler::PIXIV].to_vec()).build();
    /// ```
    pub fn db_mask(&mut self, db_mask: Vec<u32>) -> &mut HandlerBuilder {
        self.db_mask = Some(db_mask);
        self
    }

    /// Sets which database indices you want excluded on search for the Handler.
    ///
    /// ### Arguments
    /// * db_mask_i - A vector of u32s representing the database indices you wish to have excluded in your search.
    ///
    /// ### Examples
    /// ```
    /// use rustnao::{Handler, HandlerBuilder};
    /// let handle = HandlerBuilder::default().db_mask_i([1, 2, Handler::PIXIV].to_vec()).build();
    /// ```
    pub fn db_mask_i(&mut self, db_mask_i: Vec<u32>) -> &mut HandlerBuilder {
        self.db_mask_i = Some(db_mask_i);
        self
    }

    /// Sets a database index to be searched for the Handler.  If both db and db_mask are not set, then every index is checked (db_mask_i will still apply).
    ///
    /// ### Arguments
    /// * db - A u32 representing which database index you want included.  Set it to 999 to include every index.
    ///
    /// ### Examples
    /// ```
    /// use rustnao::{Handler, HandlerBuilder};
    /// let handle = HandlerBuilder::default().db(Handler::PIXIV).build();
    /// ```
    pub fn db(&mut self, db: u32) -> &mut HandlerBuilder {
        self.db = Some(db);
        self
    }

    /// Sets the maximum number of results you want returned on search for the Handler.  You can change this number per-search.  If this is not set, by default this is set to return at most 999 results.
    ///
    /// ### Arguments
    /// * num_results - A u32 value representing how many results you want returned.
    ///
    /// ### Examples
    /// ```
    /// use rustnao::HandlerBuilder;
    /// let handle = HandlerBuilder::default().num_results(10).build();
    /// ```
    pub fn num_results(&mut self, num_results: u32) -> &mut HandlerBuilder {
        self.num_results = Some(num_results);
        self
    }

    /// Sets he minimum similarity for results by default for the Handler.  You can change this number per-search.  If this is not set, by default it is 0.0 (no minimum similarity).
    ///
    /// ### Arguments
    /// * min_similarity : A number that can be cast into a f64 representing the minimum similarity (in percent) of a result to be returned.
    ///
    /// ### Examples
    /// ```
    /// use rustnao::HandlerBuilder;
    /// let handle = HandlerBuilder::default().min_similarity(50.5).build();
    /// ```
    pub fn min_similarity<T: Into<f64>>(&mut self, min_similarity: T) -> &mut HandlerBuilder {
        self.min_similarity = Some(min_similarity.into());
        self
    }

    /// Sets whether to enable an empty filter by default for the Handler.  If this is not set, by default it is false.
    ///
    /// ### Arguments
    /// * empty_filter_enabled : A boolean representing whether you want empty URL search results to be filtered out by default.
    ///
    /// ### Examples
    /// ```
    /// use rustnao::HandlerBuilder;
    /// let handle = HandlerBuilder::default().empty_filter_enabled(true).build();
    /// ```
    pub fn empty_filter_enabled(&mut self, empty_filter_enabled: bool) -> &mut HandlerBuilder {
        self.empty_filter_enabled = Some(empty_filter_enabled);
        self
    }

    /// Builds the HandlerBuilder, returning a Handler that can be used to search.
    ///
    /// ### Examples
    /// ```
    /// use rustnao::HandlerBuilder;
    /// let handle = HandlerBuilder::default().api_key("your_api_key").db(999).num_results(50).build();
    /// ```
    pub fn build(&self) -> Handler {
        let mut api_key = "";
        match &self.api_key {
            Some(x) => api_key = x.as_str(),
            None => (),
        }

        let mut testmode = None;
        if let Some(x) = self.testmode {
            testmode = if x { Some(1) } else { Some(0) };
        }

        let mut num_results = None;
        if let Some(x) = self.num_results {
            num_results = Some(x);
        }

        let result = Handler::new(
            api_key,
            testmode,
            self.db_mask.clone(),
            self.db_mask_i.clone(),
            self.db,
            num_results,
        );
        if let Some(x) = self.min_similarity {
            result.set_min_similarity(x);
        }

        if let Some(x) = self.empty_filter_enabled {
            result.set_empty_filter(x);
        }

        result
    }
}

/// A handler struct to make SauceNAO API calls with.
///
/// ## Example
/// ```
/// use rustnao::HandlerBuilder;
/// let handle = HandlerBuilder::default().api_key("your_api_key").num_results(999).db(999).build();
/// handle.get_sauce("https://i.imgur.com/W42kkKS.jpg", None, None);
/// ```
#[derive(Debug, Clone)]
pub struct Handler {
    api_key: String,
    output_type: i32,
    testmode: Option<u32>,
    db_mask: Option<Vec<u32>>,
    db_mask_i: Option<Vec<u32>>,
    db: Option<u32>,
    num_results: Option<u32>,
    short_limit: Cell<u32>,
    long_limit: Cell<u32>,
    short_left: Cell<u32>,
    long_left: Cell<u32>,
    min_similarity: Cell<f64>,
    empty_filter_enabled: Cell<bool>,
}

impl Handler {
    /// Associated index for H-Magazines.
    pub const H_MAGAZINES: u32 = constants::H_MAGAZINES.index;
    /// Associated index for H-Game CG.
    pub const H_GAME_CG: u32 = constants::H_GAME_CG.index;
    /// Associated index for DoujinshiDB.
    pub const DOUJINSHI_DB: u32 = constants::DOUJINSHI_DB.index;
    /// Associated index for Pixiv.
    pub const PIXIV: u32 = constants::PIXIV.index;
    /// Associated index for Nico Nico Seiga.
    pub const NICO_NICO_SEIGA: u32 = constants::NICO_NICO_SEIGA.index;
    /// Associated index for Danbooru.
    pub const DANBOORU: u32 = constants::DANBOORU.index;
    /// Associated index for drawr Images.
    pub const DRAWR: u32 = constants::DRAWR.index;
    /// Associated index for Nijie Images.
    pub const NIJIE: u32 = constants::NIJIE.index;
    /// Associated index for Yand.ere.
    pub const YANDE_RE: u32 = constants::YANDE_RE.index;
    /// Associated index for Shutterstock.
    pub const SHUTTERSTOCK: u32 = constants::SHUTTERSTOCK.index;
    /// Associated index for Fakku.
    pub const FAKKU: u32 = constants::FAKKU.index;
    /// Associated index for H-Misc.
    pub const H_MISC: u32 = constants::H_MISC.index;
    /// Associated index for 2D-Market.
    pub const TWO_D_MARKET: u32 = constants::TWO_D_MARKET.index;
    /// Associated index for MediBang.
    pub const MEDIBANG: u32 = constants::MEDIBANG.index;
    /// Associated index for Anime.
    pub const ANIME: u32 = constants::ANIME.index;
    /// Associated index for H-Anime.
    pub const H_ANIME: u32 = constants::H_ANIME.index;
    /// Associated index for Movies.
    pub const MOVIES: u32 = constants::MOVIES.index;
    /// Associated index for Shows.
    pub const SHOWS: u32 = constants::SHOWS.index;
    /// Associated index for Gelbooru.
    pub const GELBOORU: u32 = constants::GELBOORU.index;
    /// Associated index for Konachan.
    pub const KONACHAN: u32 = constants::KONACHAN.index;
    /// Associated index for Sankaku Channel.
    pub const SANKAKU_CHANNEL: u32 = constants::SANKAKU_CHANNEL.index;
    /// Associated index for Anime-Pictures.net.
    pub const ANIME_PICTURES_NET: u32 = constants::ANIME_PICTURES_NET.index;
    /// Associated index for e621.net.
    pub const E621_NET: u32 = constants::E621_NET.index;
    /// Associated index for Idol Complex.
    pub const IDOL_COMPLEX: u32 = constants::IDOL_COMPLEX.index;
    /// Associated index for bcy.net Illust.
    pub const BCY_NET_ILLUST: u32 = constants::BCY_NET_ILLUST.index;
    /// Associated index for bcy.net Cosplay.
    pub const BCY_NET_COSPLAY: u32 = constants::BCY_NET_COSPLAY.index;
    /// Associated index for PortalGraphics.net.
    pub const PORTALGRAPHICS_NET: u32 = constants::PORTALGRAPHICS_NET.index;
    /// Associated index for deviantArt.
    pub const DEVIANTART: u32 = constants::DEVIANTART.index;
    /// Associated index for Pawoo.net.
    pub const PAWOO_NET: u32 = constants::PAWOO_NET.index;
    /// Associated index for Madokami.
    pub const MADOKAMI: u32 = constants::MADOKAMI.index;
    /// Associated index for Mangadex.
    pub const MANGADEX: u32 = constants::MANGADEX.index;

    /// Grabs the appropriate Source data given an index
    fn get_source(&self, index: u32) -> Option<constants::Source<'_>> {
        let mut result: Option<constants::Source<'_>> = None;
        for src in constants::LIST_OF_SOURCES.iter() {
            if src.index == index {
                result = Some(src.clone());
            }
        }
        result
    }

    // TODO: Test bitmask further!
    /// Generates a bitmask from a given vector.
    fn generate_bitmask(&self, mask: Vec<u32>) -> u32 {
        let mut res: u32 = 0;
        for m in mask {
            let offset = if m >= 18 {
                1 // TODO: This seems to be some required fix... look into!
            } else {
                0
            };
            res ^= u32::pow(2, m - offset);
        }
        res
    }

    /// Generates a url from the given image url
    fn generate_url(&self, image_path: &str, num_results: Option<u32>) -> Result<String> {
        let mut request_url = Url::parse(constants::API_URL)?;
        request_url
            .query_pairs_mut()
            .append_pair("api_key", self.api_key.as_str());
        request_url
            .query_pairs_mut()
            .append_pair("output_type", self.output_type.to_string().as_str());

        if let Some(val) = self.db {
            request_url
                .query_pairs_mut()
                .append_pair("db", val.to_string().as_str());
        }

        if let Some(val) = &self.db_mask {
            if !val.is_empty() {
                request_url.query_pairs_mut().append_pair(
                    "dbmask",
                    self.generate_bitmask(val.clone()).to_string().as_str(),
                );
            }
        }
        if let Some(val) = &self.db_mask_i {
            if !val.is_empty() {
                request_url.query_pairs_mut().append_pair(
                    "dbmaski",
                    self.generate_bitmask(val.clone()).to_string().as_str(),
                );
            }
        }

        match self.testmode {
            Some(val) => {
                request_url
                    .query_pairs_mut()
                    .append_pair("testmode", val.to_string().as_str());
            }
            None => {
                request_url.query_pairs_mut().append_pair("testmode", "0");
            }
        }

        match num_results {
            Some(results) => {
                request_url
                    .query_pairs_mut()
                    .append_pair("numres", results.to_string().as_str());
            }
            None => match self.num_results {
                Some(val) => {
                    request_url
                        .query_pairs_mut()
                        .append_pair("numres", val.to_string().as_str());
                }
                None => {
                    request_url.query_pairs_mut().append_pair("numres", "999");
                }
            },
        }
        if image_path.starts_with("https://") || image_path.starts_with("http://") {
            // Link
            request_url.query_pairs_mut().append_pair("url", image_path);
        }

        Ok(request_url.to_string())
    }

    fn new(
        api_key: &str, testmode: Option<u32>, db_mask: Option<Vec<u32>>,
        db_mask_i: Option<Vec<u32>>, db: Option<u32>, num_results: Option<u32>,
    ) -> Handler {
        Handler {
            api_key: api_key.to_string(),
            output_type: 2, // This is set to 2 by default, as we need a JSON reply
            testmode,
            db_mask,
            db_mask_i,
            db,
            num_results,
            short_limit: Cell::new(12),
            long_limit: Cell::new(200),
            short_left: Cell::new(12),
            long_left: Cell::new(200),
            min_similarity: Cell::new(0.0),
            empty_filter_enabled: Cell::new(false),
        }
    }

    /// Sets the minimum similarity threshold for ``get_sauce``.  By default this is 0.0.
    /// ## Arguments
    /// * `min_similarity` - Represents the minimum similarity threshold (in percent) you wish to set.  It can be any value that can convert to a f64.  This includes f32s, i16s, i32s, and i8s.
    ///
    /// ## Example
    /// ```
    /// use rustnao::HandlerBuilder;
    /// let handle = HandlerBuilder::default().api_key("your_api_key").num_results(999).db(999).build();
    /// handle.set_min_similarity(50);
    /// ```
    pub fn set_min_similarity<T: Into<f64>>(&self, min_similarity: T) {
        self.min_similarity.set(min_similarity.into());
    }

    /// Sets the whether empty URL results should be automatically filtered for ``get_sauce``.  
    /// ## Arguments
    /// * `enabled` - Represents whether filter should be enabled or not.  By default, this is disabled.
    ///
    /// ## Example
    /// ```
    /// use rustnao::HandlerBuilder;
    /// let handle = HandlerBuilder::default().api_key("your_api_key").num_results(999).db(999).build();
    /// handle.set_empty_filter(true);
    /// ```
    pub fn set_empty_filter(&self, enabled: bool) {
        self.empty_filter_enabled.set(enabled);
    }

    /// Gets the current short limit as an i32.  By default this is 12.
    ///
    /// ## Example
    /// ```
    /// use rustnao::HandlerBuilder;
    /// let handle = HandlerBuilder::default().api_key("your_api_key").num_results(999).db(999).build();
    /// println!("{}", handle.get_short_limit());
    /// ```
    pub fn get_short_limit(&self) -> u32 {
        self.short_limit.get()
    }

    /// Gets the current long limit as an i32.  By default this is 200.
    ///
    /// ## Example
    /// ```
    /// use rustnao::HandlerBuilder;
    /// let handle = HandlerBuilder::default().api_key("your_api_key").num_results(999).db(999).build();
    /// println!("{}", handle.get_long_limit());
    /// ```
    pub fn get_long_limit(&self) -> u32 {
        self.long_limit.get()
    }

    /// Gets the current remaining short limit as an i32.
    ///
    /// ## Example
    /// ```
    /// use rustnao::HandlerBuilder;
    /// let handle = HandlerBuilder::default().api_key("your_api_key").num_results(999).db(999).build();
    /// println!("{}", handle.get_current_short_limit());
    /// ```
    pub fn get_current_short_limit(&self) -> u32 {
        self.short_left.get()
    }

    /// Gets the current remaining long limit as an i32.
    ///
    /// ## Example
    /// ```
    /// use rustnao::HandlerBuilder;
    /// let handle = HandlerBuilder::default().api_key("your_api_key").num_results(999).db(999).build();
    /// println!("{}", handle.get_current_long_limit());
    /// ```
    pub fn get_current_long_limit(&self) -> u32 {
        self.long_left.get()
    }

    fn is_valid_min_sim(&self, min_similarity: Option<f64>) -> bool {
        if let Some(min_similarity) = min_similarity {
            if !(0.0..=100.0).contains(&min_similarity) {
                return false;
            }
        }

        true
    }

    fn is_valid_num_res(&self, num_results: Option<u32>) -> bool {
        if let Some(num_results) = num_results {
            if num_results > 999 {
                return false;
            }
        }

        true
    }

    fn process_results(
        &self, returned_sauce: SauceResult, min_similarity: Option<f64>,
    ) -> Result<Vec<Sauce>> {
        let mut ret_sauce: Vec<Sauce> = Vec::new();

        if returned_sauce.header.status >= 0 {
            // Update non-sauce fields
            self.short_left.set(returned_sauce.header.short_remaining);
            self.long_left.set(returned_sauce.header.long_remaining);
            self.short_limit
                .set(returned_sauce.header.short_limit.parse()?);
            self.long_limit
                .set(returned_sauce.header.long_limit.parse()?);

            // Actual "returned" value:
            if let Some(res) = returned_sauce.results {
                let actual_min_sim = match min_similarity {
                    Some(min_sim) => min_sim,
                    None => self.min_similarity.get(),
                };

                for sauce in res {
                    let sauce_min_sim: f64 = sauce.header.similarity.parse()?;
                    if (sauce_min_sim >= actual_min_sim)
                        && ((self.empty_filter_enabled.get() && !sauce.data.ext_urls.is_empty())
                            || !self.empty_filter_enabled.get())
                    {
                        let actual_index: u32 =
                            sauce.header.index_name.split(':').collect::<Vec<&str>>()[0]
                                .split('#')
                                .collect::<Vec<&str>>()[1]
                                .parse::<u32>()?;
                        let source: Option<constants::Source> = self.get_source(actual_index);

                        match source {
                            Some(src) => {
                                ret_sauce.push(sauce::new_sauce(
                                    sauce.data.ext_urls,
                                    sauce.data.title,
                                    src.name.to_string(),
                                    actual_index,
                                    sauce.header.index_id,
                                    sauce.header.similarity.parse().unwrap(),
                                    sauce.header.thumbnail.to_string(),
                                    match serde_json::to_value(&sauce.data.additional_fields) {
                                        Ok(x) => Some(x),
                                        Err(_x) => None,
                                    },
                                ));
                            }
                            None => {
                                ret_sauce.push(sauce::new_sauce(
                                    sauce.data.ext_urls,
                                    sauce.data.title,
                                    sauce.header.index_name,
                                    actual_index,
                                    sauce.header.index_id,
                                    sauce.header.similarity.parse().unwrap(),
                                    sauce.header.thumbnail.to_string(),
                                    None,
                                ));
                            }
                        }
                    }
                }
            }
            Ok(ret_sauce)
        } else {
            Err(Error::invalid_code(
                returned_sauce.header.status,
                returned_sauce.header.message,
            ))
        }
    }

    /// Returns a Result of either a vector of Sauce objects, which contain potential sources for the input file, or a SauceError.
    /// ## Arguments
    /// * ``image_path`` - A string slice that contains the url of the image you wish to look up.
    /// * ``num_results`` - An Option containing a u32 to specify the number of results you wish to get for this specific search.  If this is None, it will default to whatever was originally set in the Handler when it was initalized.  This can be at most 999.
    /// * ``min_similarity`` - An Option containing a f64 to specify the minimum similarity you wish to meet for a result to show up for this specific search.  If this is None, it will default to whatever was originally set in the Handler when it was initalized.
    ///
    /// ## Example
    /// ```
    /// use rustnao::HandlerBuilder;
    /// let handle = HandlerBuilder::default().api_key("your_api_key").num_results(999).db(999).build();
    /// handle.get_sauce("./tests/test.jpg", None, None);
    /// ```
    ///
    /// ## Errors
    /// If there was a problem forming a URL, reading a file, making a request, or parsing the returned JSON, an error will be returned.
    /// Furthermore, if you pass a link in which SauceNAO returns an error code, an error containing the code and message will be returned.
    pub fn get_sauce(
        &self, image_path: &str, num_results: Option<u32>, min_similarity: Option<f64>,
    ) -> Result<Vec<Sauce>> {
        // This is essentially just a blocking version of the async call... thank you, code reuse

        // TODO: Considering phasing this out, and also may need async versions of other helper functions... probably not though
        async_std::task::block_on(async {
            self.async_get_sauce(image_path, num_results, min_similarity)
                .await
        })
    }

    /// Returns a string representing a vector of Sauce objects as a serialized JSON, or an error.  Otherwise identical to ``get_sauce(...)``
    /// ## Arguments
    /// * ``image_path`` - A string slice that contains the url of the image you wish to look up.
    /// * ``num_results`` - An Option containing a u32 to specify the number of results you wish to get for this specific search.  If this is None, it will default to whatever was originally set in the Handler when it was initialized.
    /// * ``min_similarity`` - An Option containing a f64 to specify the minimum similarity you wish to meet for a result to show up for this specific search.  If this is None, it will default to whatever was originally set in the Handler when it was initialized.
    ///
    /// ## Example
    /// ```
    /// use rustnao::HandlerBuilder;
    /// let handle = HandlerBuilder::default().api_key("your_api_key").num_results(999).db(999).build();
    /// handle.get_sauce_as_pretty_json("https://i.imgur.com/W42kkKS.jpg", None, None);
    /// ```
    ///
    /// ## Errors
    /// If there was a problem forming a URL, reading a file, making a request, or parsing the returned JSON, an error will be returned.
    /// Furthermore, if you pass a link in which SauceNAO returns an error code, an error containing the code and message will be returned.
    pub fn get_sauce_as_pretty_json(
        &self, image_path: &str, num_results: Option<u32>, min_similarity: Option<f64>,
    ) -> Result<String> {
        let ret_sauce = self.get_sauce(image_path, num_results, min_similarity)?;
        Ok(serde_json::to_string_pretty(&ret_sauce)?)
    }

    /// Returns a string representing a vector of Sauce objects as a serialized JSON, or an error.
    /// ## Arguments
    /// * ``image_path`` - A string slice that contains the url of the image you wish to look up.
    /// * ``num_results`` - An Option containing a u32 to specify the number of results you wish to get for this specific search.  If this is None, it will default to whatever was originally set in the Handler when it was initialized.
    /// * ``min_similarity`` - An Option containing a f64 to specify the minimum similarity you wish to meet for a result to show up for this specific search.  If this is None, it will default to whatever was originally set in the Handler when it was initialized.
    ///
    /// ## Example
    /// ```
    /// use rustnao::HandlerBuilder;
    /// let handle = HandlerBuilder::default().api_key("your_api_key").num_results(999).db(999).build();
    /// handle.get_sauce_as_json("https://i.imgur.com/W42kkKS.jpg", None, None);
    /// ```
    ///
    /// ## Errors
    /// If there was a problem forming a URL, reading a file, making a request, or parsing the returned JSON, an error will be returned.
    /// Furthermore, if you pass a link in which SauceNAO returns an error code, an error containing the code and message will be returned.
    pub fn get_sauce_as_json(
        &self, image_path: &str, num_results: Option<u32>, min_similarity: Option<f64>,
    ) -> Result<String> {
        let ret_sauce = self.get_sauce(image_path, num_results, min_similarity)?;
        Ok(serde_json::to_string(&ret_sauce)?)
    }

    /// Asynchronously returns a Result of either a vector of Sauce objects, which contain potential sources for the input path, or a SauceError.
    /// ## Arguments
    /// * ``image_path`` - A string slice that contains the url of the image you wish to look up.
    /// * ``num_results`` - An Option containing a u32 to specify the number of results you wish to get for this specific search.  If this is None, it will default to whatever was originally set in the Handler when it was initalized.  This can be at most 999.
    /// * ``min_similarity`` - An Option containing a f64 to specify the minimum similarity you wish to meet for a result to show up for this specific search.  If this is None, it will default to whatever was originally set in the Handler when it was initalized.
    ///
    /// ## Errors
    /// If there was a problem forming a URL, reading a file, making a request, or parsing the returned JSON, an error will be returned.
    /// Furthermore, if you pass a link in which SauceNAO returns an error code, an error containing the code and message will be returned.
    pub async fn async_get_sauce(
        &self, image_path: &str, num_results: Option<u32>, min_similarity: Option<f64>,
    ) -> Result<Vec<Sauce>> {
        // Check passed in values first to see if they're valid!

        if !self.is_valid_min_sim(min_similarity) {
            return Err(Error::invalid_parameter(
                "min_similarity must be less 100.0 and greater than 0.0.".to_string(),
            ));
        } else if !self.is_valid_num_res(num_results) {
            return Err(Error::invalid_parameter(
                "num_results must be less than 999.".to_string(),
            ));
        }

        let url_string = self.generate_url(image_path, num_results)?;

        let mut returned_response =
            if !(image_path.starts_with("https://") || image_path.starts_with("http://")) {
                surf::post(&url_string)
                    .body_file(image_path)
                    .await?
                    .send()
                    .await?
            } else {
                surf::post(&url_string).await?
            };

        let returned_sauce = returned_response.body_json().await?;

        self.process_results(returned_sauce, min_similarity)
    }

    /// Asynchronously returns a string representing a vector of Sauce objects as a serialized JSON, or an error.  Otherwise identical to ``async_get_sauce(...)``
    /// ## Arguments
    /// * ``image_path`` - A string slice that contains the url of the image you wish to look up.
    /// * ``num_results`` - An Option containing a u32 to specify the number of results you wish to get for this specific search.  If this is None, it will default to whatever was originally set in the Handler when it was initialized.
    /// * ``min_similarity`` - An Option containing a f64 to specify the minimum similarity you wish to meet for a result to show up for this specific search.  If this is None, it will default to whatever was originally set in the Handler when it was initialized.
    ///
    /// ## Errors
    /// If there was a problem forming a URL, reading a file, making a request, or parsing the returned JSON, an error will be returned.
    /// Furthermore, if you pass a link in which SauceNAO returns an error code, an error containing the code and message will be returned.
    pub async fn async_get_sauce_as_json(
        &self, image_path: &str, num_results: Option<u32>, min_similarity: Option<f64>,
    ) -> Result<String> {
        let ret_sauce = self
            .async_get_sauce(image_path, num_results, min_similarity)
            .await?;
        Ok(serde_json::to_string(&ret_sauce)?)
    }

    /// Asynchronously returns a string representing a vector of Sauce objects as a serialized JSON, or an error.  Otherwise identical to ``async_get_sauce(...)``
    /// ## Arguments
    /// * ``image_path`` - A string slice that contains the url of the image you wish to look up.
    /// * ``num_results`` - An Option containing a u32 to specify the number of results you wish to get for this specific search.  If this is None, it will default to whatever was originally set in the Handler when it was initialized.
    /// * ``min_similarity`` - An Option containing a f64 to specify the minimum similarity you wish to meet for a result to show up for this specific search.  If this is None, it will default to whatever was originally set in the Handler when it was initialized.
    ///
    /// ## Errors
    /// If there was a problem forming a URL, reading a file, making a request, or parsing the returned JSON, an error will be returned.
    /// Furthermore, if you pass a link in which SauceNAO returns an error code, an error containing the code and message will be returned.
    pub async fn async_get_sauce_as_pretty_json(
        &self, image_path: &str, num_results: Option<u32>, min_similarity: Option<f64>,
    ) -> Result<String> {
        let ret_sauce = self
            .async_get_sauce(image_path, num_results, min_similarity)
            .await?;
        Ok(serde_json::to_string_pretty(&ret_sauce)?)
    }
}

/// A trait to convert to JSON and pretty JSON strings.
/// ### Example
/// Implementing for a Sauce vector into a pretty JSON string:
/// ```
/// use rustnao::{HandlerBuilder, ToJSON};
/// let handle = HandlerBuilder::default().api_key("your_api_key").num_results(999).db(999).build();
/// let result = handle.get_sauce("./tests/test.jpg", None, None);
/// if result.is_ok() {
///     result.unwrap().to_json_pretty();
/// }
/// ```
pub trait ToJSON {
    /// Converts to a Result containing a JSON string.
    /// ### Example
    /// ```
    /// use rustnao::{HandlerBuilder, ToJSON};
    /// let handle = HandlerBuilder::default().api_key("your_api_key").num_results(999).db(999).build();
    /// let result = handle.get_sauce("./tests/test.jpg", None, None);
    /// if result.is_ok() {
    ///     result.unwrap().to_json();
    /// }
    /// ```
    /// ### Errors
    /// There may be a problem converting the object to a JSON string, so this will throw an Error if that is encountered.
    fn to_json(&self) -> Result<String>;

    /// Converts to a Result containing a pretty JSON string.
    /// ### Example
    /// ```
    /// use rustnao::{HandlerBuilder, ToJSON};
    /// let handle = HandlerBuilder::default().api_key("your_api_key").num_results(999).db(999).build();
    /// let result = handle.get_sauce("./tests/test.jpg", None, None);
    /// if result.is_ok() {
    ///     result.unwrap().to_json_pretty();
    /// }
    /// ```
    /// ### Errors
    /// There may be a problem converting the object to a JSON string, so this will throw an Error if that is encountered.
    fn to_json_pretty(&self) -> Result<String>;
}

impl ToJSON for Vec<Sauce> {
    /// Converts a Sauce vector into a pretty JSON string.
    fn to_json_pretty(&self) -> Result<String> {
        Ok(serde_json::to_string_pretty(self)?)
    }

    /// Converts a Sauce vector into a JSON string.
    fn to_json(&self) -> Result<String> {
        Ok(serde_json::to_string(self)?)
    }
}