anilist_moe 0.4.0

Anilist_Moe is a Rust Wrapper for the Anilist API. This library allows you to seamlessly interact with Anilist's Public API with and without authentication. This currently supports Anime, Manga, Users, Staff, Forum, Threads, Recommendations, Reviews and User Activities
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
#[cfg(feature = "activity")]
use crate::endpoints::ActivityEndpoint;
#[cfg(feature = "airing")]
use crate::endpoints::AiringEndpoint;
#[cfg(feature = "character")]
use crate::endpoints::CharacterEndpoint;
#[cfg(feature = "common")]
use crate::endpoints::CommonEndpoint;
#[cfg(feature = "forum")]
use crate::endpoints::ForumEndpoint;
#[cfg(feature = "media")]
use crate::endpoints::MediaEndpoint;
#[cfg(feature = "medialist")]
use crate::endpoints::MediaListEndpoint;
#[cfg(feature = "notification")]
use crate::endpoints::NotificationEndpoint;
#[cfg(feature = "recommendation")]
use crate::endpoints::RecommendationEndpoint;
#[cfg(feature = "review")]
use crate::endpoints::ReviewEndpoint;
#[cfg(feature = "staff")]
use crate::endpoints::StaffEndpoint;
#[cfg(feature = "studio")]
use crate::endpoints::StudioEndpoint;
#[cfg(feature = "user")]
use crate::endpoints::UserEndpoint;
use crate::errors::AniListError;
use crate::objects::responses::GraphQLResponse;
use crate::utils::{RetryConfig, retry_with_backoff};
use reqwest::header::{HeaderMap, HeaderName, HeaderValue};
use reqwest::{Client, Response, StatusCode};
use serde::Serialize;
use serde_json::{Value, from_value};
use std::borrow::Cow;
use std::fmt;
use std::sync::Arc;
use std::time::Duration;
/// The default AniList GraphQL API endpoint
const ANILIST_API_URL: &str = "https://graphql.anilist.co";

/// User-Agent header for identifying this library
const USER_AGENT: &str = concat!("anilist-moe/", env!("CARGO_PKG_VERSION"), " (Rust)");

/// Content-Type header value (reused to avoid allocations)
const CONTENT_TYPE_JSON: &str = "application/json";

/// Authorization header prefix
const BEARER_PREFIX: &str = "Bearer ";

/// Internal shared state for the client
struct ClientInner {
    client: Client,
    token: Option<String>,
    retry_config: RetryConfig,
    base_url: Cow<'static, str>,
}

/// The main client for interacting with the AniList API.
///
/// This client handles all API requests, authentication, rate limiting,
/// and error handling. It provides access to all AniList API endpoints
/// through specialized endpoint methods.
///
/// # Examples
///
/// ```rust
/// use anilist_moe::AniListClient;
///
/// // Create a client without authentication
/// let client = AniListClient::new();
///
/// // Create a client with authentication
/// let authenticated_client = AniListClient::with_token("your_token_here");
/// ```
#[derive(Clone)]
pub struct AniListClient {
    inner: Arc<ClientInner>,
}

// Implement Debug manually to avoid exposing sensitive token information
impl fmt::Debug for AniListClient {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("AniListClient")
            .field("base_url", &self.inner.base_url)
            .field("has_token", &self.inner.token.is_some())
            .field("retry_config", &self.inner.retry_config)
            .finish()
    }
}

impl AniListClient {
    /// Creates a new AniList client without authentication.
    ///
    /// This client can access all public endpoints but cannot perform
    /// authenticated actions like posting activities or managing lists.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use anilist_moe::AniListClient;
    ///
    /// let client = AniListClient::new();
    /// ```
    #[must_use]
    pub fn new() -> Self {
        AniListClientBuilder::new().build()
    }
    /// Creates a new AniList client with authentication.
    ///
    /// # Arguments
    ///
    /// * `token` - The OAuth2 Bearer token for authentication
    ///
    /// # Examples
    ///
    /// ```rust
    /// use anilist_moe::AniListClient;
    ///
    /// let client = AniListClient::with_token("your_access_token");
    /// ```
    #[must_use]
    pub fn with_token(token: impl Into<String>) -> Self {
        AniListClientBuilder::new().token(token).build()
    }

