-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathscript.js
More file actions
1861 lines (1699 loc) · 79.7 KB
/
Copy pathscript.js
File metadata and controls
1861 lines (1699 loc) · 79.7 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
// ==UserScript==
// @name NTR ToolBox
// @namespace http://tampermonkey.net/
// @version v0.6
// @author TheNano
// @description ToolBox for Novel Translate bot website
// @match https://books.fishhawk.top/*
// @match https://books1.fishhawk.top/*
// @match https://n.novelia.cc/*
// @icon https://github.com/LittleSurvival/NTR-ToolBox/blob/main/icon.jpg?raw=true
// @grant GM_openInTab
// @license All Rights Reserved
// ==/UserScript==
(function () {
'use strict';
if (window._NTRToolBoxInstance) {
return;
}
window._NTRToolBoxInstance = true;
const CONFIG_VERSION = 20;
const VERSION = 'v0.6';
const CONFIG_STORAGE_KEY = 'NTR_ToolBox_Config';
const IS_MOBILE = /Mobi|Android/i.test(navigator.userAgent);
const domainAllowed = (location.hostname === 'books.fishhawk.top' || location.hostname === 'books1.fishhawk.top' || location.hostname === 'n.novelia.cc');
// -----------------------------------
// Module settings
// -----------------------------------
function newBooleanSetting(nameDefault, boolDefault) {
return { name: nameDefault, type: 'boolean', value: Boolean(boolDefault) };
}
function newNumberSetting(nameDefault, numDefault) {
return { name: nameDefault, type: 'number', value: Number(numDefault || 0) };
}
function newStringSetting(nameDefault, strDefault) {
return { name: nameDefault, type: 'string', value: String(strDefault == null ? '' : strDefault) };
}
function newSelectSetting(nameDefault, arrOptions, valDefault) {
return { name: nameDefault, type: 'select', value: valDefault, options: arrOptions };
}
function getModuleSetting(mod, key) {
if (!mod.settings) return undefined;
const found = mod.settings.find(s => s.name === key);
return found ? found.value : undefined;
}
function isModuleEnabledByWhitelist(modItem) {
if (!modItem.whitelist) {
return domainAllowed;
}
const whitelist = modItem.whitelist;
const parts = Array.isArray(whitelist) ? whitelist : [whitelist];
return domainAllowed && parts.some(p => {
if (typeof p === 'string') {
if (p.endsWith('/*')) {
const base = p.slice(0, -2);
return location.pathname.startsWith(base) || location.pathname === base;
}
return location.pathname.includes(p);
}
return false;
});
}
// -----------------------------------
// Module definitions
// -----------------------------------
const moduleAddSakuraTranslator = {
name: '添加Sakura翻譯器',
type: 'onclick',
whitelist: '/workspace/sakura',
settings: [
newNumberSetting('數量', 5),
newStringSetting('名稱', 'NTR translator '),
newStringSetting('鏈接', 'https://sakura-share.one'),
newStringSetting('bind', 'none'),
],
run: async function (cfg) {
const totalCount = getModuleSetting(cfg, '數量') || 1;
const namePrefix = getModuleSetting(cfg, '名稱') || '';
const linkValue = getModuleSetting(cfg, '鏈接') || '';
StorageUtils.addSakuraWorker(namePrefix, linkValue, totalCount);
}
}
const moduleAddGPTTranslator = {
name: '添加GPT翻譯器',
type: 'onclick',
whitelist: '/workspace/gpt',
settings: [
newNumberSetting('數量', 5),
newStringSetting('名稱', 'NTR translator '),
newStringSetting('模型', 'deepseek-chat'),
newStringSetting('鏈接', 'https://api.deepseek.com'),
newStringSetting('Key', 'sk-wait-for-input'),
newStringSetting('bind', 'none'),
],
run: async function (cfg) {
const totalCount = getModuleSetting(cfg, '數量') || 1;
const namePrefix = getModuleSetting(cfg, '名稱') || '';
const model = getModuleSetting(cfg, '模型') || '';
const apiKey = getModuleSetting(cfg, 'Key') || '';
const apiUrl = getModuleSetting(cfg, '鏈接') || '';
StorageUtils.addGPTWorker(namePrefix, model, apiUrl, apiKey, totalCount);
}
};
const moduleDeleteTranslator = {
name: '刪除翻譯器',
type: 'onclick',
whitelist: '/workspace',
settings: [
newStringSetting('排除', '共享,本机,AutoDL'),
newStringSetting('bind', 'none'),
],
run: async function (cfg) {
const excludeStr = getModuleSetting(cfg, '排除') || '';
const excludeArr = excludeStr.split(',').filter(x => x);
if (location.href.endsWith('gpt')) {
StorageUtils.removeAllWorkers(StorageUtils.gpt, excludeArr);
} else if (location.href.endsWith('sakura')) {
StorageUtils.removeAllWorkers(StorageUtils.sakura, excludeArr);
}
}
};
const moduleLaunchTranslator = {
name: '啟動翻譯器',
type: 'onclick',
whitelist: '/workspace',
settings: [
newNumberSetting('延遲間隔', 50),
newNumberSetting('最多啟動', 999),
newBooleanSetting('避免無效啟動', true),
newStringSetting('排除', '本机,AutoDL'),
newStringSetting('bind', 'none'),
],
run: async function (cfg, auto) {
const intervalVal = getModuleSetting(cfg, '延遲間隔') || 50;
const maxClick = getModuleSetting(cfg, '最多啟動') || 999;
const noEmptyLaunch = getModuleSetting(cfg, '避免無效啟動');
const allBtns = [...document.querySelectorAll('button')].filter(btn => {
if (!auto && noEmptyLaunch) return true;
const listItem = btn.closest('.n-list-item');
if (listItem) {
const errorMessages = listItem.querySelectorAll('div');
return !Array.from(errorMessages).some(div => div.textContent.includes("TypeError: Failed to fetch"));
}
return true;
});
const delay = ms => new Promise(r => setTimeout(r, ms));
let idx = 0, clickCount = 0, lastRunning = 0, emptyCheck = 0;
async function nextClick() {
while (idx < allBtns.length && clickCount < maxClick) {
const btn = allBtns[idx++];
if (btn.textContent.includes('启动')) {
btn.click();
clickCount++;
await delay(intervalVal);
}
if (noEmptyLaunch) {
let running = [...document.querySelectorAll('button')].filter(btn => btn.textContent.includes('停止')).length;
if (running == lastRunning) emptyCheck++;
if (emptyCheck > 3) break;
}
}
}
await nextClick();
}
};
const moduleQueueSakuraV2 = {
name: '排隊Sakura v2',
type: 'onclick',
whitelist: ['/wenku', '/novel', '/favorite'],
progress: { percentage: 0, info: '' },
settings: [
newNumberSetting('單次擷取web數量(可破限)', 20),
newNumberSetting('擷取單頁wenku數量(deving)', 20),
newSelectSetting('模式', ['常規', '過期', '重翻'], '常規'),
newSelectSetting('分段', ['智能', '固定'], '智能'),
newNumberSetting('智能均分任務上限', 1000),
newNumberSetting('智能均分章節下限', 5),
newNumberSetting('固定均分任務', 6),
newBooleanSetting('R18(需登入)', true),
newStringSetting('bind', 'none'),
],
run: async function (cfg) {
const webCatchLimit = getModuleSetting(cfg, '單次擷取web數量(可破限)') || 20;
const wenkuCatchLimit = getModuleSetting(cfg, '擷取單頁wenku數量(deving)') || 20;
const pair = getModuleSetting(cfg, '固定均分任務') || 6;
const smartJobLimit = getModuleSetting(cfg, '智能均分任務上限') || 1000;
const smartChapterLimit = getModuleSetting(cfg, '智能均分章節下限') || 5;
const type = TaskUtils.getTypeString(window.location.pathname);
const mode = getModuleSetting(cfg, '模式') || '常規';
const sepMode = getModuleSetting(cfg, '分段') || '智能';
const r18Bypass = getModuleSetting(cfg, 'R18(需登入)');
let results = [];
let errorFlag = false;
const maxRetries = 3;
const modeMap = { '常規': '常规', '過期': '过期', '重翻': '重翻' };
const cnMode = modeMap[mode] || '常规';
switch (type) {
case 'wenkus': {
const wenkuIds = TaskUtils.wenkuIds();
const apiEndpoint = `/api/wenku/`;
await Promise.all(
wenkuIds.map(async (id) => {
let attempts = 0;
let success = false;
while (attempts < maxRetries && !success) {
try {
const response = await script.fetch(`${window.location.origin}${apiEndpoint}${id}`, r18Bypass);
if (!response.ok) throw new Error('Network response was not ok');
const data = await response.json();
const volumeIds = data.volumeJp.map(volume => volume.volumeId);
volumeIds.forEach(name => results.push({ task: TaskUtils.wenkuLinkBuilder(id, name, SettingUtils.getTranslateMode(mode)), description: name }))
success = true;
} catch (error) {
NotificationUtils.showError(`Failed to fetch data for ID ${id}, attempt ${attempts + 1}.`);
attempts++;
if (attempts < maxRetries) {
await new Promise(resolve => setTimeout(resolve, 1000));
}
}
}
})
);
await StorageUtils.addJobs(StorageUtils.sakura, results);
break;
};
case 'wenku': {
await TaskUtils.clickButtons(cnMode);
await TaskUtils.clickButtons('排队Sakura');
break;
}
case 'novels': {
const apiUrl = TaskUtils.webSearchApi(webCatchLimit);
try {
const response = await script.fetch(`${window.location.origin}${apiUrl}`, r18Bypass);
if (!response.ok) throw new Error('Network response was not ok');
const data = await response.json();
const novels = data.items.map(item => {
const title = item.titleZh ?? item.titleJp;
return {
url: `/${item.providerId}/${item.novelId}`,
description: title,
total: item.total,
sakura: item.sakura
};
});
results = sepMode == '智能'
? await TaskUtils.assignTasksSmart(novels, smartJobLimit, smartChapterLimit, SettingUtils.getTranslateMode(mode))
: await TaskUtils.assignTasksStatic(novels, pair, SettingUtils.getTranslateMode(mode));
await StorageUtils.addJobs(StorageUtils.sakura, results);
} catch (error) {
errorFlag = true;
NotificationUtils.showError(`Failed to fetch data for ID ${id}, attempt ${attempts + 1}.`)
}
break;
}
case 'novel': {
try {
const targetSpan = Array.from(document.querySelectorAll('span.n-text')).find(span => /总计 (\d+) \/ 百度 (\d+) \/ 有道 (\d+) \/ GPT (\d+) \/ Sakura (\d+)/.test(span.textContent));
const [_, total, , , , sakura] = targetSpan.textContent.match(/总计 (\d+) \/ 百度 (\d+) \/ 有道 (\d+) \/ GPT (\d+) \/ Sakura (\d+)/);
const url = window.location.pathname.split('/novel')[1];
const title = document.title;
if (title.includes('轻小说机翻机器人')) throw Error('小說頁尚未載入');
const novels = [{ url: url, total: total, sakura: sakura, description: title }];
results = sepMode == '智能'
? await TaskUtils.assignTasksSmart(novels, smartJobLimit, smartChapterLimit, SettingUtils.getTranslateMode(mode))
: await TaskUtils.assignTasksStatic(novels, pair, SettingUtils.getTranslateMode(mode));
await StorageUtils.addJobs(StorageUtils.sakura, results);
} catch (error) {
errorFlag = true;
NotificationUtils.showError(`Failed to fetch data for ${title}.`);
}
break;
}
case 'favorite-web': {
const url = new URL(window.location.href);
//get folder id
const id = url.pathname.endsWith('/web') ? 'default' : url.pathname.split('/').pop();
let tries = 0;
let page = 0;
while (true) {
const apiUrl = `${url.origin}/api/user/favored-web/${id}?page=${page}&pageSize=90&sort=update`;
let tasks = [];
let novelCount = 0;
try {
const response = await script.fetch(apiUrl);
const data = await response.json();
const novels = data.items.map(item => {
const title = item.titleZh ?? item.titleJp;
return {
url: `/${item.providerId}/${item.novelId}`,
description: title,
total: item.total,
sakura: item.sakura
};
});
novelCount = novels.length;
tasks = sepMode == '智能'
? await TaskUtils.assignTasksSmart(novels, smartJobLimit, smartChapterLimit, SettingUtils.getTranslateMode(mode))
: await TaskUtils.assignTasksStatic(novels, pair, SettingUtils.getTranslateMode(mode));
await StorageUtils.addJobs(StorageUtils.sakura, tasks);
results.push(tasks);
NotificationUtils.showSuccess(`成功排隊 ${3 * page + 1}-${3 * page + 3}頁, 共${tasks.length}個任務`);
} catch (error) {
console.log(error);
NotificationUtils.showError(`Failed to fetch data for ${id}, page ${page + 1}.`);
if (tries++ > 3) break;
continue;
}
if (novelCount < 90) break;
else page++;
}
break;
}
case 'favorite-wenku': {
const url = new URL(window.location.href);
//get folder id
const id = url.pathname.endsWith('/wenku') ? 'default' : url.pathname.split('/').pop();
let page = 0;
let tries = 0;
while (true) {
const apiUrl = `${url.origin}/api/user/favored-wenku/${id}?page=${page}&pageSize=72&sort=update`;
let tasks = [];
let novelCount = 0;
try {
const response = await script.fetch(apiUrl);
const data = await response.json();
const wenkuIds = data.items.map(novel => novel.id);
novelCount = wenkuIds.length;
await Promise.all(
wenkuIds.map(async (id) => {
let attempts = 0;
let success = false;
const apiEndpoint = `/api/wenku/`;
while (attempts < maxRetries && !success) {
try {
const response = await script.fetch(`${window.location.origin}${apiEndpoint}${id}`, r18Bypass);
if (!response.ok) throw new Error('Network response was not ok');
const data = await response.json();
const volumeIds = data.volumeJp.map(volume => volume.volumeId);
volumeIds.forEach(name => tasks.push({ task: TaskUtils.wenkuLinkBuilder(id, name, mode), description: name }))
success = true;
} catch (error) {
NotificationUtils.showError(`Failed to fetch data for ID ${id}, attempt ${attempts + 1}:`);
attempts++;
if (attempts < maxRetries) {
await new Promise(resolve => setTimeout(resolve, 1000));
}
}
}
})
);
await StorageUtils.addJobs(StorageUtils.sakura, tasks);
results.push(tasks);
NotificationUtils.showSuccess(`成功排隊 ${3 * page + 1}-${3 * page + 3}頁, 共${tasks.length}本小說`);
} catch (error) {
console.log(error);
NotificationUtils.showError(`Failed to fetch data for ${id}, page ${page + 1}.`);
if (tries > 3) break;
continue;
}
if (novelCount < 72) break;
else page++;
}
break;
}
default: { }
}
if (errorFlag) return;
const novels = new Set(results.map(result => result.description));
NotificationUtils.showSuccess(`排隊成功 : 共 ${novels.size} 本小說, 均分 ${results.length} 分段.`);
}
}
const moduleQueueGPTV2 = {
name: '排隊GPT v2',
type: 'onclick',
whitelist: ['/wenku', '/novel', '/favorite/web'],
progress: { percentage: 0, info: '' },
settings: [
newNumberSetting('單次擷取web數量(可破限)', 20),
newNumberSetting('擷取單頁wenku數量(deving)', 20),
newSelectSetting('模式', ['常規', '過期', '重翻'], '常規'),
newSelectSetting('分段', ['智能', '固定'], '智能'),
newNumberSetting('智能均分任務上限', 1000),
newNumberSetting('智能均分章節下限', 5),
newNumberSetting('固定均分任務', 6),
newBooleanSetting('R18(需登入)', true),
newStringSetting('bind', 'none'),
],
run: async function (cfg) {
const webCatchLimit = getModuleSetting(cfg, '單次擷取web數量(可破限)') || 20;
const wenkuCatchLimit = getModuleSetting(cfg, '擷取單頁wenku數量(deving)') || 20;
const pair = getModuleSetting(cfg, '固定均分任務') || 6;
const smartJobLimit = getModuleSetting(cfg, '智能均分任務上限') || 1000;
const smartChapterLimit = getModuleSetting(cfg, '智能均分章節下限') || 5;
const type = TaskUtils.getTypeString(window.location.pathname);
const mode = getModuleSetting(cfg, '模式') || '常規';
const sepMode = getModuleSetting(cfg, '分段') || '智能';
const r18Bypass = getModuleSetting(cfg, 'R18(需登入)');
let results = [];
const maxRetries = 3;
let errorFlag = false;
const modeMap = { '常規': '常规', '過期': '过期', '重翻': '重翻' };
const cnMode = modeMap[mode] || '常规';
switch (type) {
case 'wenkus': {
const wenkuIds = TaskUtils.wenkuIds();
const apiEndpoint = `/api/wenku/`;
await Promise.all(
wenkuIds.map(async (id) => {
let attempts = 0;
let success = false;
while (attempts < maxRetries && !success) {
try {
const response = await script.fetch(`${window.location.origin}${apiEndpoint}${id}`, r18Bypass);
if (!response.ok) throw new Error('Network response was not ok');
const data = await response.json();
const volumeIds = data.volumeJp.map(volume => volume.volumeId);
volumeIds.forEach(name => results.push({ task: TaskUtils.wenkuLinkBuilder(id, name, mode), description: name }))
success = true;
} catch (error) {
NotificationUtils.showError(`Failed to fetch data for ID ${id}, attempt ${attempts + 1}:`);
attempts++;
if (attempts < maxRetries) {
await new Promise(resolve => setTimeout(resolve, 1000));
}
}
}
})
);
await StorageUtils.addJobs(StorageUtils.gpt, results);
break;
};
case 'wenku': {
await TaskUtils.clickButtons(cnMode);
await TaskUtils.clickButtons('排队Sakura');
break;
}
case 'novels': {
const apiUrl = TaskUtils.webSearchApi(webCatchLimit);
try {
const response = await script.fetch(`${window.location.origin}${apiUrl}`, r18Bypass)
if (!response.ok) throw new Error('Network response was not ok');
const data = await response.json();
const novels = data.items.map(item => {
const title = item.titleZh ?? item.titleJp;
return {
url: `/${item.providerId}/${item.novelId}`,
description: title,
total: item.total,
gpt: item.gpt
};
});
results = sepMode == '智能'
? await TaskUtils.assignTasksSmart(novels, smartJobLimit, smartChapterLimit, SettingUtils.getTranslateMode(mode))
: await TaskUtils.assignTasksStatic(novels, pair, SettingUtils.getTranslateMode(mode));
await StorageUtils.addJobs(StorageUtils.gpt, results);
} catch (error) {
errorFlag = true;
NotificationUtils.showError(`Failed to fetch data for ID ${id}, attempt ${attempts + 1}:`);
}
break;
}
case 'novel': {
try {
const targetSpan = Array.from(document.querySelectorAll('span.n-text')).find(span => /总计 (\d+) \/ 百度 (\d+) \/ 有道 (\d+) \/ GPT (\d+) \/ Sakura (\d+)/.test(span.textContent));
const [_, total, , , gpt] = targetSpan.textContent.match(/总计 (\d+) \/ 百度 (\d+) \/ 有道 (\d+) \/ GPT (\d+) \/ Sakura (\d+)/);
const url = window.location.pathname.split('/novel')[1];
const title = document.title;
if (title.includes('轻小说机翻机器人')) throw Error('小說頁尚未載入');
const novels = [{ url: url, total: total, gpt: gpt, description: title }]
results = sepMode == '智能'
? await TaskUtils.assignTasksSmart(novels, smartJobLimit, smartChapterLimit, SettingUtils.getTranslateMode(mode))
: await TaskUtils.assignTasksStatic(novels, pair, SettingUtils.getTranslateMode(mode));
await StorageUtils.addJobs(StorageUtils.gpt, results);
} catch (error) {
errorFlag = true;
NotificationUtils.showError(`Failed to fetch data for ${title}.`);
}
break;
}
case 'favorite-web': {
const url = new URL(window.location.href);
//get folder id
const id = url.pathname.endsWith('/web') ? 'default' : url.pathname.split('/').pop();
let tries = 0;
let page = 0;
while (true) {
const apiUrl = `${url.origin}/api/user/favored-web/${id}?page=${page}&pageSize=90&sort=update`;
let tasks = [];
let novelCount = 0;
try {
const response = await script.fetch(apiUrl);
const data = await response.json();
const novels = data.items.map(item => {
const title = item.titleZh ?? item.titleJp;
return {
url: `/${item.providerId}/${item.novelId}`,
description: title,
total: item.total,
gpt: item.gpt
};
});
novelCount = novels.length;
tasks = sepMode == '智能'
? await TaskUtils.assignTasksSmart(novels, smartJobLimit, smartChapterLimit, SettingUtils.getTranslateMode(mode))
: await TaskUtils.assignTasksStatic(novels, pair, SettingUtils.getTranslateMode(mode));
await StorageUtils.addJobs(StorageUtils.gpt, tasks);
results.push(tasks);
NotificationUtils.showSuccess(`成功排隊 ${3 * page + 1}-${3 * page + 3}頁, 共${novelCount}本小說`);
} catch (error) {
console.log(error);
NotificationUtils.showError(`Failed to fetch data for ${id}, page ${page + 1}.`);
if (tries++ > 3) break;
continue;
}
if (novelCount < 90) break;
else page++;
}
break;
}
case 'favorite-wenku': {
const url = new URL(window.location.href);
//get folder id
const id = url.pathname.endsWith('/wenku') ? 'default' : url.pathname.split('/').pop();
let page = 0;
let tries = 0;
while (true) {
const apiUrl = `${url.origin}/api/user/favored-wenku/${id}?page=${page}&pageSize=72&sort=update`;
let tasks = [];
let novelCount = 0;
try {
const response = await script.fetch(apiUrl);
const data = await response.json();
const wenkuIds = data.items.map(novel => novel.id);
novelCount = wenkuIds.length;
await Promise.all(
wenkuIds.map(async (id) => {
let attempts = 0;
let success = false;
const apiEndpoint = `/api/wenku/`;
while (attempts < maxRetries && !success) {
try {
const response = await script.fetch(`${window.location.origin}${apiEndpoint}${id}`, r18Bypass);
if (!response.ok) throw new Error('Network response was not ok');
const data = await response.json();
const volumeIds = data.volumeJp.map(volume => volume.volumeId);
volumeIds.forEach(name => tasks.push({ task: TaskUtils.wenkuLinkBuilder(id, name, mode), description: name }))
success = true;
} catch (error) {
NotificationUtils.showError(`Failed to fetch data for ID ${id}, attempt ${attempts + 1}:`);
attempts++;
if (attempts < maxRetries) {
await new Promise(resolve => setTimeout(resolve, 1000));
}
}
}
})
);
await StorageUtils.addJobs(StorageUtils.gpt, tasks);
results.push(tasks);
NotificationUtils.showSuccess(`成功排隊 ${3 * page + 1}-${3 * page + 3}頁, 共${tasks.length}本小說`);
} catch (error) {
console.log(error);
NotificationUtils.showError(`Failed to fetch data for ${id}, page ${page + 1}.`);
if (tries > 3) break;
continue;
}
if (novelCount < 72) break;
else page++;
}
break;
}
default: { }
}
if (errorFlag) return;
const novels = new Set(results.map(result => result.description));
NotificationUtils.showSuccess(`排隊成功 : 共 ${novels.size} 本小說, 均分 ${results.length} 分段.`);
}
}
const moduleAutoRetry = {
name: '自動重試',
type: 'keep',
whitelist: '/workspace/*',
settings: [
newNumberSetting('最大重試次數', 99),
newBooleanSetting('置頂重試任務', false),
newBooleanSetting('重啟翻譯器', true),
],
_attempts: 0,
_lastRun: 0,
_interval: 1000,
run: async function (cfg) {
const now = Date.now();
if (now - this._lastRun < this._interval) return;
this._lastRun = now;
const maxAttempts = getModuleSetting(cfg, '最大重試次數') || 99;
const relaunch = getModuleSetting(cfg, '重啟翻譯器') || 3;
const moveToTop = getModuleSetting(cfg, '置頂重試任務');
if (!this._boundClickHandler) {
this._boundClickHandler = (e) => {
if (e.target.tagName === 'button') {
this._attempts = 0;
}
};
document.addEventListener('click', this._boundClickHandler);
}
const listItems = document.querySelectorAll('.n-list-item');
const unfinished = [...listItems].filter(item => {
const desc = item.querySelector('.n-thing-main__description');
return desc && desc.textContent.includes('未完成');
});
async function retryTasks(attempts) {
const hasStop = [...document.querySelectorAll('button')].some(b => b.textContent === '停止');
if (!hasStop) {
const retryBtns = [...document.querySelectorAll('button')].filter(b => b.textContent.includes('重试未完成任务'));
if (retryBtns[0]) {
const clickCount = Math.min(unfinished.length, listItems.length);
for (let i = 0; i < clickCount; i++) {
retryBtns[0].click();
}
if (moveToTop) {
TaskUtils.clickTaskMoveToTop(unfinished.length);
}
attempts++;
}
}
return attempts;
}
if (unfinished.length > 0 && this._attempts < maxAttempts) {
this._attempts = await retryTasks(this._attempts);
script.delay(10);
if (relaunch) {
script.runModule('啟動翻譯器');
}
}
}
};
const moduleSyncStorage = {
name: '資料同步',
type: 'onclick',
whitelist: '/workspace/*',
hidden: true,
settings: [
newStringSetting('bind', 'none')
],
run: async function (cfg) {
}
}
const defaultModules = [
moduleAddSakuraTranslator,
moduleAddGPTTranslator,
moduleDeleteTranslator,
moduleLaunchTranslator,
moduleQueueSakuraV2,
moduleQueueGPTV2,
moduleAutoRetry,
moduleSyncStorage,
];
// -----------------------------------
// Setting Utils
// -----------------------------------
class SettingUtils {
static getTranslateMode(mode) {
const map = { '常規': 'normal', '過期': 'expire', '重翻': 'all' };
return map[mode];
}
}
// -----------------------------------
// TaskUtils Utils
// -----------------------------------
class TaskUtils {
static getTypeString = (url) => {
const patterns = {
'wenkus': new RegExp(`^/wenku(\\?.*)?$`), // Matches /wenku and /wenku?params
'wenku': new RegExp(`^/wenku\\/.*(\\?.*)?$`), // Matches /wenku/* and /wenku/*?params
'novels': new RegExp(`^/novel(\\?.*)?$`), // Matches /novel and /novel?params
'novel': new RegExp(`^/novel\\/.*(\\?.*)?$`), // Matches /novel/*/* and /novel/*/*?params
'favorite-web': new RegExp(`^/favorite/web(/.*)?(\\?.*)?$`), // Matches /favorite/web and /favorite/web/* and /favorite/web?params
'favorite-wenku': new RegExp(`^/favorite/wenku(/.*)?(\\?.*)?$`), // Matches /favorite/wenku and /favorite/wenku/* and /favorite/wenku?params
'favorite-local': new RegExp(`^/favorite/local(/.*)?(\\?.*)?$`) // Matches /favorite/local and /favorite/local/* and /favorite/local?params
};
for (const [key, pattern] of Object.entries(patterns)) {
if (pattern.test(url)) {
return key;
}
}
return null;
};
static wenkuLinkBuilder(series, name, mode) {
return `wenku/${series}/${name}?level=${mode}&forceMetadata=false&startIndex=0&endIndex=65536`
}
static webLinkBuilder(url, from = 0, to = 65536, mode) {
return `web${url}?level=${mode}&forceMetadata=false&startIndex=${from}&endIndex=${to}`
}
//return "id"
static wenkuIds() {
const links = [...document.querySelectorAll('a[href^="/wenku/"]')];
return links.map(link => link.getAttribute('href').split('/wenku/')[1]);
}
//return api link
static webSearchApi(limit = 20) {
const urlParams = new URLSearchParams(location.search), page = Math.max(urlParams.get('page') - 1 || 0, 0);
const input = document.querySelector('input[placeholder="中/日文标题或作者"]');
let rawQuery = input ? input.value.trim() : '';
const query = encodeURIComponent(rawQuery);
const selected = [...document.querySelectorAll('.n-text.__text-dark-131ezvy-p')].map(e => e.textContent.trim());
const sourceMap = {
Kakuyomu: 'kakuyomu',
'成为小说家吧': 'syosetu',
Novelup: 'novelup',
Hameln: 'hameln',
Pixiv: 'pixiv',
Alphapolis: 'alphapolis'
};
const typeMap = { '连载中': '1', '已完结': '2', '短篇': '3', '全部': '0' };
const levelMap = { '一般向': '1', 'R18': '2', '全部': '0' };
const translateMap = { 'GPT': '1', 'Sakura': '2', '全部': '0' };
const sortMap = { '更新': '0', '点击': '1', '相关': '2' };
const providers = Object.keys(sourceMap)
.filter(k => selected.includes(k))
.map(k => sourceMap[k])
.join(',') || 'kakuyomu,syosetu,novelup,hameln,pixiv,alphapolis';
const tKey = Object.keys(typeMap).find(x => selected.includes(x)) || '全部';
const lKey = Object.keys(levelMap).find(x => selected.includes(x)) || '全部';
const trKey = Object.keys(translateMap).find(x => selected.includes(x)) || '全部';
const sKey = Object.keys(sortMap).find(x => selected.includes(x)) || '更新';
return `/api/novel?page=${page}&pageSize=${limit}&query=${query}` +
`&provider=${encodeURIComponent(providers)}&type=${typeMap[tKey]}&level=${levelMap[lKey]}` +
`&translate=${translateMap[trKey]}&sort=${sortMap[sKey]}`;
}
//return { task, description }
static async assignTasksSmart(novels, smartJobLimit, smartChapterLimit, mode) {
function undone(n) {
if (mode === "normal") {
const sOrG = (n.sakura ?? n.gpt) || 0;
//Using max to deal with some total > sakura situation
return Math.max(n.total - sOrG, 0);
}
return n.total;
}
const totalChapters = novels.reduce((acc, n) => acc + undone(n), 0);
const potentialMaxTask = Math.floor(totalChapters / smartChapterLimit);
let maxTasks = Math.min(potentialMaxTask, smartJobLimit);
if (maxTasks <= 0 && totalChapters > 0) {
maxTasks = smartJobLimit;
}
if (totalChapters === 0) {
return [];
}
const chunkSize = Math.ceil(totalChapters / (maxTasks || 1));
const sorted = [...novels].sort((a, b) => undone(b) - undone(a));
const result = [];
let usedTasks = 0;
for (const novel of sorted) {
let remain = undone(novel);
if (remain <= 0) continue;
let startIndex = (mode === "normal") ? (novel.total - remain) : 0;
while (remain > 0 && usedTasks < smartJobLimit) {
const thisChunk = Math.min(remain, chunkSize);
const endIndex = startIndex + thisChunk;
result.push({
task: TaskUtils.webLinkBuilder(novel.url, startIndex, endIndex, mode),
description: novel.description
});
usedTasks++;
remain -= thisChunk;
startIndex = endIndex;
if (usedTasks >= smartJobLimit) {
break;
}
}
if (usedTasks >= smartJobLimit) {
break;
}
}
return result;
}
//return { task, description }
static async assignTasksStatic(novels, parts, mode) {
function undone(n) {
if (mode === "normal") {
const sOrG = (n.sakura ?? n.gpt) || 0;
return n.total - sOrG;
}
return n.total;
}
const result = [];
for (const novel of novels) {
const totalChapters = undone(novel);
if (totalChapters <= 0) continue;
const startBase = (mode === "normal")
? (novel.total - totalChapters)
: 0;
const chunkSize = Math.ceil(totalChapters / parts);
for (let i = 0; i < parts; i++) {
const chunkStart = startBase + i * chunkSize;
const chunkEnd = (i === parts - 1)
? (startBase + totalChapters)
: (chunkStart + chunkSize);
if (chunkStart < startBase + totalChapters) {
result.push({
task: TaskUtils.webLinkBuilder(novel.url, chunkStart, chunkEnd, mode),
description: novel.description
});
}
}
}
return result;
}
static async clickTaskMoveToTop(count, reserve=true) {
const extras = document.querySelectorAll('.n-thing-header__extra');
for (let i = 0; i < count;i++) {
const offset = reserve ? extras.length - i - 1 : i;
const container = extras[offset];
const buttons = container.querySelectorAll('button');
if (buttons.length) {
buttons[0].click();
}
}
}
static async clickButtons(name = '') {
const btns = document.querySelectorAll('button');
btns.forEach(btn => {
if (name === '' || btn.textContent.includes(name)) {
btn.dispatchEvent(new MouseEvent('click', { bubbles: true, cancelable: true }));
}
});
}
}
// -----------------------------------
// Storage Utils
// -----------------------------------
class StorageUtils {
static sakura = 'sakura-workspace';
static gpt = 'gpt-workspace';
static updateUrl = [
'workspace/sakura',
'workspace/gpt'
];
static async update() {
const storageKey = (window.location.pathname.includes('workspace/sakura') ? this.sakura : (window.location.pathname.includes('workspace/gpt') ? this.gpt : null));
if (!storageKey) return;
const data = await this._getData(storageKey);
await this._setData(storageKey, data);
}
static async _setData(key, data) {
localStorage.setItem(key, JSON.stringify(data));
window.dispatchEvent(new StorageEvent('storage', {
key: key,
newValue: JSON.stringify(data),
url: window.location.href,
storageArea: localStorage
}));
}
static async _getData(key) {
let raw = localStorage.getItem(key);
if (raw) {
return JSON.parse(raw);
}
return { workers: [], jobs: [], uncompletedJobs: [] };
}
static async addSakuraWorker(id, endpoint, amount = null, prevSegLength = 500, segLength = 500) {
const total = amount ?? -1;
let data = await this._getData(this.sakura);
function _dataInsert(id, endpoint, prevSegLength, segLength) {
const worker = { id, endpoint, prevSegLength, segLength };
const existingIndex = data.workers.findIndex(w => w.id === id);
if (existingIndex !== -1) {
data.workers[existingIndex] = worker;
} else {
data.workers.push(worker);
}
}
if (total == -1) {
_dataInsert(id, endpoint, prevSegLength, segLength);
} else {
for (let i = 1; i < total + 1; i++) {
_dataInsert(id + i, endpoint, prevSegLength, segLength);
}
}
await this._setData(this.sakura, data);
}
static async addGPTWorker(id, model, endpoint, key, amount = null) {
const total = amount ?? -1;
let data = await this._getData(this.gpt);
function _dataInsert(id, model, endpoint, key) {
const worker = { id, type: 'api', model, endpoint, key };
const existingIndex = data.workers.findIndex(w => w.id === id);
if (existingIndex !== -1) {
data.workers[existingIndex] = worker;
} else {
data.workers.push(worker);
}
}
if (total == -1) {
_dataInsert(id, model, endpoint, key);
} else {
for (let i = 1; i < total + 1; i++) {
_dataInsert(id + i, model, endpoint, key);
}
}
await this._setData(this.gpt, data);
}
static async removeWorker(key, id) {
let data = await this._getData(key);
data.workers = data.workers.filter(w => w.id !== id);
await this._setData(key, data);
}
static async removeAllWorkers(key, exclude = []) {
let data = await this._getData(key);