crunchyroll-rs 0.2.5

Pure Rust implementation of the crunchyroll 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
use crate::enum_values;
use reqwest::Client;
use std::sync::Arc;

enum_values! {
    /// Enum of supported languages by Crunchyroll.
    #[allow(non_camel_case_types)]
    #[derive(Hash, Ord, PartialOrd)]
    pub enum Locale {
        ar_ME = "ar-ME"
        ar_SA = "ar-SA"
        de_DE = "de-DE"
        en_IN = "en-IN"
        en_US = "en-US"
        es_419 = "es-419"
        es_ES = "es-ES"
        es_LA = "es-LA"
        fr_FR = "fr-FR"
        hi_IN = "hi-IN"
        it_IT = "it-IT"
        ja_JP = "ja-JP"
        pt_BR = "pt-BR"
        pt_PT = "pt-PT"
        ru_RU = "ru-RU"
        zh_CN = "zh-CN"
    }
}

impl Locale {
    pub fn all() -> Vec<Locale> {
        vec![
            Locale::ar_ME,
            Locale::ar_SA,
            Locale::de_DE,
            Locale::en_IN,
            Locale::en_US,
            Locale::es_419,
            Locale::es_ES,
            Locale::es_LA,
            Locale::fr_FR,
            Locale::hi_IN,
            Locale::it_IT,
            Locale::ja_JP,
            Locale::pt_BR,
            Locale::pt_PT,
            Locale::ru_RU,
            Locale::zh_CN,
        ]
    }

    pub fn to_human_readable(&self) -> String {
        match self {
            Locale::ar_ME => "Arabic",
            Locale::ar_SA => "Arabic (Saudi Arabia)",
            Locale::de_DE => "German",
            Locale::en_IN => "English (India)",
            Locale::en_US => "English (US)",
            Locale::es_419 | Locale::es_LA => "Spanish (Latin America)",
            Locale::es_ES => "Spanish (European)",
            Locale::fr_FR => "French",
            Locale::hi_IN => "Hindi",
            Locale::it_IT => "Italian",
            Locale::ja_JP => "Japanese",
            Locale::pt_BR => "Portuguese (Brazil)",
            Locale::pt_PT => "Portuguese (Europe)",
            Locale::ru_RU => "Russian",
            Locale::zh_CN => "Chinese (China)",
            Locale::Custom(custom) => custom.as_str(),
        }
        .to_string()
    }
}

enum_values! {
    pub enum MaturityRating {
        NotMature = "M2"
        Mature = "M3"
    }
}

/// Starting point of this whole library.
#[derive(Clone, Debug)]
pub struct Crunchyroll {
    pub(crate) executor: Arc<Executor>,
}

impl Crunchyroll {
    pub fn builder() -> CrunchyrollBuilder {
        CrunchyrollBuilder::default()
    }

    /// Return the (cloned) [`Client`] which is internally used to make requests.
    pub fn client(&self) -> Client {
        self.executor.client.clone()
    }

    /// Check if the current used account has premium.
    pub fn premium(&self) -> bool {
        self.executor.details.premium
    }

    /// Return the current session token. It can be used to log-in later with
    /// [`CrunchyrollBuilder::login_with_refresh_token`] or [`CrunchyrollBuilder::login_with_etp_rt`].
    pub async fn session_token(&self) -> SessionToken {
        self.executor.config.lock().await.session_token.clone()
    }
}

mod auth {
    use crate::error::{check_request, CrunchyrollError, CrunchyrollErrorContext};
    use crate::{Crunchyroll, Locale, Request, Result};
    use chrono::{DateTime, Duration, Utc};
    use http::header;
    use reqwest::{Client, IntoUrl, RequestBuilder};
    use serde::de::DeserializeOwned;
    use serde::{Deserialize, Serialize};
    use std::ops::Add;
    use std::sync::Arc;
    use tokio::sync::Mutex;

