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
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
mod server;
mod structure;
mod utils;

use std::{
    io::Cursor,
    path::PathBuf,
    sync::RwLock,
    time::{SystemTime, UNIX_EPOCH},
};

use chrono::{Duration, Local, NaiveDateTime, TimeZone};
use chrono_tz::Asia::Shanghai;
use hashbrown::HashMap;
use image::{io::Reader, DynamicImage};
use itertools::Itertools;
use scraper::{Html, Selector};
use serde::{Deserialize, Serialize};
use serde_json::json;
use tokio::sync::OnceCell;
use tracing::{error, info};
use url::Url;

use self::structure::*;
use crate::{
    Category, ChapterInfo, Client, Comment, CommentType, ContentInfo, ContentInfos, Error,
    FindImageResult, FindTextResult, HTTPClient, LongComment, NovelDB, NovelInfo, Options,
    ShortComment, Tag, UserInfo, VolumeInfo, VolumeInfos, WordCountRange,
};

#[must_use]
#[derive(Serialize, Deserialize)]
pub(crate) struct Config {
    account: String,
    login_token: String,
}

/// Ciweimao client, use it to access Apis
#[must_use]
pub struct CiweimaoClient {
    proxy: Option<Url>,
    no_proxy: bool,
    cert_path: Option<PathBuf>,

    client: OnceCell<HTTPClient>,
    client_rss: OnceCell<HTTPClient>,

    db: OnceCell<NovelDB>,

    config: RwLock<Option<Config>>,
}

impl Client for CiweimaoClient {
    fn proxy(&mut self, proxy: Url) {
        self.proxy = Some(proxy);
    }

    fn no_proxy(&mut self) {
        self.no_proxy = true;
    }

    fn cert(&mut self, cert_path: PathBuf) {
        self.cert_path = Some(cert_path);
    }

    async fn shutdown(&self) -> Result<(), Error> {
        self.client().await?.shutdown()?;
        self.do_shutdown()?;
        Ok(())
    }

    async fn add_cookie(&self, cookie_str: &str, url: &Url) -> Result<(), Error> {
        self.client().await?.add_cookie(cookie_str, url)
    }

    async fn log_in(&self, username: String, password: Option<String>) -> Result<(), Error> {
        assert!(!username.is_empty());
        assert!(password.is_some());

        let password = password.unwrap();

        let config = match self.verify_type(&username).await? {
            VerifyType::None => {
                info!("No verification required");
                self.no_verification_login(username, password).await?
            }
            VerifyType::Geetest => {
                info!("Verify with Geetest");
                self.geetest_login(username, password).await?
            }
            VerifyType::VerifyCode => {
                info!("Verify with SMS verification code");
                self.sms_login(username, password).await?
            }
        };

        self.save_token(config);

        Ok(())
    }

    async fn logged_in(&self) -> Result<bool, Error> {
        if !self.has_token() {
            return Ok(false);
        }

        let response: GenericResponse = self.post("/reader/get_my_info", EmptyRequest {}).await?;

        if response.code == CiweimaoClient::LOGIN_EXPIRED {
            Ok(false)
        } else {
            utils::check_response_success(response.code, response.tip)?;
            Ok(true)
        }
    }

    async fn user_info(&self) -> Result<UserInfo, Error> {
        let response: UserInfoResponse = self.post("/reader/get_my_info", EmptyRequest {}).await?;
        utils::check_response_success(response.code, response.tip)?;
        let reader_info = response.data.unwrap().reader_info;

        let user_info = UserInfo {
            nickname: reader_info.reader_name.trim().to_string(),
            avatar: reader_info.avatar_url,
        };

        Ok(user_info)
    }

    async fn money(&self) -> Result<u32, Error> {
        let response: PropInfoResponse =
            self.post("/reader/get_prop_info", EmptyRequest {}).await?;
        utils::check_response_success(response.code, response.tip)?;
        let prop_info = response.data.unwrap().prop_info;

        Ok(prop_info.rest_hlb.parse()?)
    }

    async fn sign_in(&self) -> Result<(), Error> {
        let response: GenericResponse = self
            .post(
                "/reader/get_task_bonus_with_sign_recommend",
                SignRequest {
                    // always 1, from `/task/get_all_task_list`
                    task_type: 1,
                },
            )
            .await?;
        if utils::check_already_signed_in(&response.code) {
            info!("{}", CiweimaoClient::ALREADY_SIGNED_IN);
        } else {
            utils::check_response_success(response.code, response.tip)?;
        }

        Ok(())
    }

