summaryrefslogtreecommitdiff
path: root/js/AppBase.js
blob: 4aa500e5bc6a263def9443117b51cac60c88cc36 (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
'use strict'
/* global __, ngettext */
define(["dojo/_base/declare"], function (declare) {
	return declare("fox.AppBase", null, {
		_initParams: [],
		_rpc_seq: 0,
		hotkey_prefix: 0,
		hotkey_prefix_pressed: false,
		hotkey_prefix_timeout: 0,
		Scrollable: {
			scrollByPages: function (elem, page_offset) {
				if (!elem) return;

				/* keep a line or so from the previous page  */
				const offset = (elem.offsetHeight - (page_offset > 0 ? 50 : -50)) * page_offset;

				this.scroll(elem, offset);
			},
			scroll: function(elem, offset) {
				if (!elem) return;

				elem.scrollTop += offset;
			},
			isChildVisible: function(elem, ctr) {
				if (!elem) return;

				const ctop = ctr.scrollTop;
				const cbottom = ctop + ctr.offsetHeight;

				const etop = elem.offsetTop;
				const ebottom = etop + elem.offsetHeight;

				return etop >= ctop && ebottom <= cbottom ||
					etop < ctop && ebottom > ctop || ebottom > cbottom && etop < cbottom;
			},
			fitsInContainer: function (elem, ctr) {
				if (!elem) return;

				return elem.offsetTop + elem.offsetHeight <= ctr.scrollTop + ctr.offsetHeight &&
					elem.offsetTop >= ctr.scrollTop;
			}
		},
		constructor: function() {
			window.onerror = this.Error.onWindowError;
		},
		getInitParam: function(k) {
			return this._initParams[k];
		},
		setInitParam: function(k, v) {
			this._initParams[k] = v;
		},
		nightModeChanged: function(is_night, link) {
			console.log("night mode changed to", is_night);

			if (link) {
				const css_override = is_night ? "themes/night.css" : "themes/light.css";
				link.setAttribute("href", css_override + "?" + Date.now());
			}
		},
		setupNightModeDetection: function(callback) {
			if (!$("theme_css")) {
				const mql = window.matchMedia('(prefers-color-scheme: dark)');

				try {
					mql.addEventListener("change", () => {
						this.nightModeChanged(mql.matches, $("theme_auto_css"));
					});
				} catch (e) {
					console.warn("exception while trying to set MQL event listener");
				}

				const link = new Element("link", {
					rel: "stylesheet",
					id: "theme_auto_css"
				});

				if (callback) {
                    link.onload = function () {
                        document.querySelector("body").removeClassName("css_loading");
                        callback();
                    };

                    link.onerror = function(event) {
                        alert("Fatal error while loading application stylesheet: " + link.getAttribute("href"));
                    }
                }

				this.nightModeChanged(mql.matches, link);

				document.querySelector("head").appendChild(link);
			} else {
				document.querySelector("body").removeClassName("css_loading");

				if (callback) callback();
			}
		},
		enableCsrfSupport: function() {
			Ajax.Base.prototype.initialize = Ajax.Base.prototype.initialize.wrap(
				function (callOriginal, options) {

					if (App.getInitParam("csrf_token") != undefined) {
						Object.extend(options, options || { });

						if (Object.isString(options.parameters))
							options.parameters = options.parameters.toQueryParams();
						else if (Object.isHash(options.parameters))
							options.parameters = options.parameters.toObject();

						options.parameters["csrf_token"] = App.getInitParam("csrf_token");
					}

					return callOriginal(options);
				}
			);
		},
		urlParam: function(param) {
			return String(window.location.href).parseQuery()[param];
		},
		next_seq: function() {
			this._rpc_seq += 1;
			return this._rpc_seq;
		},
		get_seq: function() {
			return this._rpc_seq;
		},
		setLoadingProgress: function(p) {
			loading_progress += p;

			if (dijit.byId("loading_bar"))
				dijit.byId("loading_bar").update({progress: loading_progress});

			if (loading_progress >= 90) {
				$("overlay").hide();
			}

		},
		keyeventToAction: function(event) {

			const hotkeys_map = App.getInitParam("hotkeys");
			const keycode = event.which;
			const keychar = String.fromCharCode(keycode);

			if (keycode == 27) { // escape and drop prefix
				this.hotkey_prefix = false;
			}

			if (!this.hotkey_prefix && hotkeys_map[0].indexOf(keychar) != -1) {

				this.hotkey_prefix = keychar;
				$("cmdline").innerHTML = keychar;
				Element.show("cmdline");

				window.clearTimeout(this.hotkey_prefix_timeout);
				this.hotkey_prefix_timeout = window.setTimeout(() => {
					this.hotkey_prefix = false;
					Element.hide("cmdline");
				}, 3 * 1000);

				event.stopPropagation();

				return false;
			}

			Element.hide("cmdline");

			let hotkey_name = "";

			if (event.type == "keydown") {
				hotkey_name = "(" + keycode + ")";

				// ensure ^*char notation
				if (event.shiftKey) hotkey_name = "*" + hotkey_name;
				if (event.ctrlKey) hotkey_name = "^" + hotkey_name;
				if (event.altKey) hotkey_name = "+" + hotkey_name;
				if (event.metaKey) hotkey_name = "%" + hotkey_name;
			} else {
				hotkey_name = keychar ? keychar : "(" + keycode + ")";
			}

			const hotkey_full = this.hotkey_prefix ? this.hotkey_prefix + " " + hotkey_name : hotkey_name;
			this.hotkey_prefix = false;

			let action_name = false;

			for (const sequence in hotkeys_map[1]) {
				if (hotkeys_map[1].hasOwnProperty(sequence)) {
					if (sequence == hotkey_full) {
						action_name = hotkeys_map[1][sequence];
						break;
					}
				}
			}

			console.log('keyeventToAction', hotkey_full, '=>', action_name);

			return action_name;
		},
		cleanupMemory: function(root) {
			const dijits = dojo.query("[widgetid]", dijit.byId(root).domNode).map(dijit.byNode);

			dijits.each(function (d) {
				dojo.destroy(d.domNode);
			});

			$$("#" + root + " *").each(function (i) {
				i.parentNode ? i.parentNode.removeChild(i) : true;
			});
		},
		helpDialog: function(topic) {
			const query = "backend.php?op=backend&method=help&topic=" + encodeURIComponent(topic);

			if (dijit.byId("helpDlg"))
				dijit.byId("helpDlg").destroyRecursive();

			const dialog = new dijit.Dialog({
				id: "helpDlg",
				title: __("Help"),
				style: "width: 600px",
				href: query,
			});

			dialog.show();
		},
		displayDlg: function(title, id, param, callback) {
			Notify.progress("Loading, please wait...", true);

			const query = {op: "dlg", method: id, param: param};

			xhrPost("backend.php", query, (transport) => {
				try {
					const content = transport.responseText;

					let dialog = dijit.byId("infoBox");

					if (!dialog) {
						dialog = new dijit.Dialog({
							title: title,
							id: 'infoBox',
							style: "width: 600px",
							onCancel: function () {
								return true;
							},
							onExecute: function () {
								return true;
							},
							onClose: function () {
								return true;
							},
							content: content
						});
					} else {
						dialog.attr('title', title);
						dialog.attr('content', content);
					}

					dialog.show();

					Notify.close();

					if (callback) callback(transport);
				} catch (e) {
					this.Error.report(e);
				}
			});

			return false;
		},
		handleRpcJson: function(transport) {

			const netalert = $$("#toolbar .net-alert")[0];

			try {
				const reply = JSON.parse(transport.responseText);

				if (reply) {
					const error = reply['error'];

					if (error) {
						const code = error['code'];
						const msg = error['message'];

						console.warn("[handleRpcJson] received fatal error ", code, msg);

						if (code != 0) {
							/* global ERRORS */
							this.Error.fatal(ERRORS[code], {info: msg, code: code});
							return false;
						}
					}

					const seq = reply['seq'];

					if (seq && this.get_seq() != seq) {
						console.log("[handleRpcJson] sequence mismatch: ", seq, '!=', this.get_seq());
						return true;
					}

					const message = reply['message'];

					if (message == "UPDATE_COUNTERS") {
						console.log("need to refresh counters...");
						Feeds.requestCounters(true);
					}

					const counters = reply['counters'];

					if (counters)
						Feeds.parseCounters(counters);

					const runtime_info = reply['runtime-info'];

					if (runtime_info)
						App.parseRuntimeInfo(runtime_info);

					if (netalert) netalert.hide();

					return reply;

				} else {
					if (netalert) netalert.show();

					Notify.error("Communication problem with server.");
				}

			} catch (e) {
				if (netalert) netalert.show();

				Notify.error("Communication problem with server.");

				console.error(e);
			}

			return false;
		},
		parseRuntimeInfo: function(data) {
			for (const k in data) {
				if (data.hasOwnProperty(k)) {
					const v = data[k];

					console.log("RI:", k, "=>", v);

					if (k == "daemon_is_running" && v != 1) {
						Notify.error("<span onclick=\"App.explainError(1)\">Update daemon is not running.</span>", true);
						return;
					}

					if (k == "recent_log_events") {
						const alert = $$(".log-alert")[0];

						if (alert) {
							v > 0 ? alert.show() : alert.hide();
						}
					}

					if (k == "daemon_stamp_ok" && v != 1) {
						Notify.error("<span onclick=\"App.explainError(3)\">Update daemon is not updating feeds.</span>", true);
						return;
					}

					if (k == "max_feed_id" || k == "num_feeds") {
						if (App.getInitParam(k) != v) {
							console.log("feed count changed, need to reload feedlist.");
							Feeds.reload();
						}
					}

					this.setInitParam(k, v);
				}
			}

			PluginHost.run(PluginHost.HOOK_RUNTIME_INFO_LOADED, data);
		},
		backendSanityCallback: function (transport) {
			const reply = JSON.parse(transport.responseText);

			/* global ERRORS */

			if (!reply) {
				this.Error.fatal(ERRORS[3], {info: transport.responseText});
				return;
			}

			if (reply['error']) {
				const code = reply['error']['code'];

				if (code && code != 0) {
					return this.Error.fatal(ERRORS[code],
						{code: code, info: reply['error']['message']});
				}
			}

			console.log("sanity check ok");

			const params = reply['init-params'];

			if (params) {
				console.log('reading init-params...');

				for (const k in params) {
					if (params.hasOwnProperty(k)) {
						switch (k) {
							case "label_base_index":
								LABEL_BASE_INDEX = parseInt(params[k]);
								break;
							case "cdm_auto_catchup":
								if (params[k] == 1) {
									const hl = $("headlines-frame");
									if (hl) hl.addClassName("auto_catchup");
								}
								break;
							case "hotkeys":
								// filter mnemonic definitions (used for help panel) from hotkeys map
								// i.e. *(191)|Ctrl-/ -> *(191)

								const tmp = [];
								for (const sequence in params[k][1]) {
									if (params[k][1].hasOwnProperty(sequence)) {
										const filtered = sequence.replace(/\|.*$/, "");
										tmp[filtered] = params[k][1][sequence];
									}
								}

								params[k][1] = tmp;
								break;
						}

						console.log("IP:", k, "=>", params[k]);
						this.setInitParam(k, params[k]);
					}
				}

				// PluginHost might not be available on non-index pages
				if (typeof PluginHost !== 'undefined')
					PluginHost.run(PluginHost.HOOK_PARAMS_LOADED, App._initParams);
			}

			this.initSecondStage();
		},
		explainError: function(code) {
			return this.displayDlg(__("Error explained"), "explainError", code);
		},
		Error: {
			fatal: function (error, params) {
				params = params || {};

				if (params.code) {
					if (params.code == 6) {
						window.location.href = "index.php";
						return;
					} else if (params.code == 5) {
						window.location.href = "public.php?op=dbupdate";
						return;
					}
				}

				return this.report(error,
					Object.extend({title: __("Fatal error")}, params));
			},
			report: function(error, params) {
				params = params || {};

				if (!error) return;

				console.error("[Error.report]", error, params);

				const message = params.message ? params.message : error.toString();

				try {
					xhrPost("backend.php",
						{op: "rpc", method: "log",
							file: params.filename ? params.filename : error.fileName,
							line: params.lineno ? params.lineno : error.lineNumber,
							msg: message,
							context: error.stack},
						(transport) => {
							console.warn("[Error.report] log response", transport.responseText);
						});
				} catch (re) {
					console.error("[Error.report] exception while saving logging error on server", re);
				}

				try {
					if (dijit.byId("exceptionDlg"))
						dijit.byId("exceptionDlg").destroyRecursive();

					let stack_msg = "";

					if (error.stack)
						stack_msg += `<div><b>Stack trace:</b></div>
							<textarea name="stack" readonly="1">${error.stack}</textarea>`;

					if (params.info)
						stack_msg += `<div><b>Additional information:</b></div>
							<textarea name="stack" readonly="1">${params.info}</textarea>`;

					let content = `<div class="error-contents">
							<p class="message">${message}</p>
							${stack_msg}
							<div class="dlgButtons">
								<button dojoType="dijit.form.Button"
									onclick=\"dijit.byId('exceptionDlg').hide()">${__('Close this window')}</button>
							</div>
						</div>`;

					const dialog = new dijit.Dialog({
						id: "exceptionDlg",
						title: params.title || __("Unhandled exception"),
						style: "width: 600px",
						content: content
					});

					dialog.show();
				} catch (de) {
					console.error("[Error.report] exception while showing error dialog", de);

					alert(error.stack ? error.stack : message);
				}

			},
			onWindowError: function (message, filename, lineno, colno, error) {
				// called without context (this) from window.onerror
				App.Error.report(error,
					{message: message, filename: filename, lineno: lineno, colno: colno});
			},
		}
	});
});