-
Notifications
You must be signed in to change notification settings - Fork 13
/
crunchyroll.rs
982 lines (885 loc) · 38 KB
/
crunchyroll.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
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
//! Builder and access to the [`Crunchyroll`] struct which is required to make any action.
use crate::enum_values;
use reqwest::Client;
use std::sync::Arc;
enum_values! {
/// Enum of supported languages by Crunchyroll.
/// Crunchyroll lists the available languages in the following api results:
/// - <https://static.crunchyroll.com/config/i18n/v3/audio_languages.json>
/// - <https://static.crunchyroll.com/config/i18n/v3/timed_text_languages.json>
#[allow(non_camel_case_types)]
#[derive(Hash, Ord, PartialOrd)]
pub enum Locale {
ar_ME = "ar-ME"
ar_SA = "ar-SA"
ca_ES = "ca-ES"
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"
id_ID = "id-ID"
it_IT = "it-IT"
ja_JP = "ja-JP"
ko_KR = "ko-KR"
ms_MY = "ms-MY"
pl_PL = "pl-PL"
pt_BR = "pt-BR"
pt_PT = "pt-PT"
ru_RU = "ru-RU"
ta_IN = "ta-IN"
te_IN = "te-IN"
th_TH = "th-TH"
tr_TR = "tr-TR"
vi_VN = "vi-VN"
zh_CN = "zh-CN"
zh_HK = "zh_HK"
zh_TW = "zh-TW"
}
}
impl Locale {
pub fn all() -> Vec<Locale> {
vec![
Locale::ar_ME,
Locale::ar_SA,
Locale::ca_ES,
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::id_ID,
Locale::it_IT,
Locale::ja_JP,
Locale::ko_KR,
Locale::ms_MY,
Locale::pl_PL,
Locale::pt_BR,
Locale::pt_PT,
Locale::ru_RU,
Locale::ta_IN,
Locale::te_IN,
Locale::th_TH,
Locale::tr_TR,
Locale::vi_VN,
Locale::zh_CN,
Locale::zh_CN,
Locale::zh_TW,
]
}
pub fn to_human_readable(&self) -> String {
match self {
Locale::ar_ME => "Arabic",
Locale::ar_SA => "Arabic (Saudi Arabia)",
Locale::ca_ES => "Catalan",
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::id_ID => "Indonesian",
Locale::it_IT => "Italian",
Locale::ja_JP => "Japanese",
Locale::ko_KR => "Korean",
Locale::ms_MY => "Malay",
Locale::pl_PL => "Polish",
Locale::pt_BR => "Portuguese (Brazil)",
Locale::pt_PT => "Portuguese (Europe)",
Locale::ru_RU => "Russian",
Locale::ta_IN => "Tamil",
Locale::te_IN => "Telugu",
Locale::th_TH => "Thai",
Locale::tr_TR => "Turkish",
Locale::vi_VN => "Vietnamese",
Locale::zh_CN => "Chinese (China)",
Locale::zh_HK => "Chinese (Cantonese)",
Locale::zh_TW => "Chinese (Mandarin)",
Locale::Custom(custom) => custom.as_str(),
}
.to_string()
}
}
enum_values! {
/// Maturity rating.
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 async fn premium(&self) -> bool {
self.executor.premium().await
}
/// 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.read().await.session_token.clone()
}
}
mod auth {
use crate::error::{check_request, Error};
use crate::{Crunchyroll, Locale, Request, Result};
use chrono::{DateTime, Duration, Utc};
use reqwest::{header, Client, ClientBuilder, IntoUrl, RequestBuilder};
use serde::de::DeserializeOwned;
use serde::{Deserialize, Serialize};
use std::ops::Add;
use std::sync::Arc;
use tokio::sync::RwLock;
/// 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>,
/// Is [`None`] if generated via [`Executor::auth_anonymously`].
profile_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) preferred_audio_locale: Option<Locale>,
pub(crate) bucket: String,
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>,
pub(crate) device_id: Option<String>,
pub(crate) device_type: Option<String>,
}
#[cfg(feature = "experimental-stabilizations")]
/// Contains which fixes should be used to make the api more reliable as Crunchyroll does weird
/// stuff / delivers incorrect results.
#[derive(Clone, Debug)]
pub(crate) struct ExecutorFixes {
pub(crate) locale_name_parsing: bool,
pub(crate) season_number: bool,
}
/// Internal struct to execute all request with.
#[derive(Debug)]
pub struct Executor {
pub(crate) client: Client,
/// Must be a [`RwLock`] because `Executor` is always passed inside `Arc` which does not
/// allow direct changes to the struct.
pub(crate) config: RwLock<ExecutorConfig>,
pub(crate) details: ExecutorDetails,
#[cfg(feature = "tower")]
pub(crate) middleware: Option<tokio::sync::Mutex<crate::internal::tower::Middleware>>,
#[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.write().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,
refresh_token,
self.details.device_id.clone(),
self.details.device_type.clone(),
)
.await?
}
SessionToken::EtpRt(etp_rt) => {
Executor::auth_with_etp_rt(
&self.client,
etp_rt,
self.details.device_id.clone(),
self.details.device_type.clone(),
)
.await?
}
SessionToken::Anonymous => Executor::auth_anonymously(&self.client).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,
req,
#[cfg(feature = "tower")]
self.middleware.as_ref(),
)
.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)
}
pub(crate) async fn premium(&self) -> bool {
let executor_config = self.config.read().await;
if matches!(executor_config.session_token, SessionToken::Anonymous) {
return false;
}
#[derive(Deserialize)]
struct AccessTokenClaims {
benefits: Vec<String>,
}
let token = executor_config.access_token.as_str();
let key = jsonwebtoken::DecodingKey::from_rsa_components("", "").unwrap();
let mut validation = jsonwebtoken::Validation::default();
validation.insecure_disable_signature_validation();
jsonwebtoken::decode::<AccessTokenClaims>(token, &key, &validation)
.unwrap()
.claims
.benefits
.contains(&"cr_premium".to_string())
}
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,
email: String,
password: String,
device_id: Option<String>,
device_type: Option<String>,
) -> Result<AuthResponse> {
let endpoint = "https://www.crunchyroll.com/auth/v1/token";
let mut body = vec![
("username", email.as_ref()),
("password", password.as_ref()),
("grant_type", "password"),
("scope", "offline_access"),
];
if let Some(d_id) = &device_id {
body.extend_from_slice(&[("device_id", d_id)])
}
if let Some(d_type) = &device_type {
body.extend_from_slice(&[("device_type", d_type)])
}
let resp = client.post(endpoint)
.header(header::AUTHORIZATION, "Basic b2VkYXJteHN0bGgxanZhd2ltbnE6OWxFaHZIWkpEMzJqdVY1ZFc5Vk9TNTdkb3BkSnBnbzE=")
.header(header::CONTENT_TYPE, "application/x-www-form-urlencoded")
.body(serde_urlencoded::to_string(body).unwrap())
.send()
.await?;
check_request(endpoint.to_string(), resp).await
}
async fn auth_with_refresh_token(
client: &Client,
refresh_token: String,
device_id: Option<String>,
device_type: Option<String>,
) -> Result<AuthResponse> {
let endpoint = "https://www.crunchyroll.com/auth/v1/token";
let mut body = vec![
("refresh_token", refresh_token.as_str()),
("grant_type", "refresh_token"),
("scope", "offline_access"),
];
if let Some(d_id) = &device_id {
body.extend_from_slice(&[("device_id", d_id)])
}
if let Some(d_type) = &device_type {
body.extend_from_slice(&[("device_type", d_type)])
}
let resp = client.post(endpoint)
.header(header::AUTHORIZATION, "Basic b2VkYXJteHN0bGgxanZhd2ltbnE6OWxFaHZIWkpEMzJqdVY1ZFc5Vk9TNTdkb3BkSnBnbzE=")
.header(header::CONTENT_TYPE, "application/x-www-form-urlencoded")
.body(serde_urlencoded::to_string(body).unwrap())
.send()
.await?;
check_request(endpoint.to_string(), resp).await
}
async fn auth_with_etp_rt(
client: &Client,
etp_rt: String,
device_id: Option<String>,
device_type: Option<String>,
) -> Result<AuthResponse> {
let endpoint = "https://www.crunchyroll.com/auth/v1/token";
let mut body = vec![("grant_type", "etp_rt_cookie"), ("scope", "offline_access")];
if let Some(d_id) = &device_id {
body.extend_from_slice(&[("device_id", d_id)])
}
if let Some(d_type) = &device_type {
body.extend_from_slice(&[("device_type", d_type)])
}
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(body).unwrap())
.send()
.await?;
check_request(endpoint.to_string(), resp).await
}
}
impl Default for Executor {
fn default() -> Self {
Self {
client: Client::new(),
config: RwLock::new(ExecutorConfig {
token_type: "".to_string(),
access_token: "".to_string(),
session_token: SessionToken::RefreshToken("".into()),
session_expire: Default::default(),
}),
details: ExecutorDetails {
locale: Default::default(),
preferred_audio_locale: None,
bucket: "".to_string(),
signature: "".to_string(),
policy: "".to_string(),
key_pair_id: "".to_string(),
account_id: Ok("".to_string()),
device_id: None,
device_type: None,
},
#[cfg(feature = "tower")]
middleware: None,
#[cfg(feature = "experimental-stabilizations")]
fixes: ExecutorFixes {
locale_name_parsing: false,
season_number: 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_locale_query(self) -> ExecutorRequestBuilder {
let locale = self.executor.details.locale.clone();
self.query(&[("locale", locale)])
}
pub(crate) fn apply_preferred_audio_locale_query(self) -> ExecutorRequestBuilder {
if let Some(locale) = self.executor.details.preferred_audio_locale.clone() {
self.query(&[("preferred_audio_language", locale)])
} else {
self
}
}
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>> {
#[cfg(feature = "tower")]
if let Some(middleware) = &self.executor.middleware {
return Ok(middleware
.lock()
.await
.call(self.builder.build()?)
.await?
.bytes()
.await?
.to_vec());
}
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 {
client: Client,
locale: Locale,
preferred_audio_locale: Option<Locale>,
device_identifier: Option<(String, String)>,
#[cfg(feature = "tower")]
middleware: Option<tokio::sync::Mutex<crate::internal::tower::Middleware>>,
#[cfg(feature = "experimental-stabilizations")]
fixes: ExecutorFixes,
}
impl Default for CrunchyrollBuilder {
fn default() -> Self {
Self {
client: CrunchyrollBuilder::predefined_client_builder()
.build()
.unwrap(),
locale: Locale::en_US,
preferred_audio_locale: None,
device_identifier: None,
#[cfg(feature = "tower")]
middleware: None,
#[cfg(feature = "experimental-stabilizations")]
fixes: ExecutorFixes {
locale_name_parsing: false,
season_number: false,
},
}
}
}
impl CrunchyrollBuilder {
/// Return a [`ClientBuilder`] which has all required configurations necessary to send
/// successful requests to Crunchyroll, applied (most of the time; sometimes Crunchyroll has
/// fluctuations that requests doesn't work for a specific amount of time and after that
/// amount everything goes back to normal and works as it should). You can use this builder
/// to configure the behavior of the download client. Use [`CrunchyrollBuilder::client`] or
/// to set your built client.
pub fn predefined_client_builder() -> ClientBuilder {
let mut root_store = rustls::RootCertStore::empty();
root_store.add_trust_anchors(webpki_roots::TLS_SERVER_ROOTS.iter().map(|ta| {
rustls::OwnedTrustAnchor::from_subject_spki_name_constraints(
ta.subject.to_vec(),
ta.subject_public_key_info.to_vec(),
ta.name_constraints.clone().map(|nc| nc.to_vec()),
)
}));
let tls_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();
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/114.0.0.0 Safari/537.36 Edg/114.0.1823.67a")
.use_preconfigured_tls(tls_config)
}
/// Set a custom client that will be used in all api requests.
/// It is recommended to use the client builder from
/// [`CrunchyrollBuilder::predefined_client_builder`] as base as it has some configurations
/// which may be needed to make successful requests to Crunchyroll.
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 the audio language of media (like episodes) which should be returned when querying
/// by any other method than the direct media id. For example, if the preferred audio locale
/// were set to [`Locale::en_US`], the seasons queried with [`crate::Series::seasons`] would
/// likely have [`Locale::en_US`] as their audio locale. This might not always work on all
/// endpoints as Crunchyroll does Crunchyroll things (e.g. it seems to have no effect when
/// changing the locale and using [`Crunchyroll::query`]).
pub fn preferred_audio_locale(
mut self,
preferred_audio_locale: Locale,
) -> CrunchyrollBuilder {
self.preferred_audio_locale = Some(preferred_audio_locale);
self
}
/// Set a identifier for the session which will be opened. `device_id` is usually a random
/// UUID, `device_type` a description of the device which issues the session, e.g. `Chrome
/// on Windows` or `iPhone 15`.
pub fn device_identifier(
mut self,
device_id: String,
device_type: String,
) -> CrunchyrollBuilder {
self.device_identifier = Some((device_id, device_type));
self
}
/// Adds a [tower](https://docs.rs/tower/latest/tower/) middleware which is called on every
/// request.
#[cfg(feature = "tower")]
#[cfg_attr(docsrs, doc(cfg(feature = "tower")))]
pub fn middleware<F, S>(mut self, service: S) -> CrunchyrollBuilder
where
F: std::future::Future<Output = Result<reqwest::Response, Error>> + Send + 'static,
S: tower_service::Service<
reqwest::Request,
Response = reqwest::Response,
Error = Error,
Future = F,
> + Send
+ 'static,
{
self.middleware = Some(tokio::sync::Mutex::new(
crate::internal::tower::Middleware::new(service),
));
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::Series`]. Whenever a request
/// is made which returns [`crate::Series`], internally [`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")]
#[cfg_attr(docsrs, doc(cfg(feature = "experimental-stabilizations")))]
pub fn stabilization_locales(mut self, enable: bool) -> CrunchyrollBuilder {
self.fixes.locale_name_parsing = enable;
self
}
/// Set the season number of seasons by parsing a string which is delivered via the api too
/// and looks to be more reliable than the actual integer season number Crunchyroll provides.
#[cfg(feature = "experimental-stabilizations")]
#[cfg_attr(docsrs, doc(cfg(feature = "experimental-stabilizations")))]
pub fn stabilization_season_number(mut self, enable: bool) -> CrunchyrollBuilder {
self.fixes.season_number = 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> {
self.pre_login().await?;
let login_response = Executor::auth_anonymously(&self.client).await?;
let session_token = SessionToken::Anonymous;
self.post_login(login_response, session_token).await
}
/// Logs in with credentials (email and password) and returns a new `Crunchyroll` instance.
pub async fn login_with_credentials<S: AsRef<str>>(
self,
email: S,
password: S,
) -> Result<Crunchyroll> {
self.pre_login().await?;
let login_response = Executor::auth_with_credentials(
&self.client,
email.as_ref().to_string(),
password.as_ref().to_string(),
self.device_identifier
.as_ref()
.map(|(device_id, _)| device_id.clone()),
self.device_identifier
.as_ref()
.map(|(_, device_type)| device_type.clone()),
)
.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> {
self.pre_login().await?;
let login_response = Executor::auth_with_refresh_token(
&self.client,
refresh_token.as_ref().to_string(),
self.device_identifier
.as_ref()
.map(|(device_id, _)| device_id.clone()),
self.device_identifier
.as_ref()
.map(|(_, device_type)| device_type.clone()),
)
.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> {
self.pre_login().await?;
let login_response = Executor::auth_with_etp_rt(
&self.client,
etp_rt.as_ref().to_string(),
self.device_identifier
.as_ref()
.map(|(device_id, _)| device_id.clone()),
self.device_identifier
.as_ref()
.map(|(_, device_type)| device_type.clone()),
)
.await?;
let session_token = SessionToken::EtpRt(login_response.refresh_token.clone().unwrap());
self.post_login(login_response, session_token).await
}
async fn pre_login(&self) -> Result<()> {
// Request the index page to set cookies which are required to bypass the cloudflare bot
// check
self.client
.get("https://www.crunchyroll.com")
.send()
.await?;
Ok(())
}
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,
index_req,
#[cfg(feature = "tower")]
self.middleware.as_ref(),
)
.await?;
let crunchy = Crunchyroll {
executor: Arc::new(Executor {
client: self.client,
config: RwLock::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,
preferred_audio_locale: self.preferred_audio_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(),
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(|| {
Error::Authentication {
message: "Login with a user account to use this function"
.to_string(),
}
}),
device_id: self
.device_identifier
.as_ref()
.map(|(device_id, _)| device_id.clone()),
device_type: self
.device_identifier
.as_ref()
.map(|(_, device_type)| device_type.clone()),
},
#[cfg(feature = "tower")]
middleware: self.middleware,
#[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,
#[cfg(feature = "tower")] middleware: Option<
&tokio::sync::Mutex<crate::internal::tower::Middleware>,
>,
) -> Result<T> {
let built_req = req.build()?;
let url = built_req.url().to_string();
#[cfg(not(feature = "tower"))]
let resp = client.execute(built_req).await?;
#[cfg(feature = "tower")]
let resp = {
use std::ops::DerefMut;
if let Some(middleware) = middleware {
middleware.lock().await.deref_mut().call(built_req).await?
} else {
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| Error::Decode {
message: format!("{} at {}:{}", e, e.line(), e.column()),
content: value.to_string().into_bytes(),
url,
})
}
}
/// 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("__") {
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};