    async fn bookshelf_infos(&self) -> Result<Vec<u32>, Error> {
        let shelf_ids = self.shelf_list().await?;
        let mut result = Vec::new();

        for shelf_id in shelf_ids {
            let response: BookshelfResponse = self
                .post(
                    "/bookshelf/get_shelf_book_list_new",
                    BookshelfRequest {
                        shelf_id,
                        count: 9999,
                        page: 0,
                        order: "last_read_time",
                    },
                )
                .await?;
            utils::check_response_success(response.code, response.tip)?;

            for novel_info in response.data.unwrap().book_list {
                result.push(novel_info.book_info.book_id.parse()?);
            }
        }

        Ok(result)
    }

    async fn novel_info(&self, id: u32) -> Result<Option<NovelInfo>, Error> {
        assert!(id > 0);

        let response: NovelInfoResponse = self
            .post("/book/get_info_by_id", NovelInfoRequest { book_id: id })
            .await?;
        if response.code == CiweimaoClient::NOT_FOUND {
            return Ok(None);
        }
        utils::check_response_success(response.code, response.tip)?;

        let data = response.data.unwrap().book_info;
        let novel_info = NovelInfo {
            id,
            name: data.book_name.trim().to_string(),
            author_name: data.author_name.trim().to_string(),
            cover_url: data.cover,
            introduction: super::parse_multi_line(data.description),
            word_count: Some(data.total_word_count.parse()?),
            is_vip: Some(data.is_paid),
            is_finished: Some(data.up_status),
            create_time: data.newtime,
            update_time: Some(data.uptime),
            category: self.parse_category(data.category_index).await?,
            tags: self.parse_tags(data.tag_list).await?,
        };

        Ok(Some(novel_info))
    }

    async fn comments(
        &self,
        id: u32,
        comment_type: CommentType,
        need_replies: bool,
        page: u16,
        size: u16,
    ) -> Result<Option<Vec<Comment>>, Error> {
        let r#type = match comment_type {
            // 1 讨论
            // 2 长评
            CommentType::Short => 1,
            CommentType::Long => 2,
        };

        let response: ReviewResponse = self
            .post(
                "/book/get_review_list",
                ReviewRequest {
                    book_id: id,
                    r#type,
                    page,
                    count: size,
                },
            )
            .await?;
        utils::check_response_success(response.code, response.tip)?;
        let review_list = response.data.unwrap().review_list;

        if review_list.is_empty() {
            return Ok(None);
        }

        let mut result = Vec::with_capacity(review_list.len());

        match comment_type {
            CommentType::Short => {
                for review in review_list {
                    // 部分评论为空白字符
                    let Some(content) = super::parse_multi_line(review.review_content) else {
                        continue;
                    };

                    let review_id: u32 = review.review_id.parse()?;
                    let comment_amount: u16 = review.comment_amount.parse()?;

                    let replies = if need_replies && comment_amount > 0 {
                        self.review_comment(review_id, comment_amount).await?
                    } else {
                        None
                    };

                    let comment = ShortComment {
                        id: review_id,
                        user: UserInfo {
                            nickname: review.reader_info.reader_name.trim().to_string(),
                            avatar: review.reader_info.avatar_url,
                        },
                        content,
                        create_time: Some(review.ctime),
                        like_count: Some(review.like_amount.parse()?),
                        replies,
                    };

                    result.push(Comment::Short(comment));
                }
            }
            CommentType::Long => {
                for review in review_list {
                    let Some(content) = super::parse_multi_line(review.review_content) else {
                        continue;
                    };

                    let review_id: u32 = review.review_id.parse()?;
                    let comment_amount: u16 = review.comment_amount.parse()?;

                    let replies = if need_replies && comment_amount > 0 {
                        self.review_comment(review_id, comment_amount).await?
                    } else {
                        None
                    };

                    let comment = LongComment {
                        id: review_id,
                        user: UserInfo {
                            nickname: review.reader_info.reader_name.trim().to_string(),
                            avatar: review.reader_info.avatar_url,
                        },
                        title: review.title.trim().to_string(),
                        content,
                        create_time: Some(review.ctime),
                        like_count: Some(review.like_amount.parse()?),
                        replies,
                    };

                    result.push(Comment::Long(comment));
                }
            }
        }