    /// Stores if the refresh token or etp-rt cookie was used for login. Extract the token and use
    /// it as argument in their associated function ([`CrunchyrollBuilder::login_with_refresh_token`]
    /// or [`CrunchyrollBuilder::login_with_etp_rt`]) if you want to re-login into the account again.
    #[derive(Clone, Debug)]
    pub enum SessionToken {
        RefreshToken(String),
        EtpRt(String),
        Anonymous,
    }

    #[derive(Debug, Default, Deserialize)]
    #[cfg_attr(feature = "__test_strict", serde(deny_unknown_fields))]
    #[cfg_attr(not(feature = "__test_strict"), serde(default))]
    #[allow(dead_code)]
    struct AuthResponse {
        access_token: String,
        /// Is [`None`] if generated via [`Executor::auth_anonymously`].
        refresh_token: Option<String>,
        expires_in: i32,
        token_type: String,
        scope: String,
        country: String,
        /// Is [`None`] if generated via [`Executor::auth_anonymously`].
        account_id: Option<String>,
    }

    #[derive(Clone, Debug)]
    pub(crate) struct ExecutorConfig {
        pub(crate) token_type: String,
        pub(crate) access_token: String,
        pub(crate) session_token: SessionToken,
        pub(crate) session_expire: DateTime<Utc>,
    }

    #[allow(dead_code)]
    #[derive(Clone, Debug)]
    pub(crate) struct ExecutorDetails {
        pub(crate) locale: Locale,

        pub(crate) bucket: String,

        pub(crate) premium: bool,
        pub(crate) signature: String,
        pub(crate) policy: String,
        pub(crate) key_pair_id: String,
        /// The account id is wrapped in a [`Result`] since [`Executor::auth_anonymously`] /
        /// [`CrunchyrollBuilder::login_anonymously`] doesn't return an account id and to prevent
        /// writing error messages multiple times in functions which require the account id to be
        /// set they can just get the id or return the fix set error message.
        pub(crate) account_id: Result<String>,
    }

    /// Contains which fixes should be used to make the api more reliable as Crunchyroll does weird
    /// stuff / delivers incorrect results.
    #[derive(Clone, Debug)]
    #[cfg(feature = "experimental-stabilizations")]
    pub(crate) struct ExecutorFixes {
        pub(crate) locale_name_parsing: bool,
    }

    /// Internal struct to execute all request with.
    #[derive(Debug)]
    pub struct Executor {
        pub(crate) client: Client,

        /// Must be a mutex because `Executor` is always passed inside of `Arc` which does not allow
        /// direct changes to the struct.
        pub(crate) config: Mutex<ExecutorConfig>,
        pub(crate) details: ExecutorDetails,

        #[cfg(feature = "experimental-stabilizations")]
        pub(crate) fixes: ExecutorFixes,
    }

    impl Executor {
        pub(crate) fn get<U: IntoUrl>(self: &Arc<Self>, url: U) -> ExecutorRequestBuilder {
            ExecutorRequestBuilder::new(self.clone(), self.client.get(url))
        }

        pub(crate) fn post<U: IntoUrl>(self: &Arc<Self>, url: U) -> ExecutorRequestBuilder {
            ExecutorRequestBuilder::new(self.clone(), self.client.post(url))
        }

        pub(crate) fn put<U: IntoUrl>(self: &Arc<Self>, url: U) -> ExecutorRequestBuilder {
            ExecutorRequestBuilder::new(self.clone(), self.client.put(url))
        }

        pub(crate) fn patch<U: IntoUrl>(self: &Arc<Self>, url: U) -> ExecutorRequestBuilder {
            ExecutorRequestBuilder::new(self.clone(), self.client.patch(url))
        }

        pub(crate) fn delete<U: IntoUrl>(self: &Arc<Self>, url: U) -> ExecutorRequestBuilder {
            ExecutorRequestBuilder::new(self.clone(), self.client.delete(url))
        }

