-
Notifications
You must be signed in to change notification settings - Fork 15
Expand file tree
/
Copy pathpixiv previewer.user.js
More file actions
5505 lines (5048 loc) · 213 KB
/
pixiv previewer.user.js
File metadata and controls
5505 lines (5048 loc) · 213 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 Pixiv Previewer (Dev)
// @name:ja Pixiv Previewer (Dev)
// @name:ru Pixiv Previewer (Dev)
// @name:zh-CN Pixiv Previewer (Dev)
// @name:zh-TW Pixiv Previewer (Dev)
// @namespace https://github.com/Ocrosoft/PixivPreviewer
// @version 3.8.5
// @description Display preview images (support single image, multiple images, moving images); Download animation(.zip); Sorting the search page by favorite count(and display it).
// @description:zh-CN 显示预览图(支持单图,多图,动图);动图压缩包下载;搜索页按热门度(收藏数)排序并显示收藏数。
// @description:ja プレビュー画像の表示(単一画像、複数画像、動画のサポート); アニメーションのダウンロード(.zip); お気に入りの数で検索ページをソートします(そして表示します)。
// @description:zh-TW 顯示預覽圖像(支持單幅圖像,多幅圖像,運動圖像); 下載動畫(.zip); 按收藏夾數對搜索頁進行排序(並顯示)。
// @description:ru Отображение превью изображений (поддержка одиночных, множественных и анимированных изображений); Скачивание анимаций (.zip); Сортировка страницы поиска по количеству добавлений в закладки (с отображением количества).
// @author Ocrosoft
// @match *://www.pixiv.net/*
// @grant unsafeWindow
// @grant GM.xmlHttpRequest
// @grant GM_xmlhttpRequest
// @license GPLv3
// @icon https://t0.gstatic.com/faviconV2?client=SOCIAL&type=FAVICON&fallback_opts=TYPE,SIZE,URL&size=32&url=https://www.pixiv.net
// @icon64 https://t0.gstatic.com/faviconV2?client=SOCIAL&type=FAVICON&fallback_opts=TYPE,SIZE,URL&size=64&url=https://www.pixiv.net
// @require https://update.greasyfork.org/scripts/515994/1478507/gh_2215_make_GM_xhr_more_parallel_again.js
// @require https://openuserjs.org/src/libs/sizzle/GM_config.js
// ==/UserScript==
// https://greasyfork.org/zh-CN/scripts/417761-ilog
function ILog() {
this.prefix = '';
this.v = function (value) {
if (level <= this.LogLevel.Verbose) {
console.log(this.prefix + value);
}
}
this.i = function (info) {
if (level <= this.LogLevel.Info) {
console.info(this.prefix + info);
}
}
this.w = function (warning) {
if (level <= this.LogLevel.Warning) {
console.warn(this.prefix + warning);
}
}
this.e = function (error) {
if (level <= this.LogLevel.Error) {
console.error(this.prefix + error);
}
}
this.d = function (element) {
if (level <= this.LogLevel.Verbose) {
console.log(element);
}
}
this.setLogLevel = function (logLevel) {
level = logLevel;
}
this.LogLevel = {
Verbose: 0,
Info: 1,
Warning: 2,
Error: 3,
};
let level = this.LogLevel.Warning;
}
var iLog = new ILog();
var GM__xmlHttpRequest;
if ("undefined" != typeof (GM_xmlhttpRequest)) {
GM__xmlHttpRequest = GM_xmlhttpRequest;
} else {
GM__xmlHttpRequest = GM.xmlHttpRequest;
}
//
// Required for iOS <6, where Blob URLs are not available. This is slow...
// Source: https://gist.github.com/jonleighton/958841
function base64ArrayBuffer(arrayBuffer, off, byteLength) {
var base64 = '';
var encodings = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/';
var bytes = new Uint8Array(arrayBuffer);
var byteRemainder = byteLength % 3;
var mainLength = off + byteLength - byteRemainder;
var a, b, c, d;
var chunk;
// Main loop deals with bytes in chunks of 3
for (var i = off; i < mainLength; i = i + 3) {
// Combine the three bytes into a single integer
chunk = (bytes[i] << 16) | (bytes[i + 1] << 8) | bytes[i + 2];
// Use bitmasks to extract 6-bit segments from the triplet
a = (chunk & 16515072) >> 18; // 16515072 = (2^6 - 1) << 18
b = (chunk & 258048) >> 12; // 258048 = (2^6 - 1) << 12
c = (chunk & 4032) >> 6; // 4032 = (2^6 - 1) << 6
d = chunk & 63; // 63 = 2^6 - 1
// Convert the raw binary segments to the appropriate ASCII encoding
base64 += encodings[a] + encodings[b] + encodings[c] + encodings[d];
}
// Deal with the remaining bytes and padding
if (byteRemainder == 1) {
chunk = bytes[mainLength];
a = (chunk & 252) >> 2; // 252 = (2^6 - 1) << 2
// Set the 4 least significant bits to zero
b = (chunk & 3) << 4; // 3 = 2^2 - 1
base64 += encodings[a] + encodings[b] + '==';
} else if (byteRemainder == 2) {
chunk = (bytes[mainLength] << 8) | bytes[mainLength + 1];
a = (chunk & 64512) >> 10; // 64512 = (2^6 - 1) << 10
b = (chunk & 1008) >> 4; // 1008 = (2^6 - 1) << 4
// Set the 2 least significant bits to zero
c = (chunk & 15) << 2; // 15 = 2^4 - 1
base64 += encodings[a] + encodings[b] + encodings[c] + '=';
}
return base64;
}
function ZipImagePlayer(options) {
this.op = options;
this._URL = (window.URL || window.webkitURL || window.MozURL
|| window.MSURL);
this._Blob = (window.Blob || window.WebKitBlob || window.MozBlob
|| window.MSBlob);
this._BlobBuilder = (window.BlobBuilder || window.WebKitBlobBuilder
|| window.MozBlobBuilder || window.MSBlobBuilder);
this._Uint8Array = (window.Uint8Array || window.WebKitUint8Array
|| window.MozUint8Array || window.MSUint8Array);
this._DataView = (window.DataView || window.WebKitDataView
|| window.MozDataView || window.MSDataView);
this._ArrayBuffer = (window.ArrayBuffer || window.WebKitArrayBuffer
|| window.MozArrayBuffer || window.MSArrayBuffer);
this._maxLoadAhead = 0;
if (!this._URL) {
this._debugLog("No URL support! Will use slower data: URLs.");
// Throttle loading to avoid making playback stalling completely while
// loading images...
this._maxLoadAhead = 10;
}
if (!this._Blob) {
this._error("No Blob support");
}
if (!this._Uint8Array) {
this._error("No Uint8Array support");
}
if (!this._DataView) {
this._error("No DataView support");
}
if (!this._ArrayBuffer) {
this._error("No ArrayBuffer support");
}
this._isSafari = Object.prototype.toString.call(
window.HTMLElement).indexOf('Constructor') > 0;
this._loadingState = 0;
this._dead = false;
this._context = options.canvas.getContext("2d");
this._files = {};
this._frameCount = this.op.metadata.frames.length;
this._debugLog("Frame count: " + this._frameCount);
this._frame = 0;
this._loadFrame = 0;
this._frameImages = [];
this._paused = false;
this._loadTimer = null;
this._startLoad();
if (this.op.autoStart) {
this.play();
} else {
this._paused = true;
}
}
ZipImagePlayer.prototype = {
_trailerBytes: 30000,
_failed: false,
_mkerr: function (msg) {
var _this = this;
return function () {
_this._error(msg);
}
},
_error: function (msg) {
this._failed = true;
throw Error("ZipImagePlayer error: " + msg);
},
_debugLog: function (msg) {
if (this.op.debug) {
console.log(msg);
}
},
_load: function (offset, length, callback) {
var _this = this;
// Unfortunately JQuery doesn't support ArrayBuffer XHR
var xhr = new XMLHttpRequest();
xhr.addEventListener("load", function (ev) {
if (_this._dead) {
return;
}
_this._debugLog("Load: " + offset + " " + length + " status=" +
xhr.status);
if (xhr.status == 200) {
_this._debugLog("Range disabled or unsupported, complete load");
offset = 0;
length = xhr.response.byteLength;
_this._len = length;
_this._buf = xhr.response;
_this._bytes = new _this._Uint8Array(_this._buf);
} else {
if (xhr.status != 206) {
_this._error("Unexpected HTTP status " + xhr.status);
}
if (xhr.response.byteLength != length) {
_this._error("Unexpected length " +
xhr.response.byteLength +
" (expected " + length + ")");
}
_this._bytes.set(new _this._Uint8Array(xhr.response), offset);
}
if (callback) {
callback.apply(_this, [offset, length]);
}
}, false);
xhr.addEventListener("error", this._mkerr("Fetch failed"), false);
xhr.open("GET", this.op.source);
xhr.responseType = "arraybuffer";
if (offset != null && length != null) {
var end = offset + length;
xhr.setRequestHeader("Range", "bytes=" + offset + "-" + (end - 1));
if (this._isSafari) {
// Range request caching is broken in Safari
// https://bugs.webkit.org/show_bug.cgi?id=82672
xhr.setRequestHeader("Cache-control", "no-cache");
xhr.setRequestHeader("If-None-Match", Math.random().toString());
}
}
/*this._debugLog("Load: " + offset + " " + length);*/
xhr.send();
},
_startLoad: function () {
var _this = this;
if (!this.op.source) {
// Unpacked mode (individiual frame URLs) - just load the frames.
this._loadNextFrame();
return;
}
$.ajax({
url: this.op.source,
type: "HEAD"
}).done(function (data, status, xhr) {
if (_this._dead) {
return;
}
_this._pHead = 0;
_this._pNextHead = 0;
_this._pFetch = 0;
var len = parseInt(xhr.getResponseHeader("Content-Length"));
if (!len) {
_this._debugLog("HEAD request failed: invalid file length.");
_this._debugLog("Falling back to full file mode.");
_this._load(null, null, function (off, len) {
_this._pTail = 0;
_this._pHead = len;
_this._findCentralDirectory();
});
return;
}
_this._debugLog("Len: " + len);
_this._len = len;
_this._buf = new _this._ArrayBuffer(len);
_this._bytes = new _this._Uint8Array(_this._buf);
var off = len - _this._trailerBytes;
if (off < 0) {
off = 0;
}
_this._pTail = len;
_this._load(off, len - off, function (off, len) {
_this._pTail = off;
_this._findCentralDirectory();
});
}).fail(this._mkerr("Length fetch failed"));
},
_findCentralDirectory: function () {
// No support for ZIP file comment
var dv = new this._DataView(this._buf, this._len - 22, 22);
if (dv.getUint32(0, true) != 0x06054b50) {
this._error("End of Central Directory signature not found");
}
var cd_count = dv.getUint16(10, true);
var cd_size = dv.getUint32(12, true);
var cd_off = dv.getUint32(16, true);
if (cd_off < this._pTail) {
this._load(cd_off, this._pTail - cd_off, function () {
this._pTail = cd_off;
this._readCentralDirectory(cd_off, cd_size, cd_count);
});
} else {
this._readCentralDirectory(cd_off, cd_size, cd_count);
}
},
_readCentralDirectory: function (offset, size, count) {
var dv = new this._DataView(this._buf, offset, size);
var p = 0;
for (var i = 0; i < count; i++) {
if (dv.getUint32(p, true) != 0x02014b50) {
this._error("Invalid Central Directory signature");
}
var compMethod = dv.getUint16(p + 10, true);
var uncompSize = dv.getUint32(p + 24, true);
var nameLen = dv.getUint16(p + 28, true);
var extraLen = dv.getUint16(p + 30, true);
var cmtLen = dv.getUint16(p + 32, true);
var off = dv.getUint32(p + 42, true);
if (compMethod != 0) {
this._error("Unsupported compression method");
}
p += 46;
var nameView = new this._Uint8Array(this._buf, offset + p, nameLen);
var name = "";
for (var j = 0; j < nameLen; j++) {
name += String.fromCharCode(nameView[j]);
}
p += nameLen + extraLen + cmtLen;
/*this._debugLog("File: " + name + " (" + uncompSize +
" bytes @ " + off + ")");*/
this._files[name] = { off: off, len: uncompSize };
}
// Two outstanding fetches at any given time.
// Note: the implementation does not support more than two.
if (this._pHead >= this._pTail) {
this._pHead = this._len;
$(this).triggerHandler("loadProgress", [this._pHead / this._len]);
this._loadNextFrame();
} else {
this._loadNextChunk();
this._loadNextChunk();
}
},
_loadNextChunk: function () {
if (this._pFetch >= this._pTail) {
return;
}
var off = this._pFetch;
var len = this.op.chunkSize;
if (this._pFetch + len > this._pTail) {
len = this._pTail - this._pFetch;
}
this._pFetch += len;
this._load(off, len, function () {
if (off == this._pHead) {
if (this._pNextHead) {
this._pHead = this._pNextHead;
this._pNextHead = 0;
} else {
this._pHead = off + len;
}
if (this._pHead >= this._pTail) {
this._pHead = this._len;
}
/*this._debugLog("New pHead: " + this._pHead);*/
$(this).triggerHandler("loadProgress",
[this._pHead / this._len]);
if (!this._loadTimer) {
this._loadNextFrame();
}
} else {
this._pNextHead = off + len;
}
this._loadNextChunk();
});
},
_fileDataStart: function (offset) {
var dv = new DataView(this._buf, offset, 30);
var nameLen = dv.getUint16(26, true);
var extraLen = dv.getUint16(28, true);
return offset + 30 + nameLen + extraLen;
},
_isFileAvailable: function (name) {
var info = this._files[name];
if (!info) {
this._error("File " + name + " not found in ZIP");
}
if (this._pHead < (info.off + 30)) {
return false;
}
return this._pHead >= (this._fileDataStart(info.off) + info.len);
},
_loadNextFrame: function () {
if (this._dead) {
return;
}
var frame = this._loadFrame;
if (frame >= this._frameCount) {
return;
}
var meta = this.op.metadata.frames[frame];
if (!this.op.source) {
// Unpacked mode (individiual frame URLs)
this._loadFrame += 1;
this._loadImage(frame, meta.file, false);
return;
}
if (!this._isFileAvailable(meta.file)) {
return;
}
this._loadFrame += 1;
var off = this._fileDataStart(this._files[meta.file].off);
var end = off + this._files[meta.file].len;
var url;
var mime_type = this.op.metadata.mime_type || "image/png";
if (this._URL) {
var slice;
if (!this._buf.slice) {
slice = new this._ArrayBuffer(this._files[meta.file].len);
var view = new this._Uint8Array(slice);
view.set(this._bytes.subarray(off, end));
} else {
slice = this._buf.slice(off, end);
}
var blob;
try {
blob = new this._Blob([slice], { type: mime_type });
}
catch (err) {
this._debugLog("Blob constructor failed. Trying BlobBuilder..."
+ " (" + err.message + ")");
var bb = new this._BlobBuilder();
bb.append(slice);
blob = bb.getBlob();
}
/*_this._debugLog("Loading " + meta.file + " to frame " + frame);*/
url = this._URL.createObjectURL(blob);
this._loadImage(frame, url, true);
} else {
url = ("data:" + mime_type + ";base64,"
+ base64ArrayBuffer(this._buf, off, end - off));
this._loadImage(frame, url, false);
}
},
_loadImage: function (frame, url, isBlob) {
var _this = this;
var image = new Image();
var meta = this.op.metadata.frames[frame];
image.addEventListener('load', function () {
_this._debugLog("Loaded " + meta.file + " to frame " + frame);
if (isBlob) {
_this._URL.revokeObjectURL(url);
}
if (_this._dead) {
return;
}
_this._frameImages[frame] = image;
$(_this).triggerHandler("frameLoaded", frame);
if (_this._loadingState == 0) {
_this._displayFrame.apply(_this);
}
if (frame >= (_this._frameCount - 1)) {
_this._setLoadingState(2);
_this._buf = null;
_this._bytes = null;
} else {
if (!_this._maxLoadAhead ||
(frame - _this._frame) < _this._maxLoadAhead) {
_this._loadNextFrame();
} else if (!_this._loadTimer) {
_this._loadTimer = setTimeout(function () {
_this._loadTimer = null;
_this._loadNextFrame();
}, 200);
}
}
});
image.src = url;
},
_setLoadingState: function (state) {
if (this._loadingState != state) {
this._loadingState = state;
$(this).triggerHandler("loadingStateChanged", [state]);
}
},
_displayFrame: function () {
if (this._dead) {
return;
}
var _this = this;
var meta = this.op.metadata.frames[this._frame];
this._debugLog("Displaying frame: " + this._frame + " " + meta.file);
var image = this._frameImages[this._frame];
if (!image) {
this._debugLog("Image not available!");
this._setLoadingState(0);
return;
}
if (this._loadingState != 2) {
this._setLoadingState(1);
}
if (this.op.autosize) {
if (this._context.canvas.width != image.width || this._context.canvas.height != image.height) {
// make the canvas autosize itself according to the images drawn on it
// should set it once, since we don't have variable sized frames
this._context.canvas.width = image.width;
this._context.canvas.height = image.height;
}
};
this._context.clearRect(0, 0, this.op.canvas.width,
this.op.canvas.height);
this._context.drawImage(image, 0, 0);
$(this).triggerHandler("frame", this._frame);
if (!this._paused) {
this._timer = setTimeout(function () {
_this._timer = null;
_this._nextFrame.apply(_this);
}, meta.delay);
}
},
_nextFrame: function (frame) {
if (this._frame >= (this._frameCount - 1)) {
if (this.op.loop) {
this._frame = 0;
} else {
this.pause();
return;
}
} else {
this._frame += 1;
}
this._displayFrame();
},
play: function () {
if (this._dead) {
return;
}
if (this._paused) {
$(this).triggerHandler("play", [this._frame]);
this._paused = false;
this._displayFrame();
}
},
pause: function () {
if (this._dead) {
return;
}
if (!this._paused) {
if (this._timer) {
clearTimeout(this._timer);
}
this._paused = true;
$(this).triggerHandler("pause", [this._frame]);
}
},
rewind: function () {
if (this._dead) {
return;
}
this._frame = 0;
if (this._timer) {
clearTimeout(this._timer);
}
this._displayFrame();
},
stop: function () {
this._debugLog("Stopped!");
this._dead = true;
if (this._timer) {
clearTimeout(this._timer);
}
if (this._loadTimer) {
clearTimeout(this._loadTimer);
}
this._frameImages = null;
this._buf = null;
this._bytes = null;
$(this).triggerHandler("stop");
},
getCurrentFrame: function () {
return this._frame;
},
getLoadedFrames: function () {
return this._frameImages.length;
},
getFrameCount: function () {
return this._frameCount;
},
hasError: function () {
return this._failed;
}
}
// https://greasyfork.org/zh-CN/scripts/417760-checkjquery
var checkJQuery = function () {
let jqueryCdns = [
'http://code.jquery.com/jquery-2.1.4.min.js',
'https://ajax.aspnetcdn.com/ajax/jquery/jquery-2.1.4.min.js',
'https://ajax.googleapis.com/ajax/libs/jquery/2.1.4/jquery.min.js',
'https://cdn.staticfile.org/jquery/2.1.4/jquery.min.js',
'https://apps.bdimg.com/libs/jquery/2.1.4/jquery.min.js',
];
function isJQueryValid() {
try {
let wd = unsafeWindow;
if (wd.jQuery && !wd.$) {
wd.$ = wd.jQuery;
}
$();
return true;
} catch (exception) {
return false;
}
}
function insertJQuery(url) {
let script = document.createElement('script');
script.src = url;
document.head.appendChild(script);
return script;
}
function converProtocolIfNeeded(url) {
let isHttps = location.href.indexOf('https://') != -1;
let urlIsHttps = url.indexOf('https://') != -1;
if (isHttps && !urlIsHttps) {
return url.replace('http://', 'https://');
} else if (!isHttps && urlIsHttps) {
return url.replace('https://', 'http://');
}
return url;
}
function waitAndCheckJQuery(cdnIndex, resolve) {
if (cdnIndex >= jqueryCdns.length) {
iLog.e('无法加载 JQuery,正在退出。');
resolve(false);
return;
}
let url = converProtocolIfNeeded(jqueryCdns[cdnIndex]);
iLog.i('尝试第 ' + (cdnIndex + 1) + ' 个 JQuery CDN:' + url + '。');
let script = insertJQuery(url);
setTimeout(function () {
if (isJQueryValid()) {
iLog.i('已加载 JQuery。');
resolve(true);
} else {
iLog.w('无法访问。');
script.remove();
waitAndCheckJQuery(cdnIndex + 1, resolve);
}
}, 100);
}
return new Promise(function (resolve) {
if (isJQueryValid()) {
iLog.i('已加载 jQuery。');
resolve(true);
} else {
iLog.i('未发现 JQuery,尝试加载。');
waitAndCheckJQuery(0, resolve);
}
});
}
let Lang = {
// 自动选择
auto: -1,
// 中文-中国大陆
zh_CN: 0,
// 英语-美国
en_US: 1,
// 俄语-俄罗斯
ru_RU: 2,
// 日本語-日本
ja_JP: 3,
};
let Texts = {};
Texts[Lang.zh_CN] = {
// 安装或更新后弹出的提示
install_title: '欢迎使用 PixivPreviewer',
install_body: '<div style="position: absolute;left: 50%;top: 30%;font-size: 20px; color: white;transform:translate(-50%,0);"><p style="text-indent: 2em;">欢迎反馈问题和提出建议! ☞<a style="color: green;" href="https://greasyfork.org/zh-CN/scripts/30766-pixiv-previewer/feedback" target="_blank">反馈页面</a></p><br><p style="text-indent: 2em;">如果您是第一次使用,推荐到 ☞<a style="color: green;" href="https://greasyfork.org/zh-CN/scripts/30766-pixiv-previewer" target="_blank">详情页</a> 查看脚本介绍。</p></div>',
upgrade_body: '<h3>新的设置菜单!</h3>  <p style="text-indent: 2em;">感谢各位使用 Pixiv Previewer,本次更新调整了设置菜单的视觉效果,欢迎反馈问题和提出建议! ☞<a style="color: green;" href="https://greasyfork.org/zh-CN/scripts/30766-pixiv-previewer/feedback" target="_blank">反馈页面</a></p>',
// 设置项
setting_settingSection: '设置',
setting_language: '语言',
setting_preview: '预览',
setting_animePreview: '动图预览',
setting_sortSection: '排序',
setting_sort: '排序(仅搜索页生效)',
setting_anime: '动图下载(动图预览及详情页生效)',
setting_origin: '预览时优先显示原图(慢)',
setting_previewDelay: '延迟显示预览图(毫秒)',
setting_previewByKey: '使用按键控制预览图展示(Ctrl)',
setting_previewByKeyHelp: '开启后鼠标移动到图片上不再展示预览图,按下Ctrl键才展示,同时“延迟显示预览”设置项不生效。',
setting_maxPage: '每次排序时统计的最大页数',
setting_hideWork: '隐藏收藏数少于设定值的作品',
setting_hideAiWork: '隐藏 AI 生成作品',
setting_onlyAiWork: '只显示 AI 生成作品',
setting_hideFav: '排序时隐藏已收藏的作品',
setting_hideFollowed: '排序时隐藏已关注画师作品',
setting_hideByTag: '排序时隐藏指定标签的作品',
setting_hideByTagPlaceholder: '输入标签名,如 "tag1|tag2",支持正则',
setting_hideByUser: '排序时隐藏指定用户的作品',
setting_hideByUserPlaceholder: '输入用户ID,如 "12345|67890"',
setting_clearFollowingCache: '清除缓存',
setting_clearFollowingCacheHelp: '关注画师信息会在本地保存一天,如果希望立即更新,请点击清除缓存',
setting_followingCacheCleared: '已清除缓存,请刷新页面。',
setting_blank: '使用新标签页打开作品详情页',
setting_turnPage: '使用键盘←→进行翻页(排序后的搜索页)',
setting_save: '保存设置',
setting_reset: '重置脚本',
setting_resetHint: '这会删除所有设置,相当于重新安装脚本,确定要重置吗?',
setting_novelSort: '小说排序',
setting_novelMaxPage: '小说排序时统计的最大页数',
setting_novelHideWork: '隐藏收藏数少于设定值的作品',
setting_novelHideFav: '排序时隐藏已收藏的作品',
setting_previewFullScreen: '全屏预览',
setting_scrollLockWhenPreview: '预览时阻止页面滚动',
setting_logLevel: '日志等级',
setting_novelSection: '小说排序',
setting_close: '关闭',
setting_maxXhr: '收藏数并发(推荐 64)',
setting_hideByCountLessThan: '隐藏图片张数少于设定值的作品',
setting_hideByCountMoreThan: '隐藏图片张数多于设定值的作品',
// 搜索时过滤值太高
sort_noWork: '没有可以显示的作品(隐藏了 %1 个作品)',
sort_getWorks: '正在获取第%1/%2页作品',
sort_getBookmarkCount: '获取收藏数:%1/%2',
sort_getPublicFollowing: '获取公开关注画师',
sort_getPrivateFollowing: '获取私有关注画师',
sort_filtering: '过滤%1收藏量低于%2的作品',
sort_filteringHideFavorite: '已收藏和',
sort_fullSizeThumb: '全尺寸缩略图(搜索页、用户页)',
sort_sortByBookmark: '按❤️排序',
sort_sortByLike: '按👍排序',
sort_sortByView: '按👀排序',
// 小说排序
nsort_getWorks: '正在获取第1%/2%页作品',
nsort_sorting: '正在按收藏量排序',
nsort_hideFav: '排序时隐藏已收藏的作品',
nsort_hideFollowed: '排序时隐藏已关注作者作品',
text_sort: '排序'
};
// translate by google
Texts[Lang.en_US] = {
install_title: 'Welcome to PixivPreviewer',
install_body: '<div style="position: absolute;left: 50%;top: 30%;font-size: 20px; color: white;transform:translate(-50%,0);"><p style="text-indent: 2em;">Feedback questions and suggestions are welcome! ☞<a style="color: green;" href="https://greasyfork.org/zh-CN/scripts/30766-pixiv-previewer/feedback" target="_blank">Feedback Page</a></p><br><p style="text-indent: 2em;">If you are using it for the first time, it is recommended to go to the ☞<a style="color: green;" href="https://greasyfork.org/zh-CN/scripts/30766-pixiv-previewer" target="_blank">Details Page</a> to see the script introduction.</p></div>',
upgrade_body: '<h3>New settings menu!</h3>  <p style="text-indent: 2em;">Thanks to all Pixiv Previewer users, this update adjusts the visual effect of the settings menu, and feedback questions and suggestions are welcome! ☞<a style="color: green;" href="https://greasyfork.org/zh-CN/scripts/30766-pixiv-previewer/feedback" target="_blank">Feedback Page</a></p>',
setting_settingSection: 'Settings',
setting_language: 'Language',
setting_preview: 'Preview',
setting_animePreview: 'Animation preview',
setting_sortSection: 'Sorting',
setting_sort: 'Sorting (Search page)',
setting_anime: 'Animation download (Preview and Artwork page)',
setting_origin: 'Display original image when preview (slow)',
setting_previewDelay: 'Delay of display preview image(Million seconds)',
setting_previewByKey: 'Use keys to control the preview image display (Ctrl)',
setting_previewByKeyHelp: 'After enabling it, move the mouse to the picture and no longer display the preview image. Press the Ctrl key to display it, and the "Delayed Display Preview" setting item does not take effect.',
setting_maxPage: 'Maximum number of pages counted per sort',
setting_hideWork: 'Hide works with bookmark count less than set value',
setting_hideAiWork: 'Hide AI works',
setting_onlyAiWork: 'Show only AI-generated works',
setting_hideFav: 'Hide favorites when sorting',
setting_hideFollowed: 'Hide artworks of followed artists when sorting',
setting_hideByTag: 'Hide artworks by tag',
setting_hideByTagPlaceholder: 'Input tag name, e.g. "tag1|tag2", regular expressions supported',
setting_hideByUser: 'Hide artworks by user',
setting_hideByUserPlaceholder: 'Input user ID, e.g. "12345|67890"',
setting_clearFollowingCache: 'Clear Cache',
setting_clearFollowingCacheHelp: 'The folloing artists info. will be saved locally for one day, if you want to update immediately, please click this to clear cache',
setting_followingCacheCleared: 'Success, please refresh the page.',
setting_blank: 'Open works\' details page in new tab',
setting_turnPage: 'Use ← → to turn pages (Search page)',
setting_save: 'Save',
setting_reset: 'Reset',
setting_resetHint: 'This will delete all settings and set it to default. Are you sure?',
setting_novelSort: 'Sorting (Novel)',
setting_novelMaxPage: 'Maximum number of pages counted for novel sorting',
setting_novelHideWork: 'Hide works with bookmark count less than set value',
setting_novelHideFav: 'Hide favorites when sorting',
setting_previewFullScreen: 'Full screen preview',
setting_scrollLockWhenPreview: 'Prevent page scrolling during preview',
setting_logLevel: 'Log Level',
setting_novelSection: 'Novel Sorting',
setting_close: 'Close',
setting_maxXhr: 'Bookmark count concurrency (recommended 64)',
setting_hideByCountLessThan: 'Hide works with image count less than set value',
setting_hideByCountMoreThan: 'Hide works with image count more than set value',
sort_noWork: 'No works to display (%1 works hideen)',
sort_getWorks: 'Getting artworks of page: %1 of %2',
sort_getBookmarkCount: 'Getting bookmark count of artworks:%1 of %2',
sort_getPublicFollowing: 'Getting public following list',
sort_getPrivateFollowing: 'Getting private following list',
sort_filtering: 'Filtering%1works with bookmark count less than %2',
sort_filteringHideFavorite: ' favorited works and ',
sort_fullSizeThumb: 'Display not cropped images.(Search page and User page only.)',
sort_sortByBookmark: 'Sort by ❤️',
sort_sortByLike: 'Sort by 👍',
sort_sortByView: 'Sort by 👀',
nsort_getWorks: 'Getting novels of page: 1% of 2%',
nsort_sorting: 'Sorting by bookmark cound',
nsort_hideFav: 'Hide favorites when sorting',
nsort_hideFollowed: 'Hide artworks of followed authors when sorting',
text_sort: 'sort',
};
// RU: перевод от vanja-san
Texts[Lang.ru_RU] = {
install_title: 'Добро пожаловать в PixivPreviewer',
install_body: '<div style="position: absolute;left: 50%;top: 30%;font-size: 20px; color: white;transform:translate(-50%,0);"><p style="text-indent: 2em;">Вопросы и предложения приветствуются! ☞<a style="color: green;" href="https://greasyfork.org/zh-CN/scripts/30766-pixiv-previewer/feedback" target="_blank">Страница обратной связи</a></p><br><p style="text-indent: 2em;">Если вы используете это впервые, рекомендуется перейти к ☞<a style="color: green;" href="https://greasyfork.org/zh-CN/scripts/30766-pixiv-previewer" target="_blank">Странице подробностей</a>, чтобы посмотреть введение в скрипт.</p></div>',
upgrade_body: '<h3>Новое меню настроек!</h3>  <p style="text-indent: 2em;">Спасибо всем пользователям Pixiv Previewer, это обновление изменило визуальный эффект меню настроек, вопросы и предложения приветствуются! ☞<a style="color: green;" href="https://greasyfork.org/zh-CN/scripts/30766-pixiv-previewer/feedback" target="_blank">Страница обратной связи</a></p>',
setting_settingSection: 'Настройки',
setting_language: 'Язык',
setting_preview: 'Предпросмотр',
setting_animePreview: 'Анимация предпросмотра',
setting_sortSection: 'Сортировка',
setting_sort: 'Сортировка (Страница поиска)',
setting_anime: 'Анимация скачивания (Страницы предпросмотра и Artwork)',
setting_origin: 'При предпросмотре, показывать изображения с оригинальным качеством (медленно)',
setting_previewDelay: 'Задержка отображения предпросмотра изображения (Миллион секунд)',
setting_previewByKey: 'Использовать клавиши для управления отображением предпросмотра изображения (Ctrl)',
setting_previewByKeyHelp: 'После включения, перемещение мыши к изображению больше не отображает предпросмотр изображения. Нажмите клавишу Ctrl, чтобы отобразить его, и параметр "Задержка отображения предпросмотра" не будет действовать.',
setting_maxPage: 'Максимальное количество страниц, подсчитанных за сортировку',
setting_hideWork: 'Скрыть работы с количеством закладок меньше установленного значения',
setting_hideAiWork: 'Скрыть работы, созданные ИИ',
setting_onlyAiWork: 'Показывать только работы, созданные ИИ',
setting_hideFav: 'При сортировке, скрыть избранное',
setting_hideFollowed: 'При сортировке, скрыть работы художников на которых подписаны',
setting_hideByTag: 'При сортировке, скрыть работы с указанным тегом',
setting_hideByTagPlaceholder: 'Введите имя тега, например "tag1|tag2", поддерживается регулярное выражение',
setting_hideByUser: 'При сортировке, скрыть работы от указанного пользователя',
setting_hideByUserPlaceholder: 'Введите ID пользователя, например "12345|67890"',
setting_clearFollowingCache: 'Очистить кэш',
setting_clearFollowingCacheHelp: 'Следующая информация о художниках будет сохранена локально в течение одного дня, если вы хотите обновить её немедленно, нажмите на эту кнопку, чтобы очистить кэш',
setting_followingCacheCleared: 'Готово, обновите страницу.',
setting_blank: 'Открывать страницу с описанием работы на новой вкладке',
setting_turnPage: 'Использовать ← → для перелистывания страниц (Страница поиска)',
setting_save: 'Сохранить',
setting_reset: 'Сбросить',
setting_resetHint: 'Это удалит все настройки и установит их по умолчанию. Продолжить?',
setting_novelSort: 'Сортировка (Роман)',
setting_novelMaxPage: 'Максимальное количество страниц, подсчитанных за сортировку романа',
setting_novelHideWork: 'Скрыть работы с количеством закладок меньше установленного значения',
setting_novelHideFav: 'При сортировке, скрыть избранное',
setting_previewFullScreen: 'Предпросмотр в полноэкранном режиме',
setting_scrollLockWhenPreview: 'Блокировать прокрутку страницы при предпросмотре',
setting_novelSection: 'Сортировка (Роман)',
setting_close: 'Закрыть',
setting_maxXhr: 'Количество закладок (рекомендуется 64)',
setting_hideByCountLessThan: 'Скрыть работы с количеством изображений меньше установленного значения',
setting_hideByCountMoreThan: 'Скрыть работы с количеством изображений больше установленного значения',
sort_noWork: 'Нет работ для отображения (%1 works hidden)',
sort_getWorks: 'Получение иллюстраций страницы: %1 из %2',
sort_getBookmarkCount: 'Получение количества закладок artworks:%1 из %2',
sort_getPublicFollowing: 'Получение публичного списка подписок',
sort_getPrivateFollowing: 'Получение приватного списка подписок',
sort_filtering: 'Фильтрация %1 работ с количеством закладок меньше чем %2',
sort_filteringHideFavorite: ' избранные работы и ',
sort_fullSizeThumb: 'Показать неотредактированное изображение (Страницы поиска и Artwork)',
sort_sortByBookmark: 'Сортировать по ❤️',
sort_sortByLike: 'Сортировать по 👍',
sort_sortByView: 'Сортировать по 👀',
nsort_getWorks: 'Получение романов страницы: 1% из 2%',
nsort_sorting: 'Сортировка по количеству закладок',
nsort_hideFav: 'При сортировке, скрыть избранное',
nsort_hideFollowed: 'При сортировке, скрыть работы художников на которых подписаны',
text_sort: 'Сортировать'
};
Texts[Lang.ja_JP] = {
install_title: 'Welcome to PixivPreviewer',
install_body: '<div style="position: absolute;left: 50%;top: 30%;font-size: 20px; color: white;transform:translate(-50%,0);"><p style="text-indent: 2em;">ご意見や提案は大歓迎です! ☞<a style="color: green;" href="https://greasyfork.org/ja/scripts/30766-pixiv-previewer/feedback" target="_blank">フィードバックページ</a></p><br><p style="text-indent: 2em;">初めて使う場合は、☞<a style="color: green;" href="https://greasyfork.org/ja/scripts/30766-pixiv-previewer" target="_blank">詳細ページ</a> でスクリプトの紹介を見ることをお勧めします。</p></div>',
upgrade_body: '<h3>新しい設定メニュー!</h3>  <p style="text-indent: 2em;">Pixiv Previewerをご利用いただきありがとうございます。このアップデートでは、設定メニューのビジュアルエフェクトが調整されました。問題や提案をお待ちしております! ☞<a style="color: green;" href="https://greasyfork.org/ja/scripts/30766-pixiv-previewer/feedback" target="_blank">フィードバックページ</a></p>',
setting_settingSection: '設定',
setting_language: '言語',
setting_preview: 'プレビュー機能',
setting_animePreview: 'うごイラプレビュー',
setting_sortSection: 'ソート',
setting_sort: 'ソート',
setting_anime: 'うごイラダウンロード',
setting_origin: '最大サイズの画像を表示する(遅くなる可能性がある)',
setting_previewDelay: 'カーソルを重ねてからプレビューするまでの遅延(ミリ秒)',
setting_previewByKey: 'キーでプレビュー画像の表示を制御する (Ctrl)',
setting_previewByKeyHelp: 'これを有効にすると、画像にマウスを移動してもプレビュー画像が表示されなくなります。Ctrlキーを押すと表示され、 \"遅延表示プレビュー\" の設定項目は無効になります。',
setting_maxPage: 'ソートするときに取得する最大ページ数',
setting_hideWork: '一定以下のブクマーク数の作品を非表示にする',
setting_hideAiWork: 'AIの作品を非表示にする',
setting_onlyAiWork: 'AI生成作品のみ表示',
setting_hideFav: 'ブックマーク数をソート時に非表示にする',
setting_hideFollowed: 'ソート時にフォローしているアーティストの作品を非表示',
setting_hideByTag: 'ソート時に指定したタグの作品を非表示',
setting_hideByTagPlaceholder: 'タグ名を入力してください(例:"tag1|tag2"、正規表現対応)',
setting_hideByUser: 'ソート時に指定したユーザーの作品を非表示',
setting_hideByUserPlaceholder: 'ユーザーIDを入力してください(例:"12345|67890")',
setting_clearFollowingCache: 'キャッシュをクリア',
setting_clearFollowingCacheHelp: 'フォローしているアーティストの情報がローカルに1日保存されます。すぐに更新したい場合は、このキャッシュをクリアしてください。',
setting_followingCacheCleared: '成功しました。ページを更新してください。',
setting_blank: '作品の詳細ページを新しいタブで開く',
setting_turnPage: '← → を使用してページをめくる(検索ページ)',
setting_save: 'Save',
setting_reset: 'Reset',
setting_resetHint: 'これにより、すべての設定が削除され、デフォルトに設定されます。よろしいですか?',
setting_novelSort: 'ソート(小説)',
setting_novelMaxPage: '小説のソートのページ数の最大値',
setting_novelHideWork: '設定値未満のブックマーク数の作品を非表示',
setting_novelHideFav: 'ソート時にお気に入りを非表示',
setting_previewFullScreen: '全画面プレビュー',
setting_scrollLockWhenPreview: 'プレビュー時にページのスクロールをロックする',
setting_novelSection: 'ソート(小説)',
setting_close: '閉じる',
setting_maxXhr: 'ブックマーク数の同時リクエスト数(推奨64)',
setting_hideByCountLessThan: '画像数が設定値未満の作品を非表示',
setting_hideByCountMoreThan: '画像数が設定値を超える作品を非表示',
sort_noWork: '表示する作品がありません(%1 作品が非表示)',
sort_getWorks: 'ページの作品を取得中:%1 / %2',
sort_getBookmarkCount: '作品のブックマーク数を取得中:%1 / %2',
sort_getPublicFollowing: '公開フォロー一覧を取得中',
sort_getPrivateFollowing: '非公開フォロー一覧を取得中',
sort_filtering: 'ブックマーク数が%2未満の作品%1件をフィルタリング',
sort_filteringHideFavorite: ' お気に入り登録済みの作品および ',
sort_fullSizeThumb: 'トリミングされていない画像を表示(検索ページおよびユーザーページのみ)。',
sort_sortByBookmark: '❤️ でソート',
sort_sortByLike: '👍 でソート',
sort_sortByView: '👀 でソート',
nsort_getWorks: '小説のページを取得中:1% / 2%',
nsort_sorting: 'ブックマーク数で並べ替え',
nsort_hideFav: 'ソート時にお気に入りを非表示',
nsort_hideFollowed: 'ソート時にフォロー済み作者の作品を非表示',
text_sort: 'ソート'
};
// 语言
let g_language = Lang.auto;
// 版本号,第三位不需要跟脚本的版本号对上,第三位更新只有需要弹更新提示的时候才需要更新这里
let g_version = '3.7.37';
// 添加收藏需要这个
let g_csrfToken = '';
// 打的日志数量,超过一定数值清空控制台
let g_logCount = 0;
// 当前页面类型
let g_pageType = -1;
// 图片详情页的链接,使用时替换 #id#
let g_artworkUrl = '/artworks/#id#';
// 获取图片链接的链接
let g_getArtworkUrl = '/ajax/illust/#id#/pages';
// 获取动图下载链接的链接
let g_getUgoiraUrl = '/ajax/illust/#id#/ugoira_meta';
// 获取小说列表的链接
let g_getNovelUrl = '/ajax/search/novels/#key#?word=#key#&p=#page#'
// 鼠标位置
let g_mousePos = { x: 0, y: 0 };
// 加载中图片
let g_loadingImage = 'https://pp-1252089172.cos.ap-chengdu.myqcloud.com/loading.gif';
// 页面打开时的 url
let initialUrl = location.href;
// 设置
let g_settings;
// 排序时同时请求收藏量的 Request 数量,没必要太多,并不会加快速度
let g_maxXhr = 64;
// 排序是否完成(如果排序时页面出现了非刷新切换,强制刷新)
let g_sortComplete = true;
// 页面相关的一些预定义,包括处理页面元素等
let PageType = {
// 搜索(不包含小说搜索)
Search: 0,
// 关注的新作品
BookMarkNew: 1,
// 发现
Discovery: 2,
// 用户主页
Member: 3,
// 首页
Home: 4,
// 排行榜
Ranking: 5,
// 大家的新作品
NewIllust: 6,
// R18
R18: 7,
// 自己的收藏页
BookMark: 8,
// 动态
Stacc: 9,
// 作品详情页(处理动图预览及下载)
Artwork: 10,
// 小说页
NovelSearch: 11,
// 搜索顶部 tab
SearchTop: 12,
// 总数
PageTypeCount: 13,
};
let Pages = {};