        Ok(Some(result))
    }

    async fn volume_infos(&self, id: u32) -> Result<Option<VolumeInfos>, Error> {
        let response: VolumesResponse = self
            .post(
                "/chapter/get_updated_chapter_by_division_new",
                VolumesRequest { book_id: id },
            )
            .await?;
        utils::check_response_success(response.code, response.tip)?;
        let chapter_list = response.data.unwrap().chapter_list;

        let chapter_prices = self.chapter_prices(id).await?;

        let mut volume_infos = VolumeInfos::new();
        for item in chapter_list {
            let mut volume_info = VolumeInfo {
                id: item.division_id.parse()?,
                title: item.division_name.trim().to_string(),
                chapter_infos: Vec::new(),
            };

            for chapter in item.chapter_list {
                let chapter_id: u32 = chapter.chapter_id.parse()?;
                let price = chapter_prices.get(&chapter_id).copied();
                let mut is_valid = true;

                // e.g. 该章节未审核通过
                if price.is_none() {
                    info!("Price not found: {chapter_id}");
                    is_valid = false;
                }

                let chapter_info = ChapterInfo {
                    novel_id: Some(id),
                    id: chapter_id,
                    title: chapter.chapter_title.trim().to_string(),
                    word_count: Some(chapter.word_count.parse()?),
                    create_time: Some(chapter.mtime),
                    update_time: None,
                    is_vip: Some(chapter.is_paid),
                    price,
                    payment_required: Some(!chapter.auth_access),
                    is_valid: Some(chapter.is_valid && is_valid),
                };

                volume_info.chapter_infos.push(chapter_info);
            }

            volume_infos.push(volume_info);
        }

        Ok(Some(volume_infos))
    }

    async fn content_infos(&self, info: &ChapterInfo) -> Result<ContentInfos, Error> {
        let content;

        match self.db().await?.find_text(info).await? {
            FindTextResult::Ok(str) => {
                content = str;
            }
            other => {
                let cmd = self.chapter_cmd(info.id).await?;
                let key = crate::sha256(cmd.as_bytes());

                let response: ChapsResponse = self
                    .post(
                        "/chapter/get_cpt_ifm",
                        ChapsRequest {
                            chapter_id: info.id.to_string(),
                            chapter_command: cmd,
                        },
                    )
                    .await?;
                utils::check_response_success(response.code, response.tip)?;

                content = simdutf8::basic::from_utf8(&crate::aes_256_cbc_no_iv_base64_decrypt(
                    key,
                    response.data.unwrap().chapter_info.txt_content,
                )?)?
                .to_string();

                match other {
                    FindTextResult::None => self.db().await?.insert_text(info, &content).await?,
                    FindTextResult::Outdate => self.db().await?.update_text(info, &content).await?,
                    FindTextResult::Ok(_) => (),
                }
            }
        }

        let mut content_infos = ContentInfos::new();
        for line in content
            .lines()
            .map(|line| line.trim())
            .filter(|line| !line.is_empty())
        {
            if line.starts_with("<img") {
                if let Some(url) = CiweimaoClient::parse_image_url(line) {
                    content_infos.push(ContentInfo::Image(url));
                }
            } else {
                content_infos.push(ContentInfo::Text(line.to_string()));
            }
        }

        Ok(content_infos)
    }

    async fn buy_chapter(&self, info: &ChapterInfo) -> Result<(), Error> {
        let response: GenericResponse = self
            .post(
                "/chapter/buy",
                BuyRequest {
                    chapter_id: info.id.to_string(),
                },
            )
            .await?;
        utils::check_response_success(response.code, response.tip)?;

        Ok(())
    }

    async fn image(&self, url: &Url) -> Result<DynamicImage, Error> {
        match self.db().await?.find_image(url).await? {
            FindImageResult::Ok(image) => Ok(image),
            FindImageResult::None => {
                let response = self.get_rss(url).await?;
                let bytes = response.bytes().await?;

                let image = Reader::new(Cursor::new(&bytes))
                    .with_guessed_format()?
                    .decode()?;

                self.db().await?.insert_image(url, bytes).await?;

                Ok(image)
            }
        }
    }

    async fn categories(&self) -> Result<&Vec<Category>, Error> {
        static CATEGORIES: OnceCell<Vec<Category>> = OnceCell::const_new();

        CATEGORIES
            .get_or_try_init(|| async {
                let response: CategoryResponse =
                    self.post("/meta/get_meta_data", EmptyRequest {}).await?;
                utils::check_response_success(response.code, response.tip)?;

                let mut result = Vec::new();
                for category in response.data.unwrap().category_list {
                    for category_detail in category.category_detail {
                        result.push(Category {
                            id: Some(category_detail.category_index.parse()?),
                            parent_id: None,
                            name: category_detail.category_name.trim().to_string(),
                        });
                    }
                }

                result.sort_unstable_by_key(|x| x.id.unwrap());

                Ok(result)
            })
            .await
    }

    async fn tags(&self) -> Result<&Vec<Tag>, Error> {
        static TAGS: OnceCell<Vec<Tag>> = OnceCell::const_new();

        TAGS.get_or_try_init(|| async {
            let response: TagResponse = self
                .post("/book/get_official_tag_list", EmptyRequest {})
                .await?;
            utils::check_response_success(response.code, response.tip)?;

            let mut result = Vec::new();
            for tag in response.data.unwrap().official_tag_list {
                result.push(Tag {
                    id: None,
                    name: tag.tag_name.trim().to_string(),
                });
            }

            result.push(Tag {
                id: None,
                name: String::from("橘子"),
            });
            result.push(Tag {
                id: None,
                name: String::from("变身"),
            });
            result.push(Tag {
                id: None,
                name: String::from("性转"),
            });
            result.push(Tag {
                id: None,
                name: String::from("纯百"),
            });

            Ok(result)
        })
        .await
    }

    async fn search_infos(
        &self,
        option: &Options,
        page: u16,
        size: u16,
    ) -> Result<Option<Vec<u32>>, Error> {
        let mut category_index = 0;
        if option.category.is_some() {
            category_index = option.category.as_ref().unwrap().id.unwrap();
        }

        let mut tags = Vec::new();
        if option.tags.is_some() {
            for tag in option.tags.as_ref().unwrap() {
                tags.push(json!({
                    "tag": tag.name,
                    "filter": "1"
                }));
            }
        }

        let is_paid = option.is_vip.map(|is_vip| if is_vip { 1 } else { 0 });

        let up_status = option
            .is_finished
            .map(|is_finished| if is_finished { 1 } else { 0 });

        let mut filter_word = None;
        if option.word_count.is_some() {
            match option.word_count.as_ref().unwrap() {
                WordCountRange::RangeTo(range_to) => {
                    if range_to.end < 30_0000 {
                        filter_word = Some(1);
                    }
                }
                WordCountRange::Range(range) => {
                    if range.start >= 30_0000 && range.end < 50_0000 {
                        filter_word = Some(2);
                    } else if range.start >= 50_0000 && range.end < 100_0000 {
                        filter_word = Some(3);
                    } else if range.start >= 100_0000 && range.end < 200_0000 {
                        filter_word = Some(4);
                    }
                }
                WordCountRange::RangeFrom(range_from) => {
                    if range_from.start >= 200_0000 {
                        filter_word = Some(5);
                    }
                }
            }
        }

        let mut filter_uptime = None;
        if option.update_days.is_some() {
            let update_days = *option.update_days.as_ref().unwrap();

            if update_days <= 3 {
                filter_uptime = Some(1)
            } else if update_days <= 7 {
                filter_uptime = Some(2)
            } else if update_days <= 15 {
                filter_uptime = Some(3)
            } else if update_days <= 30 {
                filter_uptime = Some(4)
            }
        }

        let order = if option.keyword.is_some() {
            // When using keyword search, many irrelevant items will appear in the search results
            // If you use sorting, you will not be able to obtain the target items
            None
        } else {
            // 人气排序
            Some("week_click")
        };

        let response: SearchResponse = self
            .post(
                "/bookcity/get_filter_search_book_list",
                SearchRequest {
                    count: size,
                    page,
                    order,
                    category_index,
                    tags: json!(tags).to_string(),
                    key: option.keyword.clone(),
                    is_paid,
                    up_status,
                    filter_uptime,
                    filter_word,
                },
            )
            .await?;
        utils::check_response_success(response.code, response.tip)?;

        let book_list = response.data.unwrap().book_list;
        if book_list.is_empty() {
            return Ok(None);
        }

        let mut result = Vec::new();
        let sys_tags = self.tags().await?;

        for novel_info in book_list {
            let mut tag_names = Vec::new();
            for tag in novel_info.tag_list {
                if let Some(sys_tag) = sys_tags.iter().find(|x| x.name == tag.tag_name.trim()) {
                    tag_names.push(sys_tag.name.clone());
                }
            }

            if CiweimaoClient::match_update_days(option, novel_info.uptime)
                && CiweimaoClient::match_excluded_tags(option, tag_names)
                && CiweimaoClient::match_word_count(option, novel_info.total_word_count.parse()?)
            {
                result.push(novel_info.book_id.parse()?);
            }
        }

        Ok(Some(result))
    }

    fn has_this_type_of_comments(comment_type: CommentType) -> bool {
        match comment_type {
            CommentType::Short => true,
            CommentType::Long => true,
        }
    }
}