    /// Configures the retry behavior for failed requests.
    ///
    /// # Arguments
    ///
    /// * `config` - The retry configuration to use
    ///
    /// # Examples
    ///
    /// ```rust
    /// use anilist_moe::{AniListClient, utils::RetryConfig};
    ///
    /// let config = RetryConfig {
    ///     max_retries: 5,
    ///     base_delay_ms: 2000,
    ///     exponential_backoff: true,
    ///     max_delay_ms: 60000,
    /// };
    ///
    /// let client = AniListClient::new().with_retry_config(config);
    /// ```
    #[must_use]
    pub fn with_retry_config(self, config: RetryConfig) -> Self {
        Self {
            inner: Arc::new(ClientInner {
                client: self.inner.client.clone(),
                token: self.inner.token.clone(),
                retry_config: config,
                base_url: self.inner.base_url.clone(),
            }),
        }
    }

    /// Sets a custom base URL for the API (useful for testing or custom endpoints).
    ///
    /// # Arguments
    ///
    /// * `base_url` - The base URL to use for API requests
    ///
    /// # Examples
    ///
    /// ```rust
    /// use anilist_moe::AniListClient;
    ///
    /// let client = AniListClient::new()
    ///     .with_base_url("https://custom-api.example.com");
    /// ```
    #[must_use]
    pub fn with_base_url(self, base_url: impl Into<String>) -> Self {
        Self {
            inner: Arc::new(ClientInner {
                client: self.inner.client.clone(),
                token: self.inner.token.clone(),
                retry_config: self.inner.retry_config,
                base_url: Cow::Owned(base_url.into()),
            }),
        }
    }

    /// Returns the media endpoint for anime and manga operations.
    #[cfg(feature = "media")]
    #[inline]
    pub fn media(&self) -> MediaEndpoint {
        MediaEndpoint::new(self.clone())
    }

    /// Returns the media endpoint for anime operations (alias for media()).
    #[cfg(feature = "media")]
    #[inline]
    pub fn anime(&self) -> MediaEndpoint {
        self.media()
    }

    /// Returns the media endpoint for manga operations (alias for media()).
    #[cfg(feature = "media")]
    #[inline]
    pub fn manga(&self) -> MediaEndpoint {
        self.media()
    }

    /// Returns the medialist endpoint for user anime/manga list operations.
    #[cfg(feature = "medialist")]
    #[inline]
    pub fn medialist(&self) -> MediaListEndpoint {
        MediaListEndpoint::new(self.clone())
    }

    /// Returns the character endpoint for character operations.
    #[cfg(feature = "character")]
    #[inline]
    pub fn character(&self) -> CharacterEndpoint {
        CharacterEndpoint::new(self.clone())
    }

    /// Returns the common endpoint for likes, follows, and favorites.
    #[cfg(feature = "common")]
    #[inline]
    pub fn common(&self) -> CommonEndpoint {
        CommonEndpoint::new(self.clone())
    }

    /// Returns the staff endpoint for staff member operations.
    #[cfg(feature = "staff")]
    #[inline]
    pub fn staff(&self) -> StaffEndpoint {
        StaffEndpoint::new(self.clone())
    }

    /// Returns the user endpoint for user profile operations.
    #[cfg(feature = "user")]
    #[inline]
    pub fn user(&self) -> UserEndpoint {
        UserEndpoint::new(self.clone())
    }

    /// Returns the studio endpoint for studio operations.
    #[cfg(feature = "studio")]
    #[inline]
    pub fn studio(&self) -> StudioEndpoint {
        StudioEndpoint::new(self.clone())
    }

    /// Returns the forum endpoint for thread and comment operations.
    #[cfg(feature = "forum")]
    #[inline]
    pub fn forum(&self) -> ForumEndpoint {
        ForumEndpoint::new(self.clone())
    }

