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
//! # tosho-rbean
//!
//! ![crates.io version](https://img.shields.io/crates/v/tosho-rbean)
//!
//! A minimal asynchronous client for 小豆 (Red Bean) API.
//!
//! The following crate is used by the [`tosho`] app.
//!
//! ## Usage
//!
//! Download the [`tosho`] app, or you can utilize this crate like any other Rust crate:
//!
//! ```rust,no_run
//! use tosho_rbean::{RBClient, RBConfig, RBPlatform};
//!
//! #[tokio::main]
//! async fn main() {
//!     let config = RBConfig {
//!         token: "123".to_string(),
//!         refresh_token: "abcxyz".to_string(),
//!         platform: RBPlatform::Android,
//!     };
//!     let mut client = RBClient::new(config);
//!     // Refresh token
//!     client.refresh_token().await.unwrap();
//!     let user = client.get_user().await.unwrap();
//!     println!("{:?}", user);
//! }
//! ```
//!
//! ## Authentication
//!
//! The following sources only have one method of authentication, and that method uses your email and password.
//!
//! ```bash
//! $ tosho rb auth email password --help
//! ```
//!
//! Or, if you use the crates:
//!
//! ```rust,no_run
//! use tosho_rbean::{RBClient, RBPlatform};
//!
//! #[tokio::main]
//! async fn main() {
//!     let login_results = RBClient::login("email@test.com", "mypassword", RBPlatform::Android).await.unwrap();
//!     println!("{:?}", login_results);
//! }
//! ```
//!
//! ## Disclaimer
//!
//! This project is designed as an experiment and to create a local copy for personal use.
//! These tools will not circumvent any paywall, and you will need to purchase and own each chapter
//! with your own account to be able to make your own local copy.
//!
//! We're not responsible if your account got deactivated.
//!
//! ## License
//!
//! This project is licensed with MIT License ([LICENSE](https://github.com/noaione/tosho-mango/blob/master/LICENSE) or <http://opensource.org/licenses/MIT>)
//!
//! [`tosho`]: https://crates.io/crates/tosho

use futures_util::StreamExt;
use std::collections::HashMap;
use tokio::io::{self, AsyncWriteExt};

use crate::models::UserAccount;
pub use config::*;
use constants::{API_HOST, BASE_API, IMAGE_HOST, TOKEN_AUTH};
use models::{
    ChapterDetailsResponse, ChapterListResponse, ChapterPageDetailsResponse, HomeResponse, Manga,
    MangaListResponse, Publisher, ReadingListItem, SortOption,
};
use serde_json::json;

pub mod config;
pub mod constants;
pub mod models;

const PATTERN: [u8; 1] = [174];

/// Main client for interacting with the 小豆 (Red Bean) API
///
/// # Examples
/// ```no_run
/// use tosho_rbean::{RBClient, RBConfig, RBPlatform};
///
/// #[tokio::main]
/// async fn main() {
///     let config = RBConfig {
///         token: "123".to_string(),
///         refresh_token: "abcxyz".to_string(),
///         platform: RBPlatform::Android,
///     };
///
///     let mut client = RBClient::new(config);
///     // Refresh token
///     client.refresh_token().await.unwrap();
///     let user = client.get_user().await.unwrap();
///     println!("{:?}", user);
/// }
/// ```
#[derive(Clone, Debug)]
pub struct RBClient {
    inner: reqwest::Client,
    config: RBConfig,
    constants: &'static crate::constants::Constants,
    token: String,
    expiry_at: Option<i64>,
}

impl RBClient {
    /// Create a new client instance.
    ///
    /// # Arguments
    /// * `config` - The configuration to use for the client.
    pub fn new(config: RBConfig) -> Self {
        Self::make_client(config, None)
    }

    /// Attach a proxy to the client.
    ///
    /// This will clone the client and return a new client with the proxy attached.
    ///
    /// # Arguments
    /// * `proxy` - The proxy to attach to the client
    pub fn with_proxy(&self, proxy: reqwest::Proxy) -> Self {
        Self::make_client(self.config.clone(), Some(proxy))
    }

