-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathweiboFilter.user.js
More file actions
1521 lines (1503 loc) · 56.1 KB
/
weiboFilter.user.js
File metadata and controls
1521 lines (1503 loc) · 56.1 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
(function () {
// 工具函数
var $ = (function () {
// 按id选择元素(默认操作)
var $ = function (id) {
return document.getElementById(id);
};
$.version = Number('${REV}');
// 按CSS选择元素
$.select = function (css) {
return document.querySelector(css);
};
var CHROME_KEY_ROOT = 'weiboPlus.';
//#if GREASEMONKEY
if (window.chrome) {
if (localStorage.getItem(CHROME_KEY_ROOT + 'chromeExtInstalled')) {
console.warn('已安装插件版本,脚本停止运行!');
return undefined; // 如果已经(曾经)安装过插件则不再继续运行脚本
}
var version = window.navigator.userAgent.match(/Chrome\/(\d+)/) && RegExp.$1;
if (version === null || version >= 27) {
// Chrome 27开始不再支持通过脚本注入方式获取unsafeWindow,也不再提供unsafeWindow符号
if (typeof unsafeWindow === 'undefined') {
console.warn('不支持Chrome ' + version + ',脚本停止运行!');
return undefined;
} else {
// Chrome 26以上仍然可以通过Tampermonkey获得unsafeWindow
console.warn('使用第三方扩展提供的unsafeWindow');
$.window = unsafeWindow;
}
} else {
// Chrome 26及以前版本虽然存在unsafeWindow符号,但实际是沙箱中的window,但可以通过脚本注入方式获取unsafeWindow
$.window = (function () {
console.warn('Chrome ' + version + ': 通过注入脚本获取unsafeWindow');
var div = document.createElement('div');
div.setAttribute('onclick', 'return window;');
return div.onclick();
})();
}
} else if (typeof unsafeWindow === 'undefined') {
alert('当前版本的“眼不见心不烦”(v${VER})不支持您使用的浏览器。\n\n插件目前只对Firefox和Chrome浏览器提供官方支持。');
return undefined;
} else {
$.window = unsafeWindow;
}
//#elseif CHROME
// Chrome插件版本主程序注入页面环境,可直接获取window对象
$.window = window;
localStorage.setItem(CHROME_KEY_ROOT + 'chromeExtInstalled', true);
//#endif
$.config = $.window.$CONFIG;
if (!$.config) {
//#if DEBUG
console.warn('找不到$CONFIG,脚本停止运行!');
//#endif
return undefined;
}
$.uid = $.config.uid;
if (!$.uid) {
//#if DEBUG
console.warn('找不到$CONFIG.uid,脚本停止运行!');
//#endif
return undefined;
}
$.oid = $.config.oid; // 页面uid(个人主页或单条微博的uid)
//#if GREASEMONKEY
if (!GM_getValue || (GM_getValue.toString && GM_getValue.toString().indexOf("not supported") > -1)) {
$.get = function (name, defVal, callback) {
var result = localStorage.getItem(CHROME_KEY_ROOT + name);
if (result === null) { result = defVal; }
if (typeof callback === 'function') {
callback(result);
} else {
return result;
}
};
$.set = function (name, value) {
localStorage.setItem(CHROME_KEY_ROOT + name, value);
};
} else {
$.get = function (name, defVal, callback) {
var result = GM_getValue(name, defVal);
if (typeof callback === 'function') {
callback(result);
} else {
return result;
}
};
$.set = GM_setValue;
}
//#elseif CHROME
var callbacks = {}, messageID = 0;
document.addEventListener('wbpPost', function (event) {
event.stopPropagation();
callbacks[event.detail.id](event.detail.value);
delete callbacks[event.detail.id];
});
$.get = function (name, defVal, callback, sync) {
// == LEGACY CODE START ==
// 将先前版本插件的设置从localStorage转移到chrome.storage.local
var lsName = 'weiboPlus.' + name, value = localStorage.getItem(lsName);
if (value !== null) {
localStorage.removeItem(lsName);
$.set(name, value);
return callback(value);
}
// == LEGACY CODE END ==
callbacks[++messageID] = callback;
document.dispatchEvent(new CustomEvent('wbpGet', { detail: {
name : name,
defVal : defVal,
id : messageID,
sync : sync
}}));
};
$.set = function (name, value, sync) {
document.dispatchEvent(new CustomEvent('wbpSet', { detail: {
name : name,
value : value,
sync : sync
}}));
};
//#endif
// 删除节点
$.remove = function (el) {
if (el) { el.parentNode.removeChild(el); }
};
// 绑定click事件
$.click = function (el, handler) {
if (el) { el.addEventListener('click', handler, false); }
};
// 返回当前页面的位置
$.scope = function () {
return document.body.classList.contains('B_index') ? 1 : document.body.classList.contains('B_profile') ? 2 : 0;
};
return $;
})();
if (!$) { return false; }
// == LEGACY CODE START ==
// 如果正在运行旧版微博则停止运行并显示提示
if ($.config.any && $.config.any.indexOf('wvr=5') === -1) {
if (confirm('您使用的“眼不见心不烦”版本(v${VER})不支持旧版微博。\n请升级到新版微博(V5),或使用较低版本(v1.0.6)的“眼不见心不烦”插件。\n如果您希望安装旧版“眼不见心不烦”,请点击“确认”。')) {
window.open('http://code.google.com/p/weibo-content-filter/downloads/list', '_blank');
}
return false;
}
// == LEGACY CODE END ==
function Options () {
// 各类型默认值
var typeDefault = {
keyword : [],
string : '',
bool : false,
radio : '',
array : [],
object : {},
internal : null
};
for (var option in this.items) {
if (this.items[option].length > 1) {
// 使用属性默认值
this[option] = this.items[option][1];
} else {
// 使用类型默认值
this[option] = typeDefault[this.items[option][0]];
}
}
}
Options.prototype = {
// 选项类型与默认值
items : {
version : ['internal', 0], // 内部变量:不在设置界面出现,不随设置导出
whiteKeywords : ['keyword'],
blackKeywords : ['keyword'],
grayKeywords : ['keyword'],
URLKeywords : ['keyword'],
sourceKeywords : ['keyword'],
sourceGrayKeywords : ['keyword'],
userBlacklist : ['array'],
tipBackColor : ['string', '#FFD0D0'],
tipTextColor : ['string', '#FF8080'],
readerModeIndex : ['bool'],
readerModeProfile : ['bool'],
readerModeTip : ['internal', false], // 内部变量:不在设置界面出现,不随设置导出
readerModeWidth : ['string', 750],
readerModeBackColor : ['string', 'rgba(100%,100%,100%,0.8)'],
mergeSidebars : ['bool'],
floatSetting : ['radio', 'Groups'],
unwrapText : ['bool'],
directBigImg : ['bool'],
directFeeds : ['bool'],
showAllGroups : ['bool'],
showAllMsgNav : ['bool'],
noDefaultFwd : ['bool'],
noDefaultCmt : ['bool'],
noDefaultGroupPub : ['bool'],
clearDefTopic : ['bool'],
overrideMyBack : ['bool'],
overrideOtherBack : ['bool'],
backColor : ['string', 'rgba(100%,100%,100%,0.2)'],
overrideMySkin : ['bool'],
overrideOtherSkin : ['bool'],
skinID : ['string', 'skinvip001'],
filterOthersOnly : ['bool'],
filterPaused : ['bool'],
filterSmiley : ['bool'],
filterPromotions : ['bool', true],
filterDeleted : ['bool'],
filterFeelings : ['bool'],
filterTaobao : ['bool'],
filterDupFwd : ['bool'],
maxDupFwd : ['string', 1],
filterFlood : ['bool'],
maxFlood : ['string', 5],
updateNotify : ['bool', true],
//#if CHROME
autoSync : ['bool', true],
//#endif
floatBtn : ['bool', true],
useCustomStyles : ['bool', true],
customStyles : ['string'],
hideMods : ['array']
},
// 去除内部变量并转换为字符串
strip : function () {
var stripped = {};
for (var option in this.items) {
if (this.items[option][0] !== 'internal') {
stripped[option] = this[option];
}
}
return JSON.stringify(stripped);
},
// 保存设置
save : function (noSync) {
this.version = $.version;
$.set($.uid.toString(), JSON.stringify(this));
//#if CHROME
if (!noSync && $options.autoSync) {
// 不必同步内部变量
$.set($.uid.toString(), this.strip(), true);
}
//#endif
},
// 载入/导入设置,输入的str为undefined(首次使用时)或string(非首次使用和导入设置时)
load : function (str) {
var parsed = {};
if (str) {
try {
parsed = JSON.parse(str.replace(/\n/g, ''));
if (typeof parsed !== 'object') { throw 0; }
} catch (e) {
parsed = {};
str = null; // 出错,最后返回false
}
}
// 填充选项
for (var option in this.items) {
if (option in parsed) {
this[option] = parsed[option];
}
}
return (str !== null);
}
};
var $options = new Options();
var $dialog = (function () {
var shown = false, dialog, content, STK;
var getDom = function (node) {
// 首页与主页API不一致
return content ? content.getDom(node) : dialog.getDomList()[node];
};
var bind = function (node, func, event) {
STK.core.evt.addEvent(getDom(node), event || 'click', func);
};
// 从显示列表建立关键词数组
var getKeywords = function (id, attr) {
return Array.prototype.map.call(getDom(id).childNodes, function (keyword) {
return attr ? keyword.getAttribute(attr) : keyword.textContent;
});
};
// 将关键词添加到显示列表
var addKeywords = function (id, list, attr) {
var keywords;
if (list instanceof Array) {
keywords = list;
} else {
keywords = [];
var str = ' ' + getDom(list).value + ' ', regex = new RegExp('(\\s"([^"]+)"\\s|\\s([^\\s]+)\\s)', 'g'), result;
while ((result = regex.exec(str)) !== null) {
keywords.push(result[2] || result[3]); // 提取关键词
--regex.lastIndex;
}
}
var illegalRegex = keywords.filter(function (keyword) {
if (!keyword || getKeywords(id, attr).indexOf(keyword) > -1) { return false; }
var keywordLink = document.createElement('a');
// 关键词是正则表达式?
if (keyword.length > 2 && keyword.charAt(0) === '/' && keyword.charAt(keyword.length - 1) === '/') {
try {
// 尝试创建正则表达式,检验正则表达式的有效性
// 调用test()是必须的,否则浏览器可能跳过该语句
RegExp(keyword.substring(1, keyword.length - 1)).test('');
} catch (e) {
return true;
}
keywordLink.className = 'regex';
}
keywordLink.title = '点击删除';
keywordLink.setAttribute('action-type', 'remove');
if (attr) { keywordLink.setAttribute(attr, keyword); }
keywordLink.href = 'javascript:void(0)';
keywordLink.textContent = keyword;
getDom(id).appendChild(keywordLink);
return false;
});
if (!(list instanceof Array)) {
// 在文本框中显示无效的正则表达式并闪烁提示
getDom(list).value = illegalRegex.join(' ');
if (illegalRegex.length) {
// 首页与主页API不一致
(STK.common.extra ? STK.common.extra.shine : STK.kit.extra.shine)(getDom(list));
}
}
};
var usercardLoaded = false;
// 将用户添加到屏蔽用户列表
var addUsers = function (id, list) {
var updateOnly = !list, div = getDom(id);
// 整个列表只载入一次
if (updateOnly && usercardLoaded) { return; }
var users = updateOnly ? getKeywords(id, 'uid') : getDom(list).value.split(' '),
unprocessed = users.length, unfound = [], searcher, params =
{ onComplete : function (result, data) {
var link;
if (updateOnly) {
link = div.querySelector('a[uid="' + data.id + '"]');
} else {
link = document.createElement('a');
}
if (result.code === '100000') { // 成功
var img = result.data.match(/<img[^>]+>/)[0];
if (!updateOnly) { data.id = img.match(/uid="([^"]+)"/)[1]; }
// 防止重复添加
if (updateOnly || getKeywords(id, 'uid').indexOf(data.id) === -1) {
link.innerHTML = '<img width="50" height="50" ' + img.match(/src="[^"]+"/)[0] + ' /><br />' + img.match(/title="([^"]+)"/)[1];
if (!updateOnly) {
// 添加新的用户
link.title = '点击删除';
link.href = 'javascript:void(0)';
link.setAttribute('uid', data.id);
link.setAttribute('action-type', 'remove');
div.appendChild(link);
}
}
} else if (updateOnly) {
link.innerHTML += '<br />(未找到)';
} else {
unfound.push(data.name);
}
if (--unprocessed === 0) {
// 全部处理完成,在文本框中显示未被添加的用户并闪烁提示
getDom(list).value = unfound.join(' ');
if (unfound.length) {
// 首页与主页API不一致
(STK.common.extra ? STK.common.extra.shine : STK.kit.extra.shine)(getDom(list));
}
}
}
};
// 首页与主页API不一致
if (STK.common.trans) {
searcher = STK.common.trans.relation.getTrans(document.domain === 'www.weibo.com' ? 'userCard2_abroad' : 'userCard2', params);
} else {
searcher = STK.conf.trans.card.getTrans(document.domain === 'www.weibo.com' ? 'userCard_abroad' : 'userCard', params);
}
users.forEach(function (user) {
var request = { type : 1 };
if (updateOnly) {
request.id = user;
} else {
request.name = user;
}
searcher.request(request);
});
usercardLoaded = true;
};
// 返回当前设置(可能未保存)
var exportSettings = function () {
var options = new Options(), radio;
for (var option in options.items) {
switch (options.items[option][0]) {
case 'keyword':
options[option] = getKeywords(option + 'List');
break;
case 'string':
options[option] = getDom(option).value;
break;
case 'bool':
options[option] = getDom(option).checked;
break;
case 'radio':
radio = getDom('tabs').querySelector('input[type="radio"][name="' + option + '"]:checked');
options[option] = radio ? radio.value : '';
break;
case 'array':
options[option] = [];
break;
case 'object':
options[option] = {};
break;
case 'internal':
// 内部变量保持不变
// WARNING: 内部变量如果是数组或对象,以下的浅拷贝方式可能导致设置的意外改变
options[option] = $options[option];
break;
}
}
options.userBlacklist = getKeywords('userBlacklist', 'uid');
for (var module in $page.modules) {
if (getDom('hide' + module).checked) {
options.hideMods.push(module);
}
}
getDom('settingsString').value = options.strip();
return options;
};
// 更新设置窗口内容,exportSettings()的反过程
var importSettings = function (options) {
var radio;
for (var option in options.items) {
switch (options.items[option][0]) {
case 'keyword':
getDom(option).value = '';
getDom(option + 'List').innerHTML = '';
addKeywords(option + 'List', options[option]);
break;
case 'string':
getDom(option).value = options[option];
break;
case 'bool':
getDom(option).checked = options[option];
break;
case 'radio':
radio = getDom('tabs').querySelector('input[type="radio"][name="' + option + '"][value="' + options[option] + '"]');
if (radio) { radio.checked = true; }
break;
}
}
getDom('userBlacklistNew').value = '';
getDom('userBlacklist').innerHTML = '';
addKeywords('userBlacklist', options.userBlacklist, 'uid');
usercardLoaded = false;
var tipBackColor = getDom('tipBackColor').value,
tipTextColor = getDom('tipTextColor').value,
tipSample = getDom('tipSample');
tipSample.style.backgroundColor = tipBackColor;
tipSample.style.borderColor = tipTextColor;
tipSample.style.color = tipTextColor;
for (var module in $page.modules) {
getDom('hide' + module).checked = (options.hideMods.indexOf(module) > -1);
}
getDom('settingsString').value = options.strip();
};
// 创建设置窗口
var createDialog = function () {
// 由于操作是异步进行的,脚本载入时STK可能尚未载入,尤其是在Firefox中
// 鉴于只有$dialog使用STK,将其设置为内部变量,仅在打开设置窗口时载入
STK = $.window.STK;
if (!STK) {
console.warn('页面尚未载入完成,无法打开设置页面!');
return false;
}
var HTML = '${HTML}', events;
dialog = STK.ui.dialog({isHold: true});
dialog.setTitle('“眼不见心不烦”(v${VER})设置');
// 首页与主页API不一致
if (dialog.getDom) {
content = STK.ui.mod.layer(HTML);
dialog.setContent(content.getOuter());
events = STK.core.evt.delegatedEvent(content.getDom('tabs'));
} else {
//content = STK.ui.mod.layer({template: HTML, appendTo: null});
dialog.setContent(HTML);
events = STK.core.evt.delegatedEvent(dialog.getDomList(true).tabs); // true用于更新DOM缓存(只需做一次)
}
// 修改屏蔽提示颜色事件
bind('tipBackColor', function () {
getDom('tipSample').style.backgroundColor = this.value;
}, 'blur');
bind('tipTextColor', function () {
getDom('tipSample').style.borderColor = this.value;
getDom('tipSample').style.color = this.value;
}, 'blur');
// 添加关键词按钮点击事件
events.add('add', 'click', function (action) {
addKeywords(action.data.list, action.data.text);
});
// 清空关键词按钮点击事件
events.add('clear', 'click', function (action) {
getDom(action.data.list).innerHTML = '';
});
// 删除关键词事件
events.add('remove', 'click', function (action) {
$.remove(action.el);
});
// 添加用户按钮点击事件
events.add('addUser', 'click', function (action) {
addUsers(action.data.list, action.data.text);
});
// 复选框标签点击事件
bind('outer', function (event) {
var node = event.target;
// 标签下可能有span等元素
if (node.parentNode && node.parentNode.tagName === 'LABEL') {
node = node.parentNode;
}
if (node.tagName === 'LABEL') {
event.preventDefault();
event.stopPropagation();
if (node.getAttribute('for')) {
// 有for属性则使用之
getDom(node.getAttribute('for')).click();
} else {
// 默认目标在标签之前(同级)
node.previousSibling.click();
}
}
});
// 标签点击事件
bind('tabHeaders', function (event) {
var node = event.target;
if (node && node.tagName === 'A') {
node.className = 'current';
getDom(node.getAttribute('tab')).style.display = '';
Array.prototype.forEach.call(this.childNodes, function (child) {
if (node !== child) {
child.className = '';
getDom(child.getAttribute('tab')).style.display = 'none';
}
});
}
});
// 点击“设置导入/导出”标签时更新内容
bind('tabHeaderSettings', exportSettings);
// 点击“用户”标签时载入用户黑名单头像
bind('tabHeaderUser', function () { addUsers('userBlacklist'); });
bind('hideAll', function () {
for (var module in $page.modules) {
getDom('hide' + module).checked = true;
}
});
bind('hideInvert', function () {
for (var module in $page.modules) {
var item = getDom('hide' + module);
item.checked = !item.checked;
}
});
// 对话框按钮点击事件
bind('import', function () {
var options = new Options();
if (options.load(getDom('settingsString').value)) {
importSettings(options);
alert('设置导入成功!');
} else {
alert('设置导入失败!\n设置信息格式有问题。');
}
});
//#if DEBUG
bind('execute', function () {
var snippet = getDom('debugSnippet').value;
//#if CHROME
if (getDom('extScope').checked) {
document.dispatchEvent(new CustomEvent('wbpDebug', { detail: {
snippet : snippet
}}));
return;
}
//#endif
try {
console.log(eval('(function(){' + snippet + '})();'));
} catch (err) {
console.error(err);
}
});
//#endif
bind('OK', function () {
$options = exportSettings();
$options.save();
$filter();
$page();
dialog.hide();
});
bind('cancel', dialog.hide);
STK.custEvent.add(dialog, 'hide', function () {
shown = false;
});
return true;
};
// 显示设置窗口
var show = function () {
if (!dialog && !createDialog()) {
return;
}
shown = true;
importSettings($options);
if (getDom('tabHeaderUser').classList.contains('current')) {
addUsers('userBlacklist');
}
dialog.show().setMiddle();
};
show.shown = function () {
return shown;
};
return show;
})();
// 关键词过滤器
var $filter = (function () {
var forwardFeeds = {}, floodFeeds = {};
// 搜索指定文本中是否包含列表中的关键词
var search = function (str, key) {
var text = str.toLowerCase(), keywords = $options[key];
if (str === '' || keywords.length === 0) { return ''; }
var matched = keywords.filter(function (keyword) {
if (!keyword) { return false; }
if (keyword.length > 2 && keyword.charAt(0) === '/' && keyword.charAt(keyword.length - 1) === '/') {
try {
// 尝试匹配正则表达式
return (RegExp(keyword.substring(1, keyword.length - 1)).test(str));
} catch (e) { }
} else {
return keyword.split('+').every(function (k) { return text.indexOf(k.toLowerCase()) > -1; });
}
return false;
});
return matched.length ? matched[0] : '';
};
// 获取微博正文
var converter = document.createElement('div');
var getText = function (content) {
// 替换表情,去掉标签
if ($options.filterSmiley) {
converter.innerHTML = content.innerHTML.replace(/<img[^>]+alt="(\[[^\]">]+\])"[^>]*>/g, '$1')
.replace(/<\/?[^>]+>/g, '').replace(/[\r\n\t]/g, '').trim();
// 利用未插入文档的div进行HTML反转义
return converter.textContent;
}
return content.textContent.replace(/[\r\n\t]/g, '').trim();
};
// 过滤微博来源
var searchSource = function (source, keywords) {
if (!source) {
source = '未通过审核应用';
} else {
// 过长的应用名称会被压缩,完整名称存放在title属性中
source = source.title || source.textContent;
}
return search(source, keywords);
};
// 过滤单条微博
var apply = function (feed) {
if (feed.firstChild && feed.firstChild.className === 'wbpTip') {
// 已被灰名单屏蔽过,移除屏蔽提示和分隔线
feed.removeChild(feed.firstChild);
feed.removeChild(feed.firstChild);
}
var mid = feed.getAttribute('mid');
if (!mid) { return false; } // 动态没有mid
var scope = $.scope(), isForward = (feed.getAttribute('isforward') === '1');
var author = (scope === 1) ? feed.querySelector('.WB_detail>.WB_info .WB_name') : null,
content = feed.querySelector('.WB_detail>.WB_text'),
source = feed.querySelector('.WB_detail>.WB_func .WB_from>em+a'),
fwdAuthor = feed.querySelector('.WB_media_expand .WB_info .WB_name'),
fwdContent = feed.querySelector('.WB_media_expand .WB_text'),
fwdSource = feed.querySelector('.WB_media_expand .WB_func .WB_from>em+a'),
fwdLink = feed.querySelector('.WB_media_expand .WB_func .WB_time'),
fmid = isForward ? (fwdLink ? fwdLink.href : null) : null,
uid = author ? author.getAttribute('usercard').match(/id=(\d+)/)[1] : null,
fuid = fwdAuthor ? fwdAuthor.getAttribute('usercard').match(/id=(\d+)/)[1] : null;
if (!content) { return false; }
var text = (scope === 1) ? '@' + author.getAttribute('nick-name') + ': ' : '';
text += getText(content);
if (isForward && fwdAuthor && fwdContent) {
// 转发内容
text += '////@' + fwdAuthor.getAttribute('nick-name') + ': ' + getText(fwdContent);
}
//#if DEBUG
console.log(text);
//#endif
if ($options.filterPaused || // 暂停屏蔽
($options.filterOthersOnly && feed.querySelector('.WB_screen a[action-type="feed_list_delete"]')) || // 不要屏蔽自己的微博(判据:工具栏是否有“删除”)
search(text, 'whiteKeywords')) { // 白名单条件
//#if DEBUG
console.warn('↑↑↑【白名单微博不会被屏蔽】↑↑↑');
//#endif
} else if ((function () { // 黑名单条件
// 屏蔽推广微博
if (scope === 1 && $options.filterPromotions && feed.getAttribute('feedtype') === 'ad') {
//#if DEBUG
console.warn('↑↑↑【推广微博被屏蔽】↑↑↑');
//#endif
return true;
}
// 屏蔽已删除微博的转发(是转发但无转发作者)
if ($options.filterDeleted && isForward && !fwdAuthor) {
//#if DEBUG
console.warn('↑↑↑【已删除微博的转发被屏蔽】↑↑↑');
//#endif
return true;
}
// 用户黑名单
if ((scope === 1 && author && $options.userBlacklist.indexOf(uid) > -1) ||
(isForward && fwdAuthor && (scope === 1 || fuid !== $.oid) && $options.userBlacklist.indexOf(fuid) > -1)) {
//#if DEBUG
console.warn('↑↑↑【被用户黑名单屏蔽】↑↑↑');
//#endif
return true;
}
// 屏蔽写心情微博
if ($options.filterFeelings && feed.querySelector('div.feelingBoxS')) {
//#if DEBUG
console.warn('↑↑↑【写心情微博被屏蔽】↑↑↑');
//#endif
return true;
}
// 屏蔽淘宝和天猫链接微博
if ($options.filterTaobao && feed.querySelector('a>i.icon_fl_tb, a>i.icon_fl_tmall')) {
//#if DEBUG
console.warn('↑↑↑【含有淘宝或天猫商品链接的微博被屏蔽】↑↑↑');
//#endif
return true;
}
// 屏蔽指定来源
if (searchSource(source, 'sourceKeywords') ||
(isForward && searchSource(fwdSource, 'sourceKeywords'))) {
//#if DEBUG
console.warn('↑↑↑【被来源黑名单屏蔽】↑↑↑');
//#endif
return true;
}
// 反版聊(屏蔽重复转发)
if ($options.filterDupFwd && fmid && forwardFeeds[fmid]) {
if (forwardFeeds[fmid].length >= Number($options.maxDupFwd) && forwardFeeds[fmid].indexOf(mid) === -1) {
//#if DEBUG
console.warn('↑↑↑【被反版聊功能屏蔽】↑↑↑');
//#endif
return true;
}
}
// 反刷屏(屏蔽同一用户大量发帖)
if ($options.filterFlood && uid && floodFeeds[uid]) {
if (floodFeeds[uid] >= Number($options.maxFlood) && floodFeeds[uid].indexOf(mid) === -1) {
//#if DEBUG
console.warn('↑↑↑【被反刷屏功能屏蔽】↑↑↑');
//#endif
return true;
}
}
// 在微博内容中搜索屏蔽关键词
if (search(text, 'blackKeywords')) {
//#if DEBUG
console.warn('↑↑↑【被关键词黑名单屏蔽】↑↑↑');
//#endif
return true;
}
// 搜索t.cn短链接
return Array.prototype.some.call(feed.getElementsByTagName('A'), function (link) {
if (link.href.substring(0, 12) === 'http://t.cn/' && search(link.title, 'URLKeywords')) {
//#if DEBUG
console.warn('↑↑↑【被链接黑名单屏蔽】↑↑↑');
//#endif
return true;
}
return false;
});
})()) {
feed.style.display = 'none'; // 直接隐藏,不显示屏蔽提示
return true;
} else { // 灰名单条件
// 搜索来源灰名单
var sourceKeyword = searchSource(source, 'sourceGrayKeywords'),
keyword = search(text, 'grayKeywords');
if (!sourceKeyword && isForward) {
sourceKeyword = searchSource(fwdSource, 'sourceGrayKeywords');
}
if (keyword || sourceKeyword) {
// 找到了待隐藏的微博
var authorClone;
if (scope === 1) {
// 添加隐藏提示链接
authorClone = author.cloneNode(false);
authorClone.textContent = '@' + author.getAttribute('nick-name');
authorClone.className = '';
}
var showFeedLink = document.createElement('a');
showFeedLink.href = 'javascript:void(0)';
showFeedLink.className = 'wbpTip';
var keywordLink = document.createElement('a');
keywordLink.href = 'javascript:void(0)';
keywordLink.className = 'wbpTipKeyword';
keywordLink.textContent = keyword || sourceKeyword;
if (scope === 1) {
showFeedLink.appendChild(document.createTextNode('本条来自'));
showFeedLink.appendChild(authorClone);
showFeedLink.appendChild(document.createTextNode('的微博因'));
} else if (scope === 2) {
showFeedLink.appendChild(document.createTextNode('本条微博因'));
}
showFeedLink.appendChild(document.createTextNode(keyword ? '内容包含“' : '来源名称包含“'));
showFeedLink.appendChild(keywordLink);
showFeedLink.appendChild(document.createTextNode('”而被隐藏,点击显示'));
var line = document.createElement('div');
line.className = 'S_line2 wbpTipLine';
feed.insertBefore(line, feed.firstChild);
feed.insertBefore(showFeedLink, line);
return true;
}
}
// 显示微博并记录
feed.style.display = '';
if (!$options.filterPaused) {
if ($options.filterDupFwd && fmid) {
if (!forwardFeeds[fmid]) {
forwardFeeds[fmid] = [];
}
if (forwardFeeds[fmid].indexOf(mid) === -1) {
forwardFeeds[fmid].push(mid);
}
}
if ($options.filterFlood && uid) {
if (!floodFeeds[uid]) {
floodFeeds[uid] = [];
}
if (floodFeeds[uid].indexOf(mid) === -1) {
floodFeeds[uid].push(mid);
}
}
}
return false;
};
// 过滤所有微博
var applyToAll = function () {
// 过滤所有微博
if ($.scope()) {
forwardFeeds = {}; floodFeeds = {};
Array.prototype.forEach.call(document.querySelectorAll('.WB_feed_type'), apply);
}
};
// 屏蔽提示相关事件的冒泡处理
var bindTipOnClick = function (node) {
if (!node) { return; }
$.click(node, function (event) {
var node = event.target;
if (node && node.tagName === 'A') {
if (node.className === 'wbpTipKeyword') {
$dialog();
event.stopPropagation(); // 防止事件冒泡触发屏蔽提示的onclick事件
} else if (node.className === 'wbpTip') {
$.remove(node.nextSibling); // 分隔线
$.remove(node);
}
}
});
};
// 处理动态载入的微博
if ($.scope()) {
bindTipOnClick($.select('.WB_feed'));
}
// 点击“查看大图”事件拦截处理
document.addEventListener('click', function (event) {
if (!$options.directBigImg || !event.target) { return true; }
var actionType = event.target.getAttribute('action-type'), actionData = event.target.getAttribute('action-data');
if ((actionType === 'images_view_tobig' || actionType === 'widget_photoview') &&
actionData && actionData.match(/pid=(\w+)&mid=(\d+)&uid=(\d+)/)) {
window.open('http://photo.weibo.com/' + RegExp.$3 +
'/wbphotos/large/mid/' + RegExp.$2 +
'/pid/' + RegExp.$1, '_blank');
event.stopPropagation();
}
}, true); // 使用事件捕捉以尽早触发事件,避免与新浪自带事件撞车
document.addEventListener('DOMNodeInserted', function (event) {
var node = event.target;
if ($.scope() === 0 || node.tagName !== 'DIV') { return; }
if (node.classList.contains('WB_feed_type')) {
// 处理动态载入的微博
apply(node);
} else if (node.classList.contains('W_loading')) {
var requestType = node.getAttribute('requesttype');
// 仅在搜索和翻页时需要初始化反刷屏/反版聊记录
// 其它情况(新微博:newFeed,同页接续:lazyload)下不需要
if (requestType === 'search' || requestType === 'page') {
forwardFeeds = {}; floodFeeds = {};
}
} else if (node.classList.contains('WB_feed') || node.querySelector('.WB_feed')) {
// 微博列表作为pagelet被一次性载入
bindTipOnClick(node);
applyToAll();
}
}, false);
return applyToAll;
})();
// 修改页面
var $page = (function () {
// 模块屏蔽设置
var modules = {
Ads : '#plc_main [id^="pl_rightmod_ads"], #Box_right [id^="ads_"], #trustPagelet_zt_hottopicv5 [class*="hot_topicad"], div[ad-data], .WB_feed .popular_buss',
Stats : '#pl_rightmod_myinfo .user_atten',
ToMe : '#pl_leftnav_common a[href^="/direct/tome"]',
Friends : '#pl_leftnav_group > div[node-type="groupList"] > .level_1_Box, #pl_leftnav_common .level_1_Box > form.left_nav_line',
InterestUser : '#trustPagelet_recom_interestv5', // 动态右边栏
Topic : '#trustPagelet_zt_hottopicv5', // 动态右边栏
Member : '#trustPagelet_recom_memberv5',
WeiboRecom : '#trustPagelet_recom_weibo', // 动态右边栏
LocationRecom : '#trustPagelet_recom_location', // 动态右边栏
MusicRecom : '#trustPagelet_recom_music', // 动态右边栏
MovieRecom : '#trustPagelet_recom_movie', // 动态右边栏
BookRecom : '#trustPagelet_recom_book', // 动态右边栏
Notice : '#pl_rightmod_noticeboard',
Footer : 'div.global_footer',
RecommendedTopic : '#pl_content_publisherTop div[node-type="recommendTopic"]',
App : '#pl_leftnav_app',
Avatar : 'dl.W_person_info',
CommentTip : 'div[node-type="feed_privateset_tip"]',
MemberTip : 'div[node-type="feed_list_shieldKeyword"]',
TimelineMods : '.B_index .WB_feed .WB_feed_type:not([mid])',
TopicCard : '.WB_feed_spec[exp-data*="value=1022-topic"]',
LocationCard : '.WB_feed_spec[exp-data*="value=1022-place"]',
FollowGuide : '.layer_userguide_brief',
HomeTip : '#pl_content_hometip',
IMNews : '.WBIM_news',
TopComment : '#pl_content_commentTopNav',
RecomFeed : 'div[node-type="feed_list_recommend"]',
MyRightSidebar : '.B_profile .W_main_c, .B_profile .WB_feed .repeat .input textarea { width: 100% } .B_profile .WB_feed .WB_screen { margin-left: 928px } .B_profile .W_main_2r',
ProfCover : '.profile_top .pf_head { top: 10px } .profile_top .pf_info { margin-top: 20px } .profile_top .S_bg5 { background-color: transparent !important } .profile_pic_top',
ProfStats : '.profile_top .user_atten',
MyMicroworld : '.W_main_c div[id^="Pl_Official_MyMicroworld__"]',
Relation : '.W_main_2r div[id^="Pl_Core_RightUserGrid__"]',
Album : '.W_main_2r div[id^="Pl_Core_RightPicMulti__"]',
ProfHotTopic : '.W_main_2r div[id^="Pl_Core_RightTextSingle__"]',
ProfHotWeibo : '.W_main_2r div[id^="Pl_Core_RightPicText__"]',
FeedRecom : '.W_main_2r div[id^="Pl_Third_Inline__"]',
MemberIcon : '.W_ico16[class*="ico_member"], .ico_member_dis',
VerifyIcon : '.approve, .approve_co',
DarenIcon : '.ico_club',
VgirlIcon : '.ico_vlady',
TaobaoIcon : '.ico_taobao',
FifaIcon : '.icon_fifa'
};
// 显示设置链接
var showSettingsBtn = function () {
if (!$('wbpShowSettings')) {
var groups = $.select('ul.sort') || $.select('ul.sort_profile');
if (!groups) { return false; }
var tab = document.createElement('li');
tab.id = 'wbpShowSettings';
tab.className = 'item';
tab.innerHTML = '<a href="javascript:void(0)" class="item_link S_func1">眼不见心不烦</a>';
$.click(tab, $dialog);
groups.appendChild(tab);
}
return true;
};
// 应用浮动按钮设置
var toggleFloatSettingsBtn = (function () {
var floatBtn = null, lastTime = null, lastTimerID = null;
// 仿照STK.comp.content.scrollToTop延时100ms显示/隐藏,防止scroll事件调用过于频繁
function scrollDelayTimer() {
if ((lastTime !== null && (new Date()).getTime() - lastTime < 500)) {
clearTimeout(lastTimerID);
lastTimerID = null;
}
lastTime = (new Date()).getTime();
lastTimerID = setTimeout(function () {
if (floatBtn) {
floatBtn.style.visibility = window.scrollY > 0 ? 'visible' : 'hidden';
}
}, 100);
}
return function () {
if (!$options.floatBtn && floatBtn) {
window.removeEventListener('scroll', scrollDelayTimer, false);
$.remove(floatBtn);
floatBtn = null;
return true;
} else if ($options.floatBtn && !floatBtn) {
var scrollToTop = $('base_scrollToTop');