summaryrefslogtreecommitdiff
path: root/extensions/userscripts
blob: 70e811a1b2673b8531a3dc42272aa85afa2113b0 (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
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
//
//  Copyright (c) 2012-2013 Stefan Bolte <portix@gmx.net>
//
//  This program is free software; you can redistribute it and/or modify
//  it under the terms of the GNU General Public License as published by
//  the Free Software Foundation; either version 3 of the License, or
//  (at your option) any later version.
//  
//  This program is distributed in the hope that it will be useful,
//  but WITHOUT ANY WARRANTY; without even the implied warranty of
//  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
//  GNU General Public License for more details.
//  
//  You should have received a copy of the GNU General Public License along
//  with this program; if not, write to the Free Software Foundation, Inc.,
//  51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
//


/*
 * TODO not finished yet
 *
 * userscripts extension, load userscripts and injects them into websites, this
 * extension is mostly greasemonkey compatible. Scripts can be loaded by either
 * specifying a path with using the configuration or putting them into
 * $XDG_CONFIG_HOME/dwb/scripts/. 
 *
 *
 * To use this extension load it with a userscript in 
 * $HOME/.config/dwb/userscripts/, e.g. 
 *
 * ------------------------------------------------------------------------------
 * |#!javascript                                                                | 
 * |                                                                            | 
 * |extensions.load("userscripts");                                             | 
 * ------------------------------------------------------------------------------
 *
 *
 * Config: An array of paths to userscripts
 *
 * Example (loading with extensions load):
 * 
 * ------------------------------------------------------------------------------
 * |extensions.load("userscripts", [ "/path/to/script1", "/path/to/script2" ]); |                    |
 * ------------------------------------------------------------------------------
 *
 * Example (extensionsrc): 
 *
 * ------------------------------------------------------------------------------
 * |return {                                                                    |
 * |  ... : {  ...  },  // other config objects                                 |
 * |                                                                            |
 * |  userscripts : [ "/path/to/script1", "/path/to/script2" ],                 |
 * |                                                                            |
 * |  ... : {  ...  }  // other config objects                                  |
 * |}                                                                           |
 * ------------------------------------------------------------------------------
 *
 * */

/*<INFO
Load userscripts and inject them into websites, mostly greasemonkey compatible
INFO>*/

var me = "userscripts";
var onStart = []; 
var onEnd = []; 
/*
//<DEFAULT_CONFIG
  // paths to userscripts, this extension will also load all scripts in 
  // $XDG_CONFIG_HOME/dwb/greasemonkey, it will also load all scripts in
  // $XDG_CONFIG_HOME/dwb/scripts but this is deprecated and will be
  // disabled in future versions.
  scripts : []
//>DEFAULT_CONFIG
*/


var metaData = {};

const DATA_DIR = data.userDataDir + "/extension_data/userscripts/resources";
const META_DATA = DATA_DIR + "/.metadata";

UserScript.prototype = new Function();
UserScript.prototype.constructor = UserScript;
function UserScript() 
{
    this.description = null;
    this.downloadURL = null;
    this.exclude = [];
    this.icon = null;
    this.include = [];
    this.match = [];
    this.name = null;
    this.namespace = null;
    this.require = [];
    this.resource = [];
    this.runAt = "document-end";
    this.unwrap = false;
    this.updateURL = null;
    this.version = null;
    this.script = null;
    this.scriptId = null;
    // scriptish
    this.delay = 0;
    this.noframes = false;
    this.priority = 0;
    this.offset = 0;
}

// Reused regular expressions
var regexes = {
    isTld : /\.tld(?:\/|:|$)/, 
    isRegExp : /^\/.*\/$/
};

var GM_compatability = function () 
{
    var DWB_scriptPrefix = "dwb_userscript_";
    if (DWB_scriptId !== undefined) 
    {
        DWB_scriptPrefix = DWB_scriptPrefix + DWB_scriptId + "_";
    }
    var GM_addStyle = function (styles) 
    {
        var style = document.createElement("style");
        style.setAttribute("type", "text/css");
        style.appendChild(document.createTextNode(styles));
        document.getElementsByTagName("head")[0].appendChild(style);
    };
    var GM_log = function (text) 
    {
        console.log(text);
    };
    var GM_setValue = function (key, value) 
    {
        if (localStorage !== null && (typeof value === "string" || typeof value === "number" || typeof value == "boolean") )
            localStorage.setItem(DWB_scriptPrefix + key, value);
        else 
            GM_log("GM_setValue only works with enabled localStorage and only for strings, numbers and booleans");
    };
    var GM_getValue = function (key, def) 
    {
        if (localStorage !== null) 
            return localStorage.getItem(DWB_scriptPrefix + key) || def;
        else 
            GM_log("GM_getValue only works with enabled localStorage");
        return undefined;
    };
    var GM_deleteValue = function (key) 
    {
        if (localStorage !== null) 
            localStorage.removeItem(DWB_scriptPrefix + key);
        else 
            GM_log("GM_deleteValue only works with enabled localStorage");
    };
    var GM_listValues = function () 
    {
        var i;
        var a = [];
        for (i=0; i<localStorage.length; i++) {
            a.push(localStorage.key(i).replace(DWB_scriptPrefix, ""));
        }
        return a;
    };
    var GM_info = function () { return undefined; };
    var GM_registerMenuCommand = function () { return undefined; };
    var GM_openInTab = function (url) { return null; };
    //var GM_getResourceText = function (name) 
    //{
    //    // TODO implemnt
    //    return ""; 
    //};
    //var GM_getResourceURL = function (name) 
    //{
    //    // TODO implemnt
    //    return ""; 
    //};
    //var GM_xmlHttpRequest = function (details) 
    //{
    //    // TODO implemnt
    //    return null;
    //};
};

function matchIncludeExclude(frame, items) //{{{
{
    var uri = frame.uri;
    var domain = frame.domain;
    var i;
    for (i=0; i<items.length; i++) 
    {
        try 
        {
            if (items[i].isTld && domain !== null) 
            {
                var reg = new RegExp("(?=.)" + domain + "($|/|:)");
                var newDomain = domain.substring(0, domain.indexOf(".")) + ".tld$1";
                uri = uri.replace(reg, newDomain);
            }
            if (items[i].regExp.test(uri)) 
                return true;
        }
        catch(e) 
        {
            script.debug(e);
        }
    }
    return false;
}//}}}

function matchMatches(frame, items) //{{{
{
    var i, item;
    var o = uriSplit(frame.uri);
    if (o === null)
        return false;
    for (i=0; i<items.length; i++) 
    {
        item = items[i];
        if (item.allUrls || 
            (item.scheme.test(o.scheme)  &&  
             item.host.test(o.host)      &&  
             (o.path === null  || item.path.test(o.path)))) 
        {
            return true;
        }

    }
  return false;
}//}}}

function doInject(frame, item) 
{
  if (item.delay > 0) 
  {
      timer.start(item.delay, function() {
          frame.inject(item.script, null, item.offset, item.unwrap);
          return false;
      });
  }
  else 
      frame.inject(item.script, null, item.offset, item.unwrap);
}

function handle(frame, array, isMainFrame) //{{{
{
    var i, item;
    for (i=0; i<array.length; i++) 
    {
        item = array[i];
        if (item.noframes && !isMainFrame)
            continue;
        try 
        {
            if (matchIncludeExclude(frame, item.exclude)) 
                continue;

            if (matchIncludeExclude(frame, item.include)) 
                doInject(frame, item);
            else if (matchMatches(frame, item.match)) 
                doInject(frame, item);
        }
        catch (e) 
        {
            script.debug(e);
        }
    }
}//}}}

function loadFinishedCallback(wv, frame) //{{{
{
    handle(frame, onEnd, wv.mainFrame === frame);
}//}}}

function loadCommittedCallback(wv) //{{{
{
    handle(wv.mainFrame, onStart, true);
}//}}}

function parseIncludeExclude(array) //{{{
{
    var i, rule;
    for (i=0; i<array.length; i++) 
    {
        rule = array[i];
        if (regexes.isRegExp.test(rule)) 
        {
            array[i] = { 
                regExp : new RegExp(rule.substring(1, rule.length-1)), 
                isTld : regexes.isTld.test(rule) 
            };
        }
        else 
        {
            array[i] = { 
                regExp : new RegExp(rule.replace(/\*/g, ".*")), 
                isTld : regexes.isTld.test(rule) 
            };
        }
    }
}//}}}

function uriSplit(uri) 
{
    var parts, scheme, host, path, idx; 
    parts = uri.split("://");
    if (parts[0] === uri) 
        return null;
    scheme = parts[0];
    idx = parts[1].indexOf("/");
    if (idx == -1) 
    {
        host = parts[1];
        path = null;
    }
    else 
    {
        host = parts[1].substring(0, idx);
        path = parts[1].substring(idx);
    }
    return { path : path, host: host, scheme : scheme }; 
}

function parseMatch(m) 
{
    var i, scheme, host, path, parts, j; 
    if (m === "<all_urls>") {
        return { allUrls : true };
    }

    var o = uriSplit(m);
    if (o === null) 
    {
        extensions.warning(me, "Invalid or unsupported match rule: " + m);
        return null;
    }
    if (!(/\*|http|https|file/.test(o.scheme))) 
    {
        extensions.warning(me, "Invalid scheme pattern: " + m);
        return null;
    }
    else 
        o.scheme = new RegExp(o.scheme.replace("*", ".*"));
    
    if (! (/^(?:\*\.[^*\/]*|[^*]*|\*)$/.test(o.host))) 
    {
        extensions.warning(me, "Invalid host pattern: " + m);
        return null;
    }
    else 
        o.host = new RegExp(o.host.replace(/([.?+^$[\]\\(){}|-])/g, "\\$1").replace("*", ".*"));
    
    if (! (/^\/.*/.test(o.path))) 
    { 
        extensions.warning(me, "Invalid path pattern: " + m);
        return null;
    }
    else if (o.path !== null) 
        o.path = new RegExp(o.path.replace(/([.?+^$[\]\\(){}|-])/g, "\\$1").replace("*", ".*"));
    
    return { host : o.host, scheme : o.scheme, path : o.path, allUrls : false };
}

function getRequirements(userscript) //{{{
{
    var i;
    for (i=0; i<userscript.require.length; i++) {
        //io.print(userscript.require[i]);
        //sendRequest(userscript.require[0], function (response, message) {
        //  ;
        //  //io.print(response);
        //});
        //sendRequest(userscripts.require[i], function (response) {
        //  io.print(response);
        //});
    }
}//}}}

function parseScript(path) //{{{
{
    var userscript;
    var i, items, key, value, idx, m, matches = [], numVal;

    var curScript = io.read(path);
    if (!curScript || (/^\s*$/).test(curScript)) 
      return;

    var metaStart = curScript.search(/(^|\n)\/\/\s*==UserScript==/);
    var metaEnd = curScript.search(/\n\/\/\s*==\/UserScript==/);

    userscript = new UserScript();

    if (metaStart == -1 || metaEnd == -1) 
    {
        userscript.script = curScript; 
        userscript.offset = 1;
        userscript.include = [ { regExp : /.*/, isTld : false} ];
        onEnd.push(userscript);
        return;
    }

    var meta = curScript.substring(metaStart, metaEnd).split("\n");
    var scriptStart = curScript.substring(metaEnd+1).indexOf("\n") + metaEnd + 1;

    var regValue = /\s[^\/@]\S?/;
    var regIsRule = /^\s*\/\/\s*@/;
    for (i=1; i<meta.length; i++) 
    {
        if (! (regIsRule.test(meta[i])) )
            continue;
        try 
        {
            items = meta[i].split(/\s+/, 2);
            key = items[1].substring(1).trim();
            idx = meta[i].search(regValue);
            value = idx >= 0 ? meta[i].substring(idx+1).trim() : null;
            if (key == "description"  || 
                key == "downloadURL"  || 
                key == "icon"         || 
                key == "name"         || 
                key == "namespace"    || 
                key == "updateURL"    || 
                key == "version") 
            {
                userscript[key] = value;
            }
            else if (typeof userscript[key] == "number") 
            {
                try 
                {
                    numVal = parseInt(value, 10);
                    if (!isNaN(numVal)) 
                        userscript[key] = numVal;
                }
                catch (e) {
                    script.debug(e);
                }
            }
            else if (key == "unwrap") 
                userscript.unwrap = true;
            else if (key == "noframes") 
                userscript.noframes = true;
            else if (key == "run-at")
                userscript.runAt = value;
            else if (userscript[key] instanceof Array) 
                    userscript[key] = userscript[key].concat(value.match(/\S+/g));
        }
        catch(e) 
        {
            script.debug(e);
        }

    }
    if (userscript.include.length === 0) 
        userscript.include.push({regExp : /.*/, isTld : false});
    else 
        parseIncludeExclude(userscript.include);
    parseIncludeExclude(userscript.exclude);
    // TODO resources

    var scriptId = new String();
    if (userscript.namespace === null || userscript.name === null) 
        userscript.scriptId = path;
    else
        userscript.scriptId = userscript.namespace + "::" + userscript.name;
    userscript.scriptId = userscript.scriptId.replace(/\s+/g, "_");
    userscript.script = "var DWB_scriptId = '" + userscript.scriptId + "';" +  
        curScript.substring(0, metaStart) + 
        curScript.substring(scriptStart) + util.getBody(GM_compatability);
    userscript.offset = meta.length + 1;

    getRequirements(userscript);

    for (i=0; i<userscript.match.length; i++) 
    {
        m = parseMatch(userscript.match[i]);
        if (m !== null) 
            matches.push(m);
    }
    userscript.match = matches;
    if (userscript.runAt == "document-start")
        onStart.push(userscript);
    else 
        onEnd.push(userscript);
}//}}}

function userscriptsStart() 
{
    var ret = false;
    if (onStart.length > 0) 
    {
        onStart.sort(function(a, b) { return b.priority - a.priority; });
        Signal.connect("loadCommitted", loadCommittedCallback);
        ret = true;
    }
    if (onEnd.length > 0) 
    {
        onEnd.sort(function(a, b) { return b.priority - a.priority; });
        Signal.connect("documentLoaded", loadFinishedCallback);
        ret = true;
    }
    if (ret == false)
    {
        extensions.error(me, "No scripts found, place scripts in $XDG_CONFIG_HOME/.config/dwb/greasemonkey");
    }
    //metaData = {};
    //onStart.concat(onEnd).forEach(function (v, k, obj) {
    //  var o = { 
    //    require     : obj[k].require,
    //    downloadURL : obj[k].downloadURL,
    //    updateURL   : obj[k].updateURL,
    //    version     : obj[k].version,
    //    resource    : obj[k].resource
    //  };
    //  metaData[obj[k].scriptId] = o;
    //});
    //io.write(META_DATA, "w", JSON.stringify(metaData));
    return ret;
}
function parseScripts(scripts) //{{{
{
    var i, path;
    for (i=0; i<scripts.length; i++) 
    {
        if (system.fileTest(scripts[i], FileTest.regular | FileTest.symlink)) 
            parseScript(scripts[i]);
    }
    [ "scripts", "greasemonkey" ].forEach(function(path) {
        var scriptDir = data.configDir + "/" + path;
        if (system.fileTest(scriptDir, FileTest.dir)) 
        {
            if (path == "scripts")
                extensions.warning(me, "Using $XDG_CONFIG_HOME/.config/dwb/scripts is deprecated, use $XDG_CONFIG_HOME/.config/dwb/greasemonkey instead");
            var lines = io.dirNames(scriptDir);
            for (i=0; i<lines.length; i++) 
            {
                if (lines[i].charAt(0) == ".")
                    continue;
                path = scriptDir + "/" + lines[i];
                if (!(/^\s*$/.test(lines[i])) && system.fileTest(path, FileTest.regular | FileTest.symlink)) 
                    parseScript(path);
            }
        }
    });

    return userscriptsStart();
}//}}}

var userscripts = {
    init : function (c) {
        return parseScripts(c ? c.scripts || [] : []);
    },
    end : function () {
        Signal.disconnect(loadFinishedCallback);
        Signal.disconnect(loadCommittedCallback);
    }
};

return userscripts;

// vim: set ft=javascript: