mangadex_api/
v5.rs

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
pub mod api_client;
pub mod at_home;
pub mod auth;
pub mod author;
pub mod captcha;
pub mod chapter;
pub mod cover;
pub mod custom_list;
pub mod feed;
pub mod forums;
pub mod legacy;
pub mod manga;
cfg_oauth! {
    pub mod oauth;
}
pub mod ping;
pub mod rating;
pub mod report;
pub mod scanlation_group;
pub mod search;
pub mod settings;
pub mod statistics;
pub mod upload;
pub mod user;

#[cfg(all(feature = "multi-thread", not(feature = "tokio-multi-thread")))]
use futures::lock::Mutex;
pub use mangadex_api_schema::v5 as schema;
use mangadex_api_schema::v5::oauth::ClientInfo;
pub(crate) use mangadex_api_schema::v5::AuthTokens;
use mangadex_api_types::error::Result;

use reqwest::Client;
#[cfg(all(
    not(feature = "multi-thread"),
    not(feature = "tokio-multi-thread"),
    not(feature = "rw-multi-thread")
))]
use std::cell::RefCell;
#[cfg(all(
    not(feature = "multi-thread"),
    not(feature = "tokio-multi-thread"),
    not(feature = "rw-multi-thread")
))]
use std::rc::Rc;
#[cfg(any(
    feature = "multi-thread",
    feature = "tokio-multi-thread",
    feature = "rw-multi-thread"
))]
use std::sync::Arc;
#[cfg(feature = "tokio-multi-thread")]
use tokio::sync::Mutex;
#[cfg(feature = "rw-multi-thread")]
use tokio::sync::RwLock;

#[cfg(feature = "utils")]
use crate::utils::download::DownloadBuilder;
use crate::v5::api_client::ApiClientEndpoint;
use crate::v5::at_home::AtHomeBuilder;
use crate::v5::auth::AuthBuilder;
use crate::v5::author::AuthorBuilder;
use crate::v5::captcha::CaptchaBuilder;
use crate::v5::chapter::ChapterBuilder;
use crate::v5::cover::CoverBuilder;
use crate::v5::custom_list::CustomListBuilder;
use crate::v5::feed::FeedBuilder;
use crate::v5::forums::ForumsEndpoint;
use crate::v5::legacy::LegacyBuilder;
use crate::v5::manga::MangaBuilder;
#[cfg(feature = "oauth")]
use crate::v5::oauth::OAuthBuider;
use crate::v5::ping::PingEndpointBuilder;
use crate::v5::rating::RatingBuilder;
use crate::v5::report::ReportBuilder;
use crate::v5::scanlation_group::ScanlationGroupBuilder;
use crate::v5::search::SearchBuilder;
use crate::v5::settings::SettingsBuilder;
use crate::v5::statistics::StatisticsBuilder;
use crate::v5::upload::UploadBuilder;
use crate::v5::user::UserBuilder;
use crate::HttpClient;
use crate::HttpClientRef;

/// API client to make requests to the MangaDex v5 API.
#[derive(Clone, Debug)]
pub struct MangaDexClient {
    pub http_client: HttpClientRef,
}

impl Default for MangaDexClient {
    /// Create a new `MangaDexClient` with the default [`reqwest::Client`](https://docs.rs/reqwest/latest/reqwest/struct.Client.html) settings.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use reqwest::Client;
    ///
    /// use mangadex_api::v5::MangaDexClient;
    ///
    /// # async fn run() -> Result<(), reqwest::Error> {
    /// let client = MangaDexClient::default();
    /// # Ok(())
    /// # }
    /// ```
    fn default() -> Self {
        Self::new_with_http_client(HttpClient::default())
    }
}

impl MangaDexClient {
    /// Create a new `MangaDexClient` with a custom [`reqwest::Client`](https://docs.rs/reqwest/latest/reqwest/struct.Client.html).
    ///
    /// # Examples
    ///
    /// ```rust
    /// use reqwest::Client;
    ///
    /// use mangadex_api::v5::MangaDexClient;
    ///
    /// # async fn run() -> Result<(), reqwest::Error> {
    /// let reqwest_client = Client::builder()
    ///     .timeout(std::time::Duration::from_secs(10))
    ///     .build()?;
    ///
    /// let client = MangaDexClient::new(reqwest_client);
    /// # Ok(())
    /// # }
    /// ```
    pub fn new(client: Client) -> Self {
        Self::new_with_http_client_ref(create_ref_counted_http_client(HttpClient::new(client)))
    }

