forked from dodying/UserJs
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathehEnhance.user.js
3389 lines (3198 loc) · 165 KB
/
ehEnhance.user.js
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
/* eslint-env browser */
// ==UserScript==
// @name [EH]Enhance
// @version 1.19.367
// @modified 2021-08-05 20:58:38
// @author dodying
// @namespace https://github.com/dodying/UserJs
// @supportURL https://github.com/dodying/UserJs/issues
// @icon https://gitee.com/dodying/userJs/raw/master/Logo.png
// 里站
// @include https://exhentai.org/
// @include https://exhentai.org/favorites.php*
// @include https://exhentai.org/?*
// @include https://exhentai.org/g/*
// @include https://exhentai.org/tag/*
// @include https://exhentai.org/uploader/*
// @include https://exhentai.org/uconfig.php
// 表站
// @include https://e-hentai.org/
// @include https://e-hentai.org/favorites.php*
// @include https://e-hentai.org/?*
// @include https://e-hentai.org/g/*
// @include https://e-hentai.org/tag/*
// @include https://e-hentai.org/uploader/*
// @include https://e-hentai.org/uconfig.php
// @grant window.close
// @grant unsafeWindow
// @grant GM_openInTab
// @grant GM_setClipboard
// @grant GM_setValue
// @grant GM_getValue
// @grant GM_listValues
// @grant GM_deleteValue
// @grant GM_addValueChangeListener
// @grant GM_xmlhttpRequest
// @grant GM_notification
// @connect *
// @require https://cdnjs.cloudflare.com/ajax/libs/jquery/3.1.0/jquery.js
// @require https://cdnjs.cloudflare.com/ajax/libs/jszip/3.1.5/jszip.js
// @run-at document-idle
// @compatible firefox 52+(ES2017)
// @compatible chrome 55+(ES2017)
// ==/UserScript==
/* global GM_info unsafeWindow GM_openInTab GM_setClipboard GM_setValue GM_getValue GM_listValues GM_deleteValue GM_addValueChangeListener GM_xmlhttpRequest GM_notification */
/* global $ jQuery JSZip */
/* eslint-disable no-debugger */
const SEL = {
EH: {
// unsafeWindow
common: {
navBar: '#nb',
pageCur: '.ptds:eq(0)>a',
pageMax: '.ptt td:gt(0):eq(-2)>a',
pagesContainerBottom: '.ptb',
},
search: { // 搜索页
checker: '.ido', // 检查是否为搜索页
displayMode: '#dms select',
mainDiv: '.ido',
keyword: '[name="f_search"]',
apply: '[name="f_search"]~input[type="submit"]',
resultTotal: '.ip:eq(0)',
resultTotalMatch: /Showing ([\d,]+) results?/,
thumb: '.glthumb',
thumbId: (id) => `it${id}`,
postedTime: '[id^="posted_"]',
// favorited: '[id^="posted_"][style]',
resultTableContainer: '.ido>*:has(.itg)',
resultTable: 'table.itg',
resultTbody: 'table.itg>tbody',
resultTr: 'table.itg>tbody>tr',
resultTr0: 'table.itg>tbody>tr:nth-child(1)',
resultTrGt0: 'table.itg>tbody>tr:not(:nth-child(1))',
nameTd: '.gl3m',
galleryA: '[href*="hentai.org/g/"]',
},
info: { // 信息页
checker: '#gdt,.d', // 检查是否为信息页
urlMatch: /^https?:\/\/e[-x]hentai\.org\/g\/\d+\/[a-z0-9]+/,
galleryId: unsafeWindow.gid,
title: '#gn',
titleJp: '#gj',
// favorite: '#gdf>#fav>.i',
infoContainer: '#gmid',
infoCategory: '#gdc',
infoUploader: '#gdn',
infoDetailTr: '#gdd tr',
infoDetailKey: '.gdt1',
infoDetailValue: '.gdt2',
tagContainer: '#taglist',
tagTr: '#taglist tr',
tagKey: '.tc',
tagDiv: '[id^="td_"]',
tagDivFromName: (name) => `[id="td_${name}"]`,
tag: '[id^="ta_"]',
tagFromName: (name) => `[id="ta_${name}"]`,
tagParody: '[id^="ta_parody"]',
nameFromTag: (id) => id.match(/t[ad]_((.*?):(.*))/) || id.match(/t[ad]_(.*)/),
tagBanned: ['ta_female:lolicon', 'ta_male:shotacon', 'ta_male:bestiality', 'ta_female:bestiality'],
btnContainer: '#gdo2',
previewContainer: '[id="gdt"]',
previewDiv: '.gdtm',
previewA: '.gdtm>div>a',
previewImg: '.gdtm>div>a>img',
uploaderComment: '#comment_0',
},
setting: { // 设置页
// changeEConfig
checker: '[name="profile_set"]', // 检查是否为搜索页
form: 'form:has(#apply)',
},
special: {
deleted: '.d', // https://e-hentai.org/g/1621568/6d89c79f2e/
},
},
EHD: {
checker: '.ehD-box',
download: 'fieldset.ehD-box .g2:contains("Download Archive")',
abort: '.ehD-pt-item:not(.ehD-pt-succeed,.ehD-pt-failed) .ehD-pt-abort',
pageRange: 'label:contains("Pages Range")>input',
// download: '.ehD-box>.g2:eq(0)'
},
};
const G = { // 全局变量
debug: false,
isIframe: window.self !== window.top,
searchPage: $(SEL.EH.search.checker).length,
infoPage: $(SEL.EH.info.checker).length,
settingPage: $(SEL.EH.setting.checker).length,
config: GM_getValue('config', {}),
'ehD-setting': JSON.parse(GM_getValue('ehD-setting', '{}')),
EHT: [],
gmetadata: [],
favicon: {
0: 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAYAAAAf8/9hAAAAL0lEQVR42mNgGBQgjU3wPzomJI+ihmoGEHIhTvWDxwBkCVxs2howjAKR/ilxQAEA0niUcVUdSr0AAAAASUVORK5CYII=',
1: 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAYAAAAf8/9hAAAAK0lEQVR42mNgGBQgjU3wPzrGp452BhDr0kFsALICbIppb8AwCkT6p8QBBQBmZWTxFXfR8AAAAABJRU5ErkJggg==',
2: 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAYAAAAf8/9hAAAANElEQVR42mNgGBQgjU3wPzomJI+ihmoGkOriQWgAsgQ2NtGBSLYBRDuZVAX0M2DgUuKAAgB3d4iRNiZLcAAAAABJRU5ErkJggg==',
3: 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAYAAAAf8/9hAAAAMElEQVR42mNgGBQgjU3wPzomJI+ihmoGkOriQWgAsgQ2NtGBSLYBwygQ6Z8SBxQAAOjoiJF+j7m3AAAAAElFTkSuQmCC',
4: 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAYAAAAf8/9hAAAANElEQVR42mNgGBQgjU3wPzrGJo+LTz0DCLlwCBiALIGNjTOcqGYAqdE+CA3AlZBob8CAAgCuIn+p3J00ugAAAABJRU5ErkJggg==',
5: 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAYAAAAf8/9hAAAANUlEQVR42mNgGBQgjU3wPzomJI+ihmoGEHIhA7kK6GcAskJsbKIDkWwDSI32QWjAwKXEAQUAd3eIkeLwZzcAAAAASUVORK5CYII=',
d: 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAYAAAAf8/9hAAAACXBIWXMAAAsTAAALEwEAmpwYAAAAIGNIUk0AAHolAACAgwAA+f8AAIDpAAB1MAAA6mAAADqYAAAXb5JfxUYAAABTSURBVHjaYvj//z8DJZiBKgaksQn+R8cMSABdjmIDkA1BMYABB0DXhMwfZAYgG4SNTXsDCHmBgYFhgA1IYxNUJioMyE5IZCflAc2NAAAAAP//AwAC/Mv3iQhmBgAAAABJRU5ErkJggg==',
p: 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAYAAAAf8/9hAAAACXBIWXMAAAsTAAALEwEAmpwYAAAAIGNIUk0AAHolAACAgwAA+f8AAIDpAAB1MAAA6mAAADqYAAAXb5JfxUYAAABTSURBVHjaYvj//z8DJZiBKgaksQn+R8cMSACbfBqb4H/qG8CAA6DLD2IDkBViYxMdiGQbQIwX8KYDmhuQxiaoTGlKlKXUAG7aZCZKMAAAAP//AwCS0Ls1SQllgAAAAABJRU5ErkJggg==',
},
introPicName: [
// /999\.(png|jpg)$/i,
/^i_\.(png|jpg)$/i,
/^zCREDIT/i,
'招募圖',
'無邪気',
/^Read(|_)(|\d+)\.(png|jpg)$/i,
/^(CEwanted|zmt)\.(png|jpg)$/i,
/^ZZ\.(png|jpg)$/,
/(credits)\.(png|jpg)$/i,
// /\.gif$/i
],
uselessStrRE: /\[.*?\]|\(.*?\)|\{.*?\}|【.*?】|[.*?]|(.*?)|~|~/g,
infoGroup: ['[]', '()', '{}', '【】'],
digitalRomaji: {
0: [['rei', 'zero'], ['0', '0', '零', '〇']],
1: [['ichi', 'i'], ['1', '1', '一', '壹', '壱']],
2: [['ni', 'ii'], ['2', '2', '二', '贰', '貮', '弐']],
3: [['san', 'sann', 'iii'], ['3', '3', '三', '参', '參']],
4: [['yon', 'yonn', 'shi', 'iv'], ['4', '4', '四', '肆']],
5: [['go', 'v'], ['5', '5', '五', '伍']],
6: [['roku', 'vi'], ['6', '6', '六', '陆', '陸']],
7: [['nana', 'shichi', 'vii'], ['7', '7', '七', '柒', '漆']],
8: [['hachi', 'viii'], ['8', '8', '八', '捌']],
9: [['kyuu', 'kyu', 'ix'], ['9', '9', '九', '玖']],
10: [['jyuu', 'jyu', 'juu', 'ju', 'x'], ['10', '10', '十', '拾']],
},
timeout: null,
downloading: false,
imageD: [],
imageS: [],
imageEnd: false,
imageData: null,
autoDownload: false,
downloadSizeChanged: false,
taskInterval: null,
this: (() => {
const used = ['addEventListener', 'alert', 'applicationCache', 'atob', 'blur', 'browser', 'btoa', 'caches', 'cancelAnimationFrame', 'cancelIdleCallback', 'captureEvents', 'chrome', 'clearInterval', 'clearTimeout', 'clientInformation', 'close', 'closed', 'confirm', 'createImageBitmap', 'crypto', 'customElements', 'decodeURI', 'decodeURI', 'decodeURIComponent', 'defaultStatus', 'defaultstatus', 'devicePixelRatio', 'dispatchEvent', 'document', 'encodeURI', 'encodeURIComponent', 'eval', 'external', 'fetch', 'find', 'focus', 'frameElement', 'frames', 'getComputedStyle', 'getSelection', 'history', 'indexedDB', 'innerHeight', 'innerWidth', 'isFinite', 'isNaN', 'isSecureContext', 'length', 'localStorage', 'location', 'locationbar', 'matchMedia', 'menubar', 'moveBy', 'moveTo', 'name', 'navigator', 'onabort', 'onafterprint', 'onanimationend', 'onanimationiteration', 'onanimationstart', 'onappinstalled', 'onauxclick', 'onbeforeinstallprompt', 'onbeforeprint', 'onbeforeunload', 'onblur', 'oncancel', 'oncanplay', 'oncanplaythrough', 'onchange', 'onclick', 'onclose', 'oncontextmenu', 'oncuechange', 'ondblclick', 'ondevicemotion', 'ondeviceorientation', 'ondeviceorientationabsolute', 'ondrag', 'ondragend', 'ondragenter', 'ondragleave', 'ondragover', 'ondragstart', 'ondrop', 'ondurationchange', 'onemptied', 'onended', 'onerror', 'onfocus', 'onformdata', 'ongotpointercapture', 'onhashchange', 'oninput', 'oninvalid', 'onkeydown', 'onkeypress', 'onkeyup', 'onlanguagechange', 'onload', 'onloadeddata', 'onloadedmetadata', 'onloadstart', 'onlostpointercapture', 'onmessage', 'onmessageerror', 'onmousedown', 'onmouseenter', 'onmouseleave', 'onmousemove', 'onmouseout', 'onmouseover', 'onmouseup', 'onmousewheel', 'onoffline', 'ononline', 'onpagehide', 'onpageshow', 'onpause', 'onplay', 'onplaying', 'onpointercancel', 'onpointerdown', 'onpointerenter', 'onpointerleave', 'onpointermove', 'onpointerout', 'onpointerover', 'onpointerrawupdate', 'onpointerup', 'onpopstate', 'onprogress', 'onratechange', 'onrejectionhandled', 'onreset', 'onresize', 'onscroll', 'onsearch', 'onseeked', 'onseeking', 'onselect', 'onselectionchange', 'onselectstart', 'onstalled', 'onstorage', 'onsubmit', 'onsuspend', 'ontimeupdate', 'ontoggle', 'ontransitionend', 'onunhandledrejection', 'onunload', 'onvolumechange', 'onwaiting', 'onwebkitanimationend', 'onwebkitanimationiteration', 'onwebkitanimationstart', 'onwebkittransitionend', 'onwheel', 'open', 'openDatabase', 'opener', 'origin', 'outerHeight', 'outerWidth', 'pageXOffset', 'pageYOffset', 'parent', 'parseFloat', 'parseInt', 'performance', 'personalbar', 'postMessage', 'print', 'prompt', 'queueMicrotask', 'releaseEvents', 'removeEventListener', 'requestAnimationFrame', 'requestIdleCallback', 'resizeBy', 'resizeTo', 'screen', 'screenLeft', 'screenTop', 'screenX', 'screenY', 'scroll', 'scrollBy', 'scrollTo', 'scrollX', 'scrollY', 'scrollbars', 'self', 'sessionStorage', 'setInterval', 'setTimeout', 'speechSynthesis', 'status', 'statusbar', 'stop', 'styleMedia', 'toolbar', 'top', 'visualViewport', 'webkitCancelAnimationFrame', 'webkitRequestAnimationFrame', 'webkitRequestFileSystem', 'webkitResolveLocalFileSystemURL', 'webkitStorageInfo'];
const variabled = {};
for (const i in this) {
if (!used.includes(i)) {
variabled[i] = this[i];
}
}
return variabled;
})(),
};
G.punctuationRegExp = /[\p{Punctuation}\p{Symbol}\p{Other}]/u;
G.punctuationWithWhiteRegExp = /[\s\p{Punctuation}\p{Symbol}\p{Other}]/u;
G.punctuationWithWhiteGroupRegExp = /([\s\p{Punctuation}\p{Symbol}\p{Other}])/u;
G.punctuationWithWhiteAllRegExp = /^[\s\p{Punctuation}\p{Symbol}\p{Other}]+$/u;
G.isPreferDisplayMode = !G.infoPage && ['m', 'p'].includes($(SEL.EH.search.displayMode).val());
G.autoDownload = window.location.hash.match(/^#[0-2]$/) && G.config.autoStartDownload;
G.downloadSizeChanged = !G['ehD-setting']['store-in-fs'] && G.config.enableEHD && G.config.showAllThumb && G.config.enableChangeSize && G.config.sizeS !== G.config.sizeD && G.config.downloadSizeChanged;
async function init() {
if (G.isIframe) {
$('<button class="ehIframeClose">Close</button>').appendTo('body').on('click', windowClose);
}
if ($(SEL.EH.special.deleted).length && window.location.href === `${GM_getValue('tasking')}#2`) {
const taskFailed = GM_getValue('taskFailed', []);
taskFailed.push(GM_getValue('tasking'));
GM_setValue('taskFailed', taskFailed);
GM_deleteValue('tasking');
windowClose();
return;
}
// GM_registerMenuCommand(GM_info.script.name + ': Show Global', function () {
// console.log({ SEL, G });
// }, 'S');
defaultConfig(); // 默认设置
addStyle(); // 添加样式
$('<div class="ehNavBar" style="bottom:0;"><div></div><div></div><div></div></div>').appendTo('body');
$(window).on({
scroll: () => {
$('.ehNavBar').attr('style', $(window).scrollTop() >= 30 && G.infoPage ? 'top:0;' : 'bottom:0;');
},
});
const now = new Date().getTime();
const lastTime = GM_getValue('EHT_checkTime', 0);
if (G.config.updateIntervalEHT !== 0 && now - lastTime >= G.config.updateIntervalEHT * 24 * 60 * 60 * 1000) {
try {
await updateEHT();
} catch (err) { }
}
if (GM_getValue('EHT', {}).version === 5) {
G.EHT = GM_getValue('EHT').data;
} else {
try {
await updateEHT();
G.EHT = GM_getValue('EHT').data;
} catch (error) {
console.log(error);
window.alert('update EHT failed, please reload this page');
return;
}
}
showConfig();
$('<button title="无人坚守模式" name="passive mode">Passive Mode</button>').on({
click: (e, remote) => {
[window.alertRaw, window.alert] = [window.alert, window.alertRaw || function () { }];
[window.confirmRaw, window.confirm] = [window.confirm, window.confirmRaw || function () { return true; }];
[window.promptRaw, window.prompt] = [window.prompt, window.promptRaw || function (message, value) { return value; }];
const status = $(e.target).attr('status');
$(e.target).attr('status', status ? null : 'on');
if (!remote) GM_setValue('passiveMode', !status);
},
}).appendTo('.ehNavBar>div:nth-child(1)');
GM_addValueChangeListener('passiveMode', (name, valueOld, value, remote) => {
if (!remote) return;
$(`.ehNavBar>div:nth-child(1)>[name="passive mode"]${value ? ':not([status])' : '[status]'}`).trigger('click', true);
});
if (GM_getValue('passiveMode', false)) {
$('.ehNavBar>div:nth-child(1)>[name="passive mode"]:not([status])').trigger('click', true);
}
if (G.infoPage) { // 信息页
if (jumpHost()) return; // 里站跳转
if (G.config.enableEHD) {
const now = new Date().getTime();
const lastTime = GM_getValue('EHD_checkTime', 0);
if (!GM_getValue('EHD_code') || (G.config.updateIntervalEHD !== 0 && now - lastTime >= G.config.updateIntervalEHD * 24 * 60 * 60 * 1000)) {
try {
await updateEHD();
} catch (err) { }
}
const fixEHDCounter = [
'window.fixEHDCounterTime = 0',
'window.fixEHDCounter = function fixEHDCounter () {',
' $(\'.ehD-pt-failed\').remove();',
' $(\'.ehD-pt:empty\').remove();',
' fixEHDCounterTime++;',
' if (totalCount <= 0) return;',
' if (totalCount === downloadedCount && failedCount > 0) {',
' failedCount = 0; checkFailed();',
' }',
' if (fetchCount < 0) {',
' // fetchCount = [...document.querySelectorAll(\'.ehD-pt-progress\')].filter(i => { const value = i.getAttribute(\'value\'); return value === null || (value * 1 < 1 && value * 1 > 0); }).length;',
' fetchCount = $(\'.ehD-pt-item:not(.ehD-pt-succeed,.ehD-pt-failed) .ehD-pt-status[data-inited-abort] .ehD-pt-abort\').length;',
' updateTotalStatus();',
' checkFailed();',
' }',
' if (downloadedCount + failedCount >= totalCount && failedCount > 0 && fetchCount > 0) {',
' retryAllFailed();',
' }',
' if (downloadedCount >= totalCount) {',
' ehDownloadPauseBtn();',
' saveDownloaded(true);',
' }',
' $(\'<tr>\').html(\'<td colspan="3">fixEHDCounter: \' + fixEHDCounterTime + \'</td>\').appendTo(\'.ehD-pt:last\');',
'};',
];
$('<button title="重置EHD计数">Fix EHD Counter</button>').on({
click: () => {
window.fixEHDCounter();
},
}).prependTo('.ehNavBar>div:nth-child(2)');
const checkAndFix = [
'window.EHDCounter = {}',
'let startLoop',
'let checkAndFixEHDCounter = function (loop) {',
' let timeout = 1 * 1000',
' if (totalCount !== 0) {',
' let obj = { totalCount, downloadedCount, failedCount, fetchCount }',
' let changed = false',
' for (let i in obj) {',
' if (window.EHDCounter[i] !== obj[i]) {',
' changed = true',
' break',
' }',
' }',
' if (changed) {',
' window.EHDCounter = obj',
' timeout = 2 * 1000',
' } else if (obj.fetchCount <= -1) {',
' window.fixEHDCounter()',
' }',
' }',
' if (loop) setTimeout(checkAndFixEHDCounter, timeout)',
'};',
'let checkAndFixEHDCounterStart = function () {',
' if (startLoop) return;',
' startLoop = true;',
' checkAndFixEHDCounter(true);',
'};',
];
const monitorDialog = [
'const pushDialogRaw = pushDialog;',
'var pushDialog = function (str) {',
' isDownloading = true;',
' checkAndFixEHDCounterStart();',
' if (["Failed!\\nFetch Pages\' URL failed, Please try again later."].includes(str)) {',
' unsafeWindow.onbeforeunload = null;',
' ehDownloadAction.click();',
' }',
' pushDialogRaw(str);',
'};',
];
$('<button tooltip="更改EHD设置" name="ehdSetting">EHD Setting: 0</button>').on({
click: () => {
window.changeEHDSetting();
},
}).prependTo('.ehNavBar>div:nth-child(2)');
const monitorProgress = [
'const settingRaw = JSON.parse(GM_getValue(\'ehD-setting\'));',
'const settingLoop = [settingRaw, JSON.parse(G.config.ehdFailed1Config), JSON.parse(G.config.ehdFailed2Config)];',
'let settingIndex = 0;',
'window.changeEHDSetting = (obj, name) => {',
' if (!obj) obj = settingIndex + 1;',
' if (typeof obj === \'number\') {',
' obj = obj % settingLoop.length;',
' settingIndex = obj;',
' name = obj;',
' obj = settingLoop[obj];',
' }',
' Object.assign(setting, obj);',
' const title = \'<pre>\' + JSON.stringify(obj, null, 2) + \'</pre>\';',
' $(\'[name="ehdSetting"]\').text(\'EHD Setting: \' + name).attr(\'title\', title).attr(\'raw-title\', title);',
'};',
'const updateProgressRaw = updateProgress;',
'var ehFailedCount = 0;',
'var updateProgress = function (nodeList, data) {',
' if (data.class === \'ehD-pt-succeed\') {',
' ehFailedCount = 0;',
' } else if ([\'ehD-pt-warning\', \'ehD-pt-failed\'].includes(data.class)) {',
' ehFailedCount++;',
' }',
' if (ehFailedCount >= G.config.ehdFailed3) {',
' if (ehDownloadPauseBtn.textContent.match(/^Pause/i)) ehDownloadPauseBtn.click();',
' window.changeEHDSetting(0);',
' ehFailedCount = 0;',
' if (GM_getValue(\'passiveMode\') && G.config.ehdFailed3Time) {',
' setTimeout(() => {',
' if (ehDownloadPauseBtn.textContent.match(/^Resume/i)) ehDownloadPauseBtn.click();',
' }, G.config.ehdFailed3Time * 1000);',
' } else {',
' window.alert(\'下载已暂停,设置已还原\');',
' }',
' } else if (ehFailedCount >= G.config.ehdFailed2) {',
' window.changeEHDSetting(2);',
' } else if (ehFailedCount >= G.config.ehdFailed1) {',
' window.changeEHDSetting(1);',
' }',
' updateProgressRaw(nodeList, data);',
'};',
];
const toEavl = [
'try {',
';(function () {',
'var loadSetting = function () { return new Promise(resolve => { resolve(GM_getValue(\'ehD-setting\')) }) }',
'let console = {}',
'for (let i in window.console) { console[i] = new Function() }',
'let alert = function () { }',
'let confirm = function () { return true }',
'let prompt = function (message, value) { return value }',
';',
GM_getValue('EHD_code'),
';',
fixEHDCounter.join('\n'),
';',
monitorDialog.join('\n'),
';',
monitorProgress.join('\n'),
';',
(G.config.fixEHDCounter ? checkAndFix.join('\n') : ''),
';',
'})();',
'} catch (error) {',
' console.error(err);',
'}',
];
eval(toEavl.join('\n')); // eslint-disable-line no-eval
} else {
const loaded = await waitForElement(SEL.EHD.checker, 30 * 1000);
if (!loaded) console.error('载入 E-Hentai-Downloader 超时');
setNotification('载入 E-Hentai-Downloader 超时');
}
$(SEL.EHD.download).click((e) => { // 使用EHD下载时, 添加到下载列表
if (e.originalEvent && G.downloadSizeChanged) autoDownload();
downloadAdd(SEL.EH.info.galleryId);
if ($('[rel="shortcut icon"]').length === 0) changeFav(G.favicon.d);
$('.ehNavBar').attr('style', 'top:0;');
});
$(window).on('unload', () => { // 关闭页面时, 从下载列表中移除
for (const i in G) delete G[i];
downloadRemove(SEL.EH.info.galleryId);
});
if (G.config.changeName) changeName(SEL.EH.info.title); // 修改本子标题(删除集会名、替换其中的罗马数字)
document.title = $(SEL.EH.info.title).text();
tagTranslate(); // 标签翻译
btnSearch(); // 按钮 -> 搜索(信息页)
if (G.config.btnFake) btnFake(); // 按钮 -> 下载空文档(信息页)
btnInfoText(); // 按钮 -> 下载info.txt(信息页)
btnTask(); // 按钮 -> 添加到下载任务(信息页)
tagEvent(); // 标签事件
abortPending(); // 终止EHD所有下载
$('<button class="ehThumbBtn">Hide</button>').on('click', (e) => { // 隐藏预览图
$(SEL.EH.info.previewContainer).toggle();
$(e.target).text($(e.target).text() === 'Show' ? 'Hide' : 'Show');
}).prependTo(SEL.EH.info.btnContainer);
if (G.config.showAllThumb) await showAllThumb();
introPic(); // 宣传图
if (G.config.enableChangeSize && G.config.sizeS !== G.config.sizeD) await checkImageSize();
await waitInMs(500);
if (G.autoDownload) await autoDownload(); // 自动开始下载
} else if (G.searchPage) { // 搜索页
if ($(SEL.EH.search.resultTotal).length && !G.isPreferDisplayMode) {
window.alert('Please change display mode to "Minimal" or "Minimal+"');
return;
}
if (jumpHost()) return; // 里站跳转
$(SEL.EH.search.apply).attr('title', '右键: 添加/删除 中文').on({
contextmenu: () => {
let value = $(SEL.EH.search.keyword).val();
value = value.match(/language:"?\w+\$?"?/) ? value.replace(/language:"?\w+\$?"?/, '').trim() : `${value} language:chinese$`;
$(SEL.EH.search.keyword).val(value);
},
});
if ($(SEL.EH.search.keyword).val()) document.title = translateText($(SEL.EH.search.keyword).val());
if (G.config.preloadResult && $(SEL.EH.common.pageCur).length) await preloadResult(G.config.preloadResult);
$('<div class="ehContainer"></div>').prependTo(SEL.EH.search.nameTd);
btnSearch2(); // 按钮 -> 搜索(搜索页)
quickDownload(); // 右键:下载
if ($(SEL.EH.search.resultTable).length) batchDownload(); // Displsy: List => 批量下载
if (G.config.btnFake) btnFake2(); // 按钮 -> 下载空文档(搜索页)
btnTask2(); // 按钮 -> 添加到下载任务(搜索页)
const _gmetadata = await getInfo() || [];
G.gmetadata.push(..._gmetadata);
if (G.config.pageCount) pageCount(); // 显示本子页数
if (G.config.languageCode) languageCode(); // 显示iso语言代码
if (G.config.checkExist) checkExist(); // 检查本地是否存在
if (G.config.changeName) changeName(SEL.EH.search.galleryA); // 修改本子标题(删除集会名、替换其中的罗马数字)
if (G.config.sortByName) sortByName(); // 本子按名称排序
if (G.config.tagPreview) tagPreview(); // 标签预览
if (G.config.checkExistAtStart) $('[name="checkExist"]').click();
hideGalleries(); // 隐藏某些画集
waitForElement('[name="checkExist"]:not([disabled])').then(() => {
if ($(SEL.EH.search.resultTable).length && G.config.preloadPaneImage) $(SEL.EH.search.thumb).filter(':visible').each((index, elem) => { unsafeWindow.load_pane_image(elem); });
changeFav(G.favicon.d);
if (window.location.hash === '#autoPage') {
if ($(SEL.EH.search.resultTrGt0).filter(':not(.ehCheckContainer):visible').length === 0) {
window.location.href = `${$(SEL.EH.common.pagesContainerBottom).find('td:last-child>a').attr('href')}#autoPage`;
} else {
setNotification(`Result ${$(SEL.EH.search.resultTrGt0).filter(':not(.ehCheckContainer):visible').length}`, '');
}
}
});
if (G.config.acLength >= 0) autoComplete(); // 自动填充
checkForNew(); // 检查有无新本子
btnSearch2Highlight();
} else if (G.settingPage) { // 设置页
return;
}
highlightBlacklist(); // 高亮黑名单相关的画廊(通用)
if (G.config.searchInOtherSites) searchInOtherSites(); // 在其他站点搜索
if (G.config.saveLink) saveLink(); // 保存链接
$('<button tooltip="重置下载列表">Clear Downloading</button>').on({
click: () => {
GM_setValue('downloading', []);
},
mouseenter: (e) => {
$(e.target).attr('title', `当前下载列表:<br> ${GM_getValue('downloading', []).join('<br> ')}`);
},
}).prependTo('.ehNavBar>div:nth-child(3)');
$(`<button name="taskControl" key-code="X" key-event="mousedown" tooltip="${htmlEscape('左键: 开始/暂停下载任务<br>中键: 取消当前下载<br>右键: 从当前任务开始')}">Start Task</button>`).on({
mousedown: (e) => {
if (e.button === 0) {
if (G.taskInterval) {
G.taskStop = true;
G.taskInterval = null;
$(e.target).text('Start Task');
} else {
task();
$(e.target).text('Stop Task');
}
} else if (e.button === 1) {
GM_deleteValue('tasking');
} else if (e.button === 2) {
const taskAll = [].concat(GM_getValue('tasking', []), GM_getValue('task', [])).map((i) => i.replace(/#\d+$/, '')).filter((i) => i).filter((item, index, array) => array.indexOf(item) === index);
GM_deleteValue('tasking');
GM_setValue('task', taskAll);
task();
$(e.target).text('Stop Task');
}
},
mouseenter: (e) => {
const task = GM_getValue('task', []);
const taskFailed = GM_getValue('taskFailed', []);
$(e.target).attr('title', `当前任务:<br> ${GM_getValue('tasking', '')}<hr>当前任务列表: ${task.length}<br> ${task.join('<br> ')}<hr>当前任务列表-失败: ${taskFailed.length}<br> ${taskFailed.join('<br> ')}`);
},
}).appendTo('.ehNavBar>div:nth-child(3)');
$('<input type="file" id="selectFileTask" name="selectFile" accept=".txt">').on({
change: (e) => {
if (!e.target.files || !e.target.files.length) {
e.target.value = null;
return;
}
const fr = new window.FileReader();
fr.onload = (e) => {
const text = e.target.result;
const tasking = GM_getValue('tasking', []);
const task = [].concat(GM_getValue('task', []), text.split(/[\r\n]+/)).map((i) => i.replace(/#\d+$/, '')).filter((i) => i && i !== tasking && i.match(SEL.EH.info.urlMatch)).filter((item, index, array) => array.indexOf(item) === index);
GM_setValue('task', task);
e.target.value = null;
};
fr.readAsText(e.target.files[0]);
},
}).appendTo('.ehNavBar>div:nth-child(3)');
$(`<button tooltip="${htmlEscape('左键: 导出下载列表(包括正在下载)<br>中键: 重置下载列表(包括正在下载)<br>右键: 导入下载列表(自动清除重复项)')}">Export Task</button>`).on({
mousedown: (e) => {
if (e.button === 0) {
const task = [].concat(GM_getValue('tasking', []), GM_getValue('task', [])).map((i) => i.replace(/#\d+$/, '')).filter((i) => i).filter((item, index, array) => array.indexOf(item) === index);
saveAs2(task.join('\n'), 'task-list.txt');
} else if (e.button === 1) {
GM_setValue('task', []);
GM_deleteValue('tasking');
} else if (e.button === 2) {
$('#selectFileTask').click();
}
},
mouseenter: (e) => {
const task = GM_getValue('task', []);
const taskFailed = GM_getValue('taskFailed', []);
$(e.target).attr('title', `当前任务:<br> ${GM_getValue('tasking', '')}<hr>当前任务列表: ${task.length}<br> ${task.join('<br> ')}<hr>当前任务列表-失败: ${taskFailed.length}<br> ${taskFailed.join('<br> ')}`);
},
}).appendTo('.ehNavBar>div:nth-child(3)');
$(`<button title="${htmlEscape('左键: 加入或移除黑名单<br>右键: 显示黑名单列表')}">Toggle Blacklist</button>`).on({
mousedown: (e) => {
if (e.button === 0) {
const value = window.prompt('如需输入正则表达式,请按"/pattern/flags"的格式输入\n其他格式视为纯文本');
if (value && value.trim()) {
toggleBlacklist(value.trim());
highlightBlacklist();
}
} else if (e.button === 1) {
} else if (e.button === 2) {
if ($('.ehBlackListContainer').length) {
$('.ehBlackListContainer').remove();
} else {
const blacklist = GM_getValue('blacklist', []);
let html = '<ul>';
html = html + blacklist.map((keyword) => `<li><a href="${G.config.searchArguments.replace(/{q}/g, encodeURIComponent(keyword))}" target="_blank">${htmlEscape(keyword)}</a> <span copy="${htmlEscape(keyword)}">复制</span></li>`).join('');
html = `${html}</ul>`;
$('<div class="ehBlackListContainer"></div>').html(html).appendTo('body');
}
}
},
}).appendTo('.ehNavBar>div:nth-child(1)');
showTooltip(); // 显示提示
$('body').on('mousedown', 'a,button,input[type="button"],div:empty', (e) => {
$(e.target).addClass('clicked fadeOutIn');
setTimeout(() => {
$(e.target).removeClass('fadeOutIn');
}, 800);
});
$('body').on('mousedown', '[copy]', (e) => {
e.preventDefault();
const copy = $(e.target).attr('copy');
setNotification(copy, '已复制');
GM_setClipboard(copy);
}).on('contextmenu', () => false);
$('.ehNavBar').attr('oncontextmenu', 'return false');
$('body').on('click', 'a[href][target="_blank"]:not([href^="#"])', (e) => {
if (e.isDefaultPrevented()) return;
let url = $(e.target).is('a') ? e.target.href : $(e.target).parents('a').attr('href');
url = new URL(url, window.location.href);
if (!(['http:', 'https:'].includes(url.protocol))) return;
e.preventDefault();
openUrl(url.href);
});
$('body').on('keydown', (e) => {
if (['text', 'number', 'textarea', 'password'].includes(e.target.type)) return;
if (!e.originalEvent.code.match(/^(Key|Digit|Numpad)(.*)$/)) return;
const key = e.originalEvent.code.match(/^(Key|Digit|Numpad)(.*)$/)[2];
if ($(`[key-code="${key}"]`).length) {
const keyEvent = $(`[key-code=${key}]`).attr('key-event');
const event = jQuery.Event(keyEvent);
if (keyEvent === 'mousedown') event.button = e.shiftKey ? 2 : 0;
$(`[key-code=${key}]`).trigger(event).addClass('clicked');
e.preventDefault();
}
});
}
function abortPending() { // 终止EHD所有下载
$('<button title="终止EHD所有下载">Force Abort</button>').on({
click: () => {
$(SEL.EHD.abort).click();
},
}).appendTo('.ehNavBar>div:nth-child(2)');
}
function addStyle() { // 添加样式
const backgroundColor = $('body').css('background-color');
$('<style></style>').text([
// global
'input[type="number"]{width:60px;border:1px solid #B5A4A4;margin:3px 1px 0;padding:1px 3px 3px;border-radius:3px;}',
'input:disabled,button:disabled{cursor:progress;color:#808080;opacity:0.7;text-decoration:line-through;}',
'.clicked{border:#f00 solid 1px;}',
'.fadeOutIn{animation:fadeOutIn ease 1s;}',
'@keyframes fadeOutIn{0% {opacity:1;} 50% {opacity:0.5;} 100% {opacity:1;}}',
'button{min-height:26px;line-height:20px;padding:1px 5px 2px;margin:0 2px;border-radius:3px;font-size:9pt;}',
'button:enabled:hover{outline:0;}',
(
window.location.host === 'e-hentai.org'
? 'button{border:2px solid #b5a4a4;color:#5c0d12;background-color:#edeada;}'
+ 'button:enabled:hover{background-color:#f3f0e0!important;border-color:#977273!important;}'
: 'button{border:2px solid #8d8d8d;color:#f1f1f1;background-color:#34353b;}'
+ 'button:enabled:hover{background-color:#43464e!important;border-color:#aeaeae!important;}'
),
// script
`.ehNavBar{display:flex;width:99%;background-color:${backgroundColor};position:fixed;z-index:1000;padding:0 10px;}`,
'.ehNavBar>div{flex-grow:1;}',
'.ehNavBar>div:nth-child(1){text-align:left;}',
'.ehNavBar>div:nth-child(2){text-align:center;}',
'.ehNavBar>div:nth-child(3){text-align:right;}',
'.ehNavBar>div>[name="container"]{max-width:120px;white-space:nowrap;overflow:hidden;text-overflow:ellipsis}',
'.btnSearch{cursor:pointer;width:16px;height:16px;float:left;}',
'.ehNavBar>div:nth-child(1)>[name="passive mode"][status="on"]{color:#f00;background:#fff;}',
'.ehNavBar>div:nth-child(1)>[name="passive mode"][status="on"]::after{content:" ON"}',
'.btnSearch::before{content:"' + '\ud83d\udd0d' + '"}',
`.ehConfig{position:fixed;top:30px;bottom:23px;left:0;right:0;min-width:720px;max-width:1200px;margin:3px auto;padding:3px 5px;;border:solid 1px black;z-index:3;overflow:auto;background-color:${backgroundColor};}`,
'.ehConfig>ul{text-align:left;}',
'.ehTagEvent{display:none;font-weight:bold;}',
'.ehTagEvent::before{margin-left:10px;content:url("https://ehgt.org/g/mr.gif") " " attr(name);}',
'.ehTagEvent>a{cursor:pointer;text-decoration:none;}',
'.ehTagEvent>a::before{margin-left:10px;margin-right:2px;content:url("https://ehgt.org/g/mr.gif");}',
'.ehDatalist{display:none;overflow-y:auto;max-height:300px;}',
'.ehDatalist>ol{list-style:decimal;text-align:left;}',
'.ehDatalist>ol>li{cursor:pointer;}',
'.ehDatalist>ol>li::after{content:" "attr(cname);font-size:9pt;font-weight:bold;}',
'.ehDatalistHover{color:#f00;font-weight:bold;font-size:large;}',
'.ehContainer>*{margin:1px;float:left;}',
'.ehExistContainer{float:left;max-width:240px;max-height:20px;overflow:auto;}',
'.ehExistContainer:hover{max-width:100%;}',
'.ehExistContainer::-webkit-scrollbar{height:2px;width:2px;}',
'.ehExistContainer::-webkit-scrollbar-track{background:#ddd;}',
'.ehExistContainer::-webkit-scrollbar-thumb{background:#666;}',
'.ehExist{display:inline-block;color:#fff;background:#000;border:black 1px solid;cursor:pointer;margin:1px;}',
'.ehExist::before{content:attr(fileSize) "M";}',
'.ehExist[filesize="0.00"]::before{content:"X";color:#f00;}',
'.ehExist[name="force"]{color:#0f0;float:left;}',
'.ehExist[name="force-nolang"]{color:#00f;}',
'.ehExist[name="force-notchinese"]{background-image:-webkit-linear-gradient(top left,#00f 50%,#b5810d 50%);color:#fff;}',
'.ehExist[name="incomplete"]{color:#f00;background:#00f;}',
'.ehExist[name="notchinese"]{color:#000;background:#f8b400;}',
'.ehLang{border:black 1px solid;color:#0f0;background:#111d5e;}',
'.ehPageCount{border:black 1px solid;color:#f00;background:#111d5e;}',
'.ehTagPreview{position:fixed;padding:5px;display:none;z-index:999999;font-size:larger;width:250px;border-color:#000;border-style:solid;color:#fff;background-color:#34353b;}',
'.ehTagPreviewLi{color:#ffffff;}',
'.ehTagPreviewLi[name="language"]>span{background-color:#ff0000;}',
'.ehTagPreviewLi[name="language"]::before{content:"语言: ";}',
'.ehTagPreviewLi[name="reclass"]::before{content:"重新分类: ";}',
'.ehTagPreviewLi[name="artist"]>span{font-size:larger;background-color:#0000ff;}',
'.ehTagPreviewLi[name="artist"]::before{content:"漫画家: ";}',
'.ehTagPreviewLi[name="group"]>span{font-size:larger;background-color:#00ff00;}',
'.ehTagPreviewLi[name="group"]::before{content:"组织: "}',
'.ehTagPreviewLi[name="parody"]>span{font-size:larger;background-color:#3d7878;}',
'.ehTagPreviewLi[name="parody"]::before{content:"同人: ";}',
'.ehTagPreviewLi[name="character"]>span{background-color:#9f0050;}',
'.ehTagPreviewLi[name="character"]::before{content:"角色: ";}',
'.ehTagPreviewLi[name="female"]>span{background-color:#00008b;}',
'.ehTagPreviewLi[name="female"]::before{content:"女: ";}',
'.ehTagPreviewLi[name="male"]>span{background-color:#800080;}',
'.ehTagPreviewLi[name="male"]::before{content:"男: ";}',
'.ehTagPreviewLi[name="misc"]>span{background-color:#808080;}',
'.ehTagPreviewLi[name="misc"]::before{content:"杂项: ";}',
'.ehTagPreviewLi[name="other"]::before{content:"未分类: ";}',
'.ehTagPreviewLi>span{display:inline;margin:0 2px;border:1px #456F78 solid;}',
'.ehTagEvent>.ehTagEventNotice[on="true"]::after{content:attr(name);}',
'.ehTagEvent>.ehTagEventNotice[on="false"]::after{content:"NOT " attr(name);}',
`.ehTooltip{max-width:50%;max-height:85%;overflow:auto;display:none;position:fixed;text-align:left;z-index:99999;border:2px solid #8d8d8d;background-color:${backgroundColor};font-size:110%;}`,
'.ehTooltip>ul{margin:0;}',
`.ehCheckTableContainer{position:fixed;top:23px;bottom:16px;left:0;right:0;min-width:950px;max-width:1200px;margin:10px auto;padding:5px;border:solid 1px black;z-index:2;background-color:${backgroundColor};}`,
'.ehCheckTableContainer>div{overflow:auto;}',
'.ehCheckTable{counter-reset:checkOrder;height:calc(100% - 65px);}',
'.ehCheckTable>table{margin:0 auto;border-collapse:collapse;}',
'.ehCheckTable th,.ehCheckTable td{border:2px ridge #000;}',
'.ehCheckTable tr>td:nth-child(1)::before{counter-increment:checkOrder;content:counter(checkOrder);}',
'.ehCheckTable a{text-decoration:none;}',
'.ehPages>a{display:inline;margin:0 1px;cursor:pointer;}',
'.ehPages>a::before{content:attr(name)}',
'.ehPagesHover{color:red;font-weight:bold;}',
'.ehCheckContainer{text-align:center;}',
'.ehCheckContainer>td{padding:3px 4px;border-right:1px solid #40454b;}',
'.ehBlacklist{color:#f00!important;background-color:#00f;}',
'.ehBlacklist:hover{color:inherit!important;background-color:inherit;}',
'[copy]{cursor:pointer;}',
'[key-code]::before{content:"(&"attr(key-code)")";text-decoration:underline;}',
'[content-after]::after{content:attr(content-after);padding-left:5px;}',
'[content-before]::before{content:attr(content-before);padding-right:5px;}',
'.icon{margin:-3px 0!important;height:16px!important;width:16px!important;}',
'.ehHighlight{color:#0f0;background-color:#000;margin:3px;font-size:125%;font-weight:bold;}',
'.ehNew{width:25px;height:12px;float:left;background-image:url(https://ehgt.org/g/n.gif);}',
'[name="selectFile"]{width:0;height:0;opacity:0;overflow:hidden;}',
`.ehNotification{display:flex;z-index:2147483647;position:fixed;bottom:1px;right:1px;border:solid 1px #000;background-color:${backgroundColor};min-width:300px;cursor:pointer;}`,
'.ehNotification>div:nth-child(1){flex:1;}',
'.ehNotification>div:nth-child(2){flex:4;}',
'.ehNotification>div:nth-child(2)>div:nth-child(1){font-size:16px;font-weight:bold;white-space:nowrap;}',
'.ehFavicion{background: url(favicon.ico) no-repeat center center;}',
'.ehIgnore{filter:blur(1px) grayscale(1);}',
'.ehIgnore:hover{filter:none;}',
'.ehIframeContainer{margin-bottom:40px;padding:2px;border:solid;}',
'.ehIframeContainer>[name="src"]{width:50%;}',
`.ehIframe{width:95%;height:${document.documentElement.clientHeight * 0.7}px;resize:vertical;}`,
'.ehIframeClose{position:fixed;top:0;right:0;z-index:99999;color:#f00;}',
'.ehThumbBtn{width:36px;height:15px;padding:3px 2px;margin:0 2px 4px 2px;float:left;border-radius:5px;border:1px solid #989898;}',
'.ehPreLike{white-space:pre-wrap;word-break:break-word;font-family:Consolas,Monaco,monospace;}',
`.ehDiffNone{color:${backgroundColor};background-color:${backgroundColor};}`,
'.ehDiffDel{background:#9d0b0b;font-size:110%;}',
'.ehDiffAdd{background:#007944;font-size:110%;}',
`.ehBlackListContainer{position:fixed;top:23px;bottom:16px;left:0;right:0;min-width:950px;max-width:1200px;margin:10px auto;padding:5px;border:solid 1px black;z-index:2;background-color:${backgroundColor};overflow:auto;text-align:justify;}`,
// html
`${SEL.EH.common.navBar}{max-width:100%;max-height:100%;}`,
`${SEL.EH.search.mainDiv},${SEL.EH.search.resultTable}{max-width:9999px!important;min-width:0!important;justify-content:center;}`,
`${SEL.EH.search.resultTr}.ehBatchActive{background-color:#669933!important;}`,
`${SEL.EH.search.resultTr}:hover{background-color:#4a86e8!important;}`,
`${SEL.EH.search.resultTr}.ehHover{background-color:#4a86e8!important;}`,
`${SEL.EH.search.thumb}{position:fixed;left:0px!important;top:50%!important;visibility:hidden;transform:translateY(-50%);}`,
`.ehTagNotice[name="Perma-ban"],${SEL.EH.info.tagDiv}[name="Perma-ban"]{color:#00f;background-color:#f00;}`,
`.ehTagNotice[name="Unlike"],${SEL.EH.info.tagDiv}[name="Unlike"]{color:#f00;background-color:#00f;}`,
`.ehTagNotice[name="Alert"],${SEL.EH.info.tagDiv}[name="Alert"]{color:#ff0;background-color:#080;}`,
`.ehTagNotice[name="Like"],${SEL.EH.info.tagDiv}[name="Like"]{color:#000;background-color:#0ff;}`,
`${SEL.EH.info.previewDiv} [name="intro"]{white-space:nowrap;}`,
`${SEL.EH.info.previewDiv} [name="intro"][on="true"]::after{content:"Block: " attr(file);}`,
`${SEL.EH.info.previewDiv} [name="intro"][on="false"]::after{content:"Unblock: " attr(file);}`,
// unknown
// '.ih>li{margin:0 2px;cursor:pointer;list-style:none;}',
// '.ih>li::before{content:attr(name) ": ";}',
// '.ih>li>span{margin:1px;}'
].join('\n')).appendTo('head');
}
async function autoDownload(isEnd) { // 自动开始下载
// isEnd false: 下载小图, true: 下载大图
if (G.downloadSizeChanged) {
if (G.imageD.length && G.imageS.length) {
const imageSize = isEnd ? G.config.sizeD : G.config.sizeS;
await changeEConfig('xr', imageSize);
changeFav(G.favicon[imageSize]);
$(SEL.EHD.pageRange).val(makeRange(isEnd ? G.imageD : G.imageS));
G.imageEnd = isEnd;
} else {
G.downloadSizeChanged = false;
$(SEL.EHD.pageRange).val(makeRange(G.imageD.length ? G.imageD : G.imageS));
}
}
$(SEL.EHD.download).last().click();
}
function autoComplete() { // 自动填充
let main = (G.config.acItem || 'language,artist,female,male,parody,character,group,misc').split(',');
main = G.EHT.filter((i) => main.includes(i.namespace));
$('<div class="ehDatalist"><ol start="0"></ol></div>').on('click', 'li', (e) => {
const value = $(SEL.EH.search.keyword).val().split(/\s+/);
value[value.length - 1] = e.target.textContent;
$(SEL.EH.search.keyword).val(value.filter((i) => i).join(' ')).focus();
$('.ehDatalist>ol').empty();
$('.ehDatalist').show();
}).appendTo($('form').has(SEL.EH.search.keyword));
let lastValue;
$(SEL.EH.search.keyword).attr('title', `当输入大于${G.config.acLength}个字符时,显示选单<br>使用主键盘区的数字/加减/方向键快速选择<br>点击/Enter/Insert键填充<br>使用输入法时,无法使用数字/加减选择`).attr('autocomplete', 'off').on({
focusin() {
$('.ehDatalist').show();
},
focusout() {
setTimeout(() => {
$('.ehDatalist').hide();
}, 100);
},
keydown(e) {
const hasItem = $('.ehDatalist li').length;
let onItem = $('.ehDatalistHover').index();
if (hasItem && e.keyCode <= 57 && e.keyCode >= 48) { // 选择选项: 0-9
e.preventDefault();
$('.ehDatalist li').eq(e.keyCode - 48).click();
} else if (hasItem && [187, 189, 37, 38, 39, 40].includes(e.keyCode)) { // 选择选项: 加减/方向键
e.preventDefault();
if ([187, 40].includes(e.keyCode)) { // 选择选项: +下
onItem = onItem + 1;
} else if ([189, 38].includes(e.keyCode)) { // 选择选项: -上
onItem = onItem - 1;
} else if (e.keyCode === 39) { // 选择选项: 右
onItem = onItem + 10;
} else if (e.keyCode === 37) { // 选择选项: 左
onItem = onItem - 10;
}
if (onItem < 0) {
onItem = 0;
} else if (onItem > hasItem - 1) {
onItem = hasItem - 1;
}
$('.ehDatalist li').removeClass('ehDatalistHover');
$('.ehDatalist li').eq(onItem).addClass('ehDatalistHover');
$('.ehDatalist').scrollTop($('.ehDatalistHover').position().top - $('.ehDatalist>ol').position().top - 150 + $('.ehDatalistHover').height() / 2);
} else if (onItem >= 0 && [13, 45].includes(e.keyCode)) { // 选择选项: Insert
e.preventDefault();
$('.ehDatalistHover').click();
}
},
keyup(e) {
let value = e.target.value.split(/\s+/);
value = value[value.length - 1];
if (value === lastValue) return;
$('.ehDatalist>ol').empty();
if (!value || (value.length <= G.config.acLength && !value.match(/[\u4e00-\u9fa5]/))) return;
lastValue = value;
value = new RegExp(reEscape(value), 'i');
main.forEach((i) => {
for (const key in i.data) {
if (key.match(value) || i.data[key].name.match(value)) {
$(`<li cname="${i.data[key].name}">${i.namespace}:"${key}$"</li>`).appendTo('.ehDatalist>ol');
}
}
});
$('.ehDatalist').show();
},
});
}
function batchDownload() { // 批量下载
$(`<th><input type="checkbox" tooltip="${htmlEscape('左键/Ctrl+A: 全选(当前表)<br>右键/Ctrl+D: 反选(当前表)<br>Shift+左键/Shift+A: 全选(所有表)<br>Shift+右键/Shift+D: 反选(所有表)')}"></th>`).appendTo(SEL.EH.search.resultTr0);
$(SEL.EH.search.resultTr0).find('th:last-child>input[type="checkbox"]').on('mousedown', (e) => {
const root = e.shiftKey ? document : $(e.target).parents().filter(SEL.EH.search.resultTable);
if (e.button === 0) {
const { checked } = e.target;
$(root).find('tr').filter(SEL.EH.search.resultTrGt0).find('td:last-child>input[type="checkbox"]:visible')
.prop('checked', !checked);
$(root).find('tr').filter(SEL.EH.search.resultTrGt0).filter(':visible:not(.ehCheckContainer)')
.toggleClass('ehBatchActive', !checked);
} else if (e.button === 2) {
$(root).find('tr').filter(SEL.EH.search.resultTrGt0).find('td:last-child>input[type="checkbox"]:visible')
.toArray()
.forEach((i) => {
const { checked } = i;
i.checked = !checked;
$(i).parents().filter(SEL.EH.search.resultTrGt0).toggleClass('ehBatchActive', !checked);
});
e.target.checked = !e.target.checked;
}
e.preventDefault();
});
$('body').on('keydown', (e) => {
if (['text', 'number', 'textarea', 'password'].includes(e.target.type)) return;
if (!e.originalEvent.code.match(/^(Key|Digit|Numpad|Arrow)(.*)$/)) return;
const key = e.originalEvent.code.match(/^(Key|Digit|Numpad|Arrow)(.*)$/)[2];
if (e.ctrlKey && key === 'A') {
const checkboxs = $(SEL.EH.search.resultTr0).find('th:last-child>input[type="checkbox"]');
if (checkboxs.not(':checked').length) {
const event = jQuery.Event('mousedown');
event.button = 0;
checkboxs.not(':checked').eq(0).trigger(event).trigger('click');
}
} else if (e.ctrlKey && key === 'D') {
const checkboxs = $(SEL.EH.search.resultTr0).find('th:last-child>input[type="checkbox"]');
if (checkboxs.filter(':checked').length) {
const event = jQuery.Event('mousedown');
event.button = 2;
checkboxs.filter(':checked').eq(0).trigger(event);
}
} else if (e.shiftKey && key === 'A') {
const event = jQuery.Event('mousedown');
event.button = 0;
event.shiftKey = true;
$(SEL.EH.search.resultTr0).find('th:last-child>input[type="checkbox"]').eq(0).trigger(event)
.trigger('click');
} else if (e.shiftKey && key === 'D') {
const event = jQuery.Event('mousedown');
event.button = 2;
event.shiftKey = true;
$(SEL.EH.search.resultTr0).find('th:last-child>input[type="checkbox"]').eq(0).trigger(event);
} else if (['Up', 'Down'].includes(key)) {
const arr = $(SEL.EH.search.resultTrGt0).filter(`:has(${SEL.EH.search.nameTd})`).filter(':visible');
const elem = arr.filter('.ehHover');
let index = elem.length ? arr.index(elem) : window.hoverLast === undefined ? -1 : window.hoverLast;
index = ['Up'].includes(key) ? index - 1 : index + 1;
window.hoverLast = index;
while (index > arr.length) index = index - arr.length;
while (index < -1) index = index + 1 + arr.length;
elem.removeClass('ehHover').find(SEL.EH.search.nameTd).trigger('mouseout');
if (index >= 0 && arr.eq(index).length) {
arr.eq(index).addClass('ehHover').find(SEL.EH.search.nameTd).trigger('mouseover');
arr.eq(index).get(0).scrollIntoView();
// tagPreview
const event = jQuery.Event('mousemove');
event.target = arr.eq(index).find(SEL.EH.search.galleryA).get(0);
event.clientX = $(event.target).offset().left - document.documentElement.scrollLeft + $(event.target).width() / 2;
event.clientY = $(event.target).offset().top - document.documentElement.scrollTop + $(event.target).height();
$('body').trigger(event);
} else {
$('.ehTagPreview').hide();
}
} else if ($('.ehHover').length && ['Right', 'Add'].includes(key)) {
$('.ehHover').find('td:last-child>input[type="checkbox"]:visible').prop('checked', false).trigger('click');
} else if ($('.ehHover').length && ['Left', 'Subtract'].includes(key)) {
$('.ehHover').find('td:last-child>input[type="checkbox"]:visible').prop('checked', true).trigger('click');
} else {
return;
}
e.preventDefault();
});
$(window).on('blur mousedown', (e) => {
if ($('.ehHover').length === 0) return;
$('.ehHover').removeClass('ehHover').find(SEL.EH.search.nameTd).trigger('mouseout');
$('.ehTagPreview').hide();
});
$(`<td title="${htmlEscape('上下键:切换行<br>左右/+-键:切换勾选状态<br>注: 因鼠标问题,预览图可能并非显示正确<br>点击/失去焦点时,隐藏')}"><input type="checkbox"></td>`).appendTo($(SEL.EH.search.resultTrGt0).filter(':not(.ehCheckContainer)'));
$(SEL.EH.search.resultTrGt0).filter(':not(.ehCheckContainer)').on('click', (e) => {
if ($(e.target).is('a,input') || $(e.target).parents().filter('a,input').length) return;
$(e.currentTarget).find('td:last-child>input[type="checkbox"]').click();
});
$(SEL.EH.search.resultTrGt0).find('td:last-child>input[type="checkbox"]').on('click', (e) => {
$(e.target).parentsUntil('tbody').eq(-1).toggleClass('ehBatchActive', e.target.checked);
});
}
const generateInfo = () => {
let infoStr = '';
infoStr = `${infoStr}${$(SEL.EH.info.title).text()}\n`;
infoStr = `${infoStr}${$(SEL.EH.info.titleJp).text()}\n`;
infoStr = `${infoStr}${window.location.href}\n\n`;
infoStr = `${infoStr}Category: ${$(SEL.EH.info.infoCategory).eq(0).text().trim()}\n`;
infoStr = `${infoStr}Uploader: ${$(SEL.EH.info.infoUploader).eq(0).text()}\n`;