    fn make_client(config: RBConfig, proxy: Option<reqwest::Proxy>) -> Self {
        let constants = crate::constants::get_constants(config.platform as u8);
        let mut headers = reqwest::header::HeaderMap::new();

        headers.insert(
            reqwest::header::USER_AGENT,
            reqwest::header::HeaderValue::from_static(constants.ua),
        );
        headers.insert(
            reqwest::header::HOST,
            reqwest::header::HeaderValue::from_static(&API_HOST),
        );
        headers.insert(
            "public",
            reqwest::header::HeaderValue::from_static(&constants.public),
        );
        headers.insert("x-user-token", config.token.parse().unwrap());

        let client = reqwest::Client::builder()
            .http2_adaptive_window(true)
            .use_rustls_tls()
            .default_headers(headers);

        let client = match proxy {
            Some(proxy) => client.proxy(proxy).build().unwrap(),
            None => client.build().unwrap(),
        };

        Self {
            inner: client,
            config: config.clone(),
            constants,
            token: config.token.clone(),
            expiry_at: None,
        }
    }

    pub fn set_expiry_at(&mut self, expiry_at: Option<i64>) {
        self.expiry_at = expiry_at;
    }

    /// Refresh the token of the client.
    ///
    /// The following function will be called on each request to ensure the token is always valid.
    ///
    /// The first request will always be a token refresh, and subsequent requests will only refresh
    /// if the token is expired.
    pub async fn refresh_token(&mut self) -> anyhow::Result<()> {
        // If the expiry time is set and it's not expired, return early
        if let Some(expiry_at) = self.expiry_at {
            if expiry_at > chrono::Utc::now().timestamp() {
                return Ok(());
            }
        }

        let json_data = json!({
            "grantType": "refresh_token",
            "refreshToken": self.config.refresh_token,
        });

        let client = reqwest::Client::builder()
            .http2_adaptive_window(true)
            .use_rustls_tls()
            .build()?;
        let request = client
            .post("https://securetoken.googleapis.com/v1/token")
            .header(reqwest::header::USER_AGENT, self.constants.image_ua)
            .query(&[("key", TOKEN_AUTH.to_string())])
            .json(&json_data)
            .send()
            .await?;

        let response = request
            .json::<crate::models::accounts::google::SecureTokenResponse>()
            .await?;

        self.token.clone_from(&response.access_token);
        self.config.token = response.access_token;
        let expiry_in = response.expires_in.parse::<i64>().unwrap();
        // Set the expiry time to 3 seconds before the actual expiry time
        self.expiry_at = Some(chrono::Utc::now().timestamp() + expiry_in - 3);

        Ok(())
    }

    /// Get the current token of the client.
    pub fn get_token(&self) -> &str {
        &self.token
    }

    /// Get the expiry time of the token.
    pub fn get_expiry_at(&self) -> Option<i64> {
        self.expiry_at
    }

    // <-- Common Helper

    async fn request<T>(
        &mut self,
        method: reqwest::Method,
        url: &str,
        json_body: Option<HashMap<String, String>>,
    ) -> anyhow::Result<T>
    where
        T: serde::de::DeserializeOwned,
    {
        self.refresh_token().await?;

        let endpoint = format!("{}{}", &*BASE_API, url);

        let request = match json_body {
            Some(json_body) => self.inner.request(method, endpoint).json(&json_body),
            None => self.inner.request(method, endpoint),
        };

        let response = request.send().await?;

        if response.status().is_success() {
            let response = response.text().await?;

            let json_de = serde_json::from_str::<T>(&response);

            match json_de {
                Ok(json_de) => Ok(json_de),
                Err(error) => {
                    let row_line = error.line() - 1;
                    let split_lines = &response.split('\n').collect::<Vec<&str>>();
                    let position = error.column();
                    let start_index = position.saturating_sub(25); // Start 25 characters before the error position
                    let end_index = position.saturating_add(25); // End 25 characters after the error position
                    let excerpt = &split_lines[row_line][start_index..end_index];

                    anyhow::bail!(
                        "Error parsing JSON at line {}, column {}: {}\nExcerpt: '{}'",
                        error.line(),
                        error.column(),
                        error,
                        excerpt
                    )
                }
            }
        } else {
            anyhow::bail!("Request failed with status: {}", response.status())
        }
    }

