aboutsummaryrefslogtreecommitdiffstats
path: root/direct_delb.js
blob: 6c57daa5176ed9102a5bb5728bd9a42fafac2b83 (plain)
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
// Vimperator plugin: direct_delb
// Maintainer: mattn <mattn.jp@gmail.com> - http://mattn.kaoriya.net
(function(){
    var isNormalize = true;

    try{
        var XMigemoCore = Components
            .classes['@piro.sakura.ne.jp/xmigemo/factory;1']
            .getService(Components.interfaces.pIXMigemoFactory)
            .getService("ja");
    }catch(ex){
        var XMigemoCore = undefined;
    }

    // copied from AutoPagerize (c) id:swdyh
    function getElementsByXPath(xpath, node) {
        node = node || document;
        var nodesSnapshot = (node.ownerDocument || node).evaluate(xpath, node, null,
                XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null);
        var data = [];
        for (var i = 0, l = nodesSnapshot.snapshotLength; i < l;
                data.push(nodesSnapshot.snapshotItem(i++)));
        return (data.length > 0) ? data : null;
    }

    function getFirstElementByXPath(xpath, node) {
        node = node || document;
        var result = (node.ownerDocument || node).evaluate(xpath, node, null,
                XPathResult.FIRST_ORDERED_NODE_TYPE, null);
        return result.singleNodeValue ? result.singleNodeValue : null;
    }

    // copied from Pagerization (c) id:ofk
    function parseHTML(str) {
        str = str.replace(/^[\s\S]*?<html(?:\s[^>]+?)?>|<\/html\s*>[\S\s]*$/ig, '');
        var res = document.implementation.createDocument(null, 'html', null);
        var range = document.createRange();
        range.setStartAfter(window.content.document.body);
        res.documentElement.appendChild(res.importNode(range.createContextualFragment(str), true));
        return res;
    }

    function getNormalizedPermalink(url){
        var xhr = new XMLHttpRequest();
        xhr.open("GET","http://api.pathtraq.com/normalize_url?url=" + url,false);
        xhr.send(null);
        if(xhr.status != 200){
            liberator.echoerr("Pathtraq: FAILED to normalize URL!!");
            return undefined;
        }
        return xhr.responseText;
    }

    liberator.plugins.delicious_tags = [];
    var deliciousUser, deliciousPassword;

    try {
        var passwordManager = Cc["@mozilla.org/login-manager;1"].getService(Ci.nsILoginManager);
        var logins = passwordManager.findLogins({}, 'https://secure.delicious.com', 'https://secure.delicious.com', null);
        if(logins.length)
            [deliciousUser, deliciousPassword] = [logins[0].username, logins[0].password];
        else
        liberator.echoerr("DeliciousBookmark: account not found");
    } catch(ex) { }

    function getTags(){
        const feed_url = 'https://api.del.icio.us/v1/tags/get';
        var xhr = new XMLHttpRequest();
        xhr.onreadystatechange = function(){
            if(xhr.readyState == 4){
                if(xhr.status == 200) {
                    var tags = xhr.responseXML.getElementsByTagName('tag');
                    for each(var tag in tags)
                        liberator.plugins.delicious_tags.push(tag.getAttribute('tag'));
                    liberator.echo("DeliciousBookmark: Tag parsing is finished. Taglist length: " + tags.length);
                } else
                    throw new Error(xhr.statusText)
            }
        };
        xhr.open("GET", feed_url, true, deliciousUser, deliciousPassword);
        xhr.send(null);
    }

    getTags();

    function addDeliciousBookmarks(url, title, comment, normalize) {
        var target = normalize ? getNormalizedPermalink(url) : url;
        var tags = [];
        var re = /\[([^\]]+)\]([^\[].*)?/g;
        if (/^\[.*\]/.test(comment)) {
            var tag, text;
            while((tag = re.exec(comment))) {
                [, tag, text] = tag;
                tags.push(tag);
            }
            comment = text || '';
        }
        var request_url = 'https://api.del.icio.us/v1/posts/add?' + [
            ['url', target], ['description', title], ['extended', comment], ['tags', tags.join(' ')]
        ].map(function(p) p[0] + '=' + encodeURIComponent(p[1])).join('&');
        var xhr = new XMLHttpRequest();
        xhr.onreadystatechange = function(){
            if(xhr.readyState == 4){
                if(xhr.status == 200)
                    liberator.echo("DeliciousBookmark: success");
                else
                    liberator.echoerr("DeliciousBookmark:" + xhr.statusText);
            }
        };
        xhr.open("GET", request_url, true);
        xhr.send(null);
    }

    liberator.commands.addUserCommand(['delbtags'],"Update DeliciousBookmark Tags", getTags, {});
    liberator.commands.addUserCommand(['delb'],"Post to DeliciousBookmark",
        function(arg){
            addDeliciousBookmarks(liberator.buffer.URL, liberator.buffer.title, arg, isNormalize);
        },{
            completer: function(filter){
                var match_result = filter.match(/(\[[^\]]*\])?\[?(.*)/); //[all, commited, now inputting]
                var m = new RegExp(XMigemoCore ? "^(" + XMigemoCore.getRegExp(match_result[2]) + ")" : "^" + match_result[2],'i');
                var completionList = [];
                for each(var tag in liberator.plugins.delicious_tags)
                    if(m.test(tag)){
                        completionList.push([(match_result[1] || "") + "[" + tag + "]","Tag"]);
                    }
                return [0, completionList];
            }
        }
    );
})();
>)!='string') throw [name, value]; return variables.get(name); }, begin: function () { let lastValue; for(let i=0,len=arguments.length;i<len;++i) { lastValue = self.eval(arguments[i]); } return lastValue; }, and: function () { let lastValue; for(let i=0,len=arguments.length;i<len;++i) { if(!(lastValue = self.eval(arguments[i]))) break; } return lastValue; }, or: function () { let lastValue; for(let i=0,len=arguments.length;i<len;++i) { if(lastValue = self.eval(arguments[i])) break; } return lastValue; }, loop: function (cond, exp) { let mainThread = services.get('threadManager').mainThread; let f = function() { if(!self.eval(cond)) return; self.eval(exp); mainThread.processNextEvent(true); f(); }; setTimeout(f, 1); }, get: function (dst, prop) { let edst = self.eval({xpath: self.eval(dst)}); if(!edst) throw [dst, prop]; return edst[prop]; }, set: function (dst, src, prop) { let edst = self.eval({xpath: self.eval(dst)}); if(!edst) throw [dst, src, prop]; edst[prop] = self.eval(src); return edst[prop]; }, xpath: function (xpath) { if((typeof xpath)!='string'||!win.document) throw [name, value]; return buffer.evaluateXPath(xpath, win.document).snapshotItem(0); }, value: function (dst, src) { let edst = self.eval({xpath: self.eval(dst)}); if(!edst) throw [dst, src]; if(src!=undefined) { // set edst.value = self.eval(src); } return edst.value; }, click: function (dst) { let edst = self.eval({xpath: self.eval(dst)}); if(!edst) throw [dst]; edst.click(); return edst; }, follow: function(dst, where) { let edst = self.eval({xpath: self.eval(dst)}); if(!edst) throw [dst, where]; buffer.followLink(edst, where?where:liberator.CURRENT_TAB) return edst; }, remove: function (dst) { let edst = self.eval({xpath: self.eval(dst)}); if(!edst) throw [dst]; edst.parentNode.removeChild(edst); return edst; }, saveLink: function (dst, skipPrompt) { let edst = self.eval({xpath: self.eval(dst)}); if(!edst) throw [dst, skipPrompt]; buffer.saveLink(edst, skipPrompt); return edst; }, innerText: function (dst, src) { let edst = self.eval({xpath: self.eval(dst)}); if(!edst) throw [dst, src]; if(src==undefined) { // get return edst.innerText; } let esrc = self.eval(src); edst.innerText = esrc; return esrc; }, innerHTML: function (dst, src) { let edst = self.eval({xpath: self.eval(dst)}); if(!edst) throw [dst, src]; if(src==undefined) { // get return edst.innerHTML; } let esrc = self.eval(src); edst.innerHTML = esrc; return esrc; }, url: function() { if(!win.document) throw []; return win.document.location.href; }, prompt: function(message, init) { if(!win) throw [message, init]; return win.prompt(message||'', init||''); }, sleep: function(delay) { return liberator.sleep(delay); }, close: function() { if(!win) throw []; return win.close(); }, jseval: function() { let f = arguments[0]; let args = Array.prototype.slice.call(arguments); args.shift(); if(typeof f!='function') throw [f].concat(args); return f.apply(this, args); }, showVariables: function (names) { if(!win.document) throw [names]; actor.showVariables(win.document, names); }, eval: function(exp) { switch(typeof exp) { default: case 'bolean': case 'number': case 'string': case 'function': return exp; case 'object': for(let sym in exp) { let args = exp[sym]; if(debugMode) logger.log('{'+sym+': '+args+'}'); try { if(args instanceof Array) { return self[sym].apply(this, args); } return self[sym](args); } catch(args if args instanceof Array) { let msg = '{'+sym+': ['+args.join(',')+']}'; liberator.reportError(msg); return false; } } } }, }; return self; } //}}} function createLabel(doc, labelID) { let label; if(!(label = doc.getElementById(labelID))) { label = doc.createElement('pre'); label.id = VariablesLabelID; label.style.position = 'absolute'; label.style.top = '0px'; label.style.left = '0px'; label.style.margin = '0px'; label.style.padding = '0px'; label.style.fontSize = '80%'; label.style.border = '1px solid #ccc'; label.style.backgroundColor = '#fff'; label.style.textAlign = 'left'; label.style.zIndex = '100'; doc.body.appendChild(label); } return label; } function urlmatcher(url) { return function(scenario) { if(scenario.pattern) { let pattern = scenario.pattern; switch(typeof pattern) { case 'string': if(url.indexOf(pattern)==-1) return false; break; case 'object': if(!pattern.test(url)) return false; break; } } if(scenario.ignore) { let ignore = scenario.ignore; switch(typeof ignore) { case 'string': if(url.indexOf(ignore)!=-1) return false; break; case 'object': if(ignore.test(url)) return false; break; } } return true; } } let self = { enabled: true, readScenarioDirectory: function(name, fun) { io.getRuntimeDirectories(SCENARIO_DIR).forEach(function(dir) { $U.readDirectory(dir.path, name, fun); }); }, loadLocalScenario: function(name) { if(!name) name = '\.js$'; if(liberator.globalVariables.userScenario) loadedScenarioList.push(liberator.globalVariables.userScenario); self.readScenarioDirectory(name, function(file) { logger.log('load scenario '+file.path); io.source(file.path); }); loadedScenarioList.forEach(function(list) { for(let event in list) { self.addListener(event, list[event]); } }); }, showVariables: function(doc, names) { if(!doc) doc = window.content.document; if(!names) { names = [name for([name, value] in variables)]; } let label = createLabel(doc, VariablesLabelID); label.innerHTML = [arg+': '+variables.get(arg) for each(arg in names)].join("\n"); }, clear: function () { variables.clear(); }, addListener: function (eventType, scenarioList) { if(!scenarioList || scenarioList.length==0) return scenarioList; getBrowser().addEventListener(eventType, function (event) { if (!self.enabled) return; let context = ScenarioContext(event); let url = context.url(); if(!url) return false; let matchfun = urlmatcher(url); scenarioList.forEach(function(scenario) { if(matchfun(scenario)) { context.eval({begin: scenario.action}); } }); }, true); }, }; return self; }; //}}} let actor = plugins.scenarioActor = ScenarioActor(); let loadedScenarioList = plugins.scenarioActor.loadedScenarioList = []; actor.enabled = !/^(?:false|0)$/i.test(liberator.globalVariables.scenario_actor_enabled); actor.loadLocalScenario(); commands.addUserCommand(['scenarioclear'], 'clear scenario-actor variables', actor.clear, { argCount: '0', }); commands.addUserCommand(['scenariovars'], 'show scenario-actor variables', function(args) { actor.showVariables(window.content.document); }, { argCount: '0', }); commands.addUserCommand(['scenarioload'], 'load local scenario', function(args) { if(args.length) { args.forEach(actor.loadLocalScenario); } else { actor.loadLocalScenario(); } }, { argCount: '*', completer: function (context, args) { let completions = []; actor.readScenarioDirectory(name, function(file) { completions.push([file.leafName, '']); }); context.completions = completions; } }); commands.addUserCommand(['scenario'], 'turn on/off scenario-actor', function(args) { if (args.length) { switch (args[0].toLowerCase()) { case 'on': actor.enabled = true; break; case 'off': actor.enabled = false; break; default: liberator.echoerr('Invalid argument: ' + args[0]); return; } } else { actor.enabled = !actor.enabled; } liberator.echo('scenario-actor was ' + (actor.enabled ? 'enabled' : 'disabled')); }, { argCount: '*', completer: function (context, args) { context.completions = [['on', 'enable scenario-actor'], ['off', 'disable scenario-actor']]; } }); })(); // vim: set fdm=marker sw=4 ts=4 et: