-
Notifications
You must be signed in to change notification settings - Fork 186
Expand file tree
/
Copy pathcopy_manga.js
More file actions
1105 lines (1012 loc) · 37.9 KB
/
Copy pathcopy_manga.js
File metadata and controls
1105 lines (1012 loc) · 37.9 KB
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
class CopyManga extends ComicSource {
name = "拷贝漫画"
key = "copy_manga"
version = "1.4.1"
minAppVersion = "1.6.0"
url = "https://cdn.jsdelivr.net/gh/venera-app/venera-configs@main/copy_manga.js"
async getReqID() {
if (this.copyRegion === "0") {
return "";
}
const reqIdUrl = "https://marketing.aiacgn.com/api/v2/adopr/query3/?format=json&ident=200100001";
let reqId = "";
try {
const response = await Network.get(reqIdUrl, this.headers);
if (response.status === 200) {
const data = JSON.parse(response.body);
reqId = data.results.request_id;
}
} catch (e) {
}
return reqId;
}
get headers() {
let token = this.loadData("token");
let secret = "M2FmMDg1OTAzMTEwMzJlZmUwNjYwNTUwYTA1NjNhNTM="
let now = new Date(Date.now());
let year = now.getFullYear();
let month = (now.getMonth() + 1).toString().padStart(2, '0');
let day = now.getDate().toString().padStart(2, '0');
let ts = Math.floor(now.getTime() / 1000).toString()
if (!token) {
token = "";
} else {
token = " " + token;
}
let sig = Convert.hmacString(
Convert.decodeBase64(secret),
Convert.encodeUtf8(ts),
"sha256"
)
return {
"User-Agent": `COPY/3.0.6`,
"source": "copyApp",
"deviceinfo": this.deviceinfo,
"dt": `${year}.${month}.${day}`,
"platform": "3",
"referer": `com.copymanga.app-3.0.6`,
"version": "3.0.6",
"device": this.device,
"pseudoid": this.pseudoid,
"Accept": "application/json",
"region": this.copyRegion,
"authorization": `Token${token}`,
"umstring": "b4c89ca4104ea9a97750314d791520ac",
"x-auth-timestamp": ts,
"x-auth-signature": sig,
}
}
// static defaultCopyVersion = "3.0.6"
// static defaultCopyPlatform = "2"
static defaultCopyRegion = "0"
static defaultImageQuality = "1500"
static defaultApiUrl = 'api.copy2000.online'
static searchApi = "/api/kb/web/searchb/comics"
get deviceinfo() {
let info = this.loadData("_deviceinfo");
if (!info) {
info = CopyManga.generateDeviceInfo();
this.saveData("_deviceinfo", info);
}
return info;
}
get device() {
let dev = this.loadData("_device");
if (!dev) {
dev = CopyManga.generateDevice();
this.saveData("_device", dev);
}
return dev;
}
get pseudoid() {
let pid = this.loadData("_pseudoid");
if (!pid) {
pid = CopyManga.generatePseudoid();
this.saveData("_pseudoid", pid);
}
return pid;
}
// get copyVersion() {
// return this.loadSetting('version')
// }
// get copyPlatform()
// return this.loadSetting('platform')
// }
static generateDeviceInfo() {
return `${randomInt(1000000, 9999999)}V-${randomInt(1000, 9999)}`;
}
static generateDevice() {
function randCharA() {
return String.fromCharCode(65 + randomInt(0, 25));
}
function randDigit() {
return String.fromCharCode(48 + randomInt(0, 9));
}
return (
randCharA() +
randCharA() +
randDigit() +
randCharA() + "." +
randDigit() +
randDigit() +
randDigit() +
randDigit() +
randDigit() +
randDigit() + "." +
randDigit() +
randDigit() +
randDigit()
);
}
static generatePseudoid() {
const chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
let pseudoid = '';
for (let i = 0; i < 16; i++) {
pseudoid += chars.charAt(randomInt(0, chars.length - 1));
}
return pseudoid;
}
get apiUrl() {
return `https://${this.loadSetting('base_url')}`
}
get copyRegion() {
return this.loadSetting('region') || this.defaultCopyRegion
}
get imageQuality() {
return this.loadSetting('image_quality') || this.defaultImageQuality
}
init() {
// 用于储存 { 作者名 : 英文参数 }
this.author_path_word_dict = {}
this.refreshSearchApi()
this.refreshAppApi()
}
/// account
/// set this to null to desable account feature
account = {
/// login func
login: async (account, pwd) => {
let salt = randomInt(1000, 9999)
let base64 = Convert.encodeBase64(Convert.encodeUtf8(`${pwd}-${salt}`))
let res = await Network.post(
`${this.apiUrl}/api/v3/login`,
{
...this.headers,
"Content-Type": "application/x-www-form-urlencoded;charset=utf-8"
},
`username=${account}&password=${base64}\n&salt=${salt}&authorization=Token+`
);
if (res.status === 200) {
let data = JSON.parse(res.body)
let token = data.results.token
this.saveData('token', token)
return "ok"
} else {
throw `Invalid Status Code ${res.status}`
}
},
// callback when user log out
logout: () => {
this.deleteData('token')
},
registerWebsite: null
}
/// explore pages
explore = [
{
title: "拷贝漫画",
type: "singlePageWithMultiPart",
load: async () => {
let dataStr = await Network.get(
`${this.apiUrl}/api/v3/h5/homeIndex`,
this.headers
)
if (dataStr.status !== 200) {
throw `Invalid status code: ${dataStr.status}`
}
let data = JSON.parse(dataStr.body)
function parseComic(comic) {
if (comic["comic"] !== null && comic["comic"] !== undefined) {
comic = comic["comic"]
}
let tags = []
if (comic["theme"] !== null && comic["theme"] !== undefined) {
tags = comic["theme"].map(t => t["name"])
}
let author = null
if (Array.isArray(comic["author"]) && comic["author"].length > 0) {
author = comic["author"][0]["name"]
}
return {
id: comic["path_word"],
title: comic["name"],
subTitle: author,
cover: comic["cover"],
tags: tags
}
}
let res = {}
res["推荐"] = data["results"]["recComics"]["list"].map(parseComic)
res["热门"] = data["results"]["hotComics"].map(parseComic)
res["最新"] = data["results"]["newComics"].map(parseComic)
res["完结"] = data["results"]["finishComics"]["list"].map(parseComic)
res["今日排行"] = data["results"]["rankDayComics"]["list"].map(parseComic)
res["本周排行"] = data["results"]["rankWeekComics"]["list"].map(parseComic)
res["本月排行"] = data["results"]["rankMonthComics"]["list"].map(parseComic)
return res
}
}
]
static category_param_dict = {
"全部": "",
"愛情": "aiqing",
"歡樂向": "huanlexiang",
"冒險": "maoxian",
"奇幻": "qihuan",
"百合": "baihe",
"校园": "xiaoyuan",
"科幻": "kehuan",
"東方": "dongfang",
"耽美": "danmei",
"生活": "shenghuo",
"格鬥": "gedou",
"轻小说": "qingxiaoshuo",
"悬疑": "xuanyi",
"其他": "qita",
"神鬼": "shengui",
"职场": "zhichang",
"TL": "teenslove",
"萌系": "mengxi",
"治愈": "zhiyu",
"長條": "changtiao",
"四格": "sige",
"节操": "jiecao",
"舰娘": "jianniang",
"竞技": "jingji",
"搞笑": "gaoxiao",
"伪娘": "weiniang",
"热血": "rexue",
"励志": "lizhi",
"性转换": "xingzhuanhuan",
"彩色": "COLOR",
"後宮": "hougong",
"美食": "meishi",
"侦探": "zhentan",
"AA": "aa",
"音乐舞蹈": "yinyuewudao",
"魔幻": "mohuan",
"战争": "zhanzheng",
"历史": "lishi",
"异世界": "yishijie",
"惊悚": "jingsong",
"机战": "jizhan",
"都市": "dushi",
"穿越": "chuanyue",
"恐怖": "kongbu",
"C100": "comiket100",
"重生": "chongsheng",
"C99": "comiket99",
"C101": "comiket101",
"C97": "comiket97",
"C96": "comiket96",
"生存": "shengcun",
"宅系": "zhaixi",
"武侠": "wuxia",
"C98": "C98",
"C95": "comiket95",
"FATE": "fate",
"转生": "zhuansheng",
"無修正": "Uncensored",
"仙侠": "xianxia",
"LoveLive": "loveLive"
}
category = {
title: "拷贝漫画",
parts: [
{
name: "拷贝漫画",
type: "fixed",
categories: ["排行"],
categoryParams: ["ranking"],
itemType: "category"
},
{
name: "主题",
type: "fixed",
categories: Object.keys(CopyManga.category_param_dict),
categoryParams: Object.values(CopyManga.category_param_dict),
itemType: "category"
}
]
}
categoryComics = {
load: async (category, param, options, page) => {
let category_url;
// 分类-排行
if (category === "排行" || param === "ranking") {
category_url = `${this.apiUrl}/api/v3/ranks?limit=30&offset=${(page - 1) * 30}&_update=true&type=1&audience_type=${options[0]}&date_type=${options[1]}`
} else {
// 分类-主题
if (category !== undefined && category !== null) {
// 若传入category,则转化为对应param
param = CopyManga.category_param_dict[category] || "";
}
options = options.map(e => e.replace("*", "-"))
category_url = `${this.apiUrl}/api/v3/comics?limit=30&offset=${(page - 1) * 30}&ordering=${options[1]}&theme=${param}&top=${options[0]}`
}
let res = await Network.get(
category_url,
this.headers
)
if (res.status !== 200) {
throw `Invalid status code: ${res.status}`
}
let data = JSON.parse(res.body)
function parseComic(comic) {
//判断是否是漫画排名格式
let sort = null
let popular = 0
let rise_sort = 0;
if (comic["sort"] !== null && comic["sort"] !== undefined) {
sort = comic["sort"]
rise_sort = comic["rise_sort"]
popular = comic["popular"]
}
if (comic["comic"] !== null && comic["comic"] !== undefined) {
comic = comic["comic"]
}
let tags = []
if (comic["theme"] !== null && comic["theme"] !== undefined) {
tags = comic["theme"].map(t => t["name"])
}
let author = null
let author_num = 0
if (Array.isArray(comic["author"]) && comic["author"].length > 0) {
author = comic["author"][0]["name"]
author_num = comic["author"].length
}
//如果是漫画排名,则描述为 排名(+升降箭头)+作者+人气
if (sort !== null) {
return {
id: comic["path_word"],
title: comic["name"],
subTitle: author,
cover: comic["cover"],
tags: tags,
description: `${sort} ${rise_sort > 0 ? '▲' : rise_sort < 0 ? '▽' : '-'}\n` +
`${author_num > 1 ? `${author} 等${author_num}位` : author}\n` +
`🔥${(popular / 10000).toFixed(1)}W`
}
//正常情况的描述为更新时间
} else {
return {
id: comic["path_word"],
title: comic["name"],
subTitle: author,
cover: comic["cover"],
tags: tags,
description: comic["datetime_updated"]
}
}
}
return {
comics: data["results"]["list"].map(parseComic),
maxPage: (data["results"]["total"] - (data["results"]["total"] % 21)) / 21 + 1
}
},
optionList: [
{
options: [
"-全部",
"japan-日漫",
"korea-韩漫",
"west-美漫",
"finish-已完结"
],
notShowWhen: null,
showWhen: Object.keys(CopyManga.category_param_dict)
},
{
options: [
"*datetime_updated-时间倒序",
"datetime_updated-时间正序",
"*popular-热度倒序",
"popular-热度正序",
],
notShowWhen: null,
showWhen: Object.keys(CopyManga.category_param_dict)
},
{
options: [
"male-男频",
"female-女频"
],
notShowWhen: null,
showWhen: ["排行"]
},
{
options: [
"day-上升最快",
"week-最近7天",
"month-最近30天",
"total-總榜單"
],
notShowWhen: null,
showWhen: ["排行"]
}
]
}
search = {
load: async (keyword, options, page) => {
let author;
if (keyword.startsWith("作者:")) {
author = keyword.substring("作者:".length).trim();
}
let res;
// 通过onClickTag传入时有"作者:"前缀,处理这种情况
if (author && author in this.author_path_word_dict) {
let path_word = encodeURIComponent(this.author_path_word_dict[author]);
res = await Network.get(
`${this.apiUrl}/api/v3/comics?limit=30&offset=${(page - 1) * 30}&ordering=-datetime_updated&author=${path_word}`,
this.headers
)
}
// 一般的搜索情况
else {
let q_type = "";
if (options && options[0]) {
q_type = options[0];
}
keyword = encodeURIComponent(keyword)
let search_url = this.loadSetting('search_api') === "webAPI"
? `${this.apiUrl}${CopyManga.searchApi}`
: `${this.apiUrl}/api/v3/search/comic`
res = await Network.get(
`${search_url}?limit=30&offset=${(page - 1) * 30}&q=${keyword}&q_type=${q_type}`,
this.headers
)
}
if (res.status !== 200) {
throw `Invalid status code: ${res.status}`
}
let data = JSON.parse(res.body)
function parseComic(comic) {
if (comic["comic"] !== null && comic["comic"] !== undefined) {
comic = comic["comic"]
}
let tags = []
if (comic["theme"] !== null && comic["theme"] !== undefined) {
tags = comic["theme"].map(t => t["name"])
}
let author = null
if (Array.isArray(comic["author"]) && comic["author"].length > 0) {
author = comic["author"][0]["name"]
}
return {
id: comic["path_word"],
title: comic["name"],
subTitle: author,
cover: comic["cover"],
tags: tags,
description: comic["datetime_updated"]
}
}
return {
comics: data["results"]["list"].map(parseComic),
maxPage: (data["results"]["total"] - (data["results"]["total"] % 21)) / 21 + 1
}
},
optionList: [
{
type: "select",
options: [
"-全部",
"name-名称",
"author-作者",
"local-汉化组"
],
label: "搜索选项"
}
]
}
favorites = {
multiFolder: false,
addOrDelFavorite: async (comicId, folderId, isAdding) => {
let is_collect = isAdding ? 1 : 0
let token = this.loadData("token");
let reqId = await this.getReqID();
let comicData = await Network.get(
`${this.apiUrl}/api/v3/comic2/${comicId}?in_mainland=true&request_id=${reqId}&platform=3`,
this.headers
)
if (comicData.status !== 200) {
throw `Invalid status code: ${comicData.status}`
}
let comic_id = JSON.parse(comicData.body).results.comic.uuid
let res = await Network.post(
`${this.apiUrl}/api/v3/member/collect/comic`,
{
...this.headers,
"Content-Type": "application/x-www-form-urlencoded;charset=utf-8",
},
`comic_id=${comic_id}&is_collect=${is_collect}&authorization=Token+${token}`
)
if (res.status === 401) {
throw `Login expired`;
}
if (res.status !== 200) {
throw `Invalid status code: ${res.status}`
}
return "ok"
},
loadComics: async (page, folder) => {
let ordering = this.loadSetting('favorites_ordering') || '-datetime_updated';
var res = await Network.get(
`${this.apiUrl}/api/v3/member/collect/comics?limit=30&offset=${(page - 1) * 30}&free_type=1&ordering=${ordering}`,
this.headers
)
if (res.status === 401) {
throw `Login expired`
}
if (res.status !== 200) {
throw `Invalid status code: ${res.status}`
}
let data = JSON.parse(res.body)
function parseComic(comic) {
if (comic["comic"] !== null && comic["comic"] !== undefined) {
comic = comic["comic"]
}
let tags = []
if (comic["theme"] !== null && comic["theme"] !== undefined) {
tags = comic["theme"].map(t => t["name"])
}
let author = null
if (Array.isArray(comic["author"]) && comic["author"].length > 0) {
author = comic["author"][0]["name"]
}
return {
id: comic["path_word"],
title: comic["name"],
subTitle: author,
cover: comic["cover"],
tags: tags,
description: comic["datetime_updated"]
}
}
return {
comics: data["results"]["list"].map(parseComic),
maxPage: (data["results"]["total"] - (data["results"]["total"] % 21)) / 21 + 1
}
}
}
comic = {
loadInfo: async (id) => {
let getChapters = async (id, groups) => {
let fetchSingle = async (id, path) => {
let reqId = await this.getReqID();
let res = await Network.get(
`${this.apiUrl}/api/v3/comic/${id}/group/${path}/chapters?limit=100&offset=0&in_mainland=true&request_id=${reqId}`,
this.headers
);
if (res.status !== 200) {
throw `Invalid status code: ${res.status}`;
}
let data = JSON.parse(res.body);
let eps = new Map();
data.results.list.forEach((e) => {
let title = e.name;
let id = e.uuid;
eps.set(id, title);
});
let maxChapter = data.results.total;
if (maxChapter > 100) {
let offset = 100;
while (offset < maxChapter) {
res = await Network.get(
`${this.apiUrl}/api/v3/comic/${id}/group/${path}/chapters?limit=100&offset=${offset}`,
this.headers
);
if (res.status !== 200) {
throw `Invalid status code: ${res.status}`;
}
data = JSON.parse(res.body);
data.results.list.forEach((e) => {
let title = e.name;
let id = e.uuid;
eps.set(id, title)
});
offset += 100;
}
}
return eps;
};
let keys = Object.keys(groups);
let result = {};
let futures = [];
for (let group of keys) {
let path = groups[group]["path_word"];
futures.push((async () => {
result[group] = await fetchSingle(id, path);
})());
}
await Promise.all(futures);
if (this.isAppVersionAfter("1.3.0")) {
// 支持多分组
let sortedResult = new Map();
for (let key of keys) {
let name = groups[key]["name"];
sortedResult.set(name, result[key]);
}
return sortedResult;
} else {
// 合并所有分组
let merged = new Map();
for (let key of keys) {
for (let [k, v] of result[key]) {
merged.set(k, v);
}
}
return merged;
}
}
let getFavoriteStatus = async (id) => {
let res = await Network.get(`${this.apiUrl}/api/v3/comic2/${id}/query`, this.headers);
if (res.status !== 200) {
throw `Invalid status code: ${res.status}`;
}
return JSON.parse(res.body).results.collect != null;
}
let reqId = await this.getReqID();
let results = await Promise.all([
Network.get(
`${this.apiUrl}/api/v3/comic2/${id}?in_mainland=true&request_id=${reqId}&platform=3`,
this.headers
),
getFavoriteStatus.bind(this)(id)
])
if (results[0].status !== 200) {
throw `Invalid status code: ${res.status}`;
}
let data = JSON.parse(results[0].body).results;
let comicData = data.comic;
let title = comicData.name;
let cover = comicData.cover;
let authors = comicData.author.map(e => e.name);
// author_path_word_dict长度限制为最大100
if (Object.keys(this.author_path_word_dict).length > 100) {
this.author_path_word_dict = {};
}
// 储存author对应的path_word
comicData.author.forEach(e => (this.author_path_word_dict[e.name] = e.path_word));
let tags = comicData.theme.map(e => e?.name).filter(name => name !== undefined && name !== null);
let updateTime = comicData.datetime_updated ? comicData.datetime_updated : "";
let description = comicData.brief;
let chapters = await getChapters(id, data.groups);
let status = comicData.status.display;
return {
title: title,
cover: cover,
description: description,
tags: {
"作者": authors,
"更新": [updateTime],
"标签": tags,
"状态": [status],
},
chapters: chapters,
isFavorite: results[1],
subId: comicData.uuid
}
},
loadEp: async (comicId, epId) => {
let attempt = 0;
const maxAttempts = 5;
let res;
let data;
while (attempt < maxAttempts) {
try {
let reqId = await this.getReqID();
res = await Network.get(
`${this.apiUrl}/api/v3/comic/${comicId}/chapter2/${epId}?in_mainland=true&request_id=${reqId}`,
{
...this.headers
}
);
if (res.status === 210) {
// 210 indicates too frequent access, extract wait time
let waitTime = 40000; // Default wait time 40s
try {
let responseBody = JSON.parse(res.body);
if (
responseBody.message &&
responseBody.message.includes("Expected available in")
) {
let match = responseBody.message.match(/(\d+)\s*seconds/);
if (match && match[1]) {
waitTime = parseInt(match[1]) * 1000;
}
}
} catch (e) {
console.log(
"Unable to parse wait time, using default wait time 40s"
);
}
console.log(`Chapter${epId} access too frequent, waiting ${waitTime / 1000}s`);
await new Promise((resolve) => setTimeout(resolve, waitTime));
throw "Retry";
}
if (res.status !== 200) {
throw `Invalid status code: ${res.status}`;
}
data = JSON.parse(res.body);
// console.log(data.results.chapter);
// Handle image link sorting
let imagesUrls = data.results.chapter.contents.map((e) => e.url);
let orders = data.results.chapter.words;
// Replace origin images urls to selected quality images urls
let hdImagesUrls = imagesUrls.map((url) =>
url.replace(/([./])c\d+x\.[a-zA-Z]+$/, `$1c${this.imageQuality}x.webp`)
)
let images = new Array(hdImagesUrls.length).fill(""); // Initialize an array with the same length as imagesUrls
// Arrange images according to orders
for (let i = 0; i < hdImagesUrls.length; i++) {
images[orders[i]] = hdImagesUrls[i];
}
return {
images: images,
};
} catch (error) {
if (error !== "Retry") {
throw error;
}
attempt++;
if (attempt >= maxAttempts) {
throw error;
}
}
}
},
loadComments: async (comicId, subId, page, replyTo) => {
let url = `${this.apiUrl}/api/v3/comments?comic_id=${subId}&limit=20&offset=${(page - 1) * 20}`;
if (replyTo) {
url = url + `&reply_id=${replyTo}&_update=true`;
}
let res = await Network.get(
url,
this.headers,
);
if (res.status !== 200) {
if (res.status === 210) {
throw "210:注冊用戶一天可以發5條評論"
}
throw `Invalid status code: ${res.status}`;
}
let data = JSON.parse(res.body);
let total = data.results.total;
return {
comments: data.results.list.map(e => {
return {
userName: replyTo ? `${e.user_name} 👉 ${e.parent_user_name}` : e.user_name, // 拷贝的回复页并没有楼中楼(所有回复都在一个response中),但会显示谁回复了谁。所以加上👉显示。
avatar: e.user_avatar,
content: e.comment,
time: e.create_at,
replyCount: e.count,
id: e.id,
}
}),
maxPage: (total - (total % 20)) / 20 + 1,
}
},
sendComment: async (comicId, subId, content, replyTo) => {
let token = this.loadData("token");
if (!token) {
throw "未登录"
}
if (!replyTo) {
replyTo = '';
}
let res = await Network.post(
`${this.apiUrl}/api/v3/member/comment`,
{
...this.headers,
"Content-Type": "application/x-www-form-urlencoded;charset=utf-8",
},
`comic_id=${subId}&comment=${encodeURIComponent(content)}&reply_id=${replyTo}`,
);
if (res.status === 401) {
error(`Login expired`);
return;
}
if (res.status !== 200) {
throw `Invalid status code: ${res.status}`;
} else {
return "ok"
}
},
loadChapterComments: async (comicId, epId, page, replyTo) => {
let url = `${this.apiUrl}/api/v3/roasts?chapter_id=${epId}&limit=20&offset=${(page - 1) * 20}`;
let res = await Network.get(
url,
this.headers,
);
if (res.status !== 200) {
throw `Invalid status code: ${res.status}`;
}
let data = JSON.parse(res.body);
let total = data.results.total;
return {
comments: data.results.list.map(e => {
return {
userName: e.user_name,
avatar: e.user_avatar,
content: e.comment,
time: e.create_at,
replyCount: null,
id: null,
}
}),
maxPage: (total - (total % 20)) / 20 + 1,
}
},
sendChapterComment: async (comicId, epId, content, replyTo) => {
let token = this.loadData("token");
if (!token) {
throw "未登录"
}
let res = await Network.post(
`${this.apiUrl}/api/v3/member/roast`,
{
...this.headers,
"Content-Type": "application/x-www-form-urlencoded;charset=utf-8",
},
`chapter_id=${epId}&roast=${encodeURIComponent(content)}`,
);
if (res.status === 401) {
throw `Login expired`;
}
if (res.status !== 200) {
if (res.status === 210) {
throw `210:评论过于频繁或评论内容过短过长`;
}
throw `Invalid status code: ${res.status}`;
} else {
return "ok"
}
},
onClickTag: (namespace, tag) => {
if (namespace === "标签") {
return {
// 'search' or 'category'
action: 'category',
keyword: `${tag}`,
// {string?} only for category action
param: null,
}
}
if (namespace === "作者") {
return {
// 'search' or 'category'
action: 'search',
keyword: `${namespace}:${tag}`,
// {string?} only for category action
param: null,
}
}
throw "未支持此类Tag检索"
}
}
settings = {
favorites_ordering: {
title: "收藏排序方式",
type: "select",
options: [
{
value: '-datetime_updated',
text: '更新时间'
},
{
value: '-datetime_modifier',
text: '收藏时间'
},
{
value: '-datetime_browse',
text: '阅读时间'
}
],
default: '-datetime_updated',
},
region: {
title: "CDN线路",
type: "select",
options: [
{
value: "1",
text: '大陆线路'
},
{
value: "0",
text: '海外线路'
},
],