        pub(crate) async fn request<T: Request + DeserializeOwned>(
            self: &Arc<Self>,
            mut req: RequestBuilder,
        ) -> Result<T> {
            let mut config = self.config.lock().await;
            if config.session_expire <= Utc::now() {
                let login_response = match config.session_token.clone() {
                    SessionToken::RefreshToken(refresh_token) => {
                        Executor::auth_with_refresh_token(self.client.clone(), refresh_token)
                            .await?
                    }
                    SessionToken::EtpRt(etp_rt) => {
                        Executor::auth_with_etp_rt(self.client.clone(), etp_rt).await?
                    }
                    SessionToken::Anonymous => {
                        Executor::auth_anonymously(self.client.clone()).await?
                    }
                };

                let mut new_config = config.clone();
                new_config.token_type = login_response.token_type;
                new_config.access_token = login_response.access_token;
                new_config.session_token = match new_config.session_token {
                    SessionToken::RefreshToken(_) => {
                        SessionToken::RefreshToken(login_response.refresh_token.unwrap())
                    }
                    SessionToken::EtpRt(_) => {
                        SessionToken::EtpRt(login_response.refresh_token.unwrap())
                    }
                    SessionToken::Anonymous => SessionToken::Anonymous,
                };
                new_config.session_expire =
                    Utc::now().add(Duration::seconds(login_response.expires_in as i64));

                *config = new_config;
            }

            req = req.header(
                header::AUTHORIZATION,
                format!("Bearer {}", config.access_token),
            );
            req = req.header(header::CONTENT_TYPE, "application/json");

            let mut resp: T = request(self.client.clone(), req).await?;

            // drop config here explicitly as `__set_executor` can call this function recursively
            // which would lead to a deadlock
            drop(config);

            resp.__set_executor(self.clone()).await;

            Ok(resp)
        }

        async fn auth_anonymously(client: Client) -> Result<AuthResponse> {
            let endpoint = "https://www.crunchyroll.com/auth/v1/token";
            let resp = client
                .post(endpoint)
                .header(header::AUTHORIZATION, "Basic Y3Jfd2ViOg==")
                .header(header::CONTENT_TYPE, "application/x-www-form-urlencoded")
                .body(
                    serde_urlencoded::to_string([
                        ("grant_type", "client_id"),
                        ("scope", "offline_access"),
                    ])
                    .unwrap(),
                )
                .send()
                .await?;

            check_request(endpoint.to_string(), resp).await
        }

        async fn auth_with_credentials(
            client: Client,
            user: String,
            password: String,
        ) -> Result<AuthResponse> {
            let endpoint = "https://www.crunchyroll.com/auth/v1/token";
            let resp = client.post(endpoint)
                .header(header::AUTHORIZATION, "Basic aHJobzlxM2F3dnNrMjJ1LXRzNWE6cHROOURteXRBU2Z6QjZvbXVsSzh6cUxzYTczVE1TY1k=")
                .header(header::CONTENT_TYPE, "application/x-www-form-urlencoded")
                .body(
                    serde_urlencoded::to_string([
                        ("username", user.as_ref()),
                        ("password", password.as_ref()),
                        ("grant_type", "password"),
                        ("scope", "offline_access"),
                    ])
                    .unwrap(),
                )
                .send()
                .await?;

            check_request(endpoint.to_string(), resp).await
        }

        async fn auth_with_refresh_token(
            client: Client,
            refresh_token: String,
        ) -> Result<AuthResponse> {
            let endpoint = "https://www.crunchyroll.com/auth/v1/token";
            let resp = client.post(endpoint)
                .header(header::AUTHORIZATION, "Basic aHJobzlxM2F3dnNrMjJ1LXRzNWE6cHROOURteXRBU2Z6QjZvbXVsSzh6cUxzYTczVE1TY1k=")
                .header(header::CONTENT_TYPE, "application/x-www-form-urlencoded")
                .body(
                    serde_urlencoded::to_string([
                        ("refresh_token", refresh_token.as_str()),
                        ("grant_type", "refresh_token"),
                        ("scope", "offline_access"),
                    ])
                    .unwrap(),
                )
                .send()
                .await?;

            check_request(endpoint.to_string(), resp).await
        }

