rust-anilist 0.1.5

A Rust wrapper for the Anilist API, providing asynchronous methods to interact with various entities like Anime, Manga, User, Person, and Character.
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
// SPDX-License-Identifier: MIT
// Copyright (c) 2022-2025 Andriel Ferreira <https://github.com/AndrielFR>

//! This module contains the `Client` struct and its related types.

use serde::Deserialize;
use std::time::Duration;

use crate::{
    models::{
        Anime, Character, Cover, Format, Image, Manga, MediaType, Person, Status, Title, User,
    },
    Error, Result,
};

/// Represents a client for interacting with an API.
///
/// The `Client` struct contains the necessary configuration for making
/// requests to an API, including the API token and the timeout duration.
#[derive(Clone, Debug, PartialEq)]
pub struct Client {
    /// The API token to use for requests.
    api_token: Option<String>,
    /// The timeout for requests (in seconds).
    timeout: Duration,
}

impl Client {
    /// Creates a new client instance with the specified timeout duration.
    ///
    /// This method initializes a new `Client` instance with the provided
    /// timeout duration.
    ///
    /// # Arguments
    ///
    /// * `timeout` - The timeout duration for requests, in seconds.
    pub fn with_timeout(duration: Duration) -> Self {
        Self {
            api_token: None,
            timeout: duration,
        }
    }

    /// Creates a new client instance with the specified API token.
    ///
    /// This method initializes a new `Client` instance with the provided
    /// API token and a default timeout duration of 20 seconds.
    ///
    /// # Arguments
    ///
    /// * `token` - A string slice that holds the API token.
    pub fn with_token(token: &str) -> Self {
        Self {
            api_token: Some(token.to_string()),
            timeout: Duration::from_secs(20),
        }
    }

    /// Sets the timeout duration for the client.
    ///
    /// This method allows you to set the timeout duration for the client
    /// in seconds. The timeout duration determines how long the client
    /// will wait for a response before timing out.
    ///
    /// # Arguments
    ///
    /// * `seconds` - The timeout duration in seconds.
    pub fn timeout(mut self, duration: Duration) -> Self {
        self.timeout = duration;
        self
    }

    /// Sets the API token for the client.
    ///
    /// This method allows you to set the API token for the client, which
    /// will be used for authenticating API requests.
    ///
    /// # Arguments
    ///
    /// * `token` - A string slice that holds the API token.
    pub fn token(mut self, token: &str) -> Self {
        self.api_token = Some(token.to_string());
        self
    }

    /// Get an anime by its ID or MAL ID.
    ///
    /// # Arguments
    ///
    /// * `id` - The ID of the anime.
    /// * `mal_id` - The MAL ID of the anime.
    ///
    /// # Errors
    ///
    /// Returns an error if the request fails.
    ///
    /// # Example
    ///
    /// ```
    /// # async fn f(client: rust_anilist::Client) -> rust_anilist::Result<()> {
    /// let anime = client.get_anime(1).await?;
    ///
    /// # Ok(())
    /// # }
    /// ```
    pub async fn get_anime(&self, id: i64) -> Result<Anime> {
        let data = self
            .request(
                MediaType::Anime,
                Action::Get,
                serde_json::json!({ "id": id }),
            )
            .await
            .map_err(|e| Error::ApiError(e.to_string()))?;

        match serde_json::from_str::<Anime>(&data["data"]["Media"].to_string()) {
            Ok(mut anime) => {
                anime.client = self.clone();
                anime.is_full_loaded = true;

                Ok(anime)
            }
            Err(e) => Err(crate::Error::ApiError(e.to_string())),
        }
    }

    /// Get a manga by its ID or MAL ID.
    ///
    /// # Arguments
    ///
    /// * `id` - The ID of the manga.
    /// * `mal_id` - The MAL ID of the manga.
    ///
    /// # Errors
    ///
    /// Returns an error if the request fails.
    ///
    /// # Example
    ///
    /// ```
    /// # async fn f(client: rust_anilist::Client) -> rust_anilist::Result<()> {
    /// let manga = client.get_manga(1).await?;
    ///
    /// # Ok(())
    /// # }
    /// ```
    pub async fn get_manga(&self, id: i64) -> Result<Manga> {
        let data = self
            .request(
                MediaType::Manga,
                Action::Get,
                serde_json::json!({ "id": id }),
            )
            .await
            .map_err(|e| Error::ApiError(e.to_string()))?;

        match serde_json::from_str::<Manga>(&data["data"]["Media"].to_string()) {
            Ok(mut manga) => {
                manga.client = self.clone();
                manga.is_full_loaded = true;

                Ok(manga)
            }
            Err(e) => Err(crate::Error::ApiError(e.to_string())),
        }
    }