#[must_use]
enum VerifyType {
    None,
    Geetest,
    VerifyCode,
}

impl CiweimaoClient {
    async fn review_comment(
        &self,
        review_id: u32,
        comment_amount: u16,
    ) -> Result<Option<Vec<ShortComment>>, Error> {
        let response: ReviewCommentResponse = self
            .post(
                "/book/get_review_comment_list",
                ReviewCommentRequest {
                    review_id,
                    page: 0,
                    count: comment_amount,
                },
            )
            .await?;
        utils::check_response_success(response.code, response.tip)?;
        let review_comment_list = response.data.unwrap().review_comment_list;

        let mut result = Vec::with_capacity(review_comment_list.len());

        for comment in review_comment_list {
            let Some(content) = super::parse_multi_line(comment.comment_content) else {
                continue;
            };

            let replies = if comment.review_comment_reply_list.is_empty() {
                None
            } else if
            // 返回的最大数量似乎为 3 个
            comment.review_comment_reply_list.len() <= 2 {
                let mut result = Vec::with_capacity(2);

                for reply in comment.review_comment_reply_list {
                    let Some(content) = super::parse_multi_line(reply.reply_content) else {
                        continue;
                    };

                    result.push(ShortComment {
                        id: reply.reply_id.parse()?,
                        user: UserInfo {
                            nickname: reply.reader_info.reader_name.trim().to_string(),
                            avatar: reply.reader_info.avatar_url,
                        },
                        content,
                        create_time: Some(reply.ctime),
                        like_count: None,
                        replies: None,
                    })
                }

                if result.is_empty() {
                    None
                } else {
                    result.sort_unstable_by_key(|x| x.create_time.unwrap());
                    Some(result.into_iter().dedup().collect_vec())
                }
            } else {
                self.review_comment_reply(comment.comment_id.parse()?)
                    .await?
            };

            result.push(ShortComment {
                id: comment.comment_id.parse()?,
                user: UserInfo {
                    nickname: comment.reader_info.reader_name.trim().to_string(),
                    avatar: comment.reader_info.avatar_url,
                },
                content,
                create_time: Some(comment.ctime),
                like_count: None,
                replies,
            });
        }

        if result.is_empty() {
            Ok(None)
        } else {
            result.sort_unstable_by_key(|x| x.create_time.unwrap());
            Ok(Some(result.into_iter().dedup().collect_vec()))
        }
    }