    /// Returns the activity endpoint for activity feed operations.
    #[cfg(feature = "activity")]
    #[inline]
    pub fn activity(&self) -> ActivityEndpoint {
        ActivityEndpoint::new(self.clone())
    }

    /// Returns the review endpoint for review operations.
    #[cfg(feature = "review")]
    #[inline]
    pub fn review(&self) -> ReviewEndpoint {
        ReviewEndpoint::new(self.clone())
    }

    /// Returns the recommendation endpoint for recommendation operations.
    #[cfg(feature = "recommendation")]
    #[inline]
    pub fn recommendation(&self) -> RecommendationEndpoint {
        RecommendationEndpoint::new(self.clone())
    }

    /// Returns the airing endpoint for airing schedule operations.
    #[cfg(feature = "airing")]
    #[inline]
    pub fn airing(&self) -> AiringEndpoint {
        AiringEndpoint::new(self.clone())
    }

    /// Returns the notification endpoint for notification operations.
    #[cfg(feature = "notification")]
    #[inline]
    pub fn notification(&self) -> NotificationEndpoint {
        NotificationEndpoint::new(self.clone())
    }

    /// Sets the authentication token for this client.
    ///
    /// Note: This creates a new client with the updated token due to Arc sharing.
    pub fn set_token(&mut self, token: &str) {
        *self = Self {
            inner: Arc::new(ClientInner {
                client: self.inner.client.clone(),
                token: Some(token.to_string()),
                retry_config: self.inner.retry_config,
                base_url: self.inner.base_url.clone(),
            }),
        };
    }

    /// Clears the authentication token from this client.
    ///
    /// Note: This creates a new client without the token due to Arc sharing.
    pub fn clear_token(&mut self) {
        *self = Self {
            inner: Arc::new(ClientInner {
                client: self.inner.client.clone(),
                token: None,
                retry_config: self.inner.retry_config,
                base_url: self.inner.base_url.clone(),
            }),
        };
    }

    /// Returns whether this client has an authentication token.
    #[inline]
    pub fn has_token(&self) -> bool {
        self.inner.token.is_some()
    }

    /// Returns the retry configuration for this client.
    #[inline]
    pub fn retry_config(&self) -> RetryConfig {
        self.inner.retry_config
    }

    pub async fn query<V: Serialize>(
        &self,
        query: &'static str,
        variables: Option<&V>,
    ) -> Result<Value, AniListError> {
        self.execute_query(query, variables).await
    }

    pub async fn fetch<T, V>(
        &self,
        query: &'static str,
        variables: Option<&V>,
    ) -> Result<T, AniListError>
    where
        T: serde::de::DeserializeOwned,
        V: Serialize,
    {
        let response_data = self.execute_query(query, variables).await?;
        let wrapper: GraphQLResponse<T> =
            from_value(response_data).map_err(|e| AniListError::ParseError {
                message: format!("Failed to deserialize response: {}", e),
            })?;
        Ok(wrapper.data)
    }

    async fn execute_query<V: Serialize>(
        &self,
        query: &'static str,
        variables: Option<&V>,
    ) -> Result<Value, AniListError> {
        retry_with_backoff(
            || async { self.raw_query(query, variables).await },
            self.inner.retry_config,
        )
        .await
    }

