pixapi 0.1.1

An API for accessing to pixiv.net
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
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
pub mod models;

use std::{collections::HashMap, error::Error, fmt::Display, str::FromStr};

use chrono::{SecondsFormat, Utc};
use md5::compute;
use models::{
    bookmark_detail::BookmarkDetail,
    illust::Illust,
    illust_page::IllustPage,
    tag::{Tags, TrendTags},
    user_detail::UserDetail,
    user_illusts::UserIllusts,
    user_page::UserPage,
};
use reqwest::{
    self,
    header::{HeaderMap, CONTENT_TYPE, IF_MODIFIED_SINCE, REFERER},
    Client, StatusCode, Url,
};
use serde::Deserialize;
use serde_json::Value;
use time::Instant;

const HASH_SALT: &'static str = "28c1fdd170a5204386cb1313c7077b34f83e4aaf4aa829ce78c231e05b0bae2c";
const BASE_API_URL_HOST: &'static str = "app-api.pixiv.net";
const ACCEPT_LANGUAGE: &'static str = "zh-CN";

#[derive(PartialEq, Default, Eq, Hash, Debug, Copy, Clone)]
pub enum Publicity {
    Public,
    Private,
    #[default]
    All,
}

#[derive(PartialEq)]
pub enum IllustType {
    Illust,
    Manga,
}

#[derive(PartialEq)]
pub enum RankingType {
    Day,
    Week,
    Month,
    DayMale,
    DayFemale,
    WeekOriginal,
    WeekRookie,
    DayR18,
    DayMaleR18,
    DayFemaleR18,
    WeekR18,
    WeekR18g,
}

impl Display for RankingType {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.write_str(match self {
            RankingType::Day => "day",
            RankingType::Week => "week",
            RankingType::Month => "month",
            RankingType::DayMale => "day_male",
            RankingType::DayFemale => "day_female",
            RankingType::WeekOriginal => "week_original",
            RankingType::WeekRookie => "week_rookie",
            RankingType::DayR18 => "day_r18",
            RankingType::DayMaleR18 => "day_male_r18",
            RankingType::DayFemaleR18 => "day_female_r18",
            RankingType::WeekR18 => "week_r18",
            RankingType::WeekR18g => "week_r18g",
        })
    }
}

impl Display for IllustType {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.write_str(match self {
            IllustType::Illust => "illust",
            IllustType::Manga => "manga",
        })
    }
}

impl Display for Publicity {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.write_str(match self {
            Publicity::Public => "public",
            Publicity::Private => "private",
            Publicity::All => "all",
        })
    }
}

#[derive(Clone, Debug)]
pub struct PixivClient {
    client: reqwest::Client,
    base_url: Url,
    refresh_token: String,
    // Надо будет поменять на auth_token: Option<String>, а то это ебаный пиздец
    auth_token: Option<String>,
    last_refresh: Instant,
}

/// Error returned on failure to authorize with pixiv.
#[derive(Debug)]
pub struct AuthError {
    reason: String,
}

#[derive(Debug)]
pub struct DownloadError {
    reason: String,
}

impl PixivClient {
    pub fn from_refresh_token(token: &str) -> Self {
        let time = Self::get_iso_date();
        let mut headers = HeaderMap::new();
        headers.insert("X-Client-Time", time.parse().unwrap());
        headers.insert(
            "X-Client-Hash",
            Self::get_hash(&(time + HASH_SALT)).parse().unwrap(),
        );
        headers.insert(
            "User-Agent",
            "PixivAndroidApp/5.0.155 (Android 10.0; Pixel C)"
                .parse()
                .unwrap(),
        );
        headers.insert("Accept-Language", ACCEPT_LANGUAGE.parse().unwrap());
        headers.insert("App-OS", "Android".parse().unwrap());
        headers.insert("App-OS-Version", "Android 10.0".parse().unwrap());
        headers.insert("App-Version", "5.0.166".parse().unwrap());
        headers.insert("Host", BASE_API_URL_HOST.parse().unwrap());

        let client_builder = Client::builder()
            .danger_accept_invalid_certs(true)
            .default_headers(headers);
        let client = client_builder.build().unwrap();
        PixivClient {
            client,
            base_url: Url::from_str("https://210.140.131.199").unwrap(),
            refresh_token: token.to_string(),
            auth_token: None,
            last_refresh: Instant::now(),
        }
    }