    async fn review_comment_reply(
        &self,
        comment_id: u32,
    ) -> Result<Option<Vec<ShortComment>>, Error> {
        let response: ReviewCommentReplyResponse = self
            .post(
                "/book/get_review_comment_reply_list",
                ReviewCommentReplyRequest {
                    comment_id,
                    page: 0,
                    count: 9999,
                },
            )
            .await?;
        utils::check_response_success(response.code, response.tip)?;

        let mut result = Vec::with_capacity(4);

        for reply in response.data.unwrap().review_comment_reply_list {
            let Some(content) = super::parse_multi_line(reply.reply_content) else {
                continue;
            };

            let comment = ShortComment {
                id: reply.reply_id.parse()?,
                user: UserInfo {
                    nickname: reply.reader_info.reader_name.trim().to_string(),
                    avatar: reply.reader_info.avatar_url,
                },
                content,
                create_time: Some(reply.ctime),
                like_count: None,
                replies: None,
            };

            result.push(comment);
        }

        if result.is_empty() {
            Ok(None)
        } else {
            result.sort_unstable_by_key(|x| x.create_time.unwrap());
            Ok(Some(result.into_iter().dedup().collect_vec()))
        }
    }

    async fn verify_type<T>(&self, username: T) -> Result<VerifyType, Error>
    where
        T: AsRef<str>,
    {
        let response: UseGeetestResponse = self
            .post(
                "/signup/use_geetest",
                UseGeetestRequest {
                    login_name: username.as_ref().to_string(),
                },
            )
            .await?;
        utils::check_response_success(response.code, response.tip)?;

        let need_use_geetest = response.data.unwrap().need_use_geetest;
        if need_use_geetest == "0" {
            Ok(VerifyType::None)
        } else if need_use_geetest == "1" {
            Ok(VerifyType::Geetest)
        } else if need_use_geetest == "2" {
            Ok(VerifyType::VerifyCode)
        } else {
            unreachable!("The value range of need_use_geetest is 0..=2");
        }
    }

