This repository has been archived by the owner on Nov 28, 2022. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 6
/
Copy pathNamuFix.user.js
4077 lines (4036 loc) · 219 KB
/
NamuFix.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 NamuFix
// @namespace http://litehell.info/
// @description 나무위키 등 더시드 사용 위키의 편집 인터페이스 등을 개선합니다.
// @include https://namu.wiki/*
// @include https://theseed.io/*
// @include https://board.namu.wiki/*
// @version 200327.0
// @author LiteHell
// @downloadURL https://namufix.wikimasonry.org/latest.js
// @require https://greasemonkey.github.io/gm4-polyfill/gm4-polyfill.js
// @require https://rawcdn.githack.com/Caligatio/jsSHA/v2.3.1/src/sha.js
// @require https://rawcdn.githack.com/zenozeng/color-hash/v1.0.3/dist/color-hash.js
// @require https://rawcdn.githack.com/ben-liang/pnglib/91a91b7f840fdf19ef34a32df8051f2178957293/pnglib.js
// @require https://rawcdn.githack.com/stewartlord/identicon.js/7c4b4efdb7e2aba458eba14b24ba14e8e2bcdb2a/identicon.js
// @require https://cdn.jsdelivr.net/npm/[email protected]
// @require https://rawcdn.githack.com/LiteHell/TooSimplePopupLib/7f2a8a81f11f980c1dfa6b5b2213cd38b8bbde3c/TooSimplePopupLib.js
// @require https://rawcdn.githack.com/wkpark/jsdifflib/dc19d085db5ae71cdff990aac8351607fee4fd01/difflib.js
// @require https://rawcdn.githack.com/wkpark/jsdifflib/dc19d085db5ae71cdff990aac8351607fee4fd01/diffview.js
// @require https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.19.3/moment-with-locales.min.js
// @require https://cdnjs.cloudflare.com/ajax/libs/moment-timezone/0.5.14/moment-timezone-with-data.min.js
// @require https://cdn.jsdelivr.net/npm/[email protected]/dist/async.min.js
// @require https://rawcdn.githack.com/mathiasbynens/he/v1.1.1/he.js
// @require https://rawcdn.githack.com/LiteHell/NamuFix/f55ab32d98c69e89949200a6b485524ae28401da/data/korCountryNames.js
// @require https://rawcdn.githack.com/LiteHell/NamuFix/f55ab32d98c69e89949200a6b485524ae28401da/FlexiColorPicker.js
// @require https://rawcdn.githack.com/LiteHell/NamuFix/f55ab32d98c69e89949200a6b485524ae28401da/skinDependency.js
// @require https://rawcdn.githack.com/LiteHell/NamuFix/f55ab32d98c69e89949200a6b485524ae28401da/src/flagUtils.js
// @require https://rawcdn.githack.com/LiteHell/NamuFix/f55ab32d98c69e89949200a6b485524ae28401da/src/hashUtils.js
// @require https://rawcdn.githack.com/LiteHell/NamuFix/f55ab32d98c69e89949200a6b485524ae28401da/src/NFStorage.js
// @require https://rawcdn.githack.com/LiteHell/NamuFix/f55ab32d98c69e89949200a6b485524ae28401da/src/utils.js
// @require https://rawcdn.githack.com/LiteHell/NamuFix/f55ab32d98c69e89949200a6b485524ae28401da/src/whoisIpUtils.js
// @require https://rawcdn.githack.com/LiteHell/NamuFix/f55ab32d98c69e89949200a6b485524ae28401da/src/namuapi.js
// @require https://rawcdn.githack.com/LiteHell/NamuFix/f55ab32d98c69e89949200a6b485524ae28401da/src/boardArchivers.js
// @connect rawcdn.githack.com
// @connect cdnjs.cloudflare.com
// @connect jsdelivr.net
// @connect api.github.com
// @connect ipinfo.io
// @connect wtfismyip.com
// @connect www.googleapis.com
// @connect web.archive.org
// @connect archive.is
// @connect www.vpngate.net
// @connect namufix.wikimasonry.org
// @connect phpgongbu.ga
// @connect namuwiki.ml
// @connect twitter.com
// @connect facebook.com
// @connect www.facebook.com
// @grant GM_openInTab
// @grant GM_xmlhttpRequest
// @grant GM_getValue
// @grant GM_setValue
// @grant GM_deleteValue
// @grant GM_listValues
// @grant GM_info
// @grant GM_getResourceURL
// @grant GM.openInTab
// @grant GM.xmlHttpRequest
// @grant GM.getValue
// @grant GM.setValue
// @grant GM.deleteValue
// @grant GM.listValues
// @grant GM.info
// @grant GM.getResourceUrl
// @run-at document-end
// @noframes
// ==/UserScript==
/* jshint ignore:start */
/*
Copyright (c) 2015 LiteHell
Permission is hereby granted, free of charge, to any person
obtaining a copy of this software and associated documentation
files (the "Software"), to deal in the Software without
restriction, including without limitation the rights to use,
copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the
Software is furnished to do so, subject to the following
conditions:
The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
OTHER DEALINGS IN THE SOFTWARE.
*/
let {
getFlagIcon
} = new flagUtils();
let {
SHA512,
SHA1,
SHA256
} = new hashUtils();
let {
nOu,
NF_addStyle,
encodeHTMLComponent,
decodeHTMLComponent,
validateIP,
formatDateTime,
formatTimespan,
insertCSS,
enterTimespanPopup
} = new utils();
let {
getIpInfo,
getIpWhois,
getVPNGateIPList,
checkVPNGateIP,
whoisPopup
} = new whoisIpUtils();
let SET = new NFStorage();
function batchBlockFunction(evt, opts) {
evt.preventDefault();
var win = TooSimplePopup();
win.title('계정/IP 일괄 차단');
win.content(function (con) {
var expire = 0;
con.innerHTML = '<p>아래에 차단할 IP주소/계정들을 입력해주세요.' + '차단 사유 : <input type="text" id="note"></input><br>' + '차단기간 : <span id="expire_display">영구</span> <a href="#" id="setExpire">(차단기간 설정)</a>(참고 : 0초 = 영구차단)<br>' + '로그인 허용 여부 : <input type="checkbox" id="allowLogin"></input><br>' + '※ IP 차단 해제시에는 차단사유/영구차단 여부/로그인 허용 여부를 설정할 필요 없으며 IP는 IPv4만 인식합니다.</p>' + '차단할 계정/IP (개행으로 구분) : <br>' + '<textarea style="width: 800px; max-width: 80vw; height: 500px; max-height: 80vh;"></textarea>';
con.querySelector('a#setExpire')
.addEventListener('click', function (evt) {
evt.preventDefault();
enterTimespanPopup('차단기간 설정', function (span) {
if (span === null) {
return alert('입력이 없습니다.');
} else {
expire = span;
con.querySelector('#expire_display')
.textContent = span == 0 ? '영구' : expire + '초 ';
}
});
})
win.button('닫기', win.close);
win.button('VPNGATE IP 불러오기', async function () {
let win = TooSimplePopup();
win.title('불러오는 중');
win.content(e => e.innerHTML = "불러오는 중입니다. 잠시만 기다려주십시오.");
let vpngateIPs = await getVPNGateIPList();
let textarea = con.querySelector('textarea');
textarea.value += '\n' + vpngateIPs.map(v => v + "/32")
.join("\n");
win.close();
})
win.button('차단기록 검색', async function () {
let searchWin = TooSimplePopup();
let queryInfo;
searchWin.title('차단기록 검색');
searchWin.content(searchWinCon => {
searchWinCon.innerHTML = `
<style>.search-prev[disabled], .search-next[disabled] {background: darkgray; text-decoration: line-through;}</style>
<div class="table-responsive-sm">
<table class="table table-striped table-bordered table-hover table-sm">
<thead>
<tr>
<td>선택</td>
<td>유형</td>
<td>실행자</td>
<td>피실행자</td>
<td>사유</td>
<td>기간</td>
<td>차단일시</td>
</tr>
</thead>
<tbody>
</tbody>
</table>
</div>
<div class="search-pagination">
</div>
`;
function processQuery() {
let waitingWin = TooSimplePopup();
waitingWin.title("진행중입니다");
waitingWin.content(waitingWinCon => waitingWinCon.innerHTML = "진행중입니다. 잠시만 기다려주십시오.");
namuapi.searchBlockHistory(queryInfo, (result) => {
queryInfo.from = result.nextResultPageFrom || null;
queryInfo.until = result.prevResultPageUntil || null;
let tbody = searchWinCon.querySelector('tbody');
tbody.innerHTML = "";
for (let i of result) {
// checkbox, type, blocker, blocked, reason, duration, at
tbody.innerHTML += `<tr data-blocked="${encodeHTMLComponent(JSON.stringify(i.blocked))}"><td><input type="checkbox" checked></td><td>${i.type}</td><td>${encodeHTMLComponent(i.blocker)}</td><td>${encodeHTMLComponent(i.blocked)}</td><td>${encodeHTMLComponent(i.reason)}</td><td>${i.duration}</td><td>${formatDateTime(i.at)}</td></tr>`;
}
waitingWin.close();
});
}
searchWin.button('검색', () => {
let queryWin = TooSimplePopup();
queryWin.title('쿼리 입력');
queryWin.content(queryWinCon => {
queryWinCon.innerHTML = `
<div>
쿼리 :
<input type="text" class="search-query" style="width: 500px; max-width: 80vw;"></input>
</div>`;
queryWin.button('실행자 검색', () => {
queryInfo = {
query: queryWinCon.querySelector('.search-query')
.value,
isAuthor: true
};
processQuery();
});
queryWin.button('내용 검색', () => {
queryInfo = {
query: queryWinCon.querySelector('.search-query')
.value,
isAuthor: false
};
processQuery();
});
queryWin.button('닫기', queryWin.close);
});
});
searchWin.button('선택된 항목 추가', () => {
let isFirst = true;
let textarea = con.querySelector('textarea');
let waitingWin = TooSimplePopup();
waitingWin.title('진행중입니다.');
waitingWin.content(c => c.innerHTML = "진행중입니다.");
for (let i of searchWinCon.querySelectorAll('tbody tr')) {
if (isFirst) {
textarea.value += '\n';
isFirst = false;
}
if (i.querySelector('input[type="checkbox"]')
.checked) textarea.value += JSON.parse(i.dataset.blocked) + "\n";
}
waitingWin.close();
});
searchWin.button('이전 결과', () => {
if (queryInfo.until) {
delete queryInfo.from;
processQuery();
} else {
alert('첫 페이지입니다.');
}
});
searchWin.button('다음 결과', () => {
if (queryInfo.from) {
delete queryInfo.until;
processQuery();
} else {
alert('마지막 페이지입니다.');
}
});
searchWin.button('닫기', searchWin.close);
});
})
function parseTextarea() {
let commonData = {
note: con.querySelector('input#note')
.value,
expire: expire,
allowLogin: con.querySelector('input#allowLogin')
.checked
}
return con.querySelector('textarea')
.value.split('\n')
.map(v => v.trim())
.filter(v => v != "")
.map((v) => {
let ipWithCIDR = /^([0-9]{1,3}\.){3}[0-9]{1,3}(\/([0-9]|[1-2][0-9]|3[0-2]))?$/;
let data = JSON.parse(JSON.stringify(commonData));
if (ipWithCIDR.test(v)) data.ip = v;
else data.id = v;
if (data.ip && !data.ip.includes("/")) data.ip += "/32";
return data;
});
}
function commonLoop(_datas, progressCallback) { // returns error object
return new Promise((resolve, reject) => {
let result = {
errors: [],
success: []
};
let datas = JSON.parse(JSON.stringify(_datas));
console.log(SET.adminReqLimit);
async.eachLimit(datas, SET.adminReqLimit, (data, callback) => {
console.log('a');
namuapi[data.handlerName](data.parameter, (err, target) => {
console.log('b');
console.log(err);
console.log(target);
if (err) {
result.errors.push({
target: data.parameter,
error: err
});
} else {
result.success.push(data.parameter);
}
if (progressCallback) progressCallback(data);
callback();
});
}, (err) => {
return resolve(result);
});
});
}
win.button('차단', async function () {
var waitingWin = TooSimplePopup();
var errors = [];
waitingWin.title('처리중');
waitingWin.content(function (wwcon) {
wwcon.innerHTML = "처리중입니다."
});
let datas = parseTextarea()
.map(v => ({
parameter: v,
handlerName: v.ip ? "blockIP" : "blockAccount"
}));
let result = await commonLoop(datas, d => waitingWin.content(wwcon => wwcon.innerHTML = `처리 완료: ${d.parameter.ip || d.parameter.id}`));
if (result.errors.length > 0) {
waitingWin.content(wwcon => {
wwcon.innerHTML = "오류가 있습니다.<br><br>" + result.errors.map(v => `${encodeHTMLComponent(v.target.ip || v.target.id)} : ${v.error}`)
.join("<br>");
});
waitingWin.button('닫기', waitingWin.close);
} else {
waitingWin.close();
}
});
win.button('차단 해제', async function () {
var waitingWin = TooSimplePopup();
var errors = [];
waitingWin.title('처리중');
waitingWin.content(function (wwcon) {
wwcon.innerHTML = "처리중입니다."
});
let datas = parseTextarea()
.map(v => {
if (v.ip) {
return {
parameter: v.ip,
handlerName: 'unblockIP'
};
} else {
let tmp = {
parameter: v,
handlerName: 'blockAccount'
};
tmp.parameter.expire = -1;
return tmp;
}
});
let result = await commonLoop(datas, d => waitingWin.content(wwcon => wwcon.innerHTML = `처리 완료: ${d.parameter.id ? d.parameter.id : d.parameter}`));
if (result.errors.length > 0) {
waitingWin.content(wwcon => {
wwcon.innerHTML = "오류가 있습니다.<br><br>" + result.errors.map(v => `${encodeHTMLComponent(v.target.id || v.target)} : ${v.error}`)
.join("<br>");
});
waitingWin.button('닫기', waitingWin.close);
} else {
waitingWin.close();
}
});
if (opts) {
if (opts.blockees)
con.querySelector('textarea').value = opts.blockees.join('\n');
}
});
}
if (location.host === 'board.namu.wiki') {
async function runBoardFix() {
await SET.load();
// 이미지 업로드 함수
function uploadXEImage(file, mid, name) {
let formData = new FormData();
formData.append('Filename', 'emoti.png')
formData.append('')
GM.xmlHttpRequest({
url: 'https://board.namu.wiki'
})
}
// 시간대 자동 변경
if (SET.noLocaltimeOnNamuBoard !== false) {
let times = document.querySelectorAll('.read_header > .meta > .time, .fbMeta .time');
let origTimezone = "UTC" // America/Asuncion 아님.
for (let i = 0; i < times.length; i++) {
let t = moment.tz(times[i].textContent.trim(), "YYYY.MM.DD HH:mm", origTimezone);
times[i].textContent = t.tz(moment.tz.guess())
.format("YYYY.MM.DD HH:mm z")
}
if (times.length !== 0) console.log(`[NamuFix] 게시판 시간대 변경 완료. ${origTimezone} > ${moment.tz.guess()}`);
}
// 아카이브 버튼
if (document.querySelector('.viewDocument .read_footer .btnArea a[onclick]') !== null) {
let extraMenuLink = document.querySelector('.viewDocument .read_footer .btnArea a[onclick]');
let documentId = /document_([0-9]+)/.exec(extraMenuLink.className)[1];
let archiveLink = document.createElement("a");
archiveLink.href = "#";
archiveLink.target = "_blank";
archiveLink.textContent = "아카이브";
let clickHandler = async (evt) => {
evt.preventDefault();
archiveLink.textContent = "(진행중)";
archiveLink.removeAttribute("href");
archiveLink.removeEventListener("click", clickHandler);
let archiveFunction = (new BoardArchiver(GM.info.script.version))[SET.defaultBoardArchiver];
let archiveUrl = await archiveFunction(documentId);
GM.openInTab(archiveUrl);
archiveLink.textContent = "아카이브됨";
archiveLink.href = archiveUrl;
};
archiveLink.addEventListener("click", clickHandler);
extraMenuLink.parentNode.insertBefore(archiveLink, extraMenuLink.nextSibling);
}
// 댓글 상용구
if (document.querySelector('.write_comment') && SET.commentMacros) {
console.log('[NamuFix] 댓글창 감지됨.')
let writeAuthorDiv = document.querySelector('.write_author');
for (let i of SET.commentMacros.split(',')) {
let macroName = i.split(':')[0];
let macroContentParts = i.split(':');
macroContentParts.shift();
let macroContent = macroContentParts.join(':');
let macroBtn = document.createElement("button");
console.log(`[NamuFix] 매크로 버튼 추가중 (이름: ${macroName}, 내용: ${macroContent})`)
macroBtn.setAttribute('type', 'button');
macroBtn.innerHTML = '상용구 (' + macroName + ')';
macroBtn.addEventListener('click', (evt) => {
evt.preventDefault();
let xeEditor = document.querySelector('.xpress-editor'),
hiddenContentInput = document.querySelector('.write_comment > input[name="content"]'),
writeForm = document.querySelector('.write_comment > .write_form');
// XE에디터 제거
xeEditor.parentNode.removeChild(xeEditor);
// 기존 content input 제거
hiddenContentInput.parentNode.removeChild(hiddenContentInput);
// content input 추가
let newContentInput = document.createElement('input');
newContentInput.setAttribute('type', 'hidden');
newContentInput.name = "content";
newContentInput.value = macroContent;
writeForm.appendChild(newContentInput);
// 댓글 작성
document.querySelector('.write_author button[type="submit"]')
.click();
})
writeAuthorDiv.appendChild(macroBtn, writeAuthorDiv.lastChild);
}
}
// 일괄 차단 메뉴추가
if (SET.addBatchBlockMenu) {
await insertCSS("https://rawcdn.githack.com/LiteHell/TooSimplePopupLib/edad912e28eeacdc3fd8b6e6b7ac5cafc46d95b6/TooSimplePopupLib.css");
let item = document.createElement('li');
item.innerHTML = '<a href="#">일괄 차단</a>';
item.querySelector('a')
.addEventListener('click', batchBlockFunction);
// 화면 작으면 일괄차단 버튼이 레이아웃을 뵈게 싫게 만듬.
let firstMenu = document.querySelector('#main-navbar ul.navbar-nav.nav > li:first-child');
firstMenu.parentNode.insertBefore(item, firstMenu);
firstMenu.parentNode.removeChild(firstMenu);
}
// 닉네임/IP주소 기여목록 링크
if (SET.userContribLinkOnBoard) {
let authors = [...document.querySelectorAll('.feedback .fbList .fbMeta .author span, .board .board_read .read_header .meta .name, .board_list tr td.author a')];
authors.forEach(i => {
let username = i.textContent.trim(),
link = `https://namu.wiki/contribution/${validateIP(username) ? 'ip' : 'author'}/${username}/document`;
if(i.tagName == 'A') {
i.href = link;
i.target = '_blank';
i.removeAttribute('onclick');
} else {
let anchor = document.createElement('a');
anchor.href = link;
anchor.style.textDecoration = 'none';
anchor.style.color = 'black';
anchor.target = '_blank';
anchor.textContent = username;
i.innerHTML = '';
i.appendChild(anchor);
}
});
}
}
runBoardFix();
} else(async function (SET) {
console.log(`[NamuFix] 현재 버전 : ${GM.info.script.version}`);
if (location.hostname == 'no-ssl.namu.wiki') location.hostname = 'namu.wiki';
await insertCSS("https://rawcdn.githack.com/LiteHell/NamuFix/284db44ac1d89ff0cbd1155c3372db38be3bc140/NamuFix.css");
await insertCSS("https://rawcdn.githack.com/LiteHell/TooSimplePopupLib/edad912e28eeacdc3fd8b6e6b7ac5cafc46d95b6/TooSimplePopupLib.css");
await insertCSS("https://rawcdn.githack.com/wkpark/jsdifflib/dc19d085db5ae71cdff990aac8351607fee4fd01/diffview.css");
console.log('[NamuFix] CSS 삽입됨.');
// 업데이트 확인
GM.xmlHttpRequest({
method: "GET",
url: "https://api.github.com/repos/LiteHell/NamuFix/releases/latest",
onload: function (res) {
var obj = JSON.parse(res.responseText);
if (typeof obj.message !== 'undefined' && obj.message.indexOf('API rate limit') != -1) {
console.log('[NamuFix] NamuFix 업데이트 연기! (GitHub API 제한에 따른 오류)');
return; // GitHub API 오류
}
var currentVersion = GM.info.script.version;
if (!obj.tag_name) {
console.log('[NamuFix] NamuFix 업데이트 연기! (최신 버전을 읽을 수 없음)');
return;
}
var latestVersion = obj.tag_name;
if (currentVersion != latestVersion) {
var scriptUrl = 'https://github.com/LiteHell/NamuFix/raw/' + latestVersion + '/NamuFix.user.js';
var win = TooSimplePopup();
win.title('새 버전 설치');
win.content(function (element) {
// 변경 사항 : obj.body
element.innerHTML = '업데이트가 있습니다.<br><br>현재 사용중인 버전 : ' + currentVersion + '<br>' + '현재 최신 버전 : ' + latestVersion + '<br><br>' + latestVersion + '버전에서의 변경 사항<pre style="border-left: 6px solid green; padding: 10px; font-size: 13px; font-family: sans-family;" id="changeLog"></pre>' + '<p><a href="' + scriptUrl + '" style="text-decoration: none;"><button type="button" style="display: block; margin: 0 auto;">최신 버전 설치</button></a></p>' + '설치 후 새로고침을 해야 적용됩니다.<br>버그 신고 및 건의는 <a href="https://github.com/LiteHell/NamuFix/issues">이슈 트래커</a>에서 해주시면 감사하겠습니다.';
element.querySelector('#changeLog')
.innerHTML = obj.body;
});
win.button('닫기', win.close);
win.button('새로고침', function () {
location.reload();
});
}
}
});
let skinDependency = getSkinDependency(new RegExp(`(${getSkinSupports().join('|')})`, 'i')
.exec(document.body.className)[1].toLowerCase());
// 문서/역사/편집 페이지 등에서 버튼 추가 함수
let addArticleButton = skinDependency.addArticleButton;
function uniqueID() {
var dt = Date.now();
var url = location.href;
var randomized = Math.floor(Math.random() * 48158964189489678525869410);
return SHA512(String(dt)
.concat(dt, '\n', url, '\n', String(randomized)));
}
function listenPJAX(callback) {
// create elements
var pjaxButton = document.createElement("button");
var scriptElement = document.createElement("script");
// configure button
pjaxButton.style.display = "none";
pjaxButton.id = "nfFuckingPJAX"
pjaxButton.addEventListener("click", callback);
// configure script
scriptElement.setAttribute("type", "text/javascript");
scriptElement.innerHTML = '$(document).bind("pjax:end", function(){document.querySelector("button#nfFuckingPJAX").click();})';
// add elements
document.body.appendChild(pjaxButton);
document.head.appendChild(scriptElement);
}
async function INITSET() { // Storage INIT
await SET.load();
if (nOu(SET.tempsaves)) SET.tempsaves = {};
if (nOu(SET.recentlyUsedTemplates)) SET.recentlyUsedTemplates = [];
if (nOu(SET.imgurDeletionLinks)) SET.imgurDeletionLinks = [];
if (nOu(SET.discussIdenti)) SET.discussIdenti = 'icon'; // icon, headBg, none
if (nOu(SET.discussIdentiLightness)) SET.discussIdentiLightness = 0.7;
if (nOu(SET.discussIdentiSaturation)) SET.discussIdentiSaturation = 0.5;
if (nOu(SET.favorites)) SET.favorites = [];
if (nOu(SET.customIdenticons)) SET.customIdenticons = {};
if (nOu(SET.discussAnchorPreviewType)) SET.discussAnchorPreviewType = 1; // 0 : None, 1 : mouseover, 2 : quote
else SET.discussAnchorPreviewType = Number(SET.discussAnchorPreviewType);
if (nOu(SET.removeNFQuotesInAnchorPreview)) SET.removeNFQuotesInAnchorPreview = false;
if (nOu(SET.lookupIPonDiscuss)) SET.lookupIPonDiscuss = true;
if (nOu(SET.ignoreNonSenkawaWarning)) SET.ignoreNonSenkawaWarning = false;
if (nOu(SET.loadUnvisibleReses)) SET.loadUnvisibleReses = false;
if (nOu(SET.ipInfoDefaultOrg)) SET.ipInfoDefaultOrg = "ipinfo.io"; //ipinfo.io, KISAISP, KISAuser, KISAuserOrISP
if (nOu(SET.autoTempsaveSpan)) SET.autoTempsaveSpan = 1000 * 60 * 5; // 5분
if (nOu(SET.addBatchBlockMenu)) SET.addBatchBlockMenu = false;
if (nOu(SET.noLocaltimeOnNamuBoard)) SET.noLocaltimeOnNamuBoard = true;
if (nOu(SET.fileUploadReqLimit)) SET.fileUploadReqLimit = 3;
if (nOu(SET.adminReqLimit)) SET.adminReqLimit = 3;
if (nOu(SET.quickBlockReasonTemplate_discuss)) SET.quickBlockReasonTemplate_discuss = '긴급조치 https://${host}/thread/${threadNo} #${messageNo}' // ${host}, ${threadNo}, ${messageNo}
if (nOu(SET.quickBlockReasonTemplate_history)) SET.quickBlockReasonTemplate_history = '긴급조치 [[${docName}]] ${revisionNo}' // ${host}, ${docName}, ${revisionNo}
if (nOu(SET.quickBlockDefaultDuration)) SET.quickBlockDefaultDuration = 0;
if (nOu(SET.addQuickBlockLink)) SET.addQuickBlockLink = false;
if (nOu(SET.notifyForUnvisibleThreads)) SET.notifyForUnvisibleThreads = false;
if (nOu(SET.checkWhoisNetTypeOnDiscuss)) SET.checkWhoisNetTypeOnDiscuss = false;
if (nOu(SET.checkedServerNotices)) SET.checkedServerNotices = [];
if (nOu(SET.additionalScript)) SET.additionalScript = "";
if (nOu(SET.umiCookie)) SET.umiCookie = "";
if (nOu(SET.unprefixedFilename)) SET.unprefixedFilename = false;
if (nOu(SET.addSnsShareButton)) SET.addSnsShareButton = false;
if (nOu(SET.commentMacros)) SET.commentMacros = '';
if (nOu(SET.ipBlockHistoryCheckDelay)) SET.ipBlockHistoryCheckDelay = 500;
if (nOu(SET.identiconLibrary)) SET.identiconLibrary = 'jdenticon'; // jdenticon, identicon, gravatar, robohash
if (nOu(SET.emphasizeResesWhenMouseover)) SET.emphasizeResesWhenMouseover = false;
if (nOu(SET.defaultBoardArchiver)) SET.defaultBoardArchiver = 'namuwikiml';
if (nOu(SET.fastRevert)) SET.fastRevert = false;
if (nOu(SET.askFastRevertLog)) SET.askFastRevertLog = false;
if (nOu(SET.fastRevertDefaultLog)) SET.fastRevertDefaultLog = '반달 복구';
if (nOu(SET.lookupIqsOnKisaWhois)) SET.lookupIqsOnKisaWhois = false;
if (nOu(SET.hideHiddenResBody)) SET.hideHiddenResBody = false;
if (nOu(SET.robohashSet)) SET.robohashSet = 'any';
if (nOu(SET.addBatchBlindButton)) SET.addBatchBlindButton = false;
if (nOu(SET.slientBlind)) SET.slientBlind = false;
if (nOu(SET.userContribLinkOnBoard)) SET.userContribLinkOnBoard = true;
if (nOu(SET.addEditRequestCloseMenu)) SET.addEditRequestCloseMenu = false;
if (nOu(SET.defaultEditRequestCloseReason)) SET.defaultEditRequestCloseReason = '반달';
await SET.save();
}
let addItemToMemberMenu = skinDependency.addItemToMemberMenu;
function makeTabs() {
var div = document.createElement("div");
div.className = "nf-tabs";
div.innerHTML = "<ul></ul>";
var ul = div.querySelector("ul");
return {
tab: function (text) {
var item = document.createElement("li");
item.innerHTML = text;
item.addEventListener('click', function () {
var selectedTabs = div.querySelectorAll('li.selected');
for (var i = 0; i < selectedTabs.length; i++) {
selectedTabs[i].className = selectedTabs[i].className.replace(/selected/mg, '');
}
item.className = "selected";
});
ul.appendChild(item);
return {
click: function (callback) {
item.addEventListener('click', callback);
return this;
},
selected: function () {
if (item.className.indexOf('selected') == -1) item.className += ' selected';
return this;
}
};
},
get: function () {
return div;
}
};
}
// i : {author : {name, isIP}, defaultReason, defaultDuration}
function quickBlockPopup(i) {
let win = TooSimplePopup();
win.title("빠른 차단");
win.content(el => {
el.innerHTML = `<p>차단 대상 : ${encodeHTMLComponent(i.author.name)} ${i.author.isIP ? "<i>(IP)</i>" : "<i>(계정)</i>"}</p>차단 사유 : <input type="text" id="reason"></input><br>차단 기간 : <input type="number" id="duration"></input><a href="#" id="enterDuration">(간편하게 입력)</a><br><div id="allowLoginDiv">로그인 허용 : <input type="checkbox" id="allowLogin"></input></div><br><i>(참고 : NamuFix 설정에서 차단기간 기본값을 변경할 수 있습니다.)`
if (!i.author.isIP) {
el.querySelector('#allowLoginDiv')
.style.display = 'none';
}
el.querySelector('a#enterDuration')
.addEventListener('click', (evt) => {
evt.preventDefault();
enterTimespanPopup("차단기간 간편입력", (span) => {
if (span) el.querySelector('#duration')
.value = span;
})
})
el.querySelector('#duration')
.value = i.defaultDuration;
el.querySelector('#reason')
.value = i.defaultReason;
el.querySelector('#reason')
.style.width = '500px';
el.querySelector('#reason')
.style.maxWidth = '30vw';
win.button('닫기', win.close);
win.button('차단', () => {
if (i.author.isIP) {
namuapi.blockIP({
ip: i.author.name,
note: el.querySelector('#reason')
.value,
expire: el.querySelector('#duration')
.value,
allowLogin: el.querySelector('#allowLogin')
.checked
}, (err, data) => {
if (err) alert('오류 발생 : ' + err);
else win.close();
})
} else {
namuapi.blockAccount({
id: i.author.name,
note: el.querySelector('#reason')
.value,
expire: el.querySelector('#duration')
.value,
allowLogin: el.querySelector('#allowLogin')
.checked
}, (err, data) => {
if (err) alert('오류 발생 : ' + err);
else win.close();
})
}
});
});
}
function createDesigner(buttonBar) {
var Designer = {};
Designer.button = function (txt) {
var btn = document.createElement('button');
btn.className = 'NamaEditor NEMenuButton';
btn.setAttribute('type', 'button');
btn.innerHTML = txt;
buttonBar.appendChild(btn);
var r = {
click: function (func) {
btn.addEventListener('click', func);
return r;
},
hoverMessage: function (msg) {
btn.setAttribute('title', msg);
return r;
},
right: function () {
btn.className += ' NEright';
return r;
},
active: function () {
btn.setAttribute('active', 'yes');
return r;
},
deactive: function () {
btn.removeAttribute('active')
return r;
},
remove: function () {
btn.parentNode.removeChild(btn);
return r;
},
use: function () {
buttonBar.appendChild(btn);
return r;
}
};
return r;
};
Designer.dropdown = function (txt) {
var dropdownButton = document.createElement("div");
var dropdown = document.createElement("div");
var dropdownList = document.createElement("ul");
dropdownButton.innerHTML = '<div class="NEDropdownButtonLabel NamaEditor">' + txt + '</div>';
dropdownButton.className = 'NamaEditor NEMenuButton';
dropdown.className = 'NamaEditor NEDropDown';
dropdown.appendChild(dropdownList);
dropdownButton.appendChild(dropdown);
buttonBar.appendChild(dropdownButton);
var dbHover = false,
dbBHover = false;
dropdown.style.display = 'none';
dropdownButton.addEventListener('click', function () {
var dropdowns = buttonBar.querySelectorAll(".NamaEditor.NEMenuButton > .NamaEditor.NEDropDown");
for (var i = 0; i < dropdowns.length; i++) {
if (dropdowns[i] != dropdown) {
dropdowns[i].style.display = 'none';
dropdowns[i].parentNode.removeAttribute("hover");
} else if (dropdown.style.display.trim() == 'none') {
dropdown.style.display = '';
dropdownButton.setAttribute("hover", "yes");
} else {
dropdown.style.display = 'none';
dropdownButton.removeAttribute("hover");
}
}
});
var hr = {
button: function (iconTxt, txt) {
var liTag = document.createElement('li');
liTag.innerHTML = '<span class="NEHeadIcon">' + iconTxt + '</span><span class="NEDescText">' + txt + '</span>'
liTag.addEventListener('click', function () {
dropdown.style.display = '';
})
dropdownList.appendChild(liTag);
var r = {
icon: function (iconTxt) {
liTag.querySelector('.NEHeadIcon')
.innerHTML = iconTxt;
return r;
},
text: function (txt) {
liTag.querySElector('.NEDescText')
.innerHTML = txt;
return r;
},
hoverMessage: function (msg) {
liTag.setAttribute('title', msg);
return r;
},
click: function (handler) {
liTag.addEventListener('click', handler);
return r;
},
right: function () {
liTag.className += 'NEright';
return r;
},
remove: function () {
dropdownList.removeChild(liTag);
return r;
},
insert: function () {
dropdownList.appendChild(liTag);
return r;
},
backwalk: function () {
dropdownList.removeChild(ilTag);
dropdownList.appendChild(ilTag);
return r;
}
};
return r;
},
right: function () {
liTag.className += 'NEright';
return hr;
},
hoverMessage: function (txt) {
dropdownButton.setAttribute('title', txt);
return hr;
},
clear: function () {
dropdownList.innerHTML = '';
return hr;
}
};
return hr;
};
return Designer;
}
function createTextProcessor(txtarea) {
var r = {};
r.value = function () {
if (arguments.length == 0) return txtarea.value;
else txtarea.value = arguments[0];
};
r.selectionText = function () {
if (arguments.length == 0) return txtarea.value.substring(txtarea.selectionStart, txtarea.selectionEnd);
else {
var s = txtarea.selectionStart;
var t = txtarea.value.substring(0, txtarea.selectionStart);
t += arguments[0];
t += txtarea.value.substring(txtarea.selectionEnd);
txtarea.value = t;
txtarea.focus();
txtarea.selectionStart = s;
txtarea.selectionEnd = s + arguments[0].length;
}
};
r.selectionStart = function () {
if (arguments.length == 0) return txtarea.selectionStart;
else txtarea.selectionStart = arguments[0];
};
r.selectionTest = function (r) {
return this.selectionText()
.search(r) != -1;
};
r.valueTest = function (r) {
return this.value()
.search(r) != -1;
};
r.selectionEnd = function () {
if (arguments.length == 0) return txtarea.selectionEnd;
else txtarea.selectionEnd = arguments[0];
};
r.selectionLength = function () {
if (arguments.length == 0) return (txtarea.selectionEnd - txtarea.selectionStart);
else txtarea.selectionEnd = txtarea.selectionStart + arguments[0];
};
r.select = function (s, e) {
txtarea.focus();
txtarea.selectionStart = s;
if (typeof e !== 'undefined') txtarea.selectionEnd = e;
}
r.WrapSelection = function (l, r) {
if (arguments.length == 1) var r = l;
var t = this.selectionText();
if (typeof t === 'undefined' || t == null || t == '') t = '내용';
var s = this.selectionStart()
t = l + t + r;
this.selectionText(t);
this.select(s + l.length, s + t.length - r.length)
};
r.ToggleWrapSelection = function (l, r) {
function isWrapped(t) {
return t.indexOf(l) == 0 && t.lastIndexOf(r) == (t.length - r.length);
}
if (arguments.length == 1) var r = l;
var t = this.selectionText();
var t_m = this.value()
.substring(this.selectionStart() - l.length, this.selectionEnd() + r.length);
var wrappedInSelection = isWrapped(t);
var wrappedOutOfSelection = isWrapped(t_m);
if (wrappedInSelection) {
var s = this.selectionStart();
this.selectionText(t.substring(l.length, t.length - r.length));
this.select(s, s + t.length - l.length - r.length);
} else if (wrappedOutOfSelection) {
var s = this.selectionStart() - l.length;
this.selectionStart(s);
this.selectionEnd(s + t_m.length);
this.selectionText(t_m.substring(l.length, t_m.length - r.length));
this.select(s, s + t_m.length - l.length - r.length);
} else {
this.WrapSelection(l, r);
}
};
return r;
}
function getFile(callback, allowMultiple) {
if (typeof allowMultiple === "undefined") var allowMultiple = false;
var elm = document.createElement("input");
elm.setAttribute("type", "file");
if (allowMultiple) elm.setAttribute("multiple", "1");
elm.style.visibility = "hidden";
elm.setAttribute("accept", "image/*");
document.body.appendChild(elm);
elm.addEventListener('change', function (evt) {
callback(evt.target.files, function () {
document.body.removeChild(elm);
})
});
elm.click();
}
await INITSET();
if (SET.lookupIqsOnKisaWhois) {
let originalWhoisPopup = whoisPopup;
whoisPopup = function (ip, opts) { originalWhoisPopup(ip, opts ? opts : {iqs: true}); };
}
console.log("[NamuFix] 설정 초기화 완료");
if (SET.umiCookie.trim()
.length !== 0) {
document.cookie = 'umi=' + SET.umiCookie + ";path=/;domain=namu.wiki";
console.log("[NamuFix] umi 쿠키 설정 완료");
}
function editRequestBlockPopup(getENV) {
return function() {
let ENV = getENV();
let win = TooSimplePopup(), getSelectedEditReqs, getCloseInfo;
let refreshEditReqs = () => {
namuapi.getOpenEditRequests(editReqs => {
win.content(container => {
container.querySelector('.editreqs tbody').innerHTML = '';
for(let i = 0; i < editReqs.length; i++) {
let editReq = editReqs[i];
let row = document.createElement('tr');
row.innerHTML = `
<td><input type="checkbox" class="editreq_sel"></input></td>
<td><input type="radio" class="editreq_sel_help_a" name="editreq_sel_help_a"></input></td>
<td><input type="radio" class="editreq_sel_help_b" name="editreq_sel_help_b"></input></td>
<td><a href="${encodeHTMLComponent('/edit_request/' + editReq.no)}" target="_blank">${editReq.no}</a></td>
<td>${editReq.docName}</td>
`
row.dataset.editReq = JSON.stringify(editReq);
[...row.querySelectorAll('.editreq_sel_help_a, .editreq_sel_help_b')].forEach(v => v.addEventListener('click', evt => {
let a = [...container.querySelectorAll('.editreq_sel_help_a')].filter(i => i.checked)[0] || null,
b = [...container.querySelectorAll('.editreq_sel_help_b')].filter(i => i.checked)[0] || null;
if(a === null || b === null)
return;
let indexA = [...container.querySelector('table tbody').childNodes].indexOf(a.parentNode.parentNode),
indexB = [...container.querySelector('table tbody').childNodes].indexOf(b.parentNode.parentNode);
if (indexA > indexB) {
let tmp = indexA;
indexA = indexB;
indexB = tmp;
}
for(let i = indexA; i <= indexB; i++) {
let editReqRow = container.querySelectorAll('table tbody tr')[i];
editReqRow.querySelector('.editreq_sel').checked = true;
}
a.checked = false;
b.checked = false;
}));
container.querySelector('.editreqs tbody').appendChild(row);
}
});
});
};
win.title('편집요청 일괄 닫기 도구');
win.content(container => {
container.innerHTML = `
닫기 사유 : <input class="closeReason" type="input"></input><br>
<input class="doBlock" type="checkbox"></input>편집 요청을 닫은 후 일괄 차단 창 표시 (편집 요청 작성자들이 자동입력됩니다)<br>
※ 참고 : 닫기 버튼은 창을 닫는 버튼입니다.<br>
<br>
<table class="table editreqs">
<thead>
<tr>
<td colspan="3">선택</td>