    /// Create a new `MangaDexClient` with a custom client reference
    pub fn new_with_http_client_ref(http_client: HttpClientRef) -> Self {
        Self { http_client }
    }
    /// Create a new `MangaDexClient` with a custom [`HttpClient`].
    ///
    /// In most cases, providing a custom [`HttpClient`] isn't necessary.
    /// This function is primarily useful for mock testing but is available for anyone that needs to
    /// change the base URL if it changes due to an unforeseen event.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use reqwest::Client;
    /// use url::Url;
    ///
    /// use mangadex_api::v5::MangaDexClient;
    /// use mangadex_api::HttpClient;
    ///
    /// # async fn run() -> anyhow::Result<()> {
    /// let reqwest_client = Client::builder()
    ///     .timeout(std::time::Duration::from_secs(10))
    ///     .build()?;
    ///
    /// let http_client = HttpClient::builder()
    ///     .client(reqwest_client)
    ///     .base_url(Url::parse("127.0.0.1:8080")?)
    ///     .build()?;
    ///
    /// let client = MangaDexClient::new_with_http_client(http_client);
    /// # Ok(())
    /// # }
    /// ```
    pub fn new_with_http_client(http_client: HttpClient) -> Self {
        Self::new_with_http_client_ref(create_ref_counted_http_client(http_client))
    }