    async fn no_verification_login(
        &self,
        username: String,
        password: String,
    ) -> Result<Config, Error> {
        let response: LoginResponse = self
            .post(
                "/signup/login",
                LoginRequest {
                    login_name: username,
                    passwd: password,
                },
            )
            .await?;
        utils::check_response_success(response.code, response.tip)?;

        let data = response.data.unwrap();

        Ok(Config {
            account: data.reader_info.account,
            login_token: data.login_token,
        })
    }

    async fn geetest_login(&self, username: String, password: String) -> Result<Config, Error> {
        let info = self.geetest_info(&username).await?;
        let geetest_challenge = info.challenge.clone();

        let validate = server::run_geetest(info).await?;

        let response: LoginResponse = self
            .post(
                "/signup/login",
                LoginCaptchaRequest {
                    login_name: username,
                    passwd: password,
                    geetest_seccode: validate.clone() + "|jordan",
                    geetest_validate: validate,
                    geetest_challenge,
                },
            )
            .await?;
        utils::check_response_success(response.code, response.tip)?;

        let data = response.data.unwrap();

        Ok(Config {
            account: data.reader_info.account,
            login_token: data.login_token,
        })
    }

    async fn geetest_info<T>(&self, username: T) -> Result<GeetestInfoResponse, Error>
    where
        T: AsRef<str>,
    {
        let timestamp = SystemTime::now().duration_since(UNIX_EPOCH)?.as_millis();

        let response = self
            .get_query(
                "/signup/geetest_first_register",
                GeetestInfoRequest {
                    t: timestamp,
                    user_id: username.as_ref().to_string(),
                },
            )
            .await?
            .json::<GeetestInfoResponse>()
            .await?;

        if response.success != 1 {
            return Err(Error::NovelApi(String::from(
                "`/signup/geetest_first_register` failed",
            )));
        }

        Ok(response)
    }

    async fn sms_login(&self, username: String, password: String) -> Result<Config, Error> {
        let timestamp = SystemTime::now()
            .duration_since(UNIX_EPOCH)
            .unwrap()
            .as_millis();

        let response: SendVerifyCodeResponse = self
            .post(
                "/signup/send_verify_code",
                SendVerifyCodeRequest {
                    login_name: username.clone(),
                    timestamp,
                    // always 5
                    verify_type: 5,
                },
            )
            .await?;
        utils::check_response_success(response.code, response.tip)?;

        let response: LoginResponse = self
            .post(
                "/signup/login",
                LoginSMSRequest {
                    login_name: username,
                    passwd: password,
                    to_code: response.data.unwrap().to_code,
                    ver_code: crate::input("Please enter SMS verification code")?,
                },
            )
            .await?;
        utils::check_response_success(response.code, response.tip)?;

        let data = response.data.unwrap();

        Ok(Config {
            account: data.reader_info.account,
            login_token: data.login_token,
        })
    }

    async fn shelf_list(&self) -> Result<Vec<u32>, Error> {
        let response: ShelfListResponse = self
            .post("/bookshelf/get_shelf_list", EmptyRequest {})
            .await?;
        utils::check_response_success(response.code, response.tip)?;

        let mut result = Vec::new();
        for shelf in response.data.unwrap().shelf_list {
            result.push(shelf.shelf_id.parse()?);
        }

        Ok(result)
    }