    fn get_iso_date() -> String {
        Utc::now().to_rfc3339_opts(SecondsFormat::Millis, false)
    }

    fn get_hash(s: &str) -> String {
        format!("{:?}", compute(s.as_bytes()))
    }

    pub async fn refresh_if_needed(&mut self) -> Result<(), AuthError> {
        if self.need_refresh() {
            self.refresh_auth().await?
        }
        Ok(())
    }

    pub fn need_refresh(&self) -> bool {
        if self.last_refresh.elapsed().whole_hours() >= 1 || self.auth_token.is_none() {
            true
        } else {
            false
        }
    }

    /// Refreshes the authentication. You should use this when your access token is close to expiring.
    /// Token valid during one hour
    pub async fn refresh_auth(&mut self) -> Result<(), AuthError> {
        const CLIENT_ID: &str = "MOBrBDS8blbauoSck0ZfDbtuzpyT";
        const CLIENT_SECRET: &str = "lsACyCD94FhDUtGTXi3QzcFE2uU1hqtDaKeqrdwj";
        let mut data = HashMap::new();

        data.insert("client_id", CLIENT_ID);
        data.insert("client_secret", CLIENT_SECRET);
        data.insert("get_secure_url", "1");

        data.insert("grant_type", "refresh_token");
        data.insert("refresh_token", &self.refresh_token);

        let client = reqwest::Client::new();
        let Ok(res) = client
            .post("https://oauth.secure.pixiv.net/auth/token")
            .form(&data)
            .send()
            .await else {
                return Err(AuthError { reason: "Bad request!".to_string() })
            };

        match res.status() {
            StatusCode::OK | StatusCode::MOVED_PERMANENTLY | StatusCode::FOUND => {
                // success
            }
            s => {
                return Err(AuthError {
                    reason: format!("Login failed. Check your refresh token. Response: {:?}", s),
                })
            }
        }

        let mut json_response: Value = res.json().await.unwrap();

        match json_response["response"]["access_token"].take() {
            Value::String(s) => {
                self.auth_token = Some(s);
            }
            _ => panic!("Failed to get access token."),
        }
        self.last_refresh = Instant::now();
        Ok(())
    }

    /// Allows you to get user recommendations
    pub async fn get_recommend(&self) -> Result<IllustPage, reqwest::Error> {
        let url = self
            .base_url
            .join("/v1/illust/recommended?filter=for_ios&include_ranking_label=true")
            .unwrap();
        let resp = self
            .client
            .get(url)
            .header(
                "Authorization",
                format!("Bearer {}", self.auth_token.as_ref().unwrap()),
            )
            .send()
            .await?;
        Ok(resp.json().await?)
    }

    /// Allows you to get a page with illustrations by url. You can use as an argument the next_url field from the IllustPage or UserPage structures.
    pub async fn get_illust_page_by_url(&self, url: &str) -> Result<IllustPage, reqwest::Error> {
        let resp = self
            .client
            .get(url)
            .header(
                "Authorization",
                format!("Bearer {}", self.auth_token.as_ref().unwrap()),
            )
            .send()
            .await?;
        Ok(resp.json().await?)
    }

    /// Allows you to get recommended users.
    pub async fn get_user_recommended(&self) -> Result<UserPage, reqwest::Error> {
        let url = self
            .base_url
            .join("/v1/user/recommended?filter=for_android")
            .unwrap();
        let resp = self
            .client
            .get(url)
            .header(
                "Authorization",
                format!("Bearer {}", self.auth_token.as_ref().unwrap()),
            )
            .send()
            .await?;
        Ok(resp.json().await?)
    }