    // --> Common Helper

    // <-- UserApiInterface.kt

    /// Get the current user account information.
    pub async fn get_user(&mut self) -> anyhow::Result<UserAccount> {
        self.request(reqwest::Method::GET, "/user/v0", None).await
    }

    /// Get the current user reading list.
    pub async fn get_reading_list(&mut self) -> anyhow::Result<Vec<ReadingListItem>> {
        self.request(reqwest::Method::GET, "/user/reading_list/v0", None)
            .await
    }

    // --> UserApiInterface.kt

    // <-- MangaApiInterface.kt

    /// Get the manga information for a specific manga.
    ///
    /// # Arguments
    /// * `uuid` - The UUID of the manga.
    pub async fn get_manga(&mut self, uuid: &str) -> anyhow::Result<Manga> {
        self.request(reqwest::Method::GET, &format!("/manga/{}/v0", uuid), None)
            .await
    }

    /// Get the manga filters for searching manga.
    pub async fn get_manga_filters(&mut self) -> anyhow::Result<Manga> {
        self.request(reqwest::Method::GET, "/manga/filters/v0", None)
            .await
    }

    /// Get chapter list for a specific manga.
    ///
    /// # Arguments
    /// * `uuid` - The UUID of the manga.
    pub async fn get_chapter_list(&mut self, uuid: &str) -> anyhow::Result<ChapterListResponse> {
        self.request(
            reqwest::Method::GET,
            &format!("/mangas/{}/chapters/v4?order=asc&count=9999&offset=0", uuid),
            None,
        )
        .await
    }

    /// Get the chapter details for a specific chapter.
    ///
    /// # Arguments
    /// * `uuid` - The UUID of the chapter.
    pub async fn get_chapter(&mut self, uuid: &str) -> anyhow::Result<ChapterDetailsResponse> {
        self.request(
            reqwest::Method::GET,
            &format!("/chapters/{}/v2", uuid),
            None,
        )
        .await
    }

    /// Get the chapter viewer for a specific chapter.
    ///
    /// # Arguments
    /// * `uuid` - The UUID of the chapter.
    pub async fn get_chapter_viewer(
        &mut self,
        uuid: &str,
    ) -> anyhow::Result<ChapterPageDetailsResponse> {
        self.request(
            reqwest::Method::GET,
            &format!("/chapters/{}/pages/v1", uuid),
            None,
        )
        .await
    }

    /// Do a search for a manga.
    ///
    /// # Arguments
    /// * `query` - The query to search for.
    /// * `offset` - The offset of the search result, default to `0`
    /// * `count` - The count of the search result, default to `999`
    /// * `sort` - The sort option of the search result, default to [`SortOption::Alphabetical`]
    pub async fn search(
        &mut self,
        query: &str,
        offset: Option<u32>,
        count: Option<u32>,
        sort: Option<SortOption>,
    ) -> anyhow::Result<MangaListResponse> {
        let offset = offset.unwrap_or(0);
        let count = count.unwrap_or(999);
        let sort = sort.unwrap_or(SortOption::Alphabetical);

        let query_param = format!(
            "sort={}&offset={}&count={}&tags=&search_string={}&publisher_slug=",
            sort, offset, count, query
        );

        self.request(
            reqwest::Method::GET,
            &format!("/mangas/v1?{}", query_param),
            None,
        )
        .await
    }

    /// Get the home page information.
    pub async fn get_home_page(&mut self) -> anyhow::Result<HomeResponse> {
        self.request(reqwest::Method::GET, "/home/v0", None).await
    }

    /// Get specific publisher information by their slug.
    ///
    /// # Arguments
    /// * `slug` - The slug of the publisher.
    pub async fn get_publisher(&mut self, slug: &str) -> anyhow::Result<Publisher> {
        self.request(
            reqwest::Method::GET,
            &format!("/publisher/slug/{}/v0", slug),
            None,
        )
        .await
    }

    // --> Image

