forked from ywzhaiqi/userChromeJS
-
Notifications
You must be signed in to change notification settings - Fork 0
/
SITEINFO_Writer.uc.js
3271 lines (2951 loc) · 133 KB
/
SITEINFO_Writer.uc.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 SITEINFO_Writer.uc.js
// @description uAutoPagerize 中文增强版的站点配置辅助工具,大幅修改了原脚本
// @namespace http://d.hatena.ne.jp/Griever/
// @author Griever, 深度修改 by ywzhaiqi
// @update 2013-8-22
// @include main
// @include chrome://browser/content/devtools/framework/toolbox.xul
// @compatibility Firefox 20 - firefox 23
// @charset UTF-8
// @version 0.5
// @homepageURL https://github.com/ywzhaiqi/userChromeJS/tree/master/uAutoPagerize
// @reviewURL http://bbs.kafan.cn/thread-1555846-1-1.html
// @note fix compatibility for firefox 23a1 by lastdream2013
// @note まだこれからつくり込む段階
// @note ツールメニューから起動する
// ==/UserScript==
/**
* 1、大幅修改以适应 uAutoPagerize 中文规则增强版,移植了 AutoPager 的自动识别功能
* 2、给自带的开发工具右键添加 "复制 xpath 的功能"
*/
location == "chrome://browser/content/browser.xul" && (function(css){
if (window.siteinfo_writer) {
window.siteinfo_writer.destroy();
delete window.siteinfo_writer;
}
let { classes: Cc, interfaces: Ci, utils: Cu, results: Cr } = Components;
if (!window.Services) Cu.import("resource://gre/modules/Services.jsm");
var ns = window.siteinfo_writer = {
USE_FIREBUG: false,
get prefs() {
delete this.prefs;
return this.prefs = Services.prefs.getBranch("siteinfo_writer.");
},
init: function() {
try{
ns["USE_FIREBUG"] = ns.prefs.getBoolPref("USE_FIREBUG");
}catch(e) {}
this.style = addStyle(css);
var overlay = '\
<overlay xmlns="http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul" \
xmlns:html="http://www.w3.org/1999/xhtml"> \
<window id="main-window">\
<vbox id="sw-container" class="sw-add-element" hidden="true">\
<hbox id="sw-hbox">\
<toolbarbutton id="sw-discovery" tooltiptext="自动识别,来自 AutoPager" oncommand="siteinfo_writer.discoveryAll(true, true);" />\
<toolbarbutton label="查看规则" oncommand="siteinfo_writer.toJSON();"/>\
<toolbarbutton label="查看规则(SP)" oncommand="siteinfo_writer.toSuperPreLoaderFormat();"/>\
<toolbarbutton id="sw-curpage-info" label="读取当前页面规则" oncommand="siteinfo_writer.getCurPageInfo();"/>\
<toolbarbutton label="从剪贴板读取规则" oncommand="siteinfo_writer.readFromClipboard();"/>\
<toolbarbutton id="sw-launch" label="启动规则" tooltiptext="启动uAutoPagerize" oncommand="siteinfo_writer.launch();"/>\
<checkbox id="sw-useiframe" label="useiframe" checked="false"/>\
<checkbox id="sw-inspect-by-firebug" label="用Firebug查看元素" checked="' + this.USE_FIREBUG +'" \
oncommand="siteinfo_writer.USE_FIREBUG=!siteinfo_writer.USE_FIREBUG" \
hidden="' + !window.Firebug + '" />\
<spacer flex="1"/>\
<toolbarbutton class="tabs-closebutton" oncommand="siteinfo_writer.hide();"/>\
</hbox>\
<grid id="sw-grid">\
<columns>\
<column />\
<column />\
<column />\
<column flex="1"/>\
<column />\
<column />\
</columns>\
<rows>\
<row>\
<label value="name" />\
<hbox />\
<toolbarbutton class="inspect"\
tooltiptext="提取网站名称"\
oncommand="siteinfo_writer.siteName.value = content.document.title;"/>\
<textbox id="sw-siteName"/>\
<hbox />\
<hbox />\
</row>\
<row>\
<label value="url" />\
<hbox />\
<toolbarbutton class="inspect"\
tooltiptext="提取地址"\
oncommand="siteinfo_writer.setUrl();"/>\
<textbox id="sw-url" oninput="siteinfo_writer.onInput(event);"/>\
<hbox />\
<hbox />\
</row>\
<row>\
<label value="nextLink" />\
<toolbarbutton class="discovery"\
tooltiptext="自动识别下一页链接"\
oncommand="siteinfo_writer.discovery(\'nextLink\');"/>\
<toolbarbutton class="inspect"\
tooltiptext="提取XPath"\
oncommand="siteinfo_writer.inspect(\'nextLink\');"/>\
<textbox id="sw-nextLink" \
onkeypress="if(event.keyCode == 13){ siteinfo_writer.xpathTest(\'nextLink\'); }"/>\
<toolbarbutton class="check"\
tooltiptext="测试XPath"\
oncommand="siteinfo_writer.xpathTest(\'nextLink\');"/>\
<toolbarbutton class="inspect-devtools"\
tooltiptext="使用Firebug或自带开发工具查看元素"\
oncommand="siteinfo_writer.inspectMix(\'nextLink\');"/>\
</row>\
<row>\
<label value="pageElement" />\
<toolbarbutton class="discovery"\
tooltiptext="自动识别内容"\
oncommand="siteinfo_writer.discovery(\'pageElement\');"/>\
<toolbarbutton class="inspect"\
tooltiptext="提取XPath"\
oncommand="siteinfo_writer.inspect(\'pageElement\');"/>\
<textbox id="sw-pageElement" \
onkeypress="if(event.keyCode == 13){ siteinfo_writer.xpathTest(\'pageElement\'); }"/>\
<toolbarbutton class="check"\
tooltiptext="测试XPath"\
oncommand="siteinfo_writer.xpathTest(\'pageElement\');"/>\
<toolbarbutton class="inspect-devtools"\
tooltiptext="使用Firebug或自带开发工具查看元素"\
oncommand="siteinfo_writer.inspectMix(\'pageElement\');"/>\
</row>\
<row hidden="true">\
<label value="insertBefore" />\
<hbox />\
<toolbarbutton class="inspect"\
tooltiptext="提取XPath"\
oncommand="siteinfo_writer.inspect(\'insertBefore\');"/>\
<textbox id="sw-insertBefore" />\
<toolbarbutton class="check"\
tooltiptext="测试XPath"\
oncommand="siteinfo_writer.xpathTest(\'insertBefore\');"/>\
<toolbarbutton class="inspect-devtools"\
tooltiptext="使用Firebug或自带开发工具查看元素"\
oncommand="siteinfo_writer.inspectMix(\'insertBefore\');"/>\
</row>\
</rows>\
</grid>\
</vbox>\
</window>\
</overlay>';
overlay = "data:application/vnd.mozilla.xul+xml;charset=utf-8," + encodeURI(overlay);
window.userChrome_js.loadOverlay(overlay, window.siteinfo_writer);
gBrowser.mPanelContainer.addEventListener('DOMContentLoaded', this, true);
window.addEventListener('unload', this, false);
},
observe: function (aSubject, aTopic, aData) {
if (aTopic == "xul-overlay-merged") {
this.popup = $("mainPopupSet").appendChild($C("menupopup", {
id: "sw-popup",
class: "sw-add-element",
}));
var menuitem = $C("menuitem", {
id: "sw-menuitem",
class: "sw-add-element",
label: "辅助定制翻页规则",
oncommand: "siteinfo_writer.show();",
});
$("devToolsSeparator").parentNode.insertBefore(menuitem, $("devToolsSeparator"));
setTimeout(function() {
if (!window.uAutoPagerize) {
$("sw-launch").hidden = true;
return;
};
let aupPopup = $("uAutoPagerize-popup");
if (aupPopup) {
let newMenuItem = menuitem.cloneNode(false);
newMenuItem.setAttribute("id", "sw-popup-menuitem");
aupPopup.appendChild(newMenuItem);
}
}, 2000);
this.container = $("sw-container");
this.url = $("sw-url");
this.siteName = $("sw-siteName");
this.nextLink = $("sw-nextLink");
this.pageElement = $("sw-pageElement");
this.useiframe = $("sw-useiframe");
this.insertBefore = $("sw-insertBefore");
this.nextLink.addEventListener("popupshowing", siteinfo_writer.textboxPopupShowing, false);
this.pageElement.addEventListener("popupshowing", siteinfo_writer.textboxPopupShowing, false);
this.insertBefore.addEventListener("popupshowing", siteinfo_writer.textboxPopupShowing, false);
this.nextLink.setAttribute("tooltiptext", '例:auto; 或 css;a#pnnext 或 //a[@id="pnnext"] 或 //div[@id="footlink"]/descendant::a[text()="下一页"]');
this.pageElement.setAttribute("tooltiptext", '例:css;#ires 或 //div[@id="ires"]');
}
},
uninit: function () {
try{
ns.prefs.setBoolPref("USE_FIREBUG", ns["USE_FIREBUG"]);
}catch(e) {}
gBrowser.mPanelContainer.removeEventListener('DOMContentLoaded', this, true);
window.removeEventListener('unload', this, false);
},
destroy: function() {
$A(document.getElementsByClassName("sw-add-element")).forEach(function(e){
e.parentNode.removeChild(e);
})
this.style && this.style.parentNode.removeChild(this.style);
this.uninit();
},
handleEvent: function(event){
switch(event.type){
case "DOMContentLoaded":
var doc = event.target,
win = doc.defaultView;
if(win.location.hostname == 'ap.teesoft.info'){
addContentStyle(doc, ".install{ display: block !important; }\
#need-ap { display: none !important; }");
this.fixAutoPagerBug(doc);
// 点击 install 自动安装
doc = win.wrappedJSObject.document;
var evt = doc.createEvent("Events");
var self = this;
doc.addEventListener(evt, function(event){
var ids = event.target.textContent;
self.requestInfoFromAP(ids);
}, false);
}
break;
case "unload":
this.uninit(event);
break;
}
},
textboxPopupShowing: function(event) {
event.currentTarget.removeEventListener(event.type, arguments.callee, false);
var popup = event.originalTarget;
var type = event.currentTarget.id.replace("sw-", "");
popup.appendChild($C("menuseparator", {}));
popup.appendChild($C("menuitem", {
label: '查看元素',
accesskey: 'Q',
oncommand: "siteinfo_writer.inspectMix('" + type + "');",
}));
popup.appendChild($C("menuitem", {
label: '@class="xxx" → contains()',
oncommand: "siteinfo_writer.class2contains('" + type + "');",
}));
popup.appendChild($C("menuitem", {
label: 'contains() → @class="xxx"',
oncommand: "siteinfo_writer.contains2class('" + type + "');",
}));
},
show: function(reset) {
let info;
if(!reset && content.ap && content.ap.info)
info = content.ap.info;
else
[, info] = uAutoPagerize.getInfo();
if(info){
this.setAllValue(info);
}else{
// this.discoveryAll(true, false);
info = {
nextLink: "auto;"
}
this.setAllValue(info)
this.setUrl();
}
this.container.hidden = false;
},
hide: function() {
this.container.hidden = true;
},
setUrl: function() {
var location = content.location;
// var url = location.protocol + "//" + location.host + location.pathname;
var url = location.href;
this.url.value = "^" + url.replace(/[()\[\]{}|+.,^$?\\]/g, '\\$&');
this.url.className = "";
},
setAllValue: function(info){
this.siteName.value = info.siteName || info.name || content.document.title;
this.nextLink.value = info.nextLink || "";
this.pageElement.value = info.pageElement || "";
this.useiframe.checked = !!info.useiframe;
this.insertBefore.value = info.insertBefore || "";
if(info.url){ // 转为字符串
let url = info.url;
let type = typeof(url);
let urlValue;
switch(type){
case "object":
urlValue = String(url).replace(/^\//, '').replace(/\/[img]*$/, '').replace(/\\\//g, '/');
break;
case "string":
if(url.match(/^\/(.*)\/[igm]?$/))
urlValue = RegExp.$1.replace(/\\\/\\\//g, '\/\/');
else
urlValue = url.replace(/\\\//g, '/').replace(/\\\\/g, '\\');
break;
}
if(urlValue)
this.url.value = urlValue;
else
this.setUrl();
}
},
toJSON: function() {
var json = "\t{";
json += "name: '" + this.siteName.value + "',\n";
json += "\t\turl: '" + this.url.value.replace(/\\/g, "\\\\") + "',\n";
json += "\t\tnextLink: '" + this.nextLink.value.replace(/'/g, '"') + "',\n";
json += "\t\tpageElement: '" + this.pageElement.value.replace(/'/g, '"') + "',\n";
if(this.useiframe.checked)
json += "\t\tuseiframe: true,\n";
if (this.insertBefore.value)
json += "\t\tinsertBefore: '" + this.insertBefore.value + "',\n";
json += "\t\texampleUrl: '" + content.location.href + "',\n";
json += "\t},";
var r=confirm("翻页规则(按确定键将其复制到剪贴板):"+'\n\n' + json);
if(r){
try{
Components.classes["@mozilla.org/widget/clipboardhelper;1"].getService(Components.interfaces.nsIClipboardHelper)
.copyString(json);
}catch(e){
alert(e);
}
}
},
toSuperPreLoaderFormat: function() {
var spdb = "\t{";
spdb += "siteName: '" + this.siteName.value + "',\n";
spdb += "\t\turl: /" + this.url.value.replace(/\//g, "\\\/") + "/i,\n";
spdb += "\t\texampleUrl: '" + content.location.href + "',\n";
spdb += "\t\tnextLink: '" + this.nextLink.value + "',\n";
spdb += "\t\tautopager: {\n";
spdb += "\t\t\tpageElement: '" + this.pageElement.value + "',\n";
if (this.useiframe.checked)
spdb += "\t\tuseiframe: true,\n";
if (this.insertBefore.value)
spdb += "\t\t\tHT_insert: ['" + this.insertBefore.value + "', 1],\n";
spdb += "\t\t}\n";
spdb += "\t},";
var r = confirm("翻页规则(SuperPreLoader格式)(按OK键将其复制到剪贴板):" + '\n\n' + spdb);
if (r) {
try {
Components.classes["@mozilla.org/widget/clipboardhelper;1"].getService(Components.interfaces.nsIClipboardHelper).copyString(spdb);
} catch (e) {
alert(e);
}
}
},
getCurPageInfo: function(){
if(!uAutoPagerize) return;
var list = uAutoPagerize.getInfoFromURL();
if(!list) return;
var self = this;
if(list.length == 1){
this.setValueFromCurPage(list[0]);
}else{
this.curPageInfos = list;
let range = document.createRange();
range.selectNodeContents(self.popup);
range.deleteContents();
range.detach();
for (let [i, info] in Iterator(list)) {
let label = (info.siteName || info.name || info.url);
if(info.type)
label += '[' + info.type + ']';
let menuitem = document.createElement("menuitem");
menuitem.setAttribute("label", label);
menuitem.setAttribute("tooltiptext", "右键点击复制");
menuitem.setAttribute("siteinfo_num", i);
self.popup.appendChild(menuitem);
// 设置当前页面的 info 为粗体
if(content.ap && content.ap.info){
let infoC = content.ap.info;
if(info.url == infoC.url && info.nextLink == infoC.nextLink && info.pageElement == infoC.pageElement)
menuitem.setAttribute("class", "sw-highlight-info");
}
menuitem.addEventListener("click", function(e){
var num = e.target.getAttribute("siteinfo_num");
var info = self.curPageInfos[num];
if(e.button == 0){
self.setValueFromCurPage(info);
}else if (e.button == 2){
copyToClipboard(siteInfoToString(info));
// alert("该站点信息已经复制");
}
});
}
self.popup.openPopup($("sw-curpage-info"), "before_after");
}
},
setValueFromCurPage: function(info){
if(typeof info == 'number'){
info = this.curPageInfos[info];
}
this.setAllValue(info);
this.urlTest();
},
// autopager 查询网站 install(a36122) 没有引号的错误。
fixAutoPagerBug: function(doc){
var link, links, onclick;
links = doc.querySelectorAll("a.install");
for (var i = links.length - 1; i >= 0; i--) {
link = links[i];
onclick = link.getAttribute("onclick").replace(/install\((\w+)\)/, "install('$1')");
link.setAttribute("onclick", onclick);
}
},
requestInfoFromAP: function(ids){
var url;
if(ids.indexOf('a') == 0){ // json 格式
url = "http://wedata.net/items/" + ids.slice(1) + ".json"
}else{
url = "http://www.teesoft.info/autopager/down/" + ids;
}
log("Request: " + url);
var xhr = new XMLHttpRequest();
xhr.onload = function(){
ns.parseInfoFromAP(xhr);
};
xhr.open("GET", url, true);
xhr.send(null);
},
parseInfoFromAP: function(xhr){
if(this.container.hidden == true){
this.container.hidden = false;
}
if(xhr.responseXML){
log("parseInfoFromAP: XML");
var xml = xhr.responseXML.documentElement;
var site = getFirstElementByXPath("/autopager/site", xml);
var urlPattern = getFirstElementByXPath("//urlPattern", site).textContent;
var urlIsRegex = getFirstElementByXPath("//urlIsRegex", site).textContent;
this.url.value = (urlIsRegex == 'false') ? wildcardToRegExpStr(urlPattern) : urlPattern;
this.siteName.value = getFirstElementByXPath("//desc", site).textContent.replace("AutoPager rule for ", "");
this.nextLink.value = getFirstElementByXPath("//linkXPath", site).textContent;
this.pageElement.value = getFirstElementByXPath("//contentXPath", site).textContent;
}else{
log("parseInfoFromAP: JSON");
var info = JSON.parse(xhr.responseText);
this.setAllValue({
name: info.name,
url: info.data.url,
nextLink: info.data.nextLink,
pageElement: info.data.pageElement
});
}
},
readFromClipboard: function(){
var dataStr = readFromClipboard();
if(dataStr){
var info = this.parseStringInfo(dataStr);
if(info){
this.setAllValue(info);
}else{
alert("剪贴板的数据格式不正确");
}
}
},
parseStringInfo: function(str) {
var lines = str.split(/\r\n|\r|\n/)
var re = /(^[^:]*?):(.*)$/
var strip = function(str) {
return str.replace(/^[\s\t{'"]*/, '').replace(/[\s,}'"]*$/, '')
}
var info = {}
for (var i = 0; i < lines.length; i++) {
lines[i] = strip(lines[i]);
if (lines[i].match(re)) {
info[RegExp.$1.trim()] = strip(RegExp.$2).trim();
}
}
var isValid = function(info) {
var infoProp = ['url', 'nextLink', 'pageElement']
for (var i = 0; i < infoProp.length; i++) {
if (!info[infoProp[i]]) {
return false
}
}
return true
}
return isValid(info) ? info : null
},
launch: function() {
if(content.ap){
var r = confirm("uAutopagerize 已经运行,是否重新启动?");
if(r)
content.ap.destroy(true);
else
return;
}
var i = {};
["url", "nextLink", "pageElement", "insertBefore"].forEach(function(type) {
if (this[type].value)
i[type] = this[type].value
}, this);
if (!i.url || !i.nextLink || !i.pageElement)
return alert("指定的值无效");
if(this.useiframe.checked)
i.useiframe = true;
let [index, nextLink, pageElement] = uAutoPagerize.getInfo([i], content);
if (index === 0) {
if (content.AutoPagerize && content.AutoPagerize.launchAutoPager)
content.AutoPagerize.launchAutoPager([i]);
else alert("翻页规则语法正确,但uAutoPagerize无法执行,可能uAutoPagerize被禁用或没有安装脚本");
} else {
alert("有错误发生,请分别检查 url、nextLink、pageElement 是否正确");
}
},
inspect: function(aType){
var self = this;
if(window.dactyl)
dactyl.execute(":js modes.push(modes.PASS_THROUGH, null, null);")
Aardvark.start(function(elem){
let items = self.findXPathes(elem);
self.createXPathPopupMenu(items, aType);
if(window.dactyl)
dactyl.execute(":js modes.cleanup();")
});
},
inspect_old: function(aType) {
if (this._inspect){
try{ // 防止页面刷新后出现的 dead object 错误
this._inspect.uninit();
}catch(e) {}
}
var self = this;
this._inspect = new Inspector(content, aType, function(items) {
if (items.length) {
self.createXPathPopupMenu(items, aType);
}
self._inspect = null;
});
},
devtools: null,
inspectMix: function(aType) {
let xpath = this[aType].value;
let doc = content.document;
var elem;
try{
if(xpath.startsWith("css;"))
elem = doc.querySelector(xpath.slice(4))
else
elem = getFirstElementByXPath(xpath, doc);
}catch(e){
return;
}
if(!elem) return;
// 载入 devtools
if(!this.devtools)
this.devtools = this.loadDevtools();
// 已经存在则直接启动
if(window.Firebug && Firebug.isInitialized && Firebug.currentContext){
this.inspectWithFirebug(elem);
return;
}else{
// 检测自带开发工具是否已经启动
let target = this.devtools.TargetFactory.forTab(gBrowser.selectedTab);
let toolbox = gDevTools.getToolbox(target);
if(toolbox){
this.inspectWithDevtools(elem);
return;
}
}
// 不存在
if(window.Firebug && this.USE_FIREBUG){
this.inspectWithFirebug(elem);
}else{
this.inspectWithDevtools(elem);
}
},
inspectWithFirebug: function(elem){
Firebug.browserOverlay.startFirebug(function(Firebug){
Firebug.Inspector.inspectFromContextMenu(elem);
});
},
loadDevtools: function(){
/*
* 有这么变的吗,四个版本,变了三次地址!!!
*/
var devtools = {};
let version = Services.appinfo.version.split(".")[0];
let DEVTOOLS_URI;
if (version >= 24) {
DEVTOOLS_URI = "resource://gre/modules/devtools/Loader.jsm";
({devtools} = Cu.import(DEVTOOLS_URI, {}));
} else if (version < 24 && version >= 23) {
DEVTOOLS_URI = "resource:///modules/devtools/gDevTools.jsm";
({devtools} = Cu.import(DEVTOOLS_URI, {}));
} else if (version < 23 && version >= 20) {
DEVTOOLS_URI = "resource:///modules/devtools/Target.jsm";
devtools = Cu.import(DEVTOOLS_URI, {});
}
return devtools;
},
inspectWithDevtools: function(elem){
let tt = this.devtools.TargetFactory.forTab(gBrowser.selectedTab);
return gDevTools.showToolbox(tt, "inspector").then((function (elem) {
return function(toolbox) {
let inspector = toolbox.getCurrentPanel();
inspector.selection.setNode(elem, "Siteinfo-writer-Inspector");
}
})(elem));
},
discoveryResult: null,
discoveryAll: function(setValue, test){
this.discoveryResult = new autopagerDiscoveryResult(content.document, []);
if(setValue){
var linkXPath = this.discoveryResult.linkXPaths[0];
var contentXPath = this.discoveryResult.contentXPaths[0];
this.setAllValue({
nextLink: linkXPath && linkXPath.xpath,
pageElement: contentXPath && contentXPath.xpath
});
}
if(test){
this.xpathTest("pageElement");
setTimeout(function(self){
self.xpathTest("nextLink");
}, 2000, this)
}
},
discovery: function(aType){
if(!this.discoveryResult)
this.discoveryAll(false, false);
var items = [];
if(aType == 'nextLink'){
items = this.discoveryResult.linkXPaths;
}else if(aType == 'pageElement'){
items = this.discoveryResult.contentXPaths;
}
this.createXPathPopupMenu(items, aType);
},
createXPathPopupMenu: function(items, aType){
let range = document.createRange();
range.selectNodeContents(this.popup);
range.deleteContents();
range.detach();
for (let [i, item] in Iterator(items)) {
if(item == "-" ){
if(i == 0 || i == (items.length - 1))
break;
this.popup.appendChild(document.createElement("menuseparator"));
continue;
}
let menuitem = document.createElement("menuitem");
menuitem.setAttribute("label", item.xpath || item);
menuitem.setAttribute("oncommand", "siteinfo_writer['"+ aType +"'].value = this.getAttribute('label');" +
"siteinfo_writer.xpathTest('"+ aType +"');");
this.popup.appendChild(menuitem);
}
this.popup.openPopup(this.container, "before_start");
},
toClearElements: [],
xpathTest: function(aType) {
var textbox = this[aType]
if (!textbox || !textbox.value) return;
var selector = textbox.value;
var autoGetLink = uAutoPagerize.autoGetLink;
var doc = content.document;
var elements = [];
if(selector.startsWith("css;")){
selector = selector.slice(4);
if(selector)
elements = doc.querySelectorAll(selector);
else
return alert("css; 后面接css选择器,例如 css;#content");
}else if(autoGetLink && selector.trim() == "auto;"){
let nextLink = autoGetLink(doc);
if(nextLink)
elements = [nextLink];
else
return alert("自动查找没有找到下一页链接");
}else{
try{
elements = getElementsByXPath(selector, doc);
} catch (e) {
return alert(e);
}
}
if(elements[0]){
elements[0].scrollIntoView();
}else{
return alert("没有找到元素");
}
var self = this;
clearElementsStyle();
for (let [i, elem] in Iterator(elements)) {
if (!("orgcss" in elem))
elem.orgcss = elem.style.cssText;
elem.style.backgroundImage = "-moz-linear-gradient(magenta, plum)";
elem.style.outline = "1px solid magenta";
this.toClearElements.push(elem);
}
if (this.timer) {
clearTimeout(this.timer);
this.timer = null;
}
this.timer = setTimeout(clearElementsStyle, 5000);
function clearElementsStyle() {
for (let [i, elem] in Iterator(self.toClearElements)) {
if ("orgcss" in elem) {
elem.orgcss?
elem.style.cssText = elem.orgcss:
elem.removeAttribute("style");
delete elem.orgcss;
}
}
self.toClearElements = [];
}
},
urlTest: function() {
var urlValue = this.url.value;
if(urlValue.startsWith("wildc;"))
urlValue = wildcardToRegExpStr(urlValue.slice(6));
try {
var regexp = new RegExp(urlValue);
if (regexp.test(content.location.href))
this.url.classList.remove("error");
else
this.url.classList.add("error");
} catch (e) {
this.url.classList.add("error");
}
},
inputTimer: null,
onInput: function(event) {
if (this.inputTimer) {
clearTimeout(this.inputTimer);
}
var self = this;
this.inputTimer = setTimeout(function() {
self.urlTest();
}, 100);
},
class2contains: function(aType) {
this[aType].value = this.splitClass(this[aType].value);
},
contains2class: function(aType) {
this[aType].value = this.normalClass(this[aType].value);
},
splitClass: function(xpath) {
return xpath.replace(/@class=\"(.+?)\"/g, function(str, cls) {
cls = cls.replace(/\s+/g, " ").replace(/^\s+|\s+$/g, "").split(" ");
for (var i = 0, l = cls.length; i < l; i++) {
cls[i] = 'contains(concat(" ",normalize-space(@class)," "), " '+ cls[i] +' ")';
}
return cls.join(" and ");
});
},
normalClass: function(xpath) {
let r = /(?:contains\(concat\(\" \"\,normalize\-space\(@class\)\,\" \"\)\, \" .+? \"\)(?: and )?)+/g;
return xpath.replace(r, function(str) {
let cls = str.split(' and ').map(function(c) c.replace(/.*\" (.*) \".*/i, '$1') );
return '@class="'+ cls.join(' ') +'"';
});
},
findXPathes: function(elem){
var doc = elem.ownerDocument;
var items = [];
items = autopagerXPath.discoveryMoreLinks(doc, items, [elem]);
return items;
},
};
/**
* autopagerXPath,来自 Autopager 扩展
*/
var autopagerXPath = {
smarttext: "next|>|下一页|下一頁|翻页|翻下页|下一章|下一张|下一幅|下一节|下一篇|后一页|前进|下篇|后页|往后|次を表示",
discoverytext: "navbar|right_arrow|pagN|page|pages|paging|下页|次页|Volgende|Volg|Verder|Напред|Следва|Næste|Nächste|Naechste|Weiter|Vorwärts|Vorwaerts|Volgende|Continue|Onward|Venonta|Seuraava|Suivant|Prochaine|Επόμενη|Næst|Successive|Successiva|Successivo|Prossima|Prossime|Prossimo|Altra|Altro|次へ|다음|Neste|Dalej|Następna|Następne|Następny|Więcej|Próximo|Înainte|Înaintare|Următor|Următoare|След|Следующая|Siguiente|Próxima|Próximos|Nästa|Sonraki|Devam|İlerle",
MAXTextLength: 20,
MAXLevel: 6,
_existingSites: null,
get existingSites() {
if(this._existingSites == null){
let info_cn = window.uAutoPagerize.SITEINFO_CN || [];
this._existingSites = window.uAutoPagerize.MY_SITEINFO.concat(info_cn) || [];
}
return this._existingSites;
},
discoveryLink: function(doc, xpathes) {
var smarttext = this.smarttext;
var discoverytext = this.discoverytext;
var url = doc.documentURI;
var body = doc.documentElement.innerHTML;
var strs = (smarttext + "|" + discoverytext).split("|");
var texts = "|";
var ignoredTexts = "|";
for (var k = 0; k < strs.length; ++k)
strs[k] = strs[k].toLowerCase().replace(new RegExp(" ", "gm"), "");
for (var k = 0; k < strs.length; ++k) {
if (strs[k].length == 0)
continue;
if (texts.indexOf("|" + strs[k] + "|") == -1 && ignoredTexts.indexOf("|" + strs[k] + "|") == -1) {
if (body.indexOf(strs[k]) != -1)
texts = texts + strs[k] + "|";
else
ignoredTexts = ignoredTexts + strs[k] + "|";
}
}
var tmpPaths = this.convertToXpath(texts);
var links = [];
var item = null;
for (var i in tmpPaths) {
//get the nodes
var urlNodes = this.evaluate(doc, tmpPaths[i]);
if (urlNodes != null && urlNodes.length != 0) {
for (var level = 1; level < this.MAXLevel; level += 1) {
var items = this.getLinkXPathItemFromNodes(doc, urlNodes, level);
for (var l in items) {
item = items[l];
if (item != null)
this.addItem(doc, links, item);
}
}
}
}
//try the links next to this page
item = new autopagerXPathItem();
item.authority = 0.2;
item.xpath = "(//a[@href and @href = %href%]/following-sibling::a[1])[translate(text(),'0123456789','')='']";
this.addItem(doc, links, item);
item = new autopagerXPathItem();
item.authority = 0.1;
item.xpath = "(//a[@href and %href% = concat(%pathname%,@href) ]/following-sibling::a[1])[translate(text(),'0123456789','')='']";
this.addItem(doc, links, item);
item = new autopagerXPathItem();
item.authority = 0.1;
item.xpath = "(//a[@href and contains(@href , concat(%pathname% , %search%))]/following-sibling::a[1])[translate(text(),'0123456789','')='']";
this.addItem(doc, links, item);
item = new autopagerXPathItem();
item.authority = 0.1;
item.xpath = "(//a[@href and contains(concat(%pathname% , %search%),@href)]/following-sibling::a[1])[translate(text(),'0123456789','')='']";
this.addItem(doc, links, item);
item = new autopagerXPathItem();
item.authority = 0.12;
item.xpath = "(//a[@href and contains(@href , %href%)]/following-sibling::a[1])[translate(text(),'0123456789','')='']";
this.addItem(doc, links, item);
item = new autopagerXPathItem();
item.authority = 0.1;
item.xpath = "(//a[@href and contains(@href , %filename%)]/following-sibling::a[1])[translate(text(),'0123456789','')='']";
this.addItem(doc, links, item);
//try to find the page navigator, then find next links
var navBars = this.evaluate(doc, "//*[count(a[text() != '' and translate(text(),'0123456789','')=''])>=2]/a[text() != '' and translate(text(),'0123456789','')='']");
if (navBars && navBars.length != 0) {
for (var level = 1; level < this.MAXLevel; level += 1) {
var paths = this.anaLyzeNavbar(doc, navBars, level);
for (var i in paths) {
item = new autopagerXPathItem();
item.authority = (this.MAXLevel / level);
item.xpath = paths[i];
if (item.xpath.indexOf("//input") != -1)
item.authority = item.authority / 2;
this.addItem(doc, links, item);
}
}
}
item = new autopagerXPathItem();
item.xpath = "//*[count(a[text() != '' and translate(text(),'0123456789','')=''])>=2 ]/*[name()='STRONG' or name()='B']/following-sibling::a[1]";
item.authority = 4;
this.addItem(doc, links, item);
links = this.mergeXPath(links);
var newlinks = [];
for (var i = 0; i < links.length; ++i) {
if (links[i].authority > 0.005 && links[i].matchCount < 40)
newlinks.push(links[i])
}
links = this.sortItems(newlinks);
// try the existing site settings
links.push("-"); // 添加分隔符
Array.slice(this.existingSites).forEach(function(site){
var existes = links.filter(function(link){
return link.xpath == site.nextLink;
});
if(existes.length) return;
var nodes = autopagerXPath.evaluate(doc, site.nextLink);
if (nodes != null && nodes.length > 0) {
item = new autopagerXPathItem();
item.authority = 4;
item.xpath = site.nextLink
item.matchCount = nodes.length
item.existing = true;
links.push(item);
}
});
return links;
},
discoveryMoreLinks: function(doc, links, nodes) {
for (var level = 1; level < this.MAXLevel; level += 1) {
var items = this.getLinkXPathItemFromNodes(doc, nodes, level);
for (var i in items) {
var item = items[i];
if (item != null)
this.addItem(doc, links, item);
}
}
links = this.mergeXPath(links);
links = this.sortItems(links);
var newLinks = [];
//filter it again
for (var i = 0; i < links.length; i++) {
var item = links[i]
if (this.isMatchNodes(doc, item.xpath, nodes))
newLinks.push(item);
}
return newLinks;
},
discoveryContent: function(doc, xpathes) {
var node = doc.body;
var url = doc.documentURI;
var items = [];
var links = [];
var item = null;
var knowLinks = [];