-
Notifications
You must be signed in to change notification settings - Fork 66
/
override.js
364 lines (325 loc) · 9.5 KB
/
override.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
/* 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 LIMIT_PERIOD = {
"3600": "this hour",
"86400": "today",
"604800": "this week"
};
function log(message) { console.log("[LBNG] " + message); }
function warn(message) { console.warn("[LBNG] " + message); }
function getElement(id) { return document.getElementById(id); }
var gAccessConfirmed = false;
var gAccessRequiredInput;
var gClockOffset;
var gOverrideConfirm;
var gOverrideMins;
var gOverrideLimit = false;
var gOverrideLimitPeriod;
var gOverrideLimitLeft;
var gOverrideSetNames = [];
var gClockTimeOpts;
// Initialize form
//
function initForm() {
//log("initForm");
// Set up JQuery UI widgets
$("#activate").button();
$("#activate").click(activateOverride);
$("#cancel").button();
$("#cancel").click(closePage);
}
// Initialize page
//
function initializePage() {
//log("initializePage");
browser.storage.local.get("sync").then(onGotSync, onError);
function onGotSync(options) {
if (options["sync"]) {
browser.storage.sync.get().then(onGot, onError);
} else {
browser.storage.local.get().then(onGot, onError);
}
}
function onGot(options) {
cleanOptions(options);
// Initialize form
initForm();
setTheme(options["theme"]);
// Get clock time format
gClockTimeOpts = {};
let clockTimeFormat = options["clockTimeFormat"];
if (clockTimeFormat > 0) {
gClockTimeOpts.hour12 = (clockTimeFormat == 1);
}
gClockOffset = options["clockOffset"];
gOverrideConfirm = options["orc"];
gOverrideMins = options["orm"];
// Check override limit (if specified)
let orln = options["orln"];
let orlp = options["orlp"];
let orlps = options["orlps"];
let orlc = options["orlc"];
if (orln && orlp) {
gOverrideLimit = true;
gOverrideLimitPeriod = LIMIT_PERIOD[orlp];
gOverrideLimitLeft = Math.max(0, orln - orlc);
let now = Math.floor(Date.now() / 1000) + (gClockOffset * 60);
let periodStart = getTimePeriodStart(now, orlp);
if (orlps == periodStart && gOverrideLimitLeft == 0) {
$("#alertLimitNum").html(orln);
$("#alertLimitReachedPeriod").html(gOverrideLimitPeriod);
$("#alertLimitReached").dialog("open");
return;
} else if (orlps != periodStart) {
gOverrideLimitLeft = orln;
}
}
// Get list of sets to override
let numSets = +options["numSets"];
for (let set = 1; set <= numSets; set++) {
if (options[`allowOverride${set}`]) {
let setName = options[`setName${set}`];
if (setName) {
gOverrideSetNames.push(`Block Set ${set} (${setName})`);
} else {
gOverrideSetNames.push(`Block Set ${set}`);
}
}
}
confirmAccess(options);
}
function onError(error) {
warn("Cannot get options: " + error);
$("#alertRetrieveError").dialog("open");
}
}
// Close page
//
function closePage() {
// Request tab close
browser.runtime.sendMessage({ type: "close" });
}
// Set focus to minutes input field
//
function focusMins() {
$("#mins").focus();
}
// Confirm access to override
//
function confirmAccess(options) {
let ora = options["ora"];
let orp = options["orp"];
let code = options["orcode"];
let password = options["password"];
let hpp = options["hpp"];
if (ora == 1 && password) {
gAccessRequiredInput = password;
if (hpp) {
$("#promptPasswordInput").attr("type", "password");
} else {
$("#promptPasswordInput").attr("type", "text");
}
$("#promptPasswordInput").val("");
$("#promptPassword").dialog("open");
$("#promptPasswordInput").focus();
} else if (ora == 8 && code) {
gAccessRequiredInput = code;
numLines = displayAccessCode(code, options["accessCodeImage"]);
resizePromptInputHeight(numLines);
$("#promptAccessCode").dialog("open");
$("#promptAccessCodeInput").focus();
} else if (ora == 9 && orp) {
gAccessRequiredInput = orp;
$("#promptPasswordInput").attr("type", "password");
$("#promptPasswordInput").val("");
$("#promptPassword").dialog("open");
$("#promptPasswordInput").focus();
} else if (ora >= 2 && ora <= 4) {
let code = createAccessCode(32);
if (ora > 2) {
code += createAccessCode(32);
}
if (ora > 3) {
code += createAccessCode(64);
}
gAccessRequiredInput = code;
numLines = displayAccessCode(code, options["accessCodeImage"]);
resizePromptInputHeight(numLines);
$("#promptAccessCodeInput").val("");
$("#promptAccessCode").dialog("open");
$("#promptAccessCodeInput").focus();
} else if (gOverrideMins) {
// Override duration already specified in General options
activateOverride();
} else {
// Override duration not specified in General options
$("#form").show();
setTimeout(focusMins, 100);
}
}
// Display access code (as text or image)
//
function displayAccessCode(code, asImage) {
let codeText = getElement("promptAccessCodeText");
let codeImage = getElement("promptAccessCodeImage");
let codeCanvas = getElement("promptAccessCodeCanvas");
let lines = [];
let idx = 0;
do {
let spaceIdx = (idx + 64 >= code.length) ? code.length : code.lastIndexOf(" ", idx + 64);
if (spaceIdx == -1) {
lines.push(code.substring(idx, idx + 64));
idx += 64;
} else {
lines.push(code.substring(idx, spaceIdx));
idx = spaceIdx + 1;
}
} while (idx < code.length - 1);
if (asImage) {
// Display code as image
codeText.style.display = "none";
codeImage.style.display = "";
let ctx = codeCanvas.getContext("2d");
ctx.font = "normal 14px monospace";
let width = ctx.measureText(code.substring(0, 64)).width + 8;
let height = lines.length * 16 + 8;
codeCanvas.width = width * devicePixelRatio;
codeCanvas.height = height * devicePixelRatio;
ctx.scale(devicePixelRatio, devicePixelRatio);
codeCanvas.style.width = width + 'px';
codeCanvas.style.height = height + 'px';
ctx.font = "normal 14px monospace"; // resizing canvas resets font!
ctx.fillStyle = "#000";
for (let i = 0; i < lines.length; i++) {
ctx.fillText(lines[i], 4, 16 * (i+1));
}
} else {
// Display code as text
codeText.style.display = "";
codeImage.style.display = "none";
for (let i = 0; i < lines.length; i++) {
codeText.appendChild(document.createTextNode(lines[i]));
codeText.appendChild(document.createElement("br"));
}
}
return lines.length;
}
// Convert #promptAccessCodeInput to a textarea and resize its height based
// on the number of lines of the access code
//
function resizePromptInputHeight(numLines) {
if (numLines < 2) return;
let codeInput = getElement("promptAccessCodeInput");
let textarea = document.createElement("textarea");
textarea.id = codeInput.id;
textarea.font = codeInput.font;
textarea.rows = numLines;
textarea.cols = codeInput.size;
codeInput.replaceWith(textarea);
}
// Activate override
//
function activateOverride() {
// Get duration from form if not already specified
if (!gOverrideMins) {
gOverrideMins = $("#mins").val();
if (!gOverrideMins || !checkPosIntFormat(gOverrideMins)) {
gOverrideMins = "";
$("#mins").val("");
$("#alertNoDuration").dialog("open");
return;
}
}
// Calculate end time for override
let endTime = Math.floor(Date.now() / 1000) + (gClockOffset * 60) + (gOverrideMins * 60);
// Request override
let message = {
type: "override",
endTime: endTime
};
browser.runtime.sendMessage(message);
if (gOverrideConfirm) {
// Show confirmation dialog
endTime = new Date(endTime * 1000);
$("#alertOverrideEndTime").html(endTime.toLocaleTimeString(undefined, gClockTimeOpts));
if (gOverrideSetNames.length > 0) {
$("#alertOverrideNoSets").hide();
$("#alertOverrideSets").show();
$("#alertOverrideSetList").html("<ul><li>" + gOverrideSetNames.join("</li><li>") + "</li></ul>");
}
if (gOverrideLimit) {
$("#alertOverrideLimit").show();
$("#alertLimitLeft").html(gOverrideLimitLeft - 1);
$("#alertLimitPeriod").html(gOverrideLimitPeriod);
}
$("#alertOverrideActivated").dialog("open");
} else {
// Close page immediately (no confirmation dialog)
closePage();
}
}
// Initialize access control prompt
//
function initAccessControlPrompt(prompt) {
// Create functions for buttons
let dialogButtons = {
OK: function () {
let input = $(`#${prompt}Input`);
if (input.val() == gAccessRequiredInput) {
gAccessConfirmed = true;
if (gOverrideMins) {
// Slight delay to allow focus to pass to new dialog
setTimeout(activateOverride, 100);
} else {
$("#form").show();
setTimeout(focusMins, 100);
}
$(`#${prompt}`).dialog("close");
} else {
input.val("");
input.effect({ effect: "highlight", color: "#ff0000" });
input.focus();
}
},
Cancel: function () {
$(`#${prompt}`).dialog("close");
}
};
// Initialize prompt dialog
$(`#${prompt}`).dialog({
autoOpen: false,
modal: true,
width: 600,
buttons: dialogButtons,
close: function (event, ui) { if (!gAccessConfirmed) closePage(); }
});
// Connect ENTER key to OK button
$(`#${prompt}Input`).keydown(
function (event) {
if (event.which == 13) {
dialogButtons.OK();
}
}
);
}
/*** STARTUP CODE BEGINS HERE ***/
// Initialize alert dialogs
$("div[id^='alert']").dialog({
autoOpen: false,
modal: true,
width: 500,
buttons: {
OK: function () { $(this).dialog("close"); }
}
});
$("#alertLimitReached").dialog({
close: function (event, ui) { closePage(); }
});
$("#alertOverrideActivated").dialog({
close: function (event, ui) { closePage(); }
});
// Initialize access control prompts
initAccessControlPrompt("promptPassword");
initAccessControlPrompt("promptAccessCode");
document.addEventListener("DOMContentLoaded", initializePage);