    /// Allows you to get the user by id
    pub async fn get_user(&self, user_id: u32) -> Result<UserDetail, reqwest::Error> {
        let mut url = self.base_url.join("/v1/user/detail").unwrap();
        url.set_query(Some(&format!("user_id={user_id}&filter=for_android")));
        let resp = self
            .client
            .get(url)
            .header(
                "Authorization",
                format!("Bearer {}", self.auth_token.as_ref().unwrap()),
            )
            .send()
            .await?;
        Ok(resp.json().await?)
    }

    /// Allows you to get custom illustrations by id and illustration type
    pub async fn get_user_ilusts(
        &self,
        user_id: u32,
        illust_type: IllustType,
    ) -> Result<UserIllusts, reqwest::Error> {
        let mut url = self.base_url.join("v1/user/illusts").unwrap();
        url.set_query(Some(&format!(
            "user_id={user_id}&type={illust_type}&filter=for_android"
        )));
        let resp = self
            .client
            .get(url)
            .header(
                "Authorization",
                format!("Bearer {}", self.auth_token.as_ref().unwrap()),
            )
            .send()
            .await?;
        Ok(resp.json().await?)
    }

    /// Allows you to get custom illustrations by id, illustration type and shift
    pub async fn get_user_ilusts_offset(
        &self,
        user_id: u32,
        illust_type: IllustType,
        offset: u32,
    ) -> Result<UserIllusts, reqwest::Error> {
        let mut url = self.base_url.join("v1/user/illusts").unwrap();
        url.set_query(Some(&format!(
            "user_id={user_id}&type={illust_type}&offset={offset}&filter=for_android"
        )));
        let resp = self
            .client
            .get(url)
            .header(
                "Authorization",
                format!("Bearer {}", self.auth_token.as_ref().unwrap()),
            )
            .send()
            .await?;
        Ok(resp.json().await?)
    }

    /// Adds an illustration to bookmarks. Returns true if the operation succeeded and false otherwise.
    pub async fn post_like_illust(
        &self,
        illust_id: u32,
        restrict: Publicity,
        tags: Vec<&str>,
    ) -> Result<bool, reqwest::Error> {
        let url = self.base_url.join("/v2/illust/bookmark/add").unwrap();
        let mut form = HashMap::new();
        form.insert("illust_id", illust_id.to_string());
        form.insert("restrict", restrict.to_string());
        if !tags.is_empty() {
            let tag_string = tags
                .into_iter()
                .map(|s| s.trim())
                .collect::<Vec<&str>>()
                .join(" ");
            form.insert("tags[]", tag_string);
        }
        let resp = self
            .client
            .post(url)
            .header(
                "Authorization",
                format!("Bearer {}", self.auth_token.as_ref().unwrap()),
            )
            .form(&form)
            .send()
            .await?;
        if resp.text().await? == "{}" {
            return Ok(true);
        }
        Ok(false)
    }

    /// Removes the illustration from bookmarks. Allows you to get custom illustrations by id and illustration type
    pub async fn post_unlike_illust(&self, illust_id: u32) -> Result<bool, reqwest::Error> {
        let url = self.base_url.join("v1/illust/bookmark/delete").unwrap();
        let mut form = HashMap::new();
        form.insert("illust_id", illust_id.to_string());
        let resp = self
            .client
            .post(url)
            .header(
                "Authorization",
                format!("Bearer {}", self.auth_token.as_ref().unwrap()),
            )
            .form(&form)
            .send()
            .await?;
        if resp.text().await? == "{}" {
            return Ok(true);
        }
        Ok(false)
    }

    /// Get an illustration removed from bookmarks?
    pub async fn get_unlike_illust(&self, illust_id: u32) -> Result<Illust, reqwest::Error> {
        let mut url = self.base_url.join("/v1/illust/bookmark/delete").unwrap();
        url.set_query(Some(&format!("illust_id={illust_id}")));
        let resp = self
            .client
            .get(url)
            .header(
                "Authorization",
                format!("Bearer {}", self.auth_token.as_ref().unwrap()),
            )
            .send()
            .await?;
        Ok(resp.json().await?)
    }