    /// Return the Reqwest `Client`.
    ///
    /// This can be used to create manual HTTP requests.
    ///
    /// Using this is generally not advised as it can provide mutable access to the [`HttpClient`].
    pub fn get_http_client(&self) -> HttpClientRef {
        self.http_client.clone()
    }
    #[cfg(all(
        not(feature = "multi-thread"),
        not(feature = "tokio-multi-thread"),
        not(feature = "rw-multi-thread")
    ))]
    pub async fn set_auth_tokens(&mut self, auth_tokens: &AuthTokens) -> Result<()> {
        let client = &mut self.http_client.try_borrow_mut()?;
        client.set_auth_tokens(auth_tokens);
        Ok(())
    }
    #[cfg(any(
        feature = "multi-thread",
        feature = "tokio-multi-thread",
        feature = "rw-multi-thread"
    ))]
    pub async fn set_auth_tokens(&self, auth_tokens: &AuthTokens) -> Result<()> {
        let mut client = {
            #[cfg(any(feature = "multi-thread", feature = "tokio-multi-thread"))]
            {
                self.http_client.lock().await
            }
            #[cfg(feature = "rw-multi-thread")]
            {
                self.http_client.write().await
            }
        };
        client.set_auth_tokens(auth_tokens);
        Ok(())
    }

    #[cfg(all(
        not(feature = "multi-thread"),
        not(feature = "tokio-multi-thread"),
        not(feature = "rw-multi-thread")
    ))]
    pub async fn clear_auth_tokens(&mut self) -> Result<()> {
        let client = {
            #[cfg(all(
                not(feature = "multi-thread"),
                not(feature = "tokio-multi-thread"),
                not(feature = "rw-multi-thread")
            ))]
            {
                &mut self.http_client.try_borrow_mut()?
            }
            #[cfg(any(feature = "multi-thread", feature = "tokio-multi-thread"))]
            {
                &mut self.http_client.lock().await
            }
            #[cfg(feature = "rw-multi-thread")]
            {
                &mut self.http_client.write().await
            }
        };
        client.clear_auth_tokens();
        Ok(())
    }
    #[cfg(any(
        feature = "multi-thread",
        feature = "tokio-multi-thread",
        feature = "rw-multi-thread"
    ))]
    pub async fn clear_auth_tokens(&self) -> Result<()> {
        let mut client = {
            #[cfg(any(feature = "multi-thread", feature = "tokio-multi-thread"))]
            {
                self.http_client.lock().await
            }
            #[cfg(feature = "rw-multi-thread")]
            {
                self.http_client.write().await
            }
        };
        client.clear_auth_tokens();
        Ok(())
    }
    pub async fn get_auth_tokens(&self) -> Result<AuthTokens> {
        let client = {
            #[cfg(all(
                not(feature = "multi-thread"),
                not(feature = "tokio-multi-thread"),
                not(feature = "rw-multi-thread")
            ))]
            {
                &self.http_client.try_borrow()?
            }
            #[cfg(any(feature = "multi-thread", feature = "tokio-multi-thread"))]
            {
                &self.http_client.lock().await
            }
            #[cfg(feature = "rw-multi-thread")]
            {
                &self.http_client.read().await
            }
        };
        client
            .get_tokens()
            .cloned()
            .ok_or(mangadex_api_types::error::Error::MissingTokens)
    }

    #[cfg(all(
        not(feature = "multi-thread"),
        not(feature = "tokio-multi-thread"),
        not(feature = "rw-multi-thread")
    ))]
    pub async fn set_captcha<A: Into<String>>(&mut self, captcha: A) -> Result<()> {
        let client = &mut self.http_client.try_borrow_mut()?;
        client.set_captcha(captcha);
        Ok(())
    }
    #[cfg(any(
        feature = "multi-thread",
        feature = "tokio-multi-thread",
        feature = "rw-multi-thread"
    ))]
    pub async fn set_captcha<A: Into<String>>(&self, captcha: A) -> Result<()> {
        let mut client = {
            #[cfg(any(feature = "multi-thread", feature = "tokio-multi-thread"))]
            {
                self.http_client.lock().await
            }
            #[cfg(feature = "rw-multi-thread")]
            {
                self.http_client.write().await
            }
        };
        client.set_captcha(captcha);
        Ok(())
    }
    pub async fn get_captcha(&self) -> Result<String> {
        let client = {
            #[cfg(all(
                not(feature = "multi-thread"),
                not(feature = "tokio-multi-thread"),
                not(feature = "rw-multi-thread")
            ))]
            {
                &self.http_client.try_borrow()?
            }
            #[cfg(any(feature = "multi-thread", feature = "tokio-multi-thread"))]
            {
                &self.http_client.lock().await
            }
            #[cfg(feature = "rw-multi-thread")]
            {
                &self.http_client.read().await
            }
        };
        client
            .get_captcha()
            .cloned()
            .ok_or(mangadex_api_types::error::Error::MissingCaptcha)
    }
    #[cfg(all(
        not(feature = "multi-thread"),
        not(feature = "tokio-multi-thread"),
        not(feature = "rw-multi-thread")
    ))]
    pub async fn clear_captcha(&mut self) -> Result<()> {
        let client = &mut self.http_client.try_borrow_mut()?;
        client.clear_captcha();
        Ok(())
    }
    #[cfg(any(
        feature = "multi-thread",
        feature = "tokio-multi-thread",
        feature = "rw-multi-thread"
    ))]
    pub async fn clear_captcha(&self) -> Result<()> {
        let mut client = {
            #[cfg(any(feature = "multi-thread", feature = "tokio-multi-thread"))]
            {
                self.http_client.lock().await
            }
            #[cfg(feature = "rw-multi-thread")]
            {
                self.http_client.write().await
            }
        };
        client.clear_captcha();
        Ok(())
    }

    cfg_oauth! {
        pub async fn get_client_info(&self) -> Result<ClientInfo> {
            let client = {
                #[cfg(all(
                    not(feature = "multi-thread"),
                    not(feature = "tokio-multi-thread"),
                    not(feature = "rw-multi-thread")
                ))]
                {
                    &self.http_client.try_borrow()?
                }
                #[cfg(any(feature = "multi-thread", feature = "tokio-multi-thread"))]
                {
                    &self.http_client.lock().await
                }
                #[cfg(feature = "rw-multi-thread")]
                {
                    &self.http_client.read().await
                }
            };
            client
                .get_client_info()
                .cloned()
                .ok_or(mangadex_api_types::error::Error::MissingClientInfo)
        }
    }
    /// Get a builder for handling the At-Home endpoints.
    ///
    /// <https://api.mangadex.org/swagger.html#/AtHome>
    pub fn at_home(&self) -> AtHomeBuilder {
        AtHomeBuilder::new(self.http_client.clone())
    }

    /// Get a builder for handling the authentication endpoints.
    ///
    /// This builder is deprecated
    ///
    /// <https://api.mangadex.org/docs/redoc.html#tag/Authentication>
    pub fn auth(&self) -> AuthBuilder {
        AuthBuilder::new(self.http_client.clone())
    }

    /// Get a builder for handling the author endpoints.
    ///
    /// <https://api.mangadex.org/swagger.html#/Author>
    pub fn author(&self) -> AuthorBuilder {
        AuthorBuilder::new(self.http_client.clone())
    }

    /// Get a builder for handling the captcha endpoints.
    ///
    /// <https://api.mangadex.org/swagger.html#/Captcha>
    pub fn captcha(&self) -> CaptchaBuilder {
        CaptchaBuilder::new(self.http_client.clone())
    }

    /// Get a builder for handling the chapter endpoints.
    ///
    /// <https://api.mangadex.org/swagger.html#/Chapter>
    pub fn chapter(&self) -> ChapterBuilder {
        ChapterBuilder::new(self.http_client.clone())
    }

    pub fn client(&self) -> ApiClientEndpoint {
        ApiClientEndpoint::new(self.http_client.clone())
    }

    /// Get a builder for handling manga volume cover art endpoints.
    ///
    /// <https://api.mangadex.org/swagger.html#/Cover>
    pub fn cover(&self) -> CoverBuilder {
        CoverBuilder::new(self.http_client.clone())
    }

    /// Get a builder for handling the custom list endpoints.
    ///
    /// <https://api.mangadex.org/swagger.html#/CustomList>
    pub fn custom_list(&self) -> CustomListBuilder {
        CustomListBuilder::new(self.http_client.clone())
    }

    /// Get a builder for handling the feed endpoints.
    ///
    /// <https://api.mangadex.org/swagger.html#/Feed>
    pub fn feed(&self) -> FeedBuilder {
        FeedBuilder::new(self.http_client.clone())
    }

    /// Get a builder for handling the infrastructure endpoints.
    ///
    /// <https://api.mangadex.org/swagger.html#/Infrastructure>
    pub fn ping(&self) -> PingEndpointBuilder {
        PingEndpointBuilder::new(self.http_client.clone())
    }

    /// Get a builder for handling the legacy endpoints.
    ///
    /// <https://api.mangadex.org/swagger.html#/Legacy>
    pub fn legacy(&self) -> LegacyBuilder {
        LegacyBuilder::new(self.http_client.clone())
    }

    /// Get a builder for handling the manga endpoints.
    ///
    /// <https://api.mangadex.org/swagger.html#/Manga>
    pub fn manga(&self) -> MangaBuilder {
        MangaBuilder::new(self.http_client.clone())
    }

    /// Get a builder for handling the rating endpoints.
    ///
    /// <https://api.mangadex.org/swagger.html#/Rating>
    pub fn rating(&self) -> RatingBuilder {
        RatingBuilder::new(self.http_client.clone())
    }

    /// Get a builder for handling the report endpoints.
    ///
    /// <https://api.mangadex.org/swagger.html#/Report>
    pub fn report(&self) -> ReportBuilder {
        ReportBuilder::new(self.http_client.clone())
    }

    /// Get a builder for handling the scanlation group endpoints.
    ///
    /// <https://api.mangadex.org/swagger.html#/ScanlationGroup>
    pub fn scanlation_group(&self) -> ScanlationGroupBuilder {
        ScanlationGroupBuilder::new(self.http_client.clone())
    }

    /// Get a builder for handling the search endpoints.
    ///
    /// This is a convenience builder that aggregates search endpoints from various categories.
    pub fn search(&self) -> SearchBuilder {
        SearchBuilder::new(self.http_client.clone())
    }

    /// Get a builder for handling the settings endpoints.
    ///
    /// <https://api.mangadex.org/swagger.html#/Settings>
    // Not public yet as the settings endpoints are not stable as of MangaDex API v5.4.9.
    pub fn settings(&self) -> SettingsBuilder {
        SettingsBuilder::new(self.http_client.clone())
    }

    /// Get a builder for handling the statistics endpoints.
    ///
    /// <https://api.mangadex.org/swagger.html#/Statistics>
    pub fn statistics(&self) -> StatisticsBuilder {
        StatisticsBuilder::new(self.http_client.clone())
    }

    /// Get a builder for handling uploads.
    ///
    /// <https://api.mangadex.org/swagger.html#/Upload>
    pub fn upload(&self) -> UploadBuilder {
        UploadBuilder::new(self.http_client.clone())
    }

    /// Get a builder for handling the user endpoints.
    ///
    /// <https://api.mangadex.org/swagger.html#/User>
    pub fn user(&self) -> UserBuilder {
        UserBuilder::new(self.http_client.clone())
    }

    /// This is an api client for
    /// `api.mangadex.dev`
    pub fn api_dev_client() -> Self {
        Self::new_with_http_client(HttpClient::api_dev_client())
    }
    cfg_utils! {
        pub fn download(&self) -> DownloadBuilder {
            DownloadBuilder::new(self.http_client.clone())
        }
    }

    pub fn forums(&self) -> ForumsEndpoint {
        ForumsEndpoint::new(self.http_client.clone())
    }

    cfg_oauth! {
        pub fn oauth(&self) -> OAuthBuider {
            OAuthBuider::new(self.http_client.clone())
        }
    }
}

