forked from nightscout/cgm-remote-monitor
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathindex.js
More file actions
1396 lines (1151 loc) · 44 KB
/
index.js
File metadata and controls
1396 lines (1151 loc) · 44 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
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
'use strict';
var _ = require('lodash');
var $ = (global && global.$) || require('jquery');
var d3 = (global && global.d3) || require('d3');
var shiroTrie = require('shiro-trie');
var Storages = require('js-storage');
var language = require('../language')();
var sandbox = require('../sandbox')();
var units = require('../units')();
var levels = require('../levels');
var times = require('../times');
var receiveDData = require('./receiveddata');
var brushing = false;
var browserSettings;
var moment = window.moment;
var timezones = moment.tz.names();
var client = {};
var hashauth = require('./hashauth');
client.hashauth = hashauth.init(client, $);
$('#loadingMessageText').html('Connecting to server');
client.headers = function headers () {
if (client.authorized) {
return {
Authorization: 'Bearer ' + client.authorized.token
};
} else if (client.hashauth) {
return {
'api-secret': client.hashauth.hash()
};
} else {
return {};
}
};
client.crashed = function crashed () {
$('#centerMessagePanel').show();
$('#loadingMessageText').html('It appears the server has crashed. Please go to Heroku or Azure and reboot the server.');
}
client.init = function init (callback) {
client.browserUtils = require('./browser-utils')($);
var token = client.browserUtils.queryParms().token;
var secret = client.hashauth.apisecrethash || Storages.localStorage.get('apisecrethash');
var src = '/api/v1/status.json?t=' + new Date().getTime();
if (secret) {
src += '&secret=' + secret;
} else if (token) {
src += '&token=' + token;
}
$.ajax({
method: 'GET'
, url: src
, headers: client.headers()
}).done(function success (serverSettings) {
if (serverSettings.runtimeState !== 'loaded') {
console.log('Server is still loading data');
$('#loadingMessageText').html('Server is starting and still loading data, retrying load in 5 seconds');
window.setTimeout(window.Nightscout.client.init, 5000);
return;
}
client.settingsFailed = false;
client.loadLanguage(serverSettings, callback);
}).fail(function fail (jqXHR) {
// check if we couldn't reach the server at all, show offline message
if (!jqXHR.readyState) {
console.log('Application appears to be OFFLINE');
$('#loadingMessageText').html('Connecting to Nightscout server failed, retrying every 5 seconds');
window.setTimeout(window.Nightscout.client.init(), 5000);
return;
}
//no server setting available, use defaults, auth, etc
if (client.settingsFailed) {
console.log('Already tried to get settings after auth, but failed');
} else {
client.settingsFailed = true;
// detect browser language
var lang = Storages.localStorage.get('language') || (navigator.language || navigator.userLanguage).toLowerCase();
if (lang !== 'zh_cn' && lang !== 'zh-cn' && lang !== 'zh_tw' && lang !== 'zh-tw') {
lang = lang.substring(0, 2);
} else {
lang = lang.replace('-', '_');
}
if (language.languages.find(l => l.code === lang)) {
language.set(lang);
} else {
language.set('en');
}
client.translate = language.translate;
// auth failed, hide loader and request for key
$('#centerMessagePanel').hide();
client.hashauth.requestAuthentication(function afterRequest () {
window.setTimeout(client.init(callback), 5000);
});
}
});
};
client.loadLanguage = function loadLanguage (serverSettings, callback) {
$('#loadingMessageText').html('Loading language file');
browserSettings = require('./browser-settings');
client.settings = browserSettings(client, serverSettings, $);
console.log('language is', client.settings.language);
let filename = language.getFilename(client.settings.language);
$.ajax({
method: 'GET'
, url: '/translations/' + filename
}).done(function success (localization) {
language.offerTranslations(localization);
console.log('Application appears to be online');
$('#centerMessagePanel').hide();
client.load(serverSettings, callback);
}).fail(function fail () {
console.error('Loading localization failed, continuing with English');
console.log('Application appears to be online');
$('#centerMessagePanel').hide();
client.load(serverSettings, callback);
});
}
client.load = function load (serverSettings, callback) {
var FORMAT_TIME_12 = '%-I:%M %p'
, FORMAT_TIME_12_COMPACT = '%-I:%M'
, FORMAT_TIME_24 = '%H:%M%'
, FORMAT_TIME_12_SCALE = '%-I %p'
, FORMAT_TIME_24_SCALE = '%H';
var history = 48;
var chart
, socket
, alarmSocket
, isInitialData = false
, opacity = { current: 1, DAY: 1, NIGHT: 0.5 }
, clientAlarms = {}
, alarmInProgress = false
, alarmMessage
, currentNotify
, currentAnnouncement
, alarmSound = 'alarm.mp3'
, urgentAlarmSound = 'alarm2.mp3'
, previousNotifyTimestamp;
client.entryToDate = function entryToDate (entry) {
if (entry.date) return entry.date;
entry.date = new Date(entry.mills);
return entry.date;
};
client.now = Date.now();
client.dataLastUpdated = 0;
client.lastPluginUpdateTime = 0;
client.ddata = require('../data/ddata')();
client.defaultForecastTime = times.mins(30).msecs;
client.forecastTime = client.now + client.defaultForecastTime;
client.entries = [];
client.ticks = require('./ticks');
//containers
var container = $('.container')
, bgStatus = $('.bgStatus')
, currentBG = $('.bgStatus .currentBG')
, majorPills = $('.bgStatus .majorPills')
, minorPills = $('.bgStatus .minorPills')
, statusPills = $('.status .statusPills')
, primary = $('.primary')
, editButton = $('#editbutton');
client.tooltip = d3.select('body').append('div')
.attr('class', 'tooltip')
.style('display', 'none');
client.settings = browserSettings(client, serverSettings, $);
language.set(client.settings.language).DOMtranslate($);
client.translate = language.translate;
client.language = language;
client.plugins = require('../plugins/')({
settings: client.settings
, extendedSettings: client.settings.extendedSettings
, language: language
, levels: levels
, moment: moment
}).registerClientDefaults();
browserSettings.loadPluginSettings(client);
client.utils = require('../utils')({
settings: client.settings
, language: language
, moment: moment
});
client.rawbg = client.plugins('rawbg');
client.delta = client.plugins('delta');
client.timeago = client.plugins('timeago');
client.direction = client.plugins('direction');
client.errorcodes = client.plugins('errorcodes');
client.ctx = {
data: {}
, bus: require('../bus')(client.settings, client.ctx)
, settings: client.settings
, pluginBase: client.plugins.base(majorPills, minorPills, statusPills, bgStatus, client.tooltip, Storages.localStorage)
, moment: moment
, timezones: timezones
};
client.ctx.language = language;
levels.translate = language.translate;
client.ctx.levels = levels;
client.ctx.notifications = require('../notifications')(client.settings, client.ctx);
client.sbx = sandbox.clientInit(client.ctx, client.now);
client.renderer = require('./renderer')(client, d3, $);
//After plugins are initialized with browser settings;
browserSettings.loadAndWireForm();
client.adminnotifies = require('./adminnotifiesclient')(client, $);
if (serverSettings && serverSettings.authorized) {
client.authorized = serverSettings.authorized;
client.authorized.lat = Date.now();
client.authorized.shiros = _.map(client.authorized.permissionGroups, function toShiro (group) {
var shiro = shiroTrie.new();
_.forEach(group, function eachPermission (permission) {
shiro.add(permission);
});
return shiro;
});
client.authorized.check = function check (permission) {
var found = _.find(client.authorized.shiros, function checkEach (shiro) {
return shiro.check(permission);
});
return _.isObject(found);
};
}
client.afterAuth = function afterAuth (isAuthenticated) {
var treatmentCreateAllowed = client.authorized ? client.authorized.check('api:treatments:create') : isAuthenticated;
var treatmentUpdateAllowed = client.authorized ? client.authorized.check('api:treatments:update') : isAuthenticated;
$('#lockedToggle').click(client.hashauth.requestAuthentication).toggle(!treatmentCreateAllowed && client.settings.showPlugins.indexOf('careportal') > -1);
$('#treatmentDrawerToggle').toggle(treatmentCreateAllowed && client.settings.showPlugins.indexOf('careportal') > -1);
$('#boluscalcDrawerToggle').toggle(treatmentCreateAllowed && client.settings.showPlugins.indexOf('boluscalc') > -1);
if (isAuthenticated) client.notifies.updateAdminNotifies();
// Edit mode
editButton.toggle(client.settings.editMode && treatmentUpdateAllowed);
editButton.click(function editModeClick (event) {
client.editMode = !client.editMode;
if (client.editMode) {
client.renderer.drawTreatments(client);
editButton.find('i').addClass('selected');
} else {
chart.focus.selectAll('.draggable-treatment')
.style('cursor', 'default')
.on('mousedown.drag', null);
editButton.find('i').removeClass('selected');
}
if (event) { event.preventDefault(); }
});
};
client.hashauth.initAuthentication(client.afterAuth);
client.focusRangeMS = times.hours(client.settings.focusHours).msecs;
$('.focus-range li[data-hours=' + client.settings.focusHours + ']').addClass('selected');
client.brushed = brushed;
client.formatTime = formatTime;
client.dataUpdate = dataUpdate;
client.careportal = require('./careportal')(client, $);
client.boluscalc = require('./boluscalc')(client, $);
var profile = require('../profilefunctions')(null, client.ctx);
client.profilefunctions = profile;
client.editMode = false;
//TODO: use the bus for updates and notifications
//client.ctx.bus.on('tick', function timedReload (tick) {
// console.info('tick', tick.now);
//});
//broadcast 'tock' event each minute, start a new setTimeout each time it fires make it happen on the minute
//see updateClock
//start the bus after setting up listeners
//client.ctx.bus.uptime( );
client.dataExtent = function dataExtent () {
if (client.entries.length > 0) {
return [client.entryToDate(client.entries[0]), client.entryToDate(client.entries[client.entries.length - 1])];
} else {
return [new Date(client.now - times.hours(history).msecs), new Date(client.now)];
}
};
client.bottomOfPills = function bottomOfPills () {
//the offset's might not exist for some tests
var bottomOfPrimary = primary.offset() ? primary.offset().top + primary.height() : 0;
var bottomOfMinorPills = minorPills.offset() ? minorPills.offset().top + minorPills.height() : 0;
var bottomOfStatusPills = statusPills.offset() ? statusPills.offset().top + statusPills.height() : 0;
return Math.max(bottomOfPrimary, bottomOfMinorPills, bottomOfStatusPills);
};
function formatTime (time, compact) {
var timeFormat = getTimeFormat(false, compact);
time = d3.timeFormat(timeFormat)(time);
if (client.settings.timeFormat !== 24) {
time = time.toLowerCase();
}
return time;
}
function getTimeFormat (isForScale, compact) {
var timeFormat = FORMAT_TIME_12;
if (client.settings.timeFormat === 24) {
timeFormat = isForScale ? FORMAT_TIME_24_SCALE : FORMAT_TIME_24;
} else {
timeFormat = isForScale ? FORMAT_TIME_12_SCALE : (compact ? FORMAT_TIME_12_COMPACT : FORMAT_TIME_12);
}
return timeFormat;
}
//TODO: replace with utils.scaleMgdl and/or utils.roundBGForDisplay
function scaleBg (bg) {
if (client.settings.units === 'mmol') {
return units.mgdlToMMOL(bg);
} else {
return bg;
}
}
function generateTitle () {
function s (value, sep) { return value ? value + ' ' : sep || ''; }
var title = '';
var status = client.timeago.checkStatus(client.sbx);
if (status !== 'current') {
var ago = client.timeago.calcDisplay(client.sbx.lastSGVEntry(), client.sbx.time);
title = s(ago.value) + s(ago.label, ' - ') + title;
} else if (client.latestSGV) {
var currentMgdl = client.latestSGV.mgdl;
if (currentMgdl < 39) {
title = s(client.errorcodes.toDisplay(currentMgdl), ' - ') + title;
} else {
var delta = client.nowSBX.properties.delta;
if (delta) {
var deltaDisplay = delta.display;
title = s(scaleBg(currentMgdl)) + s(deltaDisplay) + s(client.direction.info(client.latestSGV).label) + title;
}
}
}
return title;
}
function resetCustomTitle () {
var customTitle = client.settings.customTitle || 'Nightscout';
$('.customTitle').text(customTitle);
}
function checkAnnouncement () {
var result = {
inProgress: currentAnnouncement ? Date.now() - currentAnnouncement.received < times.mins(5).msecs : false
};
if (result.inProgress) {
var message = currentAnnouncement.message.length > 1 ? currentAnnouncement.message : currentAnnouncement.title;
result.message = message;
$('.customTitle').text(message);
} else if (currentAnnouncement) {
currentAnnouncement = null;
console.info('cleared announcement');
}
return result;
}
function updateTitle () {
var windowTitle;
var announcementStatus = checkAnnouncement();
if (alarmMessage && alarmInProgress) {
$('.customTitle').text(alarmMessage);
if (!isTimeAgoAlarmType()) {
windowTitle = alarmMessage + ': ' + generateTitle();
}
} else if (announcementStatus.inProgress && announcementStatus.message) {
windowTitle = announcementStatus.message + ': ' + generateTitle();
} else {
resetCustomTitle();
}
container.toggleClass('announcing', announcementStatus.inProgress);
$(document).attr('title', windowTitle || generateTitle());
}
// clears the current user brush and resets to the current real time data
function updateBrushToNow (skipBrushing) {
// update brush and focus chart with recent data
var brushExtent = client.dataExtent();
brushExtent[0] = new Date(brushExtent[1].getTime() - client.focusRangeMS);
// console.log('updateBrushToNow(): Resetting brush: ', brushExtent);
if (chart.theBrush) {
chart.theBrush.call(chart.brush)
chart.theBrush.call(chart.brush.move, brushExtent.map(chart.xScale2));
}
if (!skipBrushing) {
brushed();
}
}
function alarmingNow () {
return container.hasClass('alarming');
}
function inRetroMode () {
return chart && chart.inRetroMode();
}
function brushed () {
// Brush not initialized
if (!chart.theBrush) {
return;
}
if (brushing) {
return;
}
brushing = true;
// default to most recent focus period
var brushExtent = client.dataExtent();
brushExtent[0] = new Date(brushExtent[1].getTime() - client.focusRangeMS);
var brushedRange = d3.brushSelection(chart.theBrush.node());
// console.log("brushed(): coordinates: ", brushedRange);
if (brushedRange) {
brushExtent = brushedRange.map(chart.xScale2.invert);
}
// console.log('brushed(): Brushed to: ', brushExtent);
if (!brushedRange || (brushExtent[1].getTime() - brushExtent[0].getTime() !== client.focusRangeMS)) {
// ensure that brush updating is with the time range
if (brushExtent[0].getTime() + client.focusRangeMS > client.dataExtent()[1].getTime()) {
brushExtent[0] = new Date(brushExtent[1].getTime() - client.focusRangeMS);
} else {
brushExtent[1] = new Date(brushExtent[0].getTime() + client.focusRangeMS);
}
// console.log('brushed(): updating to: ', brushExtent);
chart.theBrush.call(chart.brush.move, brushExtent.map(chart.xScale2));
}
function adjustCurrentSGVClasses (value, isCurrent) {
var reallyCurrentAndNotAlarming = isCurrent && !inRetroMode() && !alarmingNow();
bgStatus.toggleClass('current', alarmingNow() || reallyCurrentAndNotAlarming);
if (!alarmingNow()) {
container.removeClass('urgent warning inrange');
if (reallyCurrentAndNotAlarming) {
container.addClass(sgvToColoredRange(value));
}
}
currentBG.toggleClass('icon-hourglass', value === 9);
currentBG.toggleClass('error-code', value < 39);
currentBG.toggleClass('bg-limit', value === 39 || value > 400);
}
function updateCurrentSGV (entry) {
var value = entry.mgdl
, isCurrent = 'current' === client.timeago.checkStatus(client.sbx);
if (value === 9) {
currentBG.text('');
} else if (value < 39) {
currentBG.html(client.errorcodes.toDisplay(value));
} else if (value < 40) {
currentBG.text('LOW');
} else if (value > 400) {
currentBG.text('HIGH');
} else {
currentBG.text(scaleBg(value));
}
adjustCurrentSGVClasses(value, isCurrent);
}
function mergeDeviceStatus (retro, ddata) {
if (!retro) {
return ddata;
}
var result = retro.map(x => Object.assign(x, ddata.find(y => y._id == x._id)));
var missingInRetro = ddata.filter(y => !retro.find(x => x._id == y._id));
result.push(...missingInRetro);
return result;
}
function updatePlugins (time) {
if (time > client.lastPluginUpdateTime && time > client.dataLastUpdated) {
if ((time - client.lastPluginUpdateTime) < 1000) {
return; // Don't update the plugins more than once a second
}
client.lastPluginUpdateTime = time;
}
//TODO: doing a clone was slow, but ok to let plugins muck with data?
//var ddata = client.ddata.clone();
client.ddata.inRetroMode = inRetroMode();
client.ddata.profile = profile;
// retro data only ever contains device statuses
// Cleate a clone of the data for the sandbox given to plugins
var mergedStatuses = client.ddata.devicestatus;
if (client.retro.data) {
mergedStatuses = mergeDeviceStatus(client.retro.data.devicestatus, client.ddata.devicestatus);
}
var clonedData = _.clone(client.ddata);
clonedData.devicestatus = mergedStatuses;
client.sbx = sandbox.clientInit(
client.ctx
, new Date(time).getTime() //make sure we send a timestamp
, clonedData
);
//all enabled plugins get a chance to set properties, even if they aren't shown
client.plugins.setProperties(client.sbx);
//only shown plugins get a chance to update visualisations
client.plugins.updateVisualisations(client.sbx);
var viewMenu = $('#viewMenu');
viewMenu.empty();
_.each(client.sbx.pluginBase.forecastInfos, function eachInfo (info) {
var forecastOption = $('<li/>');
var forecastLabel = $('<label/>');
var forecastCheckbox = $('<input type="checkbox" data-forecast-type="' + info.type + '"/>');
forecastCheckbox.prop('checked', client.settings.showForecast.indexOf(info.type) > -1);
forecastOption.append(forecastLabel);
forecastLabel.append(forecastCheckbox);
forecastLabel.append('<span>Show ' + info.label + '</span>');
forecastCheckbox.change(function onChange (event) {
var checkbox = $(event.target);
var type = checkbox.attr('data-forecast-type');
var checked = checkbox.prop('checked');
if (checked) {
client.settings.showForecast += ' ' + type;
} else {
client.settings.showForecast = _.chain(client.settings.showForecast.split(' '))
.filter(function(forecast) { return forecast !== type; })
.value()
.join(' ');
}
Storages.localStorage.set('showForecast', client.settings.showForecast);
refreshChart(true);
});
viewMenu.append(forecastOption);
});
//send data to boluscalc too
client.boluscalc.updateVisualisations(client.sbx);
}
function clearCurrentSGV () {
currentBG.text('---');
container.removeClass('alarming urgent warning inrange');
}
var nowDate = null;
var nowData = client.entries.filter(function(d) {
return d.type === 'sgv' && d.mills <= brushExtent[1].getTime();
});
var focusPoint = _.last(nowData);
function updateHeader () {
if (inRetroMode()) {
nowDate = brushExtent[1];
$('#currentTime')
.text(formatTime(nowDate, true))
.css('text-decoration', 'line-through');
} else {
nowDate = new Date(client.now);
updateClockDisplay();
}
if (focusPoint) {
if (brushExtent[1].getTime() - focusPoint.mills > times.mins(15).msecs) {
clearCurrentSGV();
} else {
updateCurrentSGV(focusPoint);
}
updatePlugins(nowDate.getTime());
} else {
clearCurrentSGV();
updatePlugins(nowDate);
}
}
updateHeader();
updateTimeAgo();
if (chart.prevChartHeight) {
chart.scroll(nowDate);
}
var top = (client.bottomOfPills() + 5);
$('#chartContainer').css({ top: top + 'px', height: $(window).height() - top - 10 });
container.removeClass('loading');
brushing = false;
}
function sgvToColor (sgv) {
var color = 'grey';
if (client.settings.theme !== 'default') {
if (sgv > client.settings.thresholds.bgHigh) {
color = 'red';
} else if (sgv > client.settings.thresholds.bgTargetTop) {
color = 'yellow';
} else if (sgv >= client.settings.thresholds.bgTargetBottom && sgv <= client.settings.thresholds.bgTargetTop && client.settings.theme === 'colors') {
color = '#4cff00';
} else if (sgv < client.settings.thresholds.bgLow) {
color = 'red';
} else if (sgv < client.settings.thresholds.bgTargetBottom) {
color = 'yellow';
}
}
return color;
}
function sgvToColoredRange (sgv) {
var range = '';
if (client.settings.theme !== 'default') {
if (sgv > client.settings.thresholds.bgHigh) {
range = 'urgent';
} else if (sgv > client.settings.thresholds.bgTargetTop) {
range = 'warning';
} else if (sgv >= client.settings.thresholds.bgTargetBottom && sgv <= client.settings.thresholds.bgTargetTop && client.settings.theme === 'colors') {
range = 'inrange';
} else if (sgv < client.settings.thresholds.bgLow) {
range = 'urgent';
} else if (sgv < client.settings.thresholds.bgTargetBottom) {
range = 'warning';
}
}
return range;
}
function formatAlarmMessage (notify) {
var announcementMessage = notify && notify.isAnnouncement && notify.message && notify.message.length > 1;
if (announcementMessage) {
return levels.toDisplay(notify.level) + ': ' + notify.message;
} else if (notify) {
return notify.title;
}
return null;
}
function setAlarmMessage (notify) {
alarmMessage = formatAlarmMessage(notify);
}
function generateAlarm (file, notify) {
alarmInProgress = true;
currentNotify = notify;
setAlarmMessage(notify);
var selector = '.audio.alarms audio.' + file;
if (!alarmingNow()) {
d3.select(selector).each(function() {
var audio = this;
playAlarm(audio);
$(this).addClass('playing');
});
console.log('Asking plugins to visualize alarms');
client.plugins.visualizeAlarm(client.sbx, notify, alarmMessage);
}
container.addClass('alarming').addClass(file === urgentAlarmSound ? 'urgent' : 'warning');
var silenceBtn = $('#silenceBtn');
silenceBtn.empty();
_.each(client.settings.snoozeMinsForAlarmEvent(notify), function eachOption (mins) {
var snoozeOption = $('<li><a data-snooze-time="' + times.mins(mins).msecs + '">' + client.translate('Silence for %1 minutes', { params: [mins] }) + '</a></li>');
snoozeOption.click(snoozeAlarm);
silenceBtn.append(snoozeOption);
});
updateTitle();
}
function snoozeAlarm (event) {
stopAlarm(true, $(event.target).data('snooze-time'));
event.preventDefault();
}
function playAlarm (audio) {
// ?mute=true disables alarms to testers.
if (client.browserUtils.queryParms().mute !== 'true') {
audio.play();
} else {
client.browserUtils.showNotification('Alarm was muted (?mute=true)');
}
}
function stopAlarm (isClient, silenceTime, notify) {
alarmInProgress = false;
alarmMessage = null;
container.removeClass('urgent warning');
d3.selectAll('audio.playing').each(function() {
var audio = this;
audio.pause();
$(this).removeClass('playing');
});
client.browserUtils.closeNotification();
container.removeClass('alarming');
updateTitle();
silenceTime = silenceTime || times.mins(5).msecs;
var alarm = null;
if (notify) {
if (notify.level) {
alarm = getClientAlarm(notify.level, notify.group);
} else if (notify.group) {
alarm = getClientAlarm(currentNotify.level, notify.group);
} else {
alarm = getClientAlarm(currentNotify.level, currentNotify.group);
}
} else if (currentNotify) {
alarm = getClientAlarm(currentNotify.level, currentNotify.group);
}
if (alarm) {
alarm.lastAckTime = Date.now();
alarm.silenceTime = silenceTime;
if (alarm.group === 'Time Ago') {
container.removeClass('alarming-timeago');
}
} else {
console.info('No alarm to ack for', notify || currentNotify);
}
// only emit ack if client invoke by button press
if (isClient && currentNotify) {
alarmSocket.emit('ack', currentNotify.level, currentNotify.group, silenceTime);
}
currentNotify = null;
brushed();
}
function refreshAuthIfNeeded () {
var clientToken = client.authorized ? client.authorized.token : null;
var token = client.browserUtils.queryParms().token || clientToken;
if (token && client.authorized) {
var renewTime = (client.authorized.exp * 1000) - times.mins(15).msecs - Math.abs((client.authorized.iat * 1000) - client.authorized.lat);
var refreshIn = Math.round((renewTime - client.now) / 1000);
if (client.now > renewTime) {
console.info('Refreshing authorization renewal');
$.ajax('/api/v2/authorization/request/' + token, {
success: function(authorized) {
if (authorized) {
console.info('Got new authorization', authorized);
authorized.lat = client.now;
client.authorized = authorized;
}
}
});
} else if (refreshIn < times.mins(5).secs) {
console.info('authorization refresh in ' + refreshIn + 's');
}
}
}
function updateClock () {
updateClockDisplay();
// Update at least every 15 seconds
var interval = Math.min(15 * 1000, (60 - (new Date()).getSeconds()) * 1000 + 5);
setTimeout(updateClock, interval);
updateTimeAgo();
if (chart) {
brushed();
}
// Dim the screen by reducing the opacity when at nighttime
if (client.settings.nightMode) {
var dateTime = new Date();
if (opacity.current !== opacity.NIGHT && (dateTime.getHours() > 21 || dateTime.getHours() < 7)) {
$('body').css({ 'opacity': opacity.NIGHT });
} else {
$('body').css({ 'opacity': opacity.DAY });
}
}
refreshAuthIfNeeded();
if (client.resetRetroIfNeeded) {
client.resetRetroIfNeeded();
}
}
function updateClockDisplay () {
if (inRetroMode()) {
return;
}
client.now = Date.now();
$('#currentTime').text(formatTime(new Date(client.now), true)).css('text-decoration', '');
}
function getClientAlarm (level, group) {
var key = level + '-' + group;
var alarm = null;
// validate the key before getting the alarm
if (Object.prototype.hasOwnProperty.call(clientAlarms, key)) {
/* eslint-disable-next-line security/detect-object-injection */ // verified false positive
alarm = clientAlarms[key];
}
if (!alarm) {
alarm = { level: level, group: group };
/* eslint-disable-next-line security/detect-object-injection */ // verified false positive
clientAlarms[key] = alarm;
}
return alarm;
}
function isTimeAgoAlarmType () {
return currentNotify && currentNotify.group === 'Time Ago';
}
function isStale (status) {
return client.settings.alarmTimeagoWarn && status === 'warn' ||
client.settings.alarmTimeagoUrgent && status === 'urgent';
}
function notAcked (alarm) {
return Date.now() >= (alarm.lastAckTime || 0) + (alarm.silenceTime || 0);
}
function checkTimeAgoAlarm (status) {
var level = status === 'urgent' ? levels.URGENT : levels.WARN;
var alarm = getClientAlarm(level, 'Time Ago');
if (isStale(status) && notAcked(alarm)) {
console.info('generating timeAgoAlarm', alarm);
container.addClass('alarming-timeago');
var display = client.timeago.calcDisplay(client.sbx.lastSGVEntry(), client.sbx.time);
var translate = client.translate;
var notify = {
title: translate('Last data received') + ' ' + display.value + ' ' + translate(display.label)
, level: status === 'urgent' ? 2 : 1
, group: 'Time Ago'
};
var sound = status === 'warn' ? alarmSound : urgentAlarmSound;
generateAlarm(sound, notify);
}
container.toggleClass('alarming-timeago', status !== 'current');
if (status === 'warn') {
container.addClass('warn');
} else if (status === 'urgent') {
container.addClass('urgent');
}
if (alarmingNow() && status === 'current' && isTimeAgoAlarmType()) {
stopAlarm(true, times.min().msecs);
}
}
function updateTimeAgo () {
var status = client.timeago.checkStatus(client.sbx);
if (status !== 'current') {
updateTitle();
}
checkTimeAgoAlarm(status);
}
function updateTimeAgoSoon () {
setTimeout(function updatingTimeAgoNow () {
updateTimeAgo();
}, times.secs(10).msecs);
}
function refreshChart (updateToNow) {
if (updateToNow) {
updateBrushToNow();
}
chart.update(false);
}
(function watchVisibility () {
// Set the name of the hidden property and the change event for visibility
var hidden, visibilityChange;
if (typeof document.hidden !== 'undefined') {
hidden = 'hidden';
visibilityChange = 'visibilitychange';
} else if (typeof document.mozHidden !== 'undefined') {
hidden = 'mozHidden';
visibilityChange = 'mozvisibilitychange';
} else if (typeof document.msHidden !== 'undefined') {
hidden = 'msHidden';
visibilityChange = 'msvisibilitychange';
} else if (typeof document.webkitHidden !== 'undefined') {
hidden = 'webkitHidden';
visibilityChange = 'webkitvisibilitychange';
}
document.addEventListener(visibilityChange, function visibilityChanged () {
var prevHidden = client.documentHidden;
/* eslint-disable-next-line security/detect-object-injection */ // verified false positive
client.documentHidden = document[hidden];
if (prevHidden && !client.documentHidden) {
console.info('Document now visible, updating - ' + new Date());
refreshChart(true);
}
});
})();
window.onresize = refreshChart;
updateClock();
updateTimeAgoSoon();
function Dropdown (el) {
this.ddmenuitem = 0;
this.$el = $(el);
var that = this;