    /// Get a character by its ID.
    ///
    /// # Arguments
    ///
    /// * `id` - The ID of the character.
    ///
    /// # Errors
    ///
    /// Returns an error if the request fails.
    ///
    /// # Example
    ///
    /// ```
    /// # async fn f(client: rust_anilist::Client) -> rust_anilist::Result<()> {
    /// let character = client.get_character(1).await?;
    ///
    /// # Ok(())
    /// # }
    /// ```
    pub async fn get_character(&self, id: i64) -> Result<Character> {
        let data = self
            .request(
                MediaType::Character,
                Action::Get,
                serde_json::json!({ "id": id }),
            )
            .await
            .map_err(|e| Error::ApiError(e.to_string()))?;

        match serde_json::from_str::<Character>(&data["data"]["Character"].to_string()) {
            Ok(mut character) => {
                character.client = self.clone();
                character.is_full_loaded = true;

                Ok(character)
            }
            Err(e) => Err(crate::Error::ApiError(e.to_string())),
        }
    }

    /// Get a character by its ID.
    ///
    /// # Arguments
    ///
    /// * `id` - The ID of the character.
    ///
    /// # Errors
    ///
    /// Returns an error if the request fails.
    ///
    /// # Example
    ///
    /// ```
    /// # async fn f(client: rust_anilist::Client) -> rust_anilist::Result<()> {
    /// let character = client.get_char(1).await?;
    ///
    /// # Ok(())
    /// # }
    /// ```
    pub async fn get_char(&self, id: i64) -> Result<Character> {
        self.get_character(id).await
    }

    /// Get a user by its ID.
    ///
    /// # Arguments
    ///
    /// * `id` - The ID of the user.
    ///
    /// # Errors
    ///
    /// Returns an error if the request fails.
    ///
    /// # Example
    ///
    /// ```
    /// # async fn f(client: rust_anilist::Client) -> rust_anilist::Result<()> {
    /// let user = client.get_user(1).await?;
    ///
    /// # Ok(())
    /// # }
    /// ```
    pub async fn get_user(&self, id: i32) -> Result<User> {
        let data = self
            .request(
                MediaType::User,
                Action::Get,
                serde_json::json!({ "id": id }),
            )
            .await
            .map_err(|e| Error::ApiError(e.to_string()))?;

        match serde_json::from_str::<User>(&data["data"]["User"].to_string()) {
            Ok(user) => Ok(user),
            Err(e) => Err(crate::Error::ApiError(e.to_string())),
        }
    }

    /// Get a user by its name.
    ///
    /// # Arguments
    ///
    /// * `name` - The name of the user.
    ///
    /// # Errors
    ///
    /// Returns an error if the request fails.
    ///
    /// # Example
    ///
    /// ```
    /// # async fn f(client: rust_anilist::Client) -> rust_anilist::Result<()> {
    /// let user = client.get_user_by_name("andrielfr").await?;
    ///
    /// # Ok(())
    /// # }
    /// ```
    pub async fn get_user_by_name<N: ToString>(&self, name: N) -> Result<User> {
        let name = name.to_string();

        let data = self
            .request(
                MediaType::User,
                Action::Get,
                serde_json::json!({ "name": name }),
            )
            .await
            .map_err(|e| Error::ApiError(e.to_string()))?;

        match serde_json::from_str::<User>(&data["data"]["User"].to_string()) {
            Ok(mut user) => {
                user.client = self.clone();
                user.is_full_loaded = true;

                Ok(user)
            }
            Err(e) => Err(crate::Error::ApiError(e.to_string())),
        }
    }

    /// Get a person by its ID.
    ///
    /// # Arguments
    ///
    /// * `id` - The ID of the person.
    ///
    /// # Errors
    ///
    /// Returns an error if the request fails.
    ///
    /// # Example
    ///
    /// ```
    /// # async fn f(client: rust_anilist::Client) -> rust_anilist::Result<()> {
    /// let person = client.get_person(1).await?;
    ///
    /// # Ok(())
    /// # }
    /// ```
    pub async fn get_person(&self, id: i64) -> Result<Person> {
        let data = self
            .request(
                MediaType::Person,
                Action::Get,
                serde_json::json!({ "id": id }),
            )
            .await
            .map_err(|e| Error::ApiError(e.to_string()))?;

        match serde_json::from_str::<Person>(&data["data"]["Staff"].to_string()) {
            Ok(mut person) => {
                person.client = self.clone();
                person.is_full_loaded = true;

                Ok(person)
            }
            Err(e) => Err(crate::Error::ApiError(e.to_string())),
        }
    }