    /// Modify the URL to get the high resolution image URL.
    ///
    /// # Arguments
    /// * `url` - The URL to modify.
    pub fn modify_url_for_highres(url: &str) -> anyhow::Result<String> {
        let mut parsed_url = url.parse::<reqwest::Url>()?;

        // Formatted: https://{hostname}/{uuid}/{img_res}.[jpg/webp]
        let path = parsed_url.path();
        let mut path_split = path.split('/').collect::<Vec<&str>>();
        let last_part = match path_split.pop() {
            Some(last_part) => last_part,
            None => anyhow::bail!("Invalid URL path: {}", path),
        };

        let filename = last_part.split_once('.');
        let (_, extension) = match filename {
            Some((filename, extension)) => (filename, extension),
            None => anyhow::bail!(
                "Invalid filename: {}, expected something like 0000.jpg",
                last_part
            ),
        };

        let hi_res = format!("2000.{}", extension);
        let new_path = format!("{}/{}", path_split.join("/"), hi_res);
        parsed_url.set_path(&new_path);

        Ok(parsed_url.to_string())
    }

    /// Stream download the image from the given URL.
    ///
    /// The URL can be obtained from [`RBClient::get_chapter_viewer`].
    ///
    /// # Parameters
    /// * `url` - The URL to download the image from.
    /// * `writer` - The writer to write the image to.
    pub async fn stream_download(
        &self,
        url: &str,
        mut writer: impl io::AsyncWrite + Unpin,
    ) -> anyhow::Result<()> {
        let res = self
            .inner
            .get(url)
            .query(&[("drm", "1")])
            .headers({
                let mut headers = reqwest::header::HeaderMap::new();
                headers.insert(
                    reqwest::header::USER_AGENT,
                    reqwest::header::HeaderValue::from_static(self.constants.image_ua),
                );
                headers.insert(
                    reqwest::header::HOST,
                    reqwest::header::HeaderValue::from_str(IMAGE_HOST.as_str()).unwrap(),
                );
                headers
            })
            .send()
            .await?;

        if !res.status().is_success() {
            anyhow::bail!("Failed to download image: {}", res.status())
        }

        // Check if we need to decrypt
        let header_name = &crate::constants::X_DRM_HEADER;
        let x_drm = res.headers().get(header_name.as_str());
        let is_drm = match x_drm {
            Some(x_drm) => x_drm == "true",
            None => false,
        };

        let mut stream = res.bytes_stream();
        while let Some(item) = stream.next().await {
            let item = item?;

            let dedrmed = if is_drm {
                decrypt_image(&item)
            } else {
                item.to_vec()
            };

            writer.write_all(&dedrmed).await?;
        }

        Ok(())
    }

    /// Try checking if the "hidden" high resolution image is available.
    ///
    /// Give the URL of any image that is requested from the API.
    pub async fn test_high_res(&self, url: &str) -> anyhow::Result<bool> {
        // Do head request to check if the high res image is available
        let url_mod = Self::modify_url_for_highres(url)?;

        let res = self
            .inner
            .head(url_mod)
            .query(&[("drm", "1")])
            .headers({
                let mut headers = reqwest::header::HeaderMap::new();
                headers.insert(
                    reqwest::header::USER_AGENT,
                    reqwest::header::HeaderValue::from_static(self.constants.image_ua),
                );
                headers.insert(
                    reqwest::header::HOST,
                    reqwest::header::HeaderValue::from_str(IMAGE_HOST.as_str()).unwrap(),
                );
                headers
            })
            .send()
            .await?;

        let success = res.status().is_success();
        let mimetype = res.headers().get(reqwest::header::CONTENT_TYPE);
        // Good mimetype are either image/jpeg or image/webp
        let good_mimetype = match mimetype {
            Some(mimetype) => mimetype == "image/jpeg" || mimetype == "image/webp",
            None => false,
        };

        Ok(success && good_mimetype)
    }

    // <-- Image

    // --> MangaApiInterface.kt