        async fn auth_with_etp_rt(client: Client, etp_rt: String) -> Result<AuthResponse> {
            let endpoint = "https://www.crunchyroll.com/auth/v1/token";
            let resp = client
                .post(endpoint)
                .header(header::AUTHORIZATION, "Basic bm9haWhkZXZtXzZpeWcwYThsMHE6")
                .header(header::CONTENT_TYPE, "application/x-www-form-urlencoded")
                .header(header::COOKIE, format!("etp_rt={}", etp_rt))
                .body(
                    serde_urlencoded::to_string([
                        ("grant_type", "etp_rt_cookie"),
                        ("scope", "offline_access"),
                    ])
                    .unwrap(),
                )
                .send()
                .await?;

            check_request(endpoint.to_string(), resp).await
        }
    }

    impl Default for Executor {
        fn default() -> Self {
            Self {
                client: Client::new(),
                config: Mutex::new(ExecutorConfig {
                    token_type: "".to_string(),
                    access_token: "".to_string(),
                    session_token: SessionToken::RefreshToken("".into()),
                    session_expire: Default::default(),
                }),
                details: ExecutorDetails {
                    locale: Default::default(),
                    account_id: Ok("".to_string()),
                    bucket: "".to_string(),
                    premium: false,
                    signature: "".to_string(),
                    policy: "".to_string(),
                    key_pair_id: "".to_string(),
                },
                #[cfg(feature = "experimental-stabilizations")]
                fixes: ExecutorFixes {
                    locale_name_parsing: false,
                },
            }
        }
    }

    pub(crate) struct ExecutorRequestBuilder {
        executor: Arc<Executor>,
        builder: RequestBuilder,
    }

    impl ExecutorRequestBuilder {
        pub(crate) fn new(executor: Arc<Executor>, builder: RequestBuilder) -> Self {
            Self { executor, builder }
        }

        pub(crate) fn query<T: Serialize + ?Sized>(mut self, query: &T) -> ExecutorRequestBuilder {
            self.builder = self.builder.query(query);

            self
        }

        pub(crate) fn apply_media_query(self) -> ExecutorRequestBuilder {
            let details = self.executor.details.clone();

            self.query(&[
                ("Signature".to_string(), details.signature),
                ("Policy".to_string(), details.policy),
                ("Key-Pair-Id".to_string(), details.key_pair_id),
            ])
        }

        pub(crate) fn apply_locale_query(self) -> ExecutorRequestBuilder {
            let locale = self.executor.details.locale.clone();
            self.query(&[("locale", locale)])
        }

        pub(crate) fn json<T: Serialize + ?Sized>(mut self, json: &T) -> ExecutorRequestBuilder {
            self.builder = self.builder.json(json);

            self
        }

        pub(crate) async fn request<T: Request + DeserializeOwned>(self) -> Result<T> {
            self.executor.request(self.builder).await
        }

        pub(crate) async fn request_raw(self) -> Result<Vec<u8>> {
            Ok(self.builder.send().await?.bytes().await?.to_vec())
        }
    }

    /// A builder to construct a new [`Crunchyroll`] instance. To create it, call
    /// [`Crunchyroll::builder`].
    pub struct CrunchyrollBuilder {
        pub(crate) client: Client,
        pub(crate) locale: Locale,

        #[cfg(feature = "experimental-stabilizations")]
        pub(crate) fixes: ExecutorFixes,
    }