    /// Search for animes.
    ///
    /// # Arguments
    ///
    /// * `title` - The title of the anime to search.
    /// * `page` - The page number to get.
    /// * `limit` - The number of animes to get per page.
    ///
    /// # Errors
    ///
    /// Returns an error if the request fails.
    ///
    /// # Example
    ///
    /// ```
    /// # async fn f(client: rust_anilist::Client) -> rust_anilist::Result<()> {
    /// let animes = client.search_anime("Naruto", 1, 10).await.unwrap();
    ///
    /// # Ok(())
    /// # }
    /// ```
    pub async fn search_anime(&self, title: &str, page: u16, limit: u16) -> Option<Vec<Anime>> {
        let result = self
            .request(
                MediaType::Anime,
                Action::Search,
                serde_json::json!({ "search": title, "page": page, "per_page": limit, }),
            )
            .await
            .map_err(|e| Error::ApiError(e.to_string()))
            .unwrap();

        if let Some(medias) = result["data"]["Page"]["media"].as_array() {
            let mut animes = Vec::new();

            for media in medias.iter() {
                animes.push(Anime {
                    id: media["id"].as_i64().unwrap(),
                    id_mal: media["idMal"].as_i64(),
                    title: Title::deserialize(&media["title"]).unwrap(),
                    format: Format::deserialize(&media["format"]).unwrap(),
                    status: Status::deserialize(&media["status"]).unwrap(),
                    description: media["description"].as_str().unwrap().to_string(),
                    cover: Cover::deserialize(&media["coverImage"]).unwrap(),
                    banner: media["bannerImage"].as_str().map(String::from),
                    average_score: media["averageScore"].as_u64().map(|x| x as u8),
                    mean_score: media["meanScore"].as_u64().map(|x| x as u8),
                    is_adult: media["isAdult"].as_bool().unwrap(),
                    url: media["siteUrl"].as_str().unwrap().to_string(),

                    client: self.clone(),
                    ..Default::default()
                });
            }

            return Some(animes);
        }

        None
    }

    /// Search for mangas.
    ///
    /// # Arguments
    ///
    /// * `title` - The title of the manga to search.
    /// * `page` - The page number to get.
    /// * `limit` - The number of mangas to get per page.
    ///
    /// # Errors
    ///
    /// Returns an error if the request fails.
    ///
    /// # Example
    ///
    /// ```
    /// # async fn f(client: rust_anilist::Client) -> rust_anilist::Result<()> {
    /// let mangas = client.search_manga("Naruto", 1, 10).await.unwrap();
    ///
    /// # Ok(())
    /// # }
    /// ```
    pub async fn search_manga(&self, title: &str, page: u16, limit: u16) -> Option<Vec<Manga>> {
        let result = self
            .request(
                MediaType::Manga,
                Action::Search,
                serde_json::json!({ "search": title, "page": page, "per_page": limit, }),
            )
            .await
            .map_err(|e| Error::ApiError(e.to_string()))
            .unwrap();

        if let Some(medias) = result["data"]["Page"]["media"].as_array() {
            let mut mangas = Vec::new();

            for media in medias.iter() {
                mangas.push(Manga {
                    id: media["id"].as_i64().unwrap(),
                    id_mal: media["idMal"].as_i64(),
                    title: Title::deserialize(&media["title"]).unwrap(),
                    format: Format::deserialize(&media["format"]).unwrap(),
                    status: Status::deserialize(&media["status"]).unwrap(),
                    description: media["description"].as_str().unwrap().to_string(),
                    cover: Cover::deserialize(&media["coverImage"]).unwrap(),
                    banner: media["bannerImage"].as_str().map(String::from),
                    average_score: media["averageScore"].as_u64().map(|x| x as u8),
                    mean_score: media["meanScore"].as_u64().map(|x| x as u8),
                    is_adult: media["isAdult"].as_bool().unwrap(),
                    url: media["siteUrl"].as_str().unwrap().to_string(),

                    client: self.clone(),
                    ..Default::default()
                });
            }

            return Some(mangas);
        }

        None
    }

    /// Search for users.
    ///
    /// # Arguments
    ///
    /// * `name` - The name of the user to search.
    /// * `page` - The page number to get.
    /// * `limit` - The number of users to get per page.
    ///
    /// # Errors
    ///
    /// Returns an error if the request fails.
    ///
    /// # Example
    ///
    /// ```
    /// # async fn f(client: rust_anilist::Client) -> rust_anilist::Result<()> {
    /// let users = client.search_user("andrielfr", 1, 10).await.unwrap();
    ///
    /// # Ok(())
    /// # }
    /// ```
    pub async fn search_user(&self, name: &str, page: u16, limit: u16) -> Option<Vec<User>> {
        let result = self
            .request(
                MediaType::User,
                Action::Search,
                serde_json::json!({ "search": name, "page": page, "per_page": limit, }),
            )
            .await
            .map_err(|e| Error::ApiError(e.to_string()))
            .unwrap();

        if let Some(users) = result["data"]["Page"]["users"].as_array() {
            let mut vec = Vec::new();

            for user in users.iter() {
                vec.push(User {
                    id: user["id"].as_i64().unwrap() as i32,
                    name: user["name"].as_str().unwrap().to_string(),
                    about: user["about"].as_str().map(String::from),
                    avatar: Image::deserialize(&user["avatar"]).ok(),
                    banner: user["bannerImage"].as_str().map(String::from),

                    client: self.clone(),
                    ..Default::default()
                });
            }

            return Some(vec);
        }

        None
    }