    pub async fn login(
        email: &str,
        password: &str,
        platform: RBPlatform,
    ) -> anyhow::Result<RBLoginResponse> {
        let constants = crate::constants::get_constants(platform as u8);

        let mut headers = reqwest::header::HeaderMap::new();
        headers.insert(
            reqwest::header::USER_AGENT,
            reqwest::header::HeaderValue::from_static(constants.image_ua),
        );

        let client_type = match platform {
            RBPlatform::Android => Some("CLIENT_TYPE_ANDROID"),
            RBPlatform::Apple => Some("CLIENT_TYPE_IOS"),
            _ => None,
        };

        let mut json_data = json!({
            "email": email,
            "password": password,
            "returnSecureToken": true,
        });
        if let Some(client_type) = client_type {
            json_data["clientType"] = client_type.into();
        }

        let client = reqwest::Client::builder()
            .http2_adaptive_window(true)
            .use_rustls_tls()
            .default_headers(headers)
            .build()?;

        let key_param = &[("key", TOKEN_AUTH.to_string())];

        // Step 1: Verify password
        let request = client
            .post("https://www.googleapis.com/identitytoolkit/v3/relyingparty/verifyPassword")
            .query(key_param)
            .json(&json_data)
            .send()
            .await?;

        let verify_resp = request
            .json::<crate::models::accounts::google::IdentityToolkitVerifyPasswordResponse>()
            .await?;

        // Step 2: Get account info
        let json_data = json!({
            "idToken": verify_resp.id_token,
        });

        let request = client
            .post("https://www.googleapis.com/identitytoolkit/v3/relyingparty/getAccountInfo")
            .query(key_param)
            .json(&json_data)
            .send()
            .await?;

        let acc_info_resp = request
            .json::<crate::models::accounts::google::IdentityToolkitAccountInfoResponse>()
            .await?;

        // Step 2.5: Find user
        let goog_user = acc_info_resp
            .users
            .iter()
            .find(|user| user.local_id == verify_resp.local_id);

        if goog_user.is_none() {
            anyhow::bail!(
                "Google user information not found for {}",
                verify_resp.local_id
            );
        }

        let goog_user = goog_user.unwrap().clone();

        // Step 3: Refresh token
        let json_data = json!({
            "grantType": "refresh_token",
            "refreshToken": verify_resp.refresh_token,
        });

        let request = client
            .post("https://securetoken.googleapis.com/v1/token")
            .query(key_param)
            .json(&json_data)
            .send()
            .await?;

        let secure_token_resp = request
            .json::<crate::models::accounts::google::SecureTokenResponse>()
            .await?;

        let expires_in = secure_token_resp.expires_in.parse::<i64>().unwrap();
        let expiry_at = chrono::Utc::now().timestamp() + expires_in - 3;

        // Step 4: Auth with 小豆
        let request = client
            .get(&format!("{}/user/v0", &*BASE_API))
            .headers({
                let mut headers = reqwest::header::HeaderMap::new();
                headers.insert(
                    reqwest::header::USER_AGENT,
                    reqwest::header::HeaderValue::from_static(constants.ua),
                );
                headers.insert(
                    "public",
                    reqwest::header::HeaderValue::from_static(&constants.public),
                );
                headers.insert(
                    "x-user-token",
                    reqwest::header::HeaderValue::from_str(&secure_token_resp.access_token)
                        .unwrap(),
                );
                headers
            })
            .send()
            .await?;

        let user_resp = request.json::<UserAccount>().await?;

        Ok(RBLoginResponse {
            token: secure_token_resp.access_token,
            refresh_token: secure_token_resp.refresh_token,
            platform,
            user: user_resp,
            google_account: goog_user,
            expiry: expiry_at,
        })
    }
}

/// Represents the login response from the 小豆 (Red Bean) API
///
/// The following struct is returned when you use [`RBClient::login`] method.
///
/// This struct wraps some other struct that can be useful for config building yourself.
#[derive(Debug, Clone)]
pub struct RBLoginResponse {
    /// The token of the account
    pub token: String,
    /// The refresh token of the account
    pub refresh_token: String,
    /// The platform of the account
    pub platform: RBPlatform,
    /// Detailed account information
    pub user: UserAccount,
    /// Detailed google account information
    pub google_account: crate::models::accounts::google::IdentityToolkitAccountInfo,
    /// Expiry time of the token
    pub expiry: i64,
}

/// A simple image decryptor for the 小豆 (Red Bean) API
///
/// # Arguments
/// * `data` - The image data to decrypt
pub fn decrypt_image(data: &[u8]) -> Vec<u8> {
    let image_data = data.to_vec();
    image_data.iter().map(|x| PATTERN[0] ^ x).collect()
}