    async fn chapter_prices(&self, novel_id: u32) -> Result<HashMap<u32, u16>, Error> {
        let response: PriceResponse = self
            .post(
                "/chapter/get_chapter_permission_list",
                PriceRequest { book_id: novel_id },
            )
            .await?;
        utils::check_response_success(response.code, response.tip)?;
        let chapter_permission_list = response.data.unwrap().chapter_permission_list;

        let mut result = HashMap::new();

        for item in chapter_permission_list {
            result.insert(item.chapter_id.parse()?, item.unit_hlb.parse()?);
        }

        Ok(result)
    }

    async fn chapter_cmd(&self, id: u32) -> Result<String, Error> {
        let response: ChapterCmdResponse = self
            .post(
                "/chapter/get_chapter_cmd",
                ChapterCmdRequest {
                    chapter_id: id.to_string(),
                },
            )
            .await?;
        utils::check_response_success(response.code, response.tip)?;

        Ok(response.data.unwrap().command)
    }

    fn match_update_days(option: &Options, update_time: NaiveDateTime) -> bool {
        if option.update_days.is_none() {
            return true;
        }

        let other_time = Shanghai.from_local_datetime(&update_time).unwrap()
            + Duration::try_days(*option.update_days.as_ref().unwrap() as i64).unwrap();

        Local::now() <= other_time
    }

    fn match_word_count(option: &Options, word_count: u32) -> bool {
        if option.word_count.is_none() {
            return true;
        }

        match option.word_count.as_ref().unwrap() {
            WordCountRange::RangeTo(range_to) => word_count <= range_to.end,
            WordCountRange::Range(range) => range.start <= word_count && word_count <= range.end,
            WordCountRange::RangeFrom(range_from) => range_from.start <= word_count,
        }
    }

    fn match_excluded_tags(option: &Options, tag_ids: Vec<String>) -> bool {
        if option.excluded_tags.is_none() {
            return true;
        }

        tag_ids.iter().all(|name| {
            !option
                .excluded_tags
                .as_ref()
                .unwrap()
                .iter()
                .any(|tag| tag.name == *name)
        })
    }

    fn parse_url<T>(str: T) -> Option<Url>
    where
        T: AsRef<str>,
    {
        let str = str.as_ref();
        if str.is_empty() {
            return None;
        }

        match Url::parse(str) {
            Ok(url) => Some(url),
            Err(error) => {
                error!("Url parse failed: {error}, content: {str}");
                None
            }
        }
    }

    async fn parse_tags(&self, tag_list: Vec<NovelInfoTag>) -> Result<Option<Vec<Tag>>, Error> {
        let sys_tags = self.tags().await?;

        let mut result = Vec::new();
        for tag in tag_list {
            let name = tag.tag_name.trim().to_string();

            // Remove non-system tags
            if sys_tags.iter().any(|item| item.name == name) {
                result.push(Tag { id: None, name });
            } else {
                info!("This tag is not a system tag and is ignored: {name}");
            }
        }

        if result.is_empty() {
            Ok(None)
        } else {
            Ok(Some(result))
        }
    }

    async fn parse_category<T>(&self, str: T) -> Result<Option<Category>, Error>
    where
        T: AsRef<str>,
    {
        let str = str.as_ref();
        if str.is_empty() {
            return Ok(None);
        }

        let categories = self.categories().await?;

        match str.parse::<u16>() {
            Ok(index) => match categories.iter().find(|item| item.id == Some(index)) {
                Some(category) => Ok(Some(category.clone())),
                None => {
                    error!("The category index does not exist: {str}");
                    Ok(None)
                }
            },
            Err(error) => {
                error!("category_index parse failed: {error}");
                Ok(None)
            }
        }
    }

    fn parse_image_url<T>(str: T) -> Option<Url>
    where
        T: AsRef<str>,
    {
        let str = str.as_ref();
        if str.is_empty() {
            return None;
        }

        let fragment = Html::parse_fragment(str);
        let selector = Selector::parse("img").unwrap();

        let element = fragment.select(&selector).next();
        if element.is_none() {
            error!("No `img` element exists: {str}");
            return None;
        }
        let element = element.unwrap();

        let url = element.value().attr("src");
        if url.is_none() {
            error!("No `src` attribute exists: {str}");
            return None;
        }
        let url = url.unwrap();

        CiweimaoClient::parse_url(url.trim())
    }
}