    async fn raw_query<V: Serialize>(
        &self,
        query: &'static str,
        variables: Option<&V>,
    ) -> Result<Value, AniListError> {
        let body = RequestBody { query, variables };

        let mut request = self
            .inner
            .client
            .post(self.inner.base_url.as_ref())
            .header("Content-Type", CONTENT_TYPE_JSON);

        if let Some(token) = &self.inner.token {
            // Preallocate the authorization header to avoid repeated allocations
            let mut auth_header = String::with_capacity(BEARER_PREFIX.len() + token.len());
            auth_header.push_str(BEARER_PREFIX);
            auth_header.push_str(token);
            request = request.header("Authorization", auth_header);
        }

        #[cfg(feature = "tracing")]
        let span = tracing::info_span!("ani_list_request");

        #[cfg(feature = "tracing")]
        use tracing::Instrument;

        let response_fut = async {
            #[cfg(feature = "tracing")]
            {
                let variables_str = variables
                    .map(|v| serde_json::to_string_pretty(v).unwrap_or_else(|_| "{}".to_string()))
                    .unwrap_or_else(|| "None".to_string());
                let full_name = std::any::type_name::<V>();
                let type_name = full_name.split("::").last().unwrap_or(full_name);
                tracing::info!(
                    "Sending AniList request:\nURL: {}\nVariables Struct: {}\nVariables Payload:\n{}",
                    self.inner.base_url,
                    type_name,
                    variables_str
                );
            }

            let response = request.json(&body).send().await?;
            let _status = response.status();
            crate::trace_info!(status = _status.as_u16(), "HTTP response received");
            self.handle_response(response).await
        };

        #[cfg(feature = "tracing")]
        {
            response_fut.instrument(span).await
        }
        #[cfg(not(feature = "tracing"))]
        {
            response_fut.await
        }
    }
    async fn handle_response(&self, response: Response) -> Result<Value, AniListError> {
        let status = response.status();
        if status.is_success() {
            let json: Value = response.json().await?;
            #[cfg(feature = "tracing")]
            {
                let pretty_response =
                    serde_json::to_string_pretty(&json).unwrap_or_else(|_| "{}".to_string());
                crate::trace_info!("Response body received:\n{}", pretty_response);
            }
            let res = self.handle_graphql_errors(json);
            if let Err(ref _e) = res {
                crate::trace_error!(error = %_e, "GraphQL query returned errors");
            }
            res
        } else {
            let _err = self.handle_http_error(status, response).await;
            crate::trace_error!(error = %_err, status = status.as_u16(), "HTTP request failed");
            Err(_err)
        }
    }

    async fn handle_http_error(&self, status: StatusCode, response: Response) -> AniListError {
        if status.as_u16() == 429 {
            return self.parse_rate_limit_error(response);
        }
        let body = response
            .text()
            .await
            .unwrap_or_else(|_| "Unknown Error".to_string());
        if status.as_u16() == 503 || crate::errors::detect_maintenance(&body) {
            return AniListError::Maintenance { message: body };
        }
        match status.as_u16() {
            400 => {
                if let Ok(json) = serde_json::from_str::<Value>(&body)
                    && json.get("errors").is_some()
                    && let Err(graphql_err) = self.handle_graphql_errors(json)
                {
                    return graphql_err;
                }
                AniListError::BadRequest { message: body }
            }
            401 => AniListError::AuthenticationRequired,
            403 => AniListError::AccessDenied,
            404 => AniListError::NotFound,
            500..=599 => AniListError::ServerError {
                status: status.as_u16(),
                message: body,
            },
            _ => AniListError::ServerError {
                status: status.as_u16(),
                message: body,
            },
        }
    }

    fn parse_rate_limit_error(&self, response: Response) -> AniListError {
        let headers = response.headers();
        let get_header = |key: &str| headers.get(key).and_then(|v| v.to_str().ok());

        if let (Some(limit), Some(remaining), Some(reset), Some(retry_after)) = (
            get_header("X-RateLimit-Limit").and_then(|s| s.parse().ok()),
            get_header("X-RateLimit-Remaining").and_then(|s| s.parse().ok()),
            get_header("X-RateLimit-Reset").and_then(|s| s.parse().ok()),
            get_header("Retry-After").and_then(|s| s.parse().ok()),
        ) {
            AniListError::RateLimit {
                limit,
                remaining,
                reset_at: reset,
                retry_after,
            }
        } else {
            AniListError::RateLimitSimple
        }
    }

