forked from Ahaochan/Tampermonkey
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Pixiv 增强.user.js
1414 lines (1329 loc) · 69.3 KB
/
Pixiv 增强.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
// ==UserScript==
// @name Pixiv Plus
// @name:zh-CN Pixiv 增强
// @name:zh-TW Pixiv 增強
// @namespace https://github.com/Ahaochan/Tampermonkey
// @version 0.8.6
// @icon https://www.pixiv.net/favicon.ico
// @description Focus on immersive experience, 1. Block ads, directly access popular pictures 2. Use user to enter the way to search 3. Search pid and uid 4. Display original image and size, picture rename, download original image | gif map | Zip|multiple map zip 5. display artist id, artist background image 6. auto load comment 7. dynamic markup work type 8. remove redirection 9. single page sort 10. control panel select desired function github: https:/ /github.com/Ahaochan/Tampermonkey, welcome to star and fork.
// @description:ja 没入型体験に焦点を当てる、1.人気の写真に直接アクセスする広告をブロックする2.検索する方法を入力するためにユーザーを使用する3.検索pidとuid 4.元の画像とサイズを表示する Zip | multiple map zip 5.アーティストID、アーティストの背景画像を表示します。6.自動ロードコメントを追加します。7.動的マークアップ作業タイプを指定します。8.リダイレクトを削除します。9.シングルページソート10.コントロールパネルを選択します。github:https:/ /github.com/Ahaochan/Tampermonkey、スターとフォークへようこそ。
// @description:zh-CN 专注沉浸式体验,1.屏蔽广告,直接访问热门图片 2.使用users入り的方式搜索 3.搜索pid和uid 4.显示原图及尺寸,图片重命名,下载原图|gif图|动图帧zip|多图zip 5.显示画师id、画师背景图 6.自动加载评论 7.对动态标记作品类型 8.去除重定向 9.单页排序 10.控制面板选择想要的功能 github:https://github.com/Ahaochan/Tampermonkey,欢迎star和fork。
// @description:zh-TW 專注沉浸式體驗,1.屏蔽廣告,直接訪問熱門圖片2.使用users入り的方式搜索3.搜索pid和uid 4.顯示原圖及尺寸,圖片重命名,下載原圖|gif圖|動圖幀zip|多圖zip 5.顯示畫師id、畫師背景圖6.自動加載評論7.對動態標記作品類型8.去除重定向9.單頁排序10.控制面板選擇想要的功能github:https:/ /github.com/Ahaochan/Tampermonkey,歡迎star和fork。
// @author Ahaochan
// @include http*://www.pixiv.net*
// @match http://www.pixiv.net/
// @connect i.pximg.net
// @connect i-f.pximg.net
// @connect i-cf.pximg.net
// @license GPL-3.0
// @supportURL https://github.com/Ahaochan/Tampermonkey
// @grant unsafeWindow
// @grant GM.xmlHttpRequest
// @grant GM.setClipboard
// @grant GM.setValue
// @grant GM.getValue
// @grant GM_addStyle
// @grant GM_xmlhttpRequest
// @grant GM_registerMenuCommand
// @grant GM_unregisterMenuCommand
// @grant GM_setClipboard
// @grant GM_setValue
// @grant GM_getValue
// @require https://cdn.bootcdn.net/ajax/libs/jquery/2.2.4/jquery.min.js
// @require https://cdn.bootcss.com/jszip/3.1.4/jszip.min.js
// @require https://cdn.bootcss.com/FileSaver.js/1.3.2/FileSaver.min.js
// @require https://greasyfork.org/scripts/2963-gif-js/code/gifjs.js?version=8596
// @require https://greasyfork.org/scripts/375359-gm4-polyfill-1-0-1/code/gm4-polyfill-101.js?version=652238
// @run-at document-end
// @noframes
// ==/UserScript==
jQuery($ => {
'use strict';
// 加载依赖
// ============================ jQuery插件 ====================================
$.fn.extend({
fitWindow () {
this.css('width', 'auto').css('height', 'auto')
.css('max-width', '').css('max-height', $(window).height());
},
replaceTagName (replaceWith) {
const tags = [];
let i = this.length;
while (i--) {
const newElement = document.createElement(replaceWith);
const thisi = this[i];
const thisia = thisi.attributes;
for (let a = thisia.length - 1; a >= 0; a--) {
const attrib = thisia[a];
newElement.setAttribute(attrib.name, attrib.value);
}
newElement.innerHTML = thisi.innerHTML;
$(thisi).after(newElement).remove();
tags[i] = newElement;
}
return $(tags);
},
getBackgroundUrl () {
const imgUrls = [];
this.each(function (index, { style }) {
let bgUrl = $(this).css('background-image') || style.backgroundImage || 'url("")';
const matchArr = bgUrl.match(/url\((['"])(.*?)\1\)/);
bgUrl = matchArr && matchArr.length >= 2 ? matchArr[2] : '';
imgUrls.push(bgUrl);
});
return imgUrls.length === 1 ? imgUrls[0] : imgUrls;
}
});
// ============================ 全局参数 ====================================
const debug = true;
const [log, error] = [debug ? console.log : () => { }, console.error];
let globalData;
let preloadData;
const initData = () => {
$.ajax({
url: location.href, async: false,
success: response => {
const html = document.createElement('html');
html.innerHTML = response;
globalData = JSON.parse($(html).find('meta[name="global-data"]').attr('content') || '{}');
preloadData = JSON.parse($(html).find('meta[name="preload-data"]').attr('content') || '{}');
}
});
};
const getPreloadData = () => {
if (!preloadData) { initData(); }
return preloadData;
};
const getGlobalData = () => {
if (!globalData) { initData(); }
return globalData;
};
const lang = (document.documentElement.getAttribute('lang') || 'en').toLowerCase();
let illustJson = {};
const illust = () => {
// 1. 判断是否已有作品id(兼容按左右方向键翻页的情况)
const preIllustId = $('body').attr('ahao_illust_id');
const paramRegex = location.href.match(/artworks\/(\d*)$/);
const urlIllustId = !!paramRegex && paramRegex.length > 0 ? paramRegex[1] : '';
// 2. 如果illust_id没变, 则不更新json
if (parseInt(preIllustId) === parseInt(urlIllustId)) {
return illustJson;
}
// 3. 如果illust_id变化, 则持久化illust_id, 且同步更新json
if (!!urlIllustId) {
$('body').attr('ahao_illust_id', urlIllustId);
$.ajax({
url: `/ajax/illust/${urlIllustId}`,
dataType: 'json',
async: false,
success: ({ body }) => illustJson = body
});
}
return illustJson;
};
const getUid = () => {
if (!preloadData || !preloadData.user || !Object.keys(preloadData.user)[0]) {
initData();
}
return preloadData && preloadData.user && Object.keys(preloadData.user)[0];
};
const observerFactory = function (option) {
let options;
if (typeof option === 'function') {
options = {
callback: option,
node: document.getElementsByTagName('body')[0],
option: { childList: true, subtree: true }
};
} else {
options = $.extend({
callback: () => { },
node: document.getElementsByTagName('body')[0],
option: { childList: true, subtree: true }
}, option);
}
const MutationObserver = window.MutationObserver || window.WebKitMutationObserver || window.MozMutationObserver;
const observer = new MutationObserver((mutations, observer) => {
options.callback.call(this, mutations, observer);
// GM.getValue('MO', true).then(function (v) { if(!v) observer.disconnect(); });
});
observer.observe(options.node, options.option);
return observer;
};
const isLogin = () => {
let status = 0;
$.ajax({ url: 'https://www.pixiv.net/setting_user.php', async: false })
.done((data, statusText, xhr) => status = xhr.status);
return status === 200;
};
// ============================ 配置信息 ====================================
const GMkeys = {
MO: 'MO', // MutationObserver 的开关
selectorShareBtn: 'selectorShareBtn', // 下载按钮的selector
selectorRightColumn: 'selectorRightColumn', // 作品页面的作者信息selector
switchImgSize: 'switch-img-size', // 是否显示图片大小的开关
switchImgPreload: 'switch-img-preload', // 是否预下载的开关
switchComment: 'switch-comment', // 是否自动加载评论的开关
switchImgMulti: 'switchImgMulti', // 是否自动加载多图的开关
switchOrderByPopular: 'switch-order-by-popular',// 是否按收藏数排序的开关(单页排序)
downloadName: 'download-name', // 下载名pattern
};
// ============================ i18n 国际化 ===============================
const i18nLib = {
ja: {
settings: '設定',
load_origin: 'load_origin',
ad_disable: 'ad_disable',
download_enable: 'download_enable',
search_enhance_UID: 'search_enhance(UID)',
search_enhance_PID: 'search_enhance(PID)',
search_enhance_Author: 'search_enhance(Author)',
artist_info: 'artist_info',
comment_load: 'comment_load',
artwork_tag: 'artwork_tag',
redirect_cancel: 'redirect_cancel',
watchlist: 'ウォッチリストに追加',
favorites: 'users入り',
author: '創作家',
},
en: {
settings: 'Settings',
load_origin: 'load_origin',
ad_disable: 'ad_disable',
download_enable: 'download_enable',
search_enhance_UID: 'search_enhance(UID)',
search_enhance_PID: 'search_enhance(PID)',
search_enhance_Author: 'search_enhance(Author)',
artist_info: 'artist_info',
comment_load: 'comment_load',
artwork_tag: 'artwork_tag',
redirect_cancel: 'redirect_cancel',
watchlist: 'Add to Watchlist',
favorites: 'favorites',
author: 'Author',
illegal: 'illegal',
download: 'download',
download_wait: 'please wait download completed',
copy_to_clipboard: 'copy to Clipboard',
background: 'background',
background_not_found: 'no-background',
loginWarning: 'Pixiv Plus Script Warning! Please login to Pixiv for a better experience! Failure to login may result in unpredictable bugs!',
illust_type_single: '[single pic]',
illust_type_multiple: '[multiple pic]',
illust_type_gif: '[gif pic]',
sort_by_popularity: 'Sort_by_popularity(single page)'
},
ko: {},
zh: {
settings: '设置',
load_origin: '加载原图',
ad_disable: '屏蔽广告',
download_enable: '开启下载',
search_enhance_UID: '搜索增强(UID)',
search_enhance_PID: '搜索增强(PID)',
search_enhance_Author: '搜索增强(作者)',
artist_info: '显示作者信息',
comment_load: '加载评论',
artwork_tag: '作品标记',
redirect_cancel: '取消重定向',
watchlist: '加入追更列表',
favorites: '收藏人数',
author: '作者',
illegal: '不合法',
download: '下载',
download_wait: '请等待下载完成',
copy_to_clipboard: '已复制到剪贴板',
background: '背景图',
background_not_found: '无背景图',
loginWarning: 'Pixiv增强 脚本警告! 请登录Pixiv获得更好的体验! 未登录可能产生不可预料的bug!',
illust_type_single: '[单图]',
illust_type_multiple: '[多图]',
illust_type_gif: '[gif图]',
sort_by_popularity: '按收藏数搜索(单页)'
},
'zh-cn': {},
'zh-tw': {
settings: '設置',
load_origin: '加載原圖',
ad_disable: '屏蔽廣告',
download_enable: '開啟下載',
search_enhance_UID: '搜索增強(UID)',
search_enhance_PID: '搜索增強(PID)',
search_enhance_Author: '搜索增強(作者)',
artist_info: '顯示作者信息',
comment_load: '加載評論',
artwork_tag: '作品標記',
redirect_cancel: '取消重定向',
watchlist: '加入追蹤列表',
favorites: '收藏人數',
author: '作者',
illegal: '不合法',
download: '下載',
download_wait: '請等待下載完成',
copy_to_clipboard: '已復製到剪貼板',
background: '背景圖',
background_not_found: '無背景圖',
loginWarning: 'Pixiv增強 腳本警告! 請登錄Pixiv獲得更好的體驗! 未登錄可能產生不可預料的bug!',
illust_type_single: '[單圖]',
illust_type_multiple: '[多圖]',
illust_type_gif: '[gif圖]',
sort_by_popularity: '按收藏數搜索(單頁)'
}
};
i18nLib['zh-cn'] = $.extend({}, i18nLib.zh);
// TODO 待翻译
i18nLib.ja = $.extend({}, i18nLib.en, i18nLib.ja);
i18nLib.ko = $.extend({}, i18nLib.en, i18nLib.ko);
const i18n = key => i18nLib[lang][key] || `i18n[${lang}][${key}] not found`;
// ============================ 功能配置 ==============================
const settingNames = [
'ad_disable',
'download_enable',
'search_enhance_UID',
'search_enhance_PID',
'search_enhance_Author',
'artist_info',
'comment_load',
'artwork_tag',
'redirect_cancel',
'load_origin'
];
const initConfig = () => {
const config = {};
for (const k of settingNames) {
let enable = GM_getValue(k)
if (enable === null || enable === undefined) {
GM.setValue(k, true);
enable = true;
}
config[k] = enable;
}
return config;
}
const config = initConfig();
const settingsPanel = () => {
const $panel = $(`
<style>
#pixiv-plus-panel-wrap {
position: fixed;
top: 0;
left: 0;
width: 100%;
height: 100%;
display: flex;
z-index: 99;
background-color: rgba(0, 0, 0, 0.32);
user-select: none;
}
#pixiv-plus-panel {
position: relative;
background-color: #fff;
border-radius: 24px;
margin: auto;
padding: 20px 40px 30px 40px;
font-size: 16px;
}
#pixiv-plus-header-wrap {
display:flex;
}
#pixiv-plus-settings-items-wrap {
display: grid;
grid-template-columns: repeat(2, 1fr);
grid-template-rows: repeat(5, 1fr);
grid-gap: 10px;
justify-items: start;
align-items: center;
}
#pixiv-plus-settings-item-wrap {
display: flex;
align-items: center;
margin: 12px 0;
gap: 12px;
}
#pixiv-plus-settings-checkbox {
width: 2em;
height: 2em;
accent-color: #987bd5;
font-weight: bold;
}
#pixiv-plus-settings-close-button {
position: absolute;
top: 10px;
right: 10px;
margin: 0;
padding: 0;
width: 25px;
height: 25px;
border: none;
cursor: pointer;
border-radius: 50%;
background-color: transparent;
transform: rotate(45deg);
transition: 0.25s background-color;
background: linear-gradient(rgb(125, 125, 125) 0%, rgb(125, 125, 125) 100%) center/18px 2px no-repeat, linear-gradient(rgb(125, 125, 125) 0%, rgb(125, 125, 125) 100%) center/2px 18px no-repeat;
}
</style>
<div id="pixiv-plus-panel-wrap" style="">
<div id="pixiv-plus-panel" >
<div id="pixiv-plus-header-wrap">
<h1>${i18n('settings')}</h1>
<div style:"flex:1"></div>
<button id="pixiv-plus-settings-close-button" type=""></button>
</div>
<hr/>
<div id="pixiv-plus-settings-items-wrap">
</div>
</div>
</div>
`);
const $items_wrap = $panel.find('#pixiv-plus-settings-items-wrap');
for (const name of settingNames) {
$items_wrap.append($(`
<div id="pixiv-plus-settings-item-wrap">
<input id="pixiv-plus-settings-checkbox" type="checkbox" name=${name} />
<label for=${name} style="font-weight: bold;">${i18n(name)}</label>
</div>
`))
}
$panel.find('input[type="checkbox"]').each(function () {
const $checkbox = $(this);
const name = $checkbox.attr('name');
GM.getValue(name, true).then(value => {
$checkbox.prop('checked', value);
});
$checkbox.on('change', () => {
const checked = $checkbox.prop('checked');
$checkbox.prop(checked, checked);
GM.setValue(name, checked);
config[name] = checked;
});
});
$('body').append($panel);
$('#pixiv-plus-settings-close-button').on('click', () => $panel.remove());
}
GM_registerMenuCommand(`${i18n('settings')}`, () => settingsPanel());
// ============================ url 页面判断 ==============================
const isArtworkPage = () => /.+artworks\/\d+.*/.test(location.href);
const isMemberIndexPage = () => /.+\/users\/\d+.*/.test(location.href);
const isMemberIllustPage = () => /.+\/member_illust\.php\?id=\d+/.test(location.href);
const isMemberBookmarkPage = () => /.+\/bookmark\.php\?id=\d+/.test(location.href);
const isMemberFriendPage = () => /.+\/mypixiv_all\.php\?id=\d+/.test(location.href);
const isMemberDynamicPage = () => /.+\/stacc.+/.test(location.href);
const isMemberPage = () => isMemberIndexPage() || isMemberIllustPage() || isMemberBookmarkPage() || isMemberFriendPage();
const isSearchPage = () => /.+\/search\.php.*/.test(location.href) || /.+\/tags\/.*\/artworks.*/.test(location.href);
// 判断是否登录
if (!isLogin()) {
alert(i18n('loginWarning'));
}
/**
* [0] => 功能配置
* [1] => ob / ob组[ob, ob创建函数,判断是否处于对应页面的函数(可选)]
* [2] => 创建ob / ob组的函数
* [3] => 判断是否处于对应页面的函数
*/
const observers = [
// 1. 屏蔽广告, 全局进行css处理
['ad_disable', null, () => {
// 1. 删除静态添加的广告
$('.ad').remove();
$('._premium-lead-tag-search-bar').hide();
$('.popular-introduction-overlay').hide();// 移除热门图片遮罩层
$('.ad-footer').remove();//移除页脚广告
// 2. 删除动态添加的广告
const adSelectors = ['iframe', '._premium-lead-promotion-banner',
'a[href="/premium/lead/lp/?g=anchor&i=popular_works_list&p=popular&page=visitor"]', // https://www.pixiv.net/tags/%E6%9D%B1%E6%96%B9/artworks?s_mode=s_tag 热门作品
'a[href="/premium/lead/lp/?g=anchor&i=work_detail_remove_ads"]'
];
return observerFactory((mutations, observer) => {
for (const mutation of mutations) {
for (const node of mutation.addedNodes) {
if (node.nodeType === Node.ELEMENT_NODE) {
for (const selector of adSelectors) {
$(node).find(selector).hide();
}
}
}
}
});
}, () => true],
// 2/3. 搜索增强
[['search_enhance_UID', 'search_enhance_PID', 'search_enhance_Author'], null, () =>
observerFactory((mutations, observer) => {
for (let i = 0, len = mutations.length; i < len; i++) {
const mutation = mutations[i];
// 1. 判断是否改变节点, 或者是否有[form]节点
const $form = $('#js-mount-point-header form:not([action]), #root div[style="position: static; z-index: auto;"] form:not([action])');
if (mutation.type !== 'childList' || !$form.length) {
continue;
}
log("搜索增强 初始化");
// 2. 搜索UID,PID和作者
($form => {
const idSearch = true;
const otherSearch = false;
const initSearch = option => {
const options = $.extend({ $form: null, placeholder: '', urlhandler: url => '', searchType: idSearch }, option);
if (!options.$form) {
error('搜索UID和PID 初始化失败, form元素获取失败');
}
// 1. 初始化表单UI
const $parent = options.$form.parent().clone();
const $form = $parent.find('form');
$form.children('div').eq(1).remove();
$form.attr('class', 'ahao-search');
options.$form.parent().before($parent);
const $input = $form.find('input[type="text"]:first');
$input.attr('placeholder', options.placeholder);
$input.val('');
// 2. 绑定submit事件
$form.submit(e => {
e.preventDefault();
const val = encodeURIComponent($input.val());
// 2.1. ID 必须为纯数字
if (options.searchType && !/^[0-9]+$/.test(val)) {
const label = options.placeholder + i18n('illegal');
alert(label);
return;
}
// 2.2. 新窗口打开url
const url = option.urlhandler(val);
window.open(url);
// 2.3. 清空input等待下次输入
$input.val('');
});
};
// 按设置加入搜索框
const searchers = [
[() => initSearch({ $form, placeholder: 'UID', urlhandler: (url) => `https://www.pixiv.net/users/${url}`, searchType: idSearch }), () => config['search_enhance_UID']],
[() => initSearch({ $form, placeholder: 'PID', urlhandler: (url) => `https://www.pixiv.net/artworks/${url}`, searchType: idSearch }), () => config['search_enhance_PID']],
[() => initSearch({ $form, placeholder: i18n('author'), urlhandler: (url) => `https://www.pixiv.net/search_user.php?nick=${url}&s_mode=s_usr`, searchType: otherSearch }), () => config['search_enhance_Author']]];
// 统计加入的搜索框
let cnt = 0;
for (const searcher of searchers) {
if ((searcher[1])()) {
(searcher[0])();
cnt++;
}
}
// 3. 修改父级grid布局
// 分类设置布局
const $parent = $form.parent().parent();
switch (cnt) {
case 0: {
$parent.css('grid-template-columns', '1fr minmax(0px, 800px) minmax(0px, 350px) 2fr');
break;
}
case 1: {
$parent.css('grid-template-columns', '1fr minmax(0px, 600px) minmax(0px, 600px) minmax(0px, 250px) 2fr');
break;
}
case 2: {
$parent.css('grid-template-columns', '1fr minmax(0px, 243px) minmax(0px, 586px) minmax(0px, 586px) minmax(0px, 243px) 2fr');
break;
}
case 3: {
$parent.css('grid-template-columns', '1fr minmax(0px, 219px) minmax(0px, 219px) minmax(0px, 538px) minmax(0px, 538px) minmax(0px, 219px) 2fr');
break;
}
default: {
break;
}
}
})($form);
// 4. 搜索条件
($form => {
const label = i18n('favorites'); // users入り
const $input = $form.find('input[type="text"]:first');
const $select = $(`
<select id="select-ahao-favorites">
<option value=""></option>
<option value="30000users入り">30000users入り</option>
<option value="20000users入り">20000users入り</option>
<option value="10000users入り">10000users入り</option>
<option value="5000users入り" > 5000users入り</option>
<option value="1000users入り" > 1000users入り</option>
<option value="500users入り" > 500users入り</option>
<option value="300users入り" > 300users入り</option>
<option value="100users入り" > 100users入り</option>
<option value="50users入り" > 50users入り</option>
</select>`);
$select.on('change', () => {
if (!!$input.val()) { $form.submit(); }
});
$form.parent().after($select);
$form.submit(e => {
e.preventDefault();
if (!!$select.val()) {
// 2.4.1. 去除旧的搜索选项
$input.val((index, val) => val.replace(/\d*users入り/g, ''));
$input.val((index, val) => val.replace(/\d*$/g, ''));
// 2.4.2. 去除多余空格
$input.val((index, val) => val.replace(/\s\s*/g, ''));
$input.val((index, val) => `${val} `);
// 2.4.3. 添加新的搜索选项
$input.val((index, val) => `${val}${$select.val()}`);
}
const value = encodeURIComponent($input.val());
if (!!value) {
location.href = `https://www.pixiv.net/tags/${value}/artworks?s_mode=s_tag`;
}
});
})($form);
observer.disconnect();
break;
}
})
, () => true],
// 4. 单张图片替换为原图格式. 追加下载按钮, 下载gif图、gif的帧压缩包、多图
['download_enable', null, async () => {
// 1. 初始化方法
const initDownloadBtn = option => {
// 下载按钮, 复制分享按钮并旋转180度
const options = $.extend({ $shareButtonContainer: undefined, id: '', text: '', clickFun: () => { } }, option);
const $downloadButtonContainer = options.$shareButtonContainer.clone();
$downloadButtonContainer.addClass('ahao-download-btn')
.attr('id', options.id)
.removeClass(options.$shareButtonContainer.attr('class'))
.css('margin-right', '10px')
.css('position', 'relative')
.css('border', '1px solid')
.css('padding', '1px 10px')
.append(`<p style="display: inline">${options.text}</p>`);
$downloadButtonContainer.find('button').css('transform', 'rotate(180deg)')
.on('click', options.clickFun);
options.$shareButtonContainer.after($downloadButtonContainer);
return $downloadButtonContainer;
};
// 单图显示图片尺寸 https://www.pixiv.net/artworks/109953681
const addImgSize = async option => {
// 从 $img 获取图片大小, after 到 $img
const options = $.extend({
$img: undefined,
position: 'absolute',
}, option);
const $img = options.$img;
const position = options.position;
if ($img.length !== 1) {
return;
}
GM.getValue(GMkeys.switchImgSize, true).then(open => {
if (!!open) {
// 1. 找到 显示图片大小 的 span, 没有则添加
let $span = $img.next('span');
if ($span.length <= 0) {
// 添加前 去除失去依赖的 span
$('body').find('.ahao-img-size').each(function () {
const $this = $(this);
const $prev = $this.prev('canvas, img');
if ($prev.length <= 0) {
$this.remove();
}
});
$img.after(`<span class="ahao-img-size" style="position: ${position}; right: 0; top: 28px;
color: #ffffff; font-size: x-large; font-weight: bold; -webkit-text-stroke: 1.0px #000000;"></span>`);
$span = $img.next('span');
}
// 2. 根据标签获取图片大小, 目前只有 canvas 和 img 两种
if ($img.prop('tagName') === 'IMG') {
const img = new Image();
img.src = $img.attr('src');
img.onload = function () {
$span.text(`${this.width}x${this.height}`);
};
} else {
const width = $img.attr('width') || $img.css('width').replace('px', '') || $img.css('max-width').replace('px', '') || 0;
const height = $img.attr('height') || $img.css('height').replace('px', '') || $img.css('max-height').replace('px', '') || 0;
$span.text(`${width}x${height}`);
}
}
});
};
const mimeType = suffix => {
const lib = { png: "image/png", jpg: "image/jpeg", gif: "image/gif" };
return lib[suffix] || `mimeType[${suffix}] not found`;
};
const getDownloadName = (name = '') =>
name.replace('{pid}', illust().illustId)
.replace('{uid}', illust().userId)
.replace('{pname}', illust().illustTitle)
.replace('{uname}', illust().userName);
;
const isMoreMode = () => illust().pageCount > 1;
const isGifMode = () => illust().illustType === 2;
const isSingleMode = () => (illust().illustType === 0 || illust().illustType === 1) && illust().pageCount === 1;
const selectorShareBtn = await GM.getValue(GMkeys.selectorShareBtn, '.UXmvz'); // section 下的 div
// 热修复下载按钮的className
const a = () => observerFactory((mutations, observer) => {
for (let i = 0, len = mutations.length; i < len; i++) {
const mutation = mutations[i];
const $target = $(mutation.target);
if ($target.prop('tagName').toLowerCase() !== 'section') continue;
const $section = $target.find('section');
if ($section.length <= 0) continue;
const className = $section.eq(0).children('div').eq(1).attr('class').split(' ')[1];
GM.setValue(GMkeys.selectorShareBtn, `.${className}`);
observer.disconnect();
return;
}
});
// 显示单图、多图原图
const b = () => observerFactory({
callback (mutations, observer) {
for (let i = 0, len = mutations.length; i < len; i++) {
const mutation = mutations[i];
const $target = $(mutation.target);
const replaceImg = ($target, attr, value) => {
const oldValue = $target.attr(attr);
if (new RegExp(`https?://i(-f|-cf)?\.pximg\.net.*\/${illust().id}_.*`).test(oldValue) &&
!new RegExp(`https?://i(-f|-cf)?\.pximg\.net/img-original.*`).test(oldValue)) {
$target.attr(attr, value).css('filter', 'none');
$target.fitWindow();
}
};
// 1. 单图、多图 DOM 结构都为 <a href=""><img/></a>
const $link = $target.find('img[src]');
$link.each(function () {
const $this = $(this);
const href = $this.parent('a').attr('href');
if (!!href && (href.endsWith('jpg') || href.endsWith('png'))) {
if (config.load_origin) {
replaceImg($this, 'src', href);
}
addImgSize({ $img: $this }); // 显示图片大小
}
});
// 2. 移除马赛克遮罩, https://www.pixiv.net/member_illust.php?mode=medium&illust_id=50358638
// $('.e2p8rxc2').hide(); // 懒得适配了, 自行去个人资料设置 https://www.pixiv.net/setting_user.php
}
},
option: { attributes: true, childList: true, subtree: true, attributeFilter: ['src', 'href'] }
});
// 下载动图帧zip, gif图
const c = () => observerFactory((mutations, observer) => {
for (let i = 0, len = mutations.length; i < len; i++) {
const mutation = mutations[i];
const $target = $(mutation.target);
// 1. 单图、多图、gif图三种模式
const $shareBtn = $target.find(selectorShareBtn);
const $canvas = $target.find('canvas');
// 2. 显示图片大小
addImgSize({ $img: $canvas })
if (!isGifMode() || mutation.type !== 'childList' ||
$shareBtn.length <= 0 ||
$target.find('#ahao-download-zip').length > 0) {
continue
}
log('下载gif图');
// 3. 初始化 下载按钮
const $zipBtn = initDownloadBtn({
$shareButtonContainer: $shareBtn,
id: 'ahao-download-zip',
text: 'zip',
});
const $gifBtn = initDownloadBtn({
$shareButtonContainer: $shareBtn,
id: 'ahao-download-gif',
text: 'gif',
clickFun () {
// 从 pixiv 官方 api 获取 gif 的数据
$.ajax({
url: `/ajax/illust/${illust().illustId}/ugoira_meta`, dataType: 'json',
success: ({ body }) => {
// 1. 初始化 gif 下载按钮 点击事件
// GIF_worker_URL 来自 https://greasyfork.org/scripts/2963-gif-js/code/gifjs.js?version=8596
let gifUrl;
const gifFrames = [];
const gifFactory = new GIF({ workers: 1, quality: 10, workerScript: GIF_worker_URL });
for (let frameIdx = 0, frames = body.frames, framesLen = frames.length; frameIdx < framesLen; frameIdx++) {
const frame = frames[frameIdx];
const url = illust().urls.original.replace('ugoira0.', `ugoira${frameIdx}.`);
GM.xmlHttpRequest({
method: 'GET',
url,
headers: { referer: 'https://www.pixiv.net/' },
overrideMimeType: 'text/plain; charset=x-user-defined',
onload ({ responseText }) {
// 2. 转为blob类型
const r = responseText;
const data = new Uint8Array(r.length);
let i = 0;
while (i < r.length) {
data[i] = r.charCodeAt(i);
i++;
}
const suffix = url.split('.').splice(-1);
const blob = new Blob([data], { type: mimeType(suffix) });
// 3. 压入gifFrames数组中, 手动同步sync
const img = document.createElement('img');
img.src = URL.createObjectURL(blob);
img.width = illust().width;
img.height = illust().height;
img.onload = () => {
gifFrames[frameIdx] = { frame: img, option: { delay: frame.delay } };
if (Object.keys(gifFrames).length >= framesLen) {
$.each(gifFrames, (i, f) => gifFactory.addFrame(f.frame, f.option));
gifFactory.render();
}
};
}
});
}
gifFactory.on('progress', pct => {
$gifBtn.find('p').text(`gif ${parseInt(pct * 100)}%`);
});
gifFactory.on('finished', blob => {
gifUrl = URL.createObjectURL(blob);
GM.getValue(GMkeys.downloadName, `{pid}`).then(name => {
const $a = $(`<a href="${gifUrl}" download="${getDownloadName(name)}"></a>`);
$gifBtn.find('button').wrap($a);
});
});
$gifBtn.find('button').off('click').on('click', () => {
if (!gifUrl) {
alert('Gif未加载完毕, 请稍等片刻!');
return;
}
// Adblock 禁止直接打开 blob url, https://github.com/jnordberg/gif.js/issues/71#issuecomment-367260284
// window.open(gifUrl);
});
}
});
}
});
// 4. 控制是否预下载, 避免多个页面导致爆内存, 直接下载 zip
$.ajax({
url: `/ajax/illust/${illust().illustId}/ugoira_meta`, dataType: 'json',
success: ({ body }) => {
GM.getValue(GMkeys.downloadName, `{pid}`).then(name => {
const $a = $(`<a href="${body.originalSrc}" download="${getDownloadName(name)}"></a>`);
$zipBtn.find('button').wrap($a);
});
}
});
GM.getValue(GMkeys.switchImgPreload, true).then(open => { if (open) { $gifBtn.find('button').click(); } });
// 5. 取消监听
GM.getValue(GMkeys.MO, true).then(v => { if (!v) observer.disconnect(); });
}
});
// 下载多图zip
const d = () => observerFactory((mutations, observer) => {
for (let i = 0, len = mutations.length; i < len; i++) {
const mutation = mutations[i];
const $target = $(mutation.target);
// 1. 单图、多图、gif图三种模式
const $shareBtn = $target.find(selectorShareBtn);
if (!isMoreMode() || mutation.type !== 'childList' || !$shareBtn.length || !!$target.find('#ahao-download-zip').length) {
continue
}
log('下载多图');
// 2. 查看全部图片
GM.getValue(GMkeys.switchImgMulti, true).then(open => { if (open) { $shareBtn.parent('section').next('button').click(); } });
// 3. 初始化 图片数量, 图片url
const zip = new JSZip();
let downloaded = 0; // 下载完成数量
const num = illust().pageCount; // 下载目标数量
const url = illust().urls.original;
const imgUrls = Array(parseInt(num)).fill()
.map((value, index) => url.replace(/_p\d\./, `_p${index}.`));
// 4. 初始化 下载按钮, 复制分享按钮并旋转180度
const $zipBtn = initDownloadBtn({
$shareButtonContainer: $shareBtn,
id: 'ahao-download-zip',
text: `${i18n('download')}`,
clickFun () {
// 3.1. 下载图片, https://wiki.greasespot.net/GM.xmlHttpRequest
if ($(this).attr('start') !== 'true') {
$(this).attr('start', true);
$.each(imgUrls, (index, url) => {
GM.xmlHttpRequest({
method: 'GET',
url,
headers: { referer: 'https://www.pixiv.net/' },
overrideMimeType: 'text/plain; charset=x-user-defined',
onload ({ responseText }) {
// 4.1. 转为blob类型
const r = responseText;
const data = new Uint8Array(r.length);
let i = 0;
while (i < r.length) {
data[i] = r.charCodeAt(i);
i++;
}
const suffix = url.split('.').splice(-1);
const blob = new Blob([data], { type: mimeType(suffix) });
// 4.2. 压缩图片
GM.getValue(GMkeys.downloadName, `{pid}`).then(name => {
zip.file(`${getDownloadName(name)}_${index}.${suffix}`, blob, { binary: true });
});
// 4.3. 手动sync, 避免下载不完全的情况
downloaded++;
$zipBtn.find('p').html(`${i18n('download')}${downloaded}/${num}`);
}
});
});
return;
}
// 3.2. 手动sync, 避免下载不完全
if (downloaded < num) {
alert(i18n('download_wait'));
return;
}
// 3.3. 使用jszip.js和FileSaver.js压缩并下载图片
GM.getValue(GMkeys.downloadName, `{pid}`).then(name => {
zip.generateAsync({ type: 'blob', base64: true })
.then(content => saveAs(content, getDownloadName(name)));
});
}
});
// 4. 控制是否预下载, 避免多个页面导致爆内存
GM.getValue(GMkeys.switchImgPreload, true).then(open => { if (open) { $zipBtn.find('button').click(); } });
// 5. 取消监听
GM.getValue(GMkeys.MO, true).then(v => { if (!v) observer.disconnect(); });
}
});
// 这里的页面判断可以去除, 判断在第1次就结束了
return [
[a(), a],
[b(), b],
[c(), c],
[d(), d]
];
}, () => isArtworkPage()],
// 5. 在画师页面和作品页面显示画师id、画师背景图, 用户头像允许右键保存
['artist_info', null, () => {
// 画师页面UI
const a = () => observerFactory((mutations, observer) => {
for (let i = 0, len = mutations.length; i < len; i++) {
const mutation = mutations[i];
// 1. 判断是否改变节点, 或者是否有[section]节点
const $target = $(mutation.target); // 多个反混淆externalLinksContainer
const externalLinksContainer = '_2AOtfl9';
const $row = $(`ul.${externalLinksContainer}`).parent();
if (mutation.type !== 'childList' || $row.length <= 0 || $('body').find('#uid').length > 0) {
continue;
}
// 1. 添加新的一行的div
const $ahaoRow = $row.clone();
const $ul = $ahaoRow.children('ul');
$ahaoRow.children(':not(ul)').remove();
$ul.empty();
$row.before($ahaoRow);
// 2. 显示画师id, 点击自动复制到剪贴板
const uid = getUid();
const $uid = $(`<li id="uid"><div style="font-size: 20px;font-weight: 700;color: #333;margin-right: 8px;line-height: 1">UID:${uid}</div></li>`)
.on('click', function () {
const $this = $(this);
$this.html(`<span>UID${i18n('copy_to_clipboard')}</span>`);
GM.setClipboard(uid);
setTimeout(() => {
$this.html(`<span>UID${uid}</span>`);
}, 2000);
});
$ul.append($uid);
// 3. 显示画师背景图
const background = preloadData.user[uid].background;
const url = (background && background.url) || '';
const $bgli = $('<li><div style="font-size: 20px;font-weight: 700;color: #333;margin-right: 8px;line-height: 1"></div></li>');
const $bg = $bgli.find('div');
if (!!url && url !== 'none') {
$bg.append(`<img src="${url}" width="30px"><a target="_blank" href="${url}">${i18n('background')}</a>`);
} else {
$bg.append(`<span>${i18n('background_not_found')}</span>`);
}
$ul.append($bgli);
// 4. 取消监听
GM.getValue(GMkeys.MO, true).then(v => { if (!v) observer.disconnect(); });
}
});
// 作品页面UI
const b = () => observerFactory((mutations, observer) => {
for (let i = 0, len = mutations.length; i < len; i++) {
const mutation = mutations[i];
// 1. 判断是否改变节点, 或者是否有[section]节点