forked from proginosko/LeechBlockNG
-
Notifications
You must be signed in to change notification settings - Fork 0
/
common.js
442 lines (404 loc) · 14 KB
/
common.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
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
const MAX_SETS = 30;
const ALL_DAY_TIMES = "0000-2400";
const DEFAULT_BLOCK_URL = "blocked.html?$S&$U";
const DELAYED_BLOCK_URL = "delayed.html?$S&$U";
const DEFAULT_ICON = { 16: "icons/leechblock16.png", 32: "icons/leechblock32.png" };
const OVERRIDE_ICON = { 16: "icons/leechblock16o.png", 32: "icons/leechblock32o.png" };
const PARSE_URL = /^((([\w-]+):\/*(\w+(?::\w+)?@)?([\w-\.]+)(?::(\d*))?)([^\?#]*))(\?[^#]*)?(#.*)?$/;
const PER_SET_OPTIONS = {
// def: default value, id: form element identifier (see options.html)
setName: { type: "string", def: "", id: "setName" },
sites: { type: "string", def: "", id: "sites" },
times: { type: "string", def: "0900-1700", id: "times" },
limitMins: { type: "string", def: "", id: "limitMins" },
limitPeriod: { type: "string", def: "", id: "limitPeriod" },
limitOffset: { type: "string", def: "", id: "limitOffset" },
conjMode: { type: "boolean", def: false, id: "conjMode" },
days: { type: "array", def: [false, true, true, true, true, true, false], id: "day" },
blockURL: { type: "string", def: DEFAULT_BLOCK_URL, id: "blockURL" },
applyFilter: { type: "boolean", def: false, id: "applyFilter" },
filterName: { type: "string", def: "grayscale", id: "filterName" },
activeBlock: { type: "boolean", def: false, id: "activeBlock" },
countFocus: { type: "boolean", def: true, id: "countFocus" },
delayFirst: { type: "boolean", def: true, id: "delayFirst" },
delaySecs: { type: "string", def: "60", id: "delaySecs" },
reloadSecs: { type: "string", def: "", id: "reloadSecs" },
allowOverride: { type: "boolean", def: false, id: "allowOverride" },
prevOpts: { type: "boolean", def: false, id: "prevOpts" },
prevAddons: { type: "boolean", def: false, id: "prevAddons" },
prevSupport: { type: "boolean", def: false, id: "prevSupport" },
showTimer: { type: "boolean", def: true, id: "showTimer" },
sitesURL: { type: "string", def: "", id: "sitesURL" },
regexpBlock: { type: "string", def: "", id: "regexpBlock" },
regexpAllow: { type: "string", def: "", id: "regexpAllow" },
ignoreHash: { type: "boolean", def: true, id: "ignoreHash" },
};
const GENERAL_OPTIONS = {
// def: default value, id: form element identifier (see options.html)
numSets: { type: "string", def: "6", id: "numSets" }, // default: 6 block sets
sync: { type: "boolean", def: false, id: "syncStorage" }, // default: use local storage
theme: { type: "string", def: "", id: "theme" }, // default: light theme
oa: { type: "string", def: "0", id: "optionsAccess" }, // default: no password or code
password: { type: "string", def: "", id: "accessPassword" }, // default: blank
hpp: { type: "boolean", def: true, id: "hidePassword" }, // default: hidden
timerVisible: { type: "boolean", def: true, id: "timerVisible" }, // default: visible
timerSize: { type: "string", def: "1", id: "timerSize" }, // default: medium
timerLocation: { type: "string", def: "0", id: "timerLocation" }, // default: top left
timerBadge: { type: "boolean", def: true, id: "timerBadge" }, // default: enabled
orm: { type: "string", def: "", id: "overrideMins" }, // default: no override
ora: { type: "string", def: "0", id: "overrideAccess" }, // default: no password or code
orc: { type: "boolean", def: true, id: "overrideConfirm" }, // default: enabled
warnSecs: { type: "string", def: "", id: "warnSecs" }, // default: no warning
warnImmediate: { type: "boolean", def: true, id: "warnImmediate" }, // default: warn only for immediate block
contextMenu: { type: "boolean", def: true, id: "contextMenu" }, // default: enabled
toolsMenu: { type: "boolean", def: true, id: "toolsMenu" }, // default: enabled
matchSubdomains: { type: "boolean", def: false, id: "matchSubdomains" }, // default: disabled
saveSecs: { type: "string", def: "10", id: "saveSecs" }, // default: every 10 seconds
processActiveTabs: { type: "boolean", def: false, id: "processActiveTabs" }, // default: disabled
accessCodeImage: { type: "boolean", def: false, id: "accessCodeImage" }, // default: disabled
autoExportSync: { type: "boolean", def: true, id: "autoExportSync" }, // default: enabled
lockdownHours: { type: "string", def: "", id: null }, // default: blank
lockdownMins: { type: "string", def: "", id: null }, // default: blank
};
function listObjectProperties(obj, name) {
let list = "";
for (let prop of Object.keys(obj).sort()) {
list += `${name}.${prop}=${obj[prop]}\n`;
}
return list;
}
// Clean options (check types and set default values where needed)
//
function cleanOptions(options) {
// General options
for (let name in GENERAL_OPTIONS) {
let type = GENERAL_OPTIONS[name].type;
let def = GENERAL_OPTIONS[name].def;
if (typeof options[`${name}`] != type) {
options[`${name}`] = def;
}
}
// Clean number of block sets
let numSets = +options["numSets"];
numSets = Math.max(1, Math.min(MAX_SETS, Math.floor(numSets)));
options["numSets"] = numSets.toString();
// Per-set options
for (let name in PER_SET_OPTIONS) {
let type = PER_SET_OPTIONS[name].type;
let def = PER_SET_OPTIONS[name].def;
for (let set = 1; set <= numSets; set++) {
if (type == "array") {
if (!Array.isArray(options[`${name}${set}`])) {
options[`${name}${set}`] = def.slice();
}
} else if (typeof options[`${name}${set}`] != type) {
options[`${name}${set}`] = def;
}
}
}
}
// Clean time data
//
// timedata[0] = start time for statistics (secs since epoch)
// timedata[1] = total time spent on sites (secs)
// timedata[2] = start time for time limit period (secs since epoch)
// timedata[3] = time spent on sites during this limit period (secs)
// timedata[4] = end time for lockdown (secs since epoch)
//
function cleanTimeData(options) {
let numSets = +options["numSets"];
for (let set = 1; set <= numSets; set++) {
let timedata = options[`timedata${set}`];
if (!Array.isArray(timedata) || timedata.length < 5) {
timedata = [Math.floor(Date.now() / 1000), 0, 0, 0, 0];
}
options[`timedata${set}`] = timedata;
}
}
// Return parsed URL (page address, arguments, and hash)
//
function getParsedURL(url) {
let results = PARSE_URL.exec(url);
if (results != null) {
let page = results[1];
let origin = results[2];
let protocol = results[3];
let userinfo = results[4];
let host = results[5];
let port = results[6];
let path = results[7];
let query = results[8];
let fragment = results[9];
return {
pageNoArgs: page,
page: (query == null) ? page : (page + query),
origin: origin,
protocol: protocol,
host: host,
path: path,
query: query,
args: (query == null) ? null : query.substring(1).split(/[;&]/),
hash: (fragment == null) ? null : fragment.substring(1)
};
} else {
warn("Cannot parse URL: " + url);
return {
pageNoArgs: null,
page: null,
origin: null,
protocol: null,
host: null,
path: null,
query: null,
args: null,
hash: null
};
}
}
// Clean list of sites
//
function cleanSites(sites) {
sites = sites.replace(/\s+/g, " ").replace(/(^ +)|( +$)|(\w+:\/+)/g, "");
sites = sites.split(" ").sort().join(" "); // sort alphabetically
return sites;
}
// Create regular expressions for matching sites to block/allow
//
function getRegExpSites(sites, matchSubdomains) {
if (!sites) {
return {
block: "",
allow: "",
keyword: ""
};
}
let blockFiles = false;
let allowFiles = false;
let patterns = sites.split(/\s+/);
let blocks = [];
let allows = [];
let keywords = [];
for (let pattern of patterns) {
if (pattern == "FILE") {
blockFiles = true;
} else if (pattern == "+FILE") {
allowFiles = true;
} else if (pattern.charAt(0) == "~") {
// Add a keyword
keywords.push(keywordToRegExp(pattern.substr(1)));
} else if (pattern.charAt(0) == "+") {
// Add a regexp to allow site(s) as exception(s)
allows.push(patternToRegExp(pattern.substr(1), matchSubdomains));
} else if (pattern.charAt(0) != "#") {
// Add a regexp to block site(s)
blocks.push(patternToRegExp(pattern, matchSubdomains));
}
}
return {
block: (blocks.length > 0)
? "^" + (blockFiles ? "file:|" : "") + "(https?|file):\\/+(" + blocks.join("|") + ")"
: (blockFiles ? "^file:" : ""),
allow: (allows.length > 0)
? "^" + (allowFiles ? "file:|" : "") + "(https?|file):\\/+(" + allows.join("|") + ")"
: (allowFiles ? "^file:" : ""),
keyword: (keywords.length > 0) ? keywords.join("|") : ""
};
}
// Convert site pattern to regular expression
//
function patternToRegExp(pattern, matchSubdomains) {
let special = /[\.\|\?\:\+\-\^\$\(\)\[\]\{\}\\]/g;
let subdomains = matchSubdomains ? "([^/]*\\.)?" : "(www\\.)?"
return subdomains + pattern
.replace(special, "\\$&") // fix special chars
.replace(/^www\\\./, "") // remove existing www prefix
.replace(/\*\\\+/g, ".+") // convert plus-wildcards
.replace(/\*{2,}/g, ".{STAR}") // convert super-wildcards
.replace(/\*/g, "[^\\/]{STAR}") // convert wildcards
.replace(/{STAR}/g, "*"); // convert stars
}
// Convert keyword to regular expression
//
function keywordToRegExp(keyword) {
let special = /[\.\|\?\:\+\-\^\$\(\)\[\]\{\}\\]/g;
return "\\b" + keyword
.replace(special, "\\$&") // fix special chars
.replace(/_+/g, "\\s+") // convert underscores
.replace(/\*+/, "\\S*") // convert wildcards
+ "\\b";
}
// Check time periods format
//
function checkTimePeriodsFormat(times) {
return (times == "") || /^[0-2]\d[0-5]\d-[0-2]\d[0-5]\d([, ]+[0-2]\d[0-5]\d-[0-2]\d[0-5]\d)*$/.test(times);
}
// Check positive integer format
//
function checkPosIntFormat(value) {
return (value == "") || /^[1-9][0-9]*$/.test(value);
}
// Check positive/negative integer format
//
function checkPosNegIntFormat(value) {
return (value == "") || /^-?[1-9][0-9]*$/.test(value);
}
// Convert times to minute periods
//
function getMinPeriods(times) {
let minPeriods = [];
if (times) {
let regexp = /^(\d\d)(\d\d)-(\d\d)(\d\d)$/;
let periods = times.split(/[, ]+/);
for (let period of periods) {
let results = regexp.exec(period);
if (results != null) {
let minPeriod = {
start: (parseInt(results[1], 10) * 60 + parseInt(results[2], 10)),
end: (parseInt(results[3], 10) * 60 + parseInt(results[4], 10))
};
minPeriods.push(minPeriod);
}
}
}
return minPeriods;
}
// Clean time periods
//
function cleanTimePeriods(times) {
// Convert to minute periods
let minPeriods = getMinPeriods(times);
if (minPeriods.length == 0) {
return ""; // nothing to do
}
// Step 1: Fix any times > 2400
for (let mp of minPeriods) {
mp.start = Math.min(mp.start, 1440);
mp.end = Math.min(mp.end, 1440);
}
// Step 2: Remove any periods without +ve duration
for (let i = 0; i < minPeriods.length; i++) {
if (minPeriods[i].start >= minPeriods[i].end) {
minPeriods.splice(i--, 1);
}
}
// Step 3: Sort periods in order of start time
minPeriods.sort(function (a, b) { return (a.start - b.start); });
// Step 4: Combine overlapping periods
for (let i = 0; i < (minPeriods.length - 1); i++) {
let mp1 = minPeriods[i];
let mp2 = minPeriods[i + 1];
if (mp2.start <= mp1.end) {
// Merge first period into second period (and back up index)
mp2.start = mp1.start;
mp2.end = Math.max(mp1.end, mp2.end);
minPeriods.splice(i--, 1);
}
}
// Convert back to string list of time periods
let cleanTimes = [];
for (let mp of minPeriods) {
let h1 = Math.floor(mp.start / 60);
let m1 = (mp.start % 60);
let h2 = Math.floor(mp.end / 60);
let m2 = (mp.end % 60);
let period =
((h1 < 10) ? "0" : "") + h1 +
((m1 < 10) ? "0" : "") + m1 +
"-" +
((h2 < 10) ? "0" : "") + h2 +
((m2 < 10) ? "0" : "") + m2;
cleanTimes.push(period);
}
return cleanTimes.join(",");
}
// Calculate start of time period from current time and time limit period
//
function getTimePeriodStart(now, limitPeriod, limitOffset) {
limitPeriod = +limitPeriod; // force value to number
limitOffset = +limitOffset; // force value to number
if (limitPeriod > 0) {
let periodStart = now - (now % limitPeriod);
// Adjust start time for timezone, DST, and Sunday as first day of week
if (limitPeriod > 3600) {
periodStart += limitOffset * 3600; // add user-specified offset (hours)
let offsetMins = new Date(now * 1000).getTimezoneOffset();
periodStart += offsetMins * 60; // add time difference
if (limitPeriod > 86400) {
periodStart -= 345600; // subtract four days (Thu back to Sun)
}
// Correct any boundary errors
while (periodStart > now) {
periodStart -= limitPeriod;
}
while (periodStart <= now - limitPeriod) {
periodStart += limitPeriod;
}
}
return periodStart;
}
return 0;
}
// Format a time in seconds to HH:MM:SS format
//
function formatTime(secs) {
let neg = (secs < 0);
secs = Math.abs(secs);
let h = Math.floor(secs / 3600);
let m = Math.floor(secs / 60) % 60;
let s = Math.floor(secs) % 60;
return (neg ? "-" : "") + ((h < 10) ? "0" + h : h)
+ ":" + ((m < 10) ? "0" + m : m)
+ ":" + ((s < 10) ? "0" + s : s);
}
// Determine whether all items in array evalate to true
//
function allTrue(array) {
if (Array.isArray(array)) {
for (let i = 0; i < array.length; i++) {
if (!array[i]) return false;
}
return true;
} else {
return false;
}
}
// Encode day selection
//
function encodeDays(days) {
let dayCode = 0;
for (let i = 0; i < 7; i++) {
if (days[i]) dayCode |= (1 << i);
}
return dayCode;
}
// Decode day selection
//
function decodeDays(dayCode) {
let days = new Array(7);
for (let i = 0; i < 7; i++) {
days[i] = ((dayCode & (1 << i)) != 0);
}
return days;
}
// Create a random access code of a specified length
//
function createAccessCode(len) {
// Omit O, 0, I, l to avoid ambiguity with some fonts
const codeChars = "~!@#$%^&*()[]{}?+-=ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz123456789";
let code = "";
for (let i = 0; i < len; i++) {
code += codeChars.charAt(Math.random() * codeChars.length);
}
return code;
}
// Set theme in current document
//
function setTheme(theme) {
let link = document.getElementById("themeLink");
if (link) {
link.href = theme ? `themes/${theme}.css` : "";
}
}