    fn handle_graphql_errors(&self, json: Value) -> Result<Value, AniListError> {
        if let Some(errors) = json.get("errors") {
            let error_message = if let Some(arr) = errors.as_array() {
                // Preallocate capacity for the joined string
                let estimated_size: usize = arr
                    .iter()
                    .map(|e| {
                        e.get("message")
                            .and_then(|m| m.as_str())
                            .map(|s| s.len() + 2)
                            .unwrap_or(15)
                    })
                    .sum();
                let mut result = String::with_capacity(estimated_size);
                for (i, e) in arr.iter().enumerate() {
                    if i > 0 {
                        result.push_str(", ");
                    }
                    result.push_str(
                        e.get("message")
                            .and_then(|m| m.as_str())
                            .unwrap_or("Unknown error"),
                    );
                }
                result
            } else {
                errors.to_string()
            };
            // Use bytes comparison for case-insensitive check to avoid allocation
            let lower = error_message.to_lowercase();
            if lower.contains("rate limit") || lower.contains("too many requests") {
                return Err(AniListError::BurstLimit);
            }
            if crate::errors::detect_maintenance(&error_message) {
                return Err(AniListError::Maintenance {
                    message: error_message,
                });
            }
            let parsed_errors: Vec<crate::errors::GraphQLErrorItem> =
                serde_json::from_value(errors.clone()).unwrap_or_default();
            Err(AniListError::GraphQL {
                message: error_message,
                errors: parsed_errors,
            })
        } else {
            Ok(json)
        }
    }
}

/// Optimized request body structure that avoids HashMap allocation
#[derive(Serialize)]
struct RequestBody<'a, V: Serialize> {
    query: &'static str,
    #[serde(skip_serializing_if = "Option::is_none")]
    variables: Option<&'a V>,
}

impl Default for AniListClient {
    fn default() -> Self {
        Self::new()
    }
}

/// A builder for configuring and creating an `AniListClient`.
#[derive(Default, Debug, Clone)]
pub struct AniListClientBuilder {
    token: Option<String>,
    retry_config: Option<RetryConfig>,
    base_url: Option<String>,
    timeout: Option<Duration>,
    headers: HeaderMap,
}

impl AniListClientBuilder {
    /// Creates a new builder with default settings.
    #[must_use]
    pub fn new() -> Self {
        Self {
            token: None,
            retry_config: None,
            base_url: None,
            timeout: None,
            headers: HeaderMap::new(),
        }
    }

    /// Sets the authentication token.
    #[must_use]
    pub fn token(mut self, token: impl Into<String>) -> Self {
        self.token = Some(token.into());
        self
    }

    /// Sets the retry configuration.
    #[must_use]
    pub fn retry_config(mut self, config: RetryConfig) -> Self {
        self.retry_config = Some(config);
        self
    }

    /// Sets the base URL.
    #[must_use]
    pub fn base_url(mut self, base_url: impl Into<String>) -> Self {
        self.base_url = Some(base_url.into());
        self
    }

    /// Sets the request timeout.
    #[must_use]
    pub fn timeout(mut self, timeout: Duration) -> Self {
        self.timeout = Some(timeout);
        self
    }

    /// Adds a custom header.
    #[must_use]
    pub fn header(mut self, name: HeaderName, value: HeaderValue) -> Self {
        self.headers.insert(name, value);
        self
    }

    /// Adds custom headers.
    #[must_use]
    pub fn headers(mut self, headers: HeaderMap) -> Self {
        self.headers.extend(headers);
        self
    }

    /// Builds and returns the configured `AniListClient`.
    ///
    /// # Panics
    ///
    /// Panics if the reqwest client fails to build.
    #[must_use]
    pub fn build(self) -> AniListClient {
        let mut client_builder = Client::builder()
            .user_agent(USER_AGENT)
            .pool_max_idle_per_host(10)
            .tcp_nodelay(true);

        if let Some(timeout) = self.timeout {
            client_builder = client_builder.timeout(timeout);
        } else {
            client_builder = client_builder.timeout(Duration::from_secs(30));
        }

        if !self.headers.is_empty() {
            client_builder = client_builder.default_headers(self.headers);
        }

        let client = client_builder.build().expect("Failed to build HTTP client");

        AniListClient {
            inner: Arc::new(ClientInner {
                client,
                token: self.token,
                retry_config: self.retry_config.unwrap_or_default(),
                base_url: self
                    .base_url
                    .map(Cow::Owned)
                    .unwrap_or_else(|| Cow::Borrowed(ANILIST_API_URL)),
            }),
        }
    }
}