    impl Default for CrunchyrollBuilder {
        fn default() -> Self {
            let mut root_store = rustls::RootCertStore::empty();
            root_store.add_server_trust_anchors(webpki_roots::TLS_SERVER_ROOTS.0.iter().map(
                |ta| {
                    rustls::OwnedTrustAnchor::from_subject_spki_name_constraints(
                        ta.subject,
                        ta.spki,
                        ta.name_constraints,
                    )
                },
            ));
            let config = rustls::ClientConfig::builder()
                .with_cipher_suites(rustls::DEFAULT_CIPHER_SUITES)
                .with_kx_groups(&[&rustls::kx_group::X25519])
                .with_protocol_versions(&[&rustls::version::TLS12, &rustls::version::TLS13])
                .unwrap()
                .with_root_certificates(root_store)
                .with_no_client_auth();

            // the client needs some extra work to be created. the tls must be custom build in order
            // to bypass the cloudflare bot check crunchyroll has applied to the website
            let client = Client::builder()
                .https_only(true)
                .cookie_store(true)
                .user_agent("Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/108.0.0.0 Safari/537.36 Edg/108.0.1462.46a")
                .use_preconfigured_tls(config)
                .build()
                .unwrap();

            Self {
                client,
                locale: Locale::en_US,
                #[cfg(feature = "experimental-stabilizations")]
                fixes: ExecutorFixes {
                    locale_name_parsing: false,
                },
            }
        }
    }

    impl CrunchyrollBuilder {
        /// Set a custom client over which all request to the api are made.
        /// Is it not recommended to overwrite the default client since its need some special
        /// configurations to bypass cloudflare.
        /// See [`CrunchyrollBuilder::default`] which minimal changes must be done to create a
        /// working custom client.
        pub fn client(mut self, client: Client) -> CrunchyrollBuilder {
            self.client = client;
            self
        }

        /// Set in which languages all results which have human readable text in it should be
        /// returned.
        pub fn locale(mut self, locale: Locale) -> CrunchyrollBuilder {
            self.locale = locale;
            self
        }

        /// Set season and episode locales by parsing the season name and check if it contains
        /// any language name.
        /// Under special circumstances, this can slow down some methods as additional request must
        /// be made. Currently, this applies to [`crate::Media<crate::Series>`]. Whenever a request
        /// is made which returns [`crate::Media<crate::Series>`], internally
        /// [`crate::Media<crate::Series>::seasons`] is called for every series.
        /// See https://github.com/crunchy-labs/crunchyroll-rs/issues/3 for more information.
        #[cfg(feature = "experimental-stabilizations")]
        pub fn stabilization_locales(mut self, enable: bool) -> CrunchyrollBuilder {
            self.fixes.locale_name_parsing = enable;
            self
        }

        /// Login without an account. This is just like if you would visit crunchyroll.com without
        /// an account. Some functions won't work if logged in with this method.
        pub async fn login_anonymously(self) -> Result<Crunchyroll> {
            let login_response = Executor::auth_anonymously(self.client.clone()).await?;
            let session_token = SessionToken::Anonymous;

            self.post_login(login_response, session_token).await
        }

        /// Logs in with credentials (username or email and password) and returns a new `Crunchyroll`
        /// instance.
        pub async fn login_with_credentials<S: AsRef<str>>(
            self,
            user: S,
            password: S,
        ) -> Result<Crunchyroll> {
            let login_response = Executor::auth_with_credentials(
                self.client.clone(),
                user.as_ref().to_string(),
                password.as_ref().to_string(),
            )
            .await?;
            let session_token =
                SessionToken::RefreshToken(login_response.refresh_token.clone().unwrap());

            self.post_login(login_response, session_token).await
        }

        /// Logs in with a refresh token. This token is obtained when logging in with
        /// [`CrunchyrollBuilder::login_with_credentials`].
        /// Note: Even though the tokens used in [`CrunchyrollBuilder::login_with_refresh_token`] and
        /// [`CrunchyrollBuilder::login_with_etp_rt`] are having the same syntax, Crunchyroll
        /// internal they're different. I had issues when I tried to log in with the refresh token
        /// on [`CrunchyrollBuilder::login_with_etp_rt`] and vice versa.
        pub async fn login_with_refresh_token<S: AsRef<str>>(
            self,
            refresh_token: S,
        ) -> Result<Crunchyroll> {
            let login_response = Executor::auth_with_refresh_token(
                self.client.clone(),
                refresh_token.as_ref().to_string(),
            )
            .await?;
            let session_token =
                SessionToken::RefreshToken(login_response.refresh_token.clone().unwrap());

            self.post_login(login_response, session_token).await
        }