    /// Allows you to get the ranking of illustrations. Date format "yyyy-mm-dd"
    pub async fn get_illust_ranking(
        &self,
        mode: RankingType,
        date: &str,
    ) -> Result<IllustPage, reqwest::Error> {
        let mut url = self.base_url.join("/v1/illust/ranking").unwrap();
        url.set_query(Some(&format!("mode={mode}&date={date}&filter=for_android")));
        let resp = self
            .client
            .get(url)
            .header(
                "Authorization",
                format!("Bearer {}", self.auth_token.as_ref().unwrap()),
            )
            .send()
            .await?;
        Ok(resp.json().await?)
    }

    /// Allows you to get the user's bookmarks
    pub async fn get_bookmarks_illust(
        &self,
        user_id: u32,
        restrict: Publicity,
        tag: Option<&str>,
    ) -> Result<IllustPage, reqwest::Error> {
        let mut url = self.base_url.join("/v1/user/bookmarks/illust").unwrap();
        let mut query = format!("user_id={user_id}&restrict={restrict}");
        if let Some(tag) = tag {
            query += &format!("tag={}", tag);
        }
        url.set_query(Some(&query));
        let resp = self
            .client
            .get(url)
            .header(
                "Authorization",
                format!("Bearer {}", self.auth_token.as_ref().unwrap()),
            )
            .send()
            .await?;
        Ok(resp.json().await?)
    }

    /// Remove user from followings
    pub async fn post_unfollow_user(&self, user_id: u32) -> Result<bool, reqwest::Error> {
        let url = self.base_url.join("/v1/user/follow/delete").unwrap();
        let mut form = HashMap::new();
        form.insert("user_id", user_id.to_string());
        let resp = self
            .client
            .post(url)
            .header(
                "Authorization",
                format!("Bearer {}", self.auth_token.as_ref().unwrap()),
            )
            .form(&form)
            .send()
            .await?;
        if resp.text().await? == "{}" {
            return Ok(true);
        }
        Ok(false)
    }

    /// Follow to user by id and restrict
    pub async fn post_follow_user(
        &self,
        user_id: u32,
        restrict: Publicity,
    ) -> Result<bool, reqwest::Error> {
        let url = self.base_url.join("/v1/user/follow/delete").unwrap();
        let mut form = HashMap::new();
        form.insert("user_id", user_id.to_string());
        form.insert("restrict", restrict.to_string());
        let resp = self
            .client
            .post(url)
            .header(
                "Authorization",
                format!("Bearer {}", self.auth_token.as_ref().unwrap()),
            )
            .form(&form)
            .send()
            .await?;
        if resp.text().await? == "{}" {
            return Ok(true);
        }
        Ok(false)
    }

    /// Get your followers
    pub async fn get_follow_user(
        &self,
        user_id: u32,
        restrict: Publicity,
    ) -> Result<UserPage, reqwest::Error> {
        let mut url = self.base_url.join("/v1/user/follower").unwrap();
        url.set_query(Some(&format!(
            "restrict={restrict}&user_id={user_id}&filter=for_android"
        )));
        let resp = self
            .client
            .get(url)
            .header(
                "Authorization",
                format!("Bearer {}", self.auth_token.as_ref().unwrap()),
            )
            .send()
            .await?;
        Ok(resp.json().await?)
    }

    /// Get last illusts from your followings
    pub async fn get_follow_illusts(
        &self,
        restrict: Publicity,
    ) -> Result<IllustPage, reqwest::Error> {
        let mut url = self.base_url.join("/v2/illust/follow").unwrap();
        url.set_query(Some(&format!("restrict={restrict}")));
        let resp = self
            .client
            .get(url)
            .header(
                "Authorization",
                format!("Bearer {}", self.auth_token.as_ref().unwrap()),
            )
            .send()
            .await?;
        Ok(resp.json().await?)
    }

    /// Allows you to get users subscribed by the user with the specified id
    pub async fn get_user_following(
        &self,
        user_id: u32,
        restrict: Publicity,
    ) -> Result<UserPage, reqwest::Error> {
        let mut url = self.base_url.join("/v1/user/following").unwrap();
        url.set_query(Some(&format!(
            "restrict={restrict}&user_id={user_id}&filter=for_android"
        )));
        let resp = self
            .client
            .get(url)
            .header(
                "Authorization",
                format!("Bearer {}", self.auth_token.as_ref().unwrap()),
            )
            .send()
            .await?;
        Ok(resp.json().await?)
    }

    pub async fn get_search_auto_complete_keywords(
        &self,
        word: &str,
    ) -> Result<Tags, reqwest::Error> {
        let mut url = self.base_url.join("/v2/search/autocomplete").unwrap();
        url.set_query(Some(&format!(
            "word={word}&merge_plain_keyword_results=true"
        )));
        let resp = self
            .client
            .get(url)
            .header(
                "Authorization",
                format!("Bearer {}", self.auth_token.as_ref().unwrap()),
            )
            .send()
            .await?;
        Ok(resp.json().await?)
    }

    pub async fn get_illust_trend_tags(&self) -> Result<TrendTags, reqwest::Error> {
        let url = self
            .base_url
            .join("/v1/trending-tags/illust?filter=for_android")
            .unwrap();
        let resp = self
            .client
            .get(url)
            .header(
                "Authorization",
                format!("Bearer {}", self.auth_token.as_ref().unwrap()),
            )
            .send()
            .await?;
        Ok(resp.json().await?)
    }

    /// search_target: ["partial_match_for_tags","exact_match_for_tags","title_and_caption"]
    /// sort: ["date_desc", "date_asc", "popular_desc"]
    /// bookmark_num - неизвестно что это
    /// В illustpage не хватает одного поля в этом ответе. Оно всегда одно и тоже search_span_limit: 31536000
    pub async fn get_search_illust(
        &self,
        word: &str,
        sort: Option<&str>,
        search_target: Option<&str>,
        start_date: Option<&str>,
        end_date: Option<&str>,
        bookmark_num: Option<u32>,
    ) -> Result<IllustPage, reqwest::Error> {
        let mut url = self.base_url.join("/v1/search/illust").unwrap();
        let mut query = format!("word={word}&filter=for_android&merge_plain_keyword_results=true");
        if let Some(sort) = sort {
            query += &format!("sort={}", sort);
        }
        if let Some(search_target) = search_target {
            query += &format!("search_target={}", search_target);
        }
        if let Some(start_date) = start_date {
            query += &format!("start_date={}", start_date);
        }
        if let Some(end_date) = end_date {
            query += &format!("end_date={}", end_date);
        }
        if let Some(bookmark_num) = bookmark_num {
            query += &format!("bookmark_num={}", bookmark_num);
        }
        url.set_query(Some(&query));
        let resp = self
            .client
            .get(url)
            .header(
                "Authorization",
                format!("Bearer {}", self.auth_token.as_ref().unwrap()),
            )
            .send()
            .await?;
        Ok(resp.json().await?)
    }

    pub async fn get_search_user(&self, word: &str) -> Result<UserPage, reqwest::Error> {
        let mut url = self.base_url.join("/v1/search/user").unwrap();
        url.set_query(Some(&format!("word={word}&filter=for_android")));
        let resp = self
            .client
            .get(url)
            .header(
                "Authorization",
                format!("Bearer {}", self.auth_token.as_ref().unwrap()),
            )
            .send()
            .await?;
        Ok(resp.json().await?)
    }

    pub async fn get_search_autocomplete(&self, word: &str) -> Result<Tags, reqwest::Error> {
        let mut url = self.base_url.join("/v2/search/autocomplete").unwrap();
        url.set_query(Some(&format!(
            "word={word}&merge_plain_keyword_results=true"
        )));
        let resp = self
            .client
            .get(url)
            .header(
                "Authorization",
                format!("Bearer {}", self.auth_token.as_ref().unwrap()),
            )
            .send()
            .await?;
        Ok(resp.json().await?)
    }

    pub async fn get_illust_related(&self, illust_id: u32) -> Result<IllustPage, reqwest::Error> {
        let mut url = self.base_url.join("/v2/illust/related").unwrap();
        url.set_query(Some(&format!("illust_id={illust_id}&filter=for_android")));
        let resp = self
            .client
            .get(url)
            .header(
                "Authorization",
                format!("Bearer {}", self.auth_token.as_ref().unwrap()),
            )
            .send()
            .await?;
        Ok(resp.json().await?)
    }

    pub async fn get_illust_bookmark_detail(
        &self,
        illust_id: u32,
    ) -> Result<BookmarkDetail, reqwest::Error> {
        let mut url = self.base_url.join("v2/illust/bookmark/detail").unwrap();
        url.set_query(Some(&format!("illust_id={illust_id}")));
        let resp = self
            .client
            .get(url)
            .header(
                "Authorization",
                format!("Bearer {}", self.auth_token.as_ref().unwrap()),
            )
            .send()
            .await?;
        #[derive(Deserialize)]
        struct A {
            bookmark_detail: BookmarkDetail,
        }
        let a: A = resp.json().await?;
        Ok(a.bookmark_detail)
    }

    pub async fn get_illust_detail(&self, illust_id: u32) -> Result<Illust, reqwest::Error> {
        let mut url = self.base_url.join("/v1/illust/detail").unwrap();
        url.set_query(Some(&format!("illust_id={illust_id}&filter=for_android")));
        let resp = self
            .client
            .get(url)
            .header(
                "Authorization",
                format!("Bearer {}", self.auth_token.as_ref().unwrap()),
            )
            .send()
            .await?;
        #[derive(Deserialize)]
        struct A {
            illust: Illust,
        }
        let a: A = resp.json().await?;
        Ok(a.illust)
    }

    pub async fn download_image(image_url: &str) -> anyhow::Result<bytes::Bytes> {
        let image_url = image_url.replace("i.pximg.net", "i-cf.pximg.net");
        let client = reqwest::Client::new();
        let resp = client
            .get(image_url)
            .header(REFERER, "https://www.pixiv.net/")
            .header(IF_MODIFIED_SINCE, "Anything date")
            .send()
            .await?;
        let Some(content_type) = resp.headers().get(CONTENT_TYPE) else {
            return Err(DownloadError {
                reason: "Response don't contains Content-Type header!".to_string()
            })?;
        };

        let content_type = content_type.to_str().unwrap();
        if content_type.contains("image/jpeg") || content_type.contains("image/png") {
            Ok(resp.bytes().await?)
        } else {
            Err(DownloadError {
                reason: "Don't image in jpeg or png formats!".to_string(),
            })?
        }
    }
}

impl Error for AuthError {
    fn description(&self) -> &str {
        "An error occurred while trying to authenticate."
    }
}

impl std::fmt::Display for AuthError {
    fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
        write!(
            f,
            "An error occurred while trying to authenticate. Reason: {:?}",
            self.reason
        )
    }
}

impl Error for DownloadError {
    fn description(&self) -> &str {
        "An error occurred while trying to download image."
    }
}

impl std::fmt::Display for DownloadError {
    fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
        write!(
            f,
            "An error occurred while trying to download image. Reason: {:?}",
            self.reason
        )
    }
}

#[cfg(test)]
mod tests {
    use crate::PixivClient;

    #[test]
    fn test() {
        let rt = tokio::runtime::Runtime::new().unwrap();
        rt.block_on(async {
            let mut client = PixivClient::from_refresh_token(env!("REFRESH_TOKEN"));
            client.refresh_auth().await.unwrap();
            let resp = client.get_recommend().await.unwrap();
            println!("{:#?}", resp);
        });
    }
}