-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathserverStatusPanel.js
More file actions
555 lines (511 loc) · 21.4 KB
/
Copy pathserverStatusPanel.js
File metadata and controls
555 lines (511 loc) · 21.4 KB
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
"use strict";
import Clutter from "gi://Clutter";
import GLib from "gi://GLib";
import St from "gi://St";
import Gio from "gi://Gio";
import GObject from "gi://GObject";
import Soup from "gi://Soup";
import * as Main from "resource:///org/gnome/shell/ui/main.js";
import * as MessageTray from 'resource:///org/gnome/shell/ui/messageTray.js';
import { Status } from "./status.js";
let notificationSource;
/**
* A series of these panels are shown when the indicator icon is clicked.
* Each shows a server status and name, and opens a browser to its URL when clicked.
*/
export const ServerStatusPanel = GObject.registerClass(
{
GTypeName: "ServerStatusPanel",
},
class ServerStatusPanel extends St.BoxLayout {
constructor(
serverSetting,
updateTaskbarCallback,
iconProvider,
...otherProps
) {
super(otherProps);
this.serverSetting = serverSetting;
this.updateTaskbarCallback = updateTaskbarCallback;
this.iconProvider = iconProvider;
// mouse rollover
this.track_hover = true;
this.reactive = true;
this.style_class = "server-panel";
// track pending requests for cleanup
this.pendingCancellables = new Set();
// click to open browser
this.connect("button-press-event", () => {
this.openBrowser(serverSetting.url);
return Clutter.EVENT_PROPAGATE;
});
// session from which to fire http requests
this.session = new Soup.Session({
timeout: serverSetting.timeout,
});
// icon displaying status by emoji icon
this.panelIcon = new St.Icon({
gicon: this.iconProvider.getIcon(Status.Init),
style_class: "icon-lg padded",
});
let panelIconDisposed = false;
this.panelIcon.connect("destroy", () => {
panelIconDisposed = true;
});
this.add_child(this.panelIcon);
// server name display
const nameLabel = new St.Label({
text: serverSetting.name,
style_class: "padded",
y_align: Clutter.ActorAlign.CENTER,
});
this.add_child(nameLabel);
// duration indicator
const durationIndicator = new St.Label({
text: "",
style_class: "duration",
});
let durationIndicatorDisposed = false;
durationIndicator.connect(
"destroy",
() => (durationIndicatorDisposed = true),
);
const durationIndicatorContainer = new St.Bin({
style_class: "bin",
x_expand: true,
x_align: Clutter.ActorAlign.END,
child: durationIndicator,
});
this.add_child(durationIndicatorContainer);
// call once then schedule
this.update(
serverSetting.url,
panelIconDisposed,
durationIndicator,
durationIndicatorDisposed,
);
// schedule recurring http requests
this.intervalID = GLib.timeout_add(
GLib.PRIORITY_DEFAULT,
serverSetting.frequency * 1000,
() => {
this.update(
serverSetting.url,
panelIconDisposed,
durationIndicator,
durationIndicatorDisposed,
);
return GLib.SOURCE_CONTINUE;
},
);
this.connect("destroy", () => {
// remove id to recurring http calls
if (this.intervalID) {
GLib.Source.remove(this.intervalID);
this.intervalID = null;
}
// clear all pending requests
if (this.pendingCancellables) {
this.pendingCancellables.forEach((cancellable) => {
if (!cancellable.is_cancelled()) {
cancellable.cancel();
this.pendingCancellables.delete(cancellable);
cancellable = null;
}
});
this.pendingCancellables = null;
}
// Clean up the HTTP session
if (this.session) {
this.session.abort();
this.session = null;
}
// Clean up instance properties
this.panelIcon.destroy();
this.panelIcon = null;
this.serverSetting = null;
this.updateTaskbarCallback = null;
this.iconProvider = null;
});
}
/**
* Returns the status of the server this panel represents.
*
* @return {Status}
*/
getStatus() {
return this.iconProvider.getStatus(this.panelIcon?.gicon);
}
/**
* Invoked on a schedule, make request with provided URL.
*
* @param {String} url
* @param {boolean} panelIconDisposed whether the panel icon has been disposed
* @param {St.Label} durationIndicator
* @param {boolean} durationIndicatorDisposed
*/
update(
url,
panelIconDisposed,
durationIndicator,
durationIndicatorDisposed,
) {
const httpMethod = this.serverSetting.isGet ? "GET" : "HEAD";
this.makeRequest(
httpMethod,
url,
this.panelIcon,
panelIconDisposed,
durationIndicator,
durationIndicatorDisposed,
);
return GLib.SOURCE_CONTINUE;
}
/**
* Execute the URL invocation asynchronously and trigger the update of the GUI.
*
* @param {String} httpMethod
* @param {String} url
* @param {St.Icon} panelIcon
* @param {boolean} panelIconDisposed
* @param {St.Label} durationIndicator
* @param {boolean} durationIndicatorDisposed
*/
makeRequest(
httpMethod,
url,
panelIcon,
panelIconDisposed,
durationIndicator,
durationIndicatorDisposed,
) {
// create http object, `new Soup.Message()` constructor is deprecated in favor of '.new' 🤨
const message = Soup.Message.new(httpMethod, url);
if (message) {
// create a cancellable for this request
const cancellable = new Gio.Cancellable();
this.pendingCancellables.add(cancellable);
// start duration calc.
const start = Date.now();
// do the actual http call
this.session.send_and_read_async(
message,
GLib.PRIORITY_DEFAULT,
cancellable,
(session, result, error) => {
// response received, complete duration calc.
const duration = Date.now() - start;
// remove completed request from pending set
this.pendingCancellables?.delete(cancellable);
if (cancellable.is_cancelled()) {
return;
}
let newIcon;
let timedOut = false;
let reason;
if (error) {
// extension unable to send request
if (panelIcon && !panelIconDisposed && this.iconProvider) {
reason = error.toString();
newIcon = this.iconProvider.getIcon(Status.Init);
}
}
if (!newIcon) {
try {
// we aren't interested in the result if there is one, make this call to get exception
session.send_and_read_finish(result);
} catch (e) {
if (panelIcon && !panelIconDisposed && this.iconProvider) {
// do not check for Gio.TlsError as it's handled later
if (e instanceof Gio.IOErrorEnum) {
if (e.matches(Gio.IOErrorEnum, Gio.IOErrorEnum.CANCELLED)) {
newIcon = this.iconProvider.getIcon(Status.Init);
} else if (e.matches(Gio.IOErrorEnum, Gio.IOErrorEnum.TIMED_OUT)) {
// Let duration calc below handle time outs; no icon or reason here.
// This allows for duration display as well as notification.
} else {
reason = e.message;
newIcon = this.iconProvider.getIcon(Status.Down);
}
} else if (e instanceof Gio.ResolverError) {
newIcon = this.iconProvider.getIcon(Status.Init);
}
}
}
}
if (!newIcon) {
// process response to get it
[reason, newIcon, timedOut] = this.processResponse(duration, message, httpMethod, url, panelIcon, panelIconDisposed);
}
// update UI
this.updateGUI(reason, newIcon, timedOut, duration, panelIcon, panelIconDisposed, durationIndicator, durationIndicatorDisposed);
});
} else {
// message was null because of malformed url
if (panelIcon && !panelIconDisposed && this.iconProvider) {
panelIcon.gicon = this.iconProvider.getIcon(Status.Bad);
this.updateTaskbarCallback?.();
}
}
}
/**
* Process the provided message; determine new icon and, if failure, reason and
* whether or not the request exceeded set timeout.
*
* @param {number} duration
* @param {Soup.Message} message
* @param {Gio.icon} panelIcon
* @param {boolean} panelIconDisposed
* @param {St.Label} durationIndicator
* @param {boolean} durationIndicatorDisposed
* @returns [reason, newIcon, timedOut] {String}, {Gio.Icon}, {boolean}
*/
processResponse(duration, message, httpMethod, url, panelIcon, panelIconDisposed) {
let reason;
let newIcon;
let timedOut = false;
// parse result if emoji widget hasn't been destroyed
if (panelIcon && !panelIconDisposed && this.iconProvider) {
// 429 Too Many Requests causes a 'bad Soup enum' error 🤨; use try-catch
try {
const soupStatus = message.status_code;
const soupStatusText = message.reason_phrase;
/*
* Check for timeout first. Soup supposedly uses status code 1 for
* timeouts but I haven't seen it or REQUEST_TIMEOUT (408).
* Also there's https://gitlab.gnome.org/GNOME/libsoup/-/issues/155.
* Use duration calc. for now.
*/
if (
soupStatus === 1 ||
soupStatus === Soup.Status.REQUEST_TIMEOUT ||
duration > (this.session.get_timeout() * 1000)
) {
// request timed out
timedOut = true;
reason = `This server timed out after ${duration / 1000} seconds.`;
newIcon = this.iconProvider.getIcon(
Status.Down,
);
} else if (
// consider 200 through 399 success result
soupStatus >= 200 &&
soupStatus < 400
) {
// success
newIcon = this.iconProvider.getIcon(
Status.Up,
);
// no error, no reason, no notification
} else if (soupStatus >= 400 && soupStatus < 500) {
// client-side error
reason = `Client-side error: ${soupStatus} ${soupStatusText}`;
newIcon = this.iconProvider.getIcon(Status.Down);
} else if (soupStatus >= 500) {
// server-side error
reason = `Server-side error: ${soupStatus} ${soupStatusText}`;
newIcon = this.iconProvider.getIcon(Status.Down);
} else if (soupStatus === 0) {
// no status set, incomplete response
[reason, newIcon] = this.handleZeroStatus(message);
} else {
// wut?
reason = `Unknown status: ${soupStatus} ${soupStatusText}`;
newIcon = this.iconProvider.getIcon(Status.Down);
}
} catch (e) {
// 429 or another status missing from the soup enum?
reason = `This server is down: ${e.message}.`;
newIcon = this.iconProvider.getIcon(Status.Down);
}
}
return [reason, newIcon, timedOut];
}
/**
* Reflect the response. Update the icons, panel text and possibly notify user.
*
* @param {String} reason
* @param {Gio.icon} newIcon
* @param {boolean} timedOut
* @param {number} duration
* @param {Gio.icon} panelIcon
* @param {boolean} panelIconDisposed
* @param {St.Label} durationIndicator
* @param {boolean} durationIndicatorDisposed
*/
updateGUI(reason, newIcon, timedOut, duration, panelIcon, panelIconDisposed, durationIndicator, durationIndicatorDisposed) {
if (panelIcon && !panelIconDisposed && this.iconProvider) {
// update row icon
panelIcon.gicon = newIcon;
// update response time label if it hasn't been destroyed
if (
durationIndicator &&
!durationIndicatorDisposed
) {
durationIndicator.text = timedOut ? `timed out @ ${this.session.get_timeout()}s` :
`${duration}ms`;
}
// notify user if we are notifying and status is down
if (this.serverSetting.notifies && (this.iconProvider.getStatus(newIcon) === Status.Down)) {
this.fireNotification(newIcon, reason);
}
}
// update main indicator icon
this.updateTaskbarCallback?.();
}
/**
* Show a desktop notification using the provided icon and this panel's name.
*
* @param {Gio.icon} icon
* @param {String} reason
*/
fireNotification(icon, reason) {
const source = this.getNotificationSource();
const notification = new MessageTray.Notification({
source: source,
title: _(this.serverSetting.name),
body: _(reason),
gicon: icon,
urgency: MessageTray.Urgency.NORMAL,
});
source.addNotification(notification);
}
/**
* Lazily creates and returns a notification source.
*
* @returns {MessageTray.Source}
*/
getNotificationSource() {
if (!notificationSource) {
notificationSource = new MessageTray.Source({
title: _("Server Status Indicator"),
iconName: "dialog-warning",
policy: new MessageTray.NotificationGenericPolicy(),
});
notificationSource.connect('destroy', _source => {
notificationSource = null;
});
Main.messageTray.add(notificationSource);
}
return notificationSource;
}
/**
* Open a web browser at supplied URL.
*
* @param {String} url
*/
openBrowser(url) {
Gio.AppInfo.launch_default_for_uri_async(
url,
null,
null,
(appInfo, result) => {
Gio.AppInfo.launch_default_for_uri_finish(result);
}
);
}
/**
* When there are certificate errors, determine their error names and resulting down icon.
*
* @param {Soup.Message} message
* @param {Gio.TlsCertificateFlags} certificateErrors
*/
handleCertificateErrors(message, certificateErrors) {
const subject = message.get_tls_peer_certificate()?.get_subject_name();
const errorNames = this.getErrorNames(certificateErrors);
return [`The server certificate for ${subject} has errors: ${errorNames} `, this.iconProvider.getIcon(Status.Down)];
}
/**
* Get the concatenated string of all the error names in the provided flags.
*
* @param {Gio.TlsCertificateFlags} errorFlags
* @returns {String}
*/
getErrorNames(errorFlags) {
if (errorFlags === 0) {
return "NO_FLAGS";
}
const names = [];
for (const [name, value] of Object.entries(Gio.TlsCertificateFlags)) {
// skip 0 (already handled above)
// bitwise &'ing to find matching values then store their names
if (value !== 0 && ((errorFlags & value) === value)) {
names.push(name);
}
}
return names.join(", ");
}
/**
* Determine the reason string and the new icon from the provided message.
*
* @param {Soup.Message} message
* @returns [{String}, {Gio.icon}]
*/
handleZeroStatus(message) {
let reason, newIcon;
if (message.status_code === 0) {
// cert failure?
const certificateErrors = message.get_tls_peer_certificate_errors();
if (certificateErrors) {
if (this.serverSetting.ignoreTLSErrors) {
// consider this server up
newIcon = this.iconProvider.getIcon(Status.Up);
} else {
const errorNames = this.getErrorNames(certificateErrors);
const subject = message.get_tls_peer_certificate()?.get_subject_name();
reason = `This server is down.The certificate for ${subject} was presented with errors: ${errorNames} `;
newIcon = this.iconProvider.getIcon(Status.Down);
}
} else {
// no status or cert errors set, just notify user
reason = "This server is down. No status or certificate errors were returned.";
newIcon = this.iconProvider.getIcon(Status.Down);
}
}
return [reason, newIcon];
}
/**
* Stop polling and cancel in-flight requests. Resets icon to Init.
* Called on system suspend.
*/
suspend() {
if (this.intervalID) {
GLib.Source.remove(this.intervalID);
this.intervalID = null;
}
this.pendingCancellables.forEach((c) => {
if (!c.is_cancelled()) {
c.cancel();
}
});
this.pendingCancellables.clear();
if (this.panelIcon) {
this.panelIcon.gicon = this.iconProvider.getIcon(Status.Init);
}
}
/**
* Restart polling after a resume event.
*/
resume() {
this.update(
this.serverSetting.url,
this.panelIconDisposed,
this.durationIndicator,
this.durationIndicatorDisposed,
);
this.intervalID = GLib.timeout_add(
GLib.PRIORITY_DEFAULT,
this.serverSetting.frequency * 1000,
() => {
this.update(
this.serverSetting.url,
this.panelIconDisposed,
this.durationIndicator,
this.durationIndicatorDisposed,
);
return GLib.SOURCE_CONTINUE;
},
);
}
}
);