    /// Send a request to the AniList API.
    ///
    /// # Arguments
    ///
    /// * `media_type` - The type of media to request.
    /// * `action` - The action to perform.
    /// * `variables` - The variables to send with the request.
    ///
    /// # Errors
    ///
    /// Returns an error if the request fails.
    async fn request(
        &self,
        media_type: MediaType,
        action: Action,
        variables: serde_json::Value,
    ) -> std::result::Result<serde_json::Value, reqwest::Error> {
        let query = Client::get_query(media_type, action).unwrap();
        let json = serde_json::json!({"query": query, "variables": variables});
        let mut body = reqwest::Client::new()
            .post("https://graphql.anilist.co/")
            .header("Content-Type", "application/json")
            .header("Accept", "application/json")
            .timeout(self.timeout)
            .body(json.to_string());

        if let Some(token) = &self.api_token {
            body = body.bearer_auth(token);
        }

        let response = body.send().await?.text().await?;
        let result = serde_json::from_str::<serde_json::Value>(&response).unwrap();

        Ok(result)
    }

    /// Get the GraphQL query for a specific media type.
    ///
    /// # Arguments
    ///
    /// * `media_type` - The type of media to get the query for.
    /// * `action` - The action to perform.
    ///
    /// # Errors
    ///
    /// Returns an error if the media type is not valid.
    fn get_query(media_type: MediaType, action: Action) -> Result<String> {
        let graphql_query = match action {
            Action::Get => {
                match media_type {
                    MediaType::Anime => include_str!("../queries/get_anime.graphql").to_string(),
                    MediaType::Manga => include_str!("../queries/get_manga.graphql").to_string(),
                    MediaType::Character => {
                        include_str!("../queries/get_character.graphql").to_string()
                    }
                    MediaType::User => include_str!("../queries/get_user.graphql").to_string(),
                    MediaType::Person => include_str!("../queries/get_person.graphql").to_string(),
                    // MediaType::Studio => include_str!("../queries/get_studio.graphql").to_string(),
                    _ => unimplemented!(),
                }
            }
            Action::Search => {
                match media_type {
                    MediaType::Anime => include_str!("../queries/search_anime.graphql").to_string(),
                    MediaType::Manga => include_str!("../queries/search_manga.graphql").to_string(),
                    // MediaType::Character => {
                    //     include_str!("../queries/search_character.graphql").to_string()
                    // }
                    MediaType::User => include_str!("../queries/search_user.graphql").to_string(),
                    // MediaType::Person => {
                    //     include_str!("../queries/search_person.graphql").to_string()
                    // }
                    // MediaType::Studio => include_str!("../queries/search_studio.graphql").to_string(),
                    _ => unimplemented!(),
                }
            }
        };

        Ok(graphql_query)
    }
}

impl Default for Client {
    fn default() -> Self {
        Client {
            api_token: None,
            timeout: Duration::from_secs(20),
        }
    }
}

/// Represents an action that can be performed by the client.
///
/// The `Action` enum defines various actions that the client can perform,
/// such as getting media by ID or searching for media.
///
/// # Variants
///
/// * `Get` - Represents the action of getting media by ID.
/// * `Search` - Represents the action of searching for media.
enum Action {
    /// Get media by ID.
    Get,
    /// Search for media.
    Search,
}

#[cfg(test)]
mod tests {
    use std::time::Duration;

    use super::*;

    #[test]
    fn test_with_timeout() {
        let duration = Duration::from_secs(30);
        let client = Client::with_timeout(duration);

        assert_eq!(client.timeout, duration);
        assert!(client.api_token.is_none());
    }

    #[test]
    fn test_with_token() {
        let api_token = "test_token";
        let client = Client::with_token(api_token);

        assert_eq!(client.timeout, Duration::from_secs(20));
        assert_eq!(client.api_token, Some(api_token.to_string()));
    }

    #[test]
    fn test_timeout() {
        let initial_duration = Duration::from_secs(30);
        let new_duration = Duration::from_secs(60);
        let client = Client::with_timeout(initial_duration).timeout(new_duration);

        assert_eq!(client.timeout, new_duration);
    }

    #[test]
    fn test_token() {
        let initial_token = "initial_token";
        let new_token = "new_token";
        let client = Client::with_token(initial_token).token(new_token);

        assert_eq!(client.api_token, Some(new_token.to_string()));
    }
}