/// Create a new reference counted `HttpClient`.
fn create_ref_counted_http_client(http_client: HttpClient) -> HttpClientRef {
    #[cfg(all(
        not(feature = "multi-thread"),
        not(feature = "tokio-multi-thread"),
        not(feature = "rw-multi-thread")
    ))]
    {
        Rc::new(RefCell::new(http_client))
    }
    #[cfg(any(feature = "multi-thread", feature = "tokio-multi-thread"))]
    {
        Arc::new(Mutex::new(http_client))
    }
    #[cfg(feature = "rw-multi-thread")]
    {
        Arc::new(RwLock::new(http_client))
    }
}

#[cfg(all(
    feature = "oauth",
    all(
        not(feature = "multi-thread"),
        not(feature = "tokio-multi-thread"),
        not(feature = "rw-multi-thread")
    )
))]
#[cfg_attr(
    docsrs,
    doc(cfg(all(
        feature = "oauth",
        all(
            not(feature = "multi-thread"),
            not(feature = "tokio-multi-thread"),
            not(feature = "rw-multi-thread")
        )
    )))
)]
impl MangaDexClient {
    pub async fn set_client_info(&mut self, client_info: &ClientInfo) -> Result<()> {
        let client = &mut self.http_client.try_borrow_mut()?;

        client.set_client_info(client_info);
        Ok(())
    }
    pub async fn clear_client_info(&mut self) -> Result<()> {
        let client = &mut self.http_client.try_borrow_mut()?;
        client.clear_client_info();
        Ok(())
    }
}

#[cfg(all(
    feature = "oauth",
    any(
        feature = "multi-thread",
        feature = "tokio-multi-thread",
        feature = "rw-multi-thread"
    )
))]
#[cfg_attr(
    docsrs,
    doc(all(
        feature = "oauth",
        any(
            feature = "multi-thread",
            feature = "tokio-multi-thread",
            feature = "rw-multi-thread"
        )
    ))
)]
impl MangaDexClient {
    pub async fn set_client_info(&self, client_info: &ClientInfo) -> Result<()> {
        let mut client = {
            #[cfg(any(feature = "multi-thread", feature = "tokio-multi-thread"))]
            {
                self.http_client.lock().await
            }
            #[cfg(feature = "rw-multi-thread")]
            {
                self.http_client.write().await
            }
        };
        client.set_client_info(client_info);
        Ok(())
    }
    pub async fn clear_client_info(&self) -> Result<()> {
        let mut client = {
            #[cfg(any(feature = "multi-thread", feature = "tokio-multi-thread"))]
            {
                self.http_client.lock().await
            }
            #[cfg(feature = "rw-multi-thread")]
            {
                self.http_client.write().await
            }
        };
        client.clear_client_info();
        Ok(())
    }
}