        /// Logs in with a etp rt cookie and returns a new `Crunchyroll` instance.
        /// This cookie can be extracted if you copy the `etp_rt` cookie from your browser.
        /// Note: Even though the tokens used in [`CrunchyrollBuilder::login_with_etp_rt`] and
        /// [`CrunchyrollBuilder::login_with_refresh_token`] are having the same syntax, Crunchyroll
        /// internal they're different. I had issues when I tried to log in with the `etp_rt`
        /// cookie on [`CrunchyrollBuilder::login_with_refresh_token`] and vice versa.
        pub async fn login_with_etp_rt<S: AsRef<str>>(self, etp_rt: S) -> Result<Crunchyroll> {
            let login_response =
                Executor::auth_with_etp_rt(self.client.clone(), etp_rt.as_ref().to_string())
                    .await?;
            let session_token = SessionToken::EtpRt(login_response.refresh_token.clone().unwrap());

            self.post_login(login_response, session_token).await
        }

        /// Logs in with a session id and returns a new `Crunchyroll` instance.
        /// The session id can be extracted if you log in to the crunchyroll website and copy the
        /// `session_id` cookie from your browser.
        /// This login method made some trouble in the past (login failed even though the session id was
        /// valid and the user logged in) and is therefore not very reliable.
        pub async fn login_with_session_id<S: AsRef<str>>(
            self,
            session_id: S,
        ) -> Result<Crunchyroll> {
            let endpoint = format!(
                "https://api.crunchyroll.com/start_session.0.json?session_id={}",
                session_id.as_ref()
            );
            let resp = self.client.get(&endpoint).send().await?;

            let etp_rt = resp.cookies().find(|c| c.name() == "etp_rt");

            if let Some(cookie) = etp_rt {
                self.login_with_etp_rt(cookie.value()).await
            } else {
                Err(CrunchyrollError::Authentication(
                    CrunchyrollErrorContext::new("invalid session id").with_url(endpoint),
                ))
            }
        }

        async fn post_login(
            self,
            login_response: AuthResponse,
            session_token: SessionToken,
        ) -> Result<Crunchyroll> {
            let index_endpoint = "https://www.crunchyroll.com/index/v2";
            #[derive(Deserialize, smart_default::SmartDefault)]
            #[cfg_attr(feature = "__test_strict", serde(deny_unknown_fields))]
            #[cfg_attr(not(feature = "__test_strict"), serde(default))]
            #[allow(dead_code)]
            struct IndexRespCms {
                bucket: String,
                #[default(DateTime::<Utc>::from(std::time::SystemTime::UNIX_EPOCH))]
                expires: DateTime<Utc>,
                key_pair_id: String,
                policy: String,
                signature: String,
            }
            #[derive(Default, Deserialize, Request)]
            #[cfg_attr(feature = "__test_strict", serde(deny_unknown_fields))]
            #[cfg_attr(not(feature = "__test_strict"), serde(default))]
            #[allow(dead_code)]
            struct IndexResp {
                cms_web: IndexRespCms,
                default_marketing_opt_in: bool,
                service_available: bool,

                #[cfg(feature = "__test_strict")]
                cms: crate::StrictValue,
                #[cfg(feature = "__test_strict")]
                cms_beta: crate::StrictValue,
            }

            let index_req = self.client.get(index_endpoint).header(
                header::AUTHORIZATION,
                format!(
                    "{} {}",
                    login_response.token_type, login_response.access_token
                ),
            );
            let index: IndexResp = request(self.client.clone(), index_req).await?;

            let crunchy = Crunchyroll {
                executor: Arc::new(Executor {
                    client: self.client,

                    config: Mutex::new(ExecutorConfig {
                        token_type: login_response.token_type,
                        access_token: login_response.access_token,
                        session_token,
                        session_expire: Utc::now()
                            .add(Duration::seconds(login_response.expires_in as i64)),
                    }),
                    details: ExecutorDetails {
                        locale: self.locale,

                        // '/' is trimmed so that urls which require it must be in .../{bucket}/... like format.
                        // this just looks cleaner
                        bucket: index
                            .cms_web
                            .bucket
                            .strip_prefix('/')
                            .unwrap_or(index.cms_web.bucket.as_str())
                            .to_string(),

                        premium: false,
                        signature: index.cms_web.signature,
                        policy: index.cms_web.policy,
                        key_pair_id: index.cms_web.key_pair_id,
                        account_id: login_response.account_id.ok_or_else(|| {
                            CrunchyrollError::Authentication(
                                "Login with a user account to use this function".into(),
                            )
                        }),
                    },
                    #[cfg(feature = "experimental-stabilizations")]
                    fixes: self.fixes,
                }),
            };

            Ok(crunchy)
        }
    }

    /// Make a request from the provided builder.
    async fn request<T: Request + DeserializeOwned>(
        client: Client,
        req: RequestBuilder,
    ) -> Result<T> {
        let built_req = req.build()?;
        let url = built_req.url().to_string();
        let resp = client.execute(built_req).await?;

        #[cfg(not(feature = "__test_strict"))]
        {
            Ok(check_request(url, resp).await?)
        }
        #[cfg(feature = "__test_strict")]
        {
            let result = check_request(url.clone(), resp).await?;

            let cleaned = clean_request(result);
            let value = serde_json::Value::deserialize(serde::de::value::MapDeserializer::new(
                cleaned.into_iter(),
            ))?;
            serde_json::from_value(value.clone()).map_err(|e| {
                CrunchyrollError::Decode(
                    CrunchyrollErrorContext::new(format!("{} at {}:{}", e, e.line(), e.column()))
                        .with_url(url)
                        .with_value(value.to_string().as_bytes()),
                )
            })
        }
    }

    /// Removes all fields which are starting and ending with `__` from a map (which is usually the
    /// response of a request). Some fields can be excluded from this process by providing the field
    /// names in `not_clean_fields`.
    #[cfg(feature = "__test_strict")]
    fn clean_request(
        mut map: serde_json::Map<String, serde_json::Value>,
    ) -> serde_json::Map<String, serde_json::Value> {
        for (key, value) in map.clone() {
            if key.starts_with("__") && key.ends_with("__") {
                if key == "__links__" {
                    let classic_crunchyroll_exception: serde_json::Map<String, serde_json::Value> =
                        serde_json::from_value(value).unwrap();
                    #[allow(clippy::if_same_then_else)]
                    if classic_crunchyroll_exception.contains_key("episode/series")
                        && classic_crunchyroll_exception.contains_key("streams")
                    {
                        // `Episode` requires the __links__ field because crunchyroll does not provide another
                        // way to obtain a stream id
                        continue;
                    } else if map
                        .get("id")
                        .unwrap_or(&serde_json::Value::default())
                        .as_str()
                        .unwrap_or("")
                        .starts_with("dynamic_collection-")
                    {
                        // `HomeFeed` has some implementations which require __links__ to be accessible
                        continue;
                    }
                }
                map.remove(key.as_str());
            } else if let Some(object) = value.as_object() {
                map.insert(
                    key,
                    serde_json::to_value(clean_request(object.clone())).unwrap(),
                );
            } else if let Some(array) = value.as_array() {
                map.insert(
                    key,
                    serde_json::to_value(clean_request_array(array.clone())).unwrap(),
                );
            }
        }
        map
    }

    #[cfg(feature = "__test_strict")]
    fn clean_request_array(mut arr: Vec<serde_json::Value>) -> Vec<serde_json::Value> {
        for (i, item) in arr.clone().iter().enumerate() {
            if let Some(object) = item.as_object() {
                arr[i] = serde_json::to_value(clean_request(object.clone())).unwrap();
            } else if let Some(array) = item.as_array() {
                arr[i] = serde_json::to_value(clean_request_array(array.clone())).unwrap();
            }
        }
        arr
    }
}

pub(crate) use auth::Executor;
pub use auth::{CrunchyrollBuilder, SessionToken};