-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathapp.js
464 lines (414 loc) · 11.5 KB
/
app.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
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
// Imports {{{
var _ = require('lodash');
var $ = jQuery = require('jquery');
var angular = require('angular');
var electron = require('electron');
var Highcharts = require('highcharts');
var moment = require('moment');
// }}}
// Replace console.log -> ipcRenderer.sendMessage('console') + original console.log {{{
console.logReal = console.log;
console.log = function() {
var args = Array.prototype.slice.call(arguments, 0);
electron.ipcRenderer.send.apply(this, ['console'].concat(args));
console.logReal.apply(this, args);
};
// }}}
// User configurable options
var options = {
chartPeriod: moment.duration(1, 'hour').as('milliseconds'), // How far backwards each chart should log - this period effectvely equals the X axis range
chartPeriodCleanup: moment.duration(5, 'minutes').as('milliseconds'), // Clean up chart data periodically
conkieStatsModules: [ // Modules we want Conkie stats to load
'cpu',
'dropbox',
'io', // Also provides 'topIO'
'memory',
'net',
'power',
'system',
'temperature',
'topCPU',
'topMemory',
],
conkieStats: { // Options passed to conkie-stats
topProcessCount: 5,
net: {
ignoreNoIP: true,
ignoreDevice: ['lo', 'wg0', 'tun0'],
},
pollFrequency: {
dropbox: 2000,
io: 5000,
memory: 5000,
net: 5000,
temperature: 5000,
},
},
mainBattery: ['BAT0', 'BAT1'], // Which battery to examine for power info (the first one found gets bound to $scope.stats.battery)
window: {
left: -10,
top: 40,
width: 240,
height: 1000,
},
};
// Code only below this line - here be dragons
// -------------------------------------------
var app = angular.module('app', [
'highcharts-ng',
]);
// Angular / Filters {{{
/**
* Format a given number of seconds as a human readable duration
* e.g. 65 => '1m 5s'
* @param {number} value The number of seconds to process
* @return {string} The formatted value
*/
app.filter('duration', function() {
return function(value) {
if (!value || !isFinite(value)) return;
var duration = moment.duration(value, 'seconds');
if (!duration) return;
var out = '';
var years = duration.years();
if (years) out += years + 'Y ';
var months = duration.months();
if (months) out += months + 'M ';
var days = duration.days();
if (days) out += days + 'd ';
var hours = duration.hours();
if (hours) out += hours + 'h ';
var minutes = duration.minutes();
if (minutes) out += minutes + 'm ';
var seconds = duration.seconds();
if (seconds) out += seconds + 's';
return out;
};
});
/**
* Return a formatted number as a file size
* e.g. 0 => 0B, 1024 => 1 kB
* @param {mixed} value The value to format
* @param {boolean} forceZero Whether the filter should return '0 B' if it doesnt know what to do
* @return {string} The formatted value
*/
app.filter('byteSize', function() {
return function(value, forceZero) {
if (!value || !isFinite(value)) return (forceZero ? '0 B' : null);
var exponent;
var unit;
var neg = value < 0;
var units = ['B', 'kB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB'];
if (neg) {
value = -value;
}
if (value < 1) {
return (neg ? '-' : '') + value + ' B';
}
exponent = Math.min(Math.floor(Math.log(value) / Math.log(1000)), units.length - 1);
value = (value / Math.pow(1000, exponent)).toFixed(2) * 1;
unit = units[exponent];
return (neg ? '-' : '') + value + ' ' + unit;
};
});
/**
* Return a number as a formatted percentage
* @param {mixed} value The value to format
* @return {string} The formatted value
*/
app.filter('percent', function() {
return function(value) {
if (!value || !isFinite(value)) return '';
return Math.round(value, 2) + '%';
};
});
// }}}
app.directive('graph', function() {
return {
scope: {
data: '=',
config: '=',
},
restrict: 'E',
template: '',
controller: function($scope) {
// Implied: $scope.elem;
$scope.$watchCollection('data', function() {
if (!$scope.elem || !$scope.data) return; // Element or data not bound yet
$scope.elem.sparkline($scope.data, $scope.config);
});
},
link: function($scope, elem, attr, ctrl) {
$scope.elem = $(elem);
},
};
});
/**
* The main Conkie controller
* Each of the data feeds are exposed via the 'stats' structure and correspond to the output of [Conkie-Stats](https://github.com/hash-bang/Conkie-Stats)
*/
app.controller('conkieController', function($scope, $interval, $timeout) {
// .stats - backend-IPC provided stats object {{{
$scope.stats = {}; // Stats object (gets updated via IPC)
/**
* Object to hold when we last had data updates - each key is the module, each value is the unix timestamp
* Since conkie-stats can provide different modules at different intervals we need to track when the mod last updated its info so we know whether to accept it as a new entry within a chart
* @type {Object}
*/
$scope.lastUpdate = {};
electron.ipcRenderer
// Event: updateStats {{{
.on('updateStats', function(e, data) {
$scope.$apply(function() {
var now = new Date();
$scope.stats = data;
// Chart data updates {{{
// .stats.power {{{
if ($scope.stats.power && (!$scope.lastUpdate.power || $scope.lastUpdate.power != data.lastUpdate.power)) {
$scope.lastUpdate.power = data.lastUpdate.power;
$scope.stats.battery = $scope.stats.power.find(function(dev) {
return (_.includes(options.mainBattery, dev.device));
});
if ($scope.stats.battery) $scope.charts.battery.series[0].data.push([now, $scope.stats.battery.percent]);
}
// }}}
// .stats.io {{{
if (_.has($scope.stats, 'io.totalRead') && isFinite($scope.stats.io.totalRead) && (!$scope.lastUpdate.io || $scope.lastUpdate.io != data.lastUpdate.io)) {
$scope.lastUpdate.io = data.lastUpdate.io;
$scope.charts.io.series[0].data.push([now, $scope.stats.io.totalRead]);
}
// }}}
// .stats.memory {{{
if (_.has($scope.stats, 'memory.used') && isFinite($scope.stats.memory.used) && (!$scope.lastUpdate.memory || $scope.lastUpdate.memory != data.lastUpdate.memory)) {
$scope.lastUpdate.memory = data.lastUpdate.memory;
if ($scope.stats.memory.total) $scope.charts.memory.yAxis.max = $scope.stats.memory.total;
$scope.charts.memory.series[0].data.push([now, $scope.stats.memory.used]);
}
// }}}
// .net {{{
var updatedNet = false;
if ($scope.stats.net && (!$scope.lastUpdate.net || $scope.lastUpdate.net != data.lastUpdate.net)) {
$scope.lastUpdate.net = data.lastUpdate.net;
updatedNet = true;
$scope.stats.net.forEach(function(adapter) {
var id = adapter.interface; // Use the adapter interface name as the chart name
// Not seen this adapter before - create a chart object {{{
if (!$scope.charts[id]) $scope.charts[id] = _.defaultsDeep({
yAxis: {
min: 0,
max: null,
},
series: [
{
// name: 'Download',
data: [],
color: '#FFFFFF',
},
{
name: 'Upload',
color: '#606060',
fillColor: 'rgba(144,144,144,0.25)',
data: [],
},
],
}, $scope.charts.template);
// }}}
// Append bandwidth data to the chart {{{
if (isFinite(adapter.downSpeed)) $scope.charts[id].series[0].data.push([now, adapter.downSpeed]);
if (isFinite(adapter.upSpeed)) $scope.charts[id].series[1].data.push([now, adapter.upSpeed]);
// }}}
});
}
// }}}
// .stats.system {{{
if (_.has($scope.stats, 'cpu.usage') && isFinite($scope.stats.cpu.usage) && (!$scope.lastUpdate.cpu || $scope.lastUpdate.cpu != data.lastUpdate.cpu)) {
$scope.lastUpdate.cpu = data.lastUpdate.cpu;
$scope.charts.cpu.series[0].data.push([now, $scope.stats.cpu.usage]);
}
// }}}
// META: .stats.netTotal {{{
$scope.stats.netTotal = $scope.stats.net.reduce(function(total, adapter) {
if (adapter.downSpeed) total.downSpeed += adapter.downSpeed;
if (adapter.upSpeed) total.upSpeed += adapter.upSpeed;
return total;
}, {
downSpeed: 0,
upSpeed: 0,
});
// }}}
// Change the periodStart of each chart {{{
_.forEach($scope.charts, function(chart, id) {
chart.options.xAxis.periodStart = new Date(now - options.chartPeriod);
});
// }}}
// }}}
});
})
// }}}
// Configure conkie-stats to provide us with information {{{
$timeout(function() {
electron.ipcRenderer
.send('statsRegister', options.conkieStatsModules)
});
$timeout(function() {
electron.ipcRenderer
.send('statsSettings', options.conkieStats);
});
// }}}
// Position the widget {{{
$timeout(function() {
electron.ipcRenderer
.send('setPosition', options.window);
});
// }}}
// Periodically clean up redundent data for all charts {{{
var cleaner = function() {
console.log('Beginning data clean');
var cleanStartTime = Date.now();
var cleanTo = Date.now() - options.chartPeriod;
_.forEach($scope.charts, function(chart, chartId) {
_.forEach(chart.series, function(series, seriesIndex) {
// Shift all data if the date has fallen off the observed time range
var beforeLength = series.data.length;
series.data = _.dropWhile(series.data, function(d) {
return (d[0] < cleanTo);
});
console.log('Cleaned charts.' + chartId + '.series.' + seriesIndex + ' from length=' + beforeLength + ' now=' + series.data.length);
});
});
console.log('End data clean. Time taken =' + (Date.now() - cleanStartTime) + 'ms');
$timeout(cleaner, options.chartPeriodCleanup);
};
$timeout(cleaner, options.chartPeriodCleanup);
// }}}
// }}}
// .time {{{
$interval(function() {
$scope.time = moment().format('HH:mm');
}, 1000);
// }}}
// Charts {{{
$scope.charts = {};
$scope.charts.template = {
size: {
width: 150,
height: 33,
},
options: {
chart: {
animation: false,
borderWidth: 0,
type: 'area',
margin: [2, 0, 2, 0],
backgroundColor: null,
borderWidth: 0,
style: {
border: '1px solid white',
},
},
credits: {
enabled: false
},
title: {
text: ''
},
xAxis: {
type: 'datetime',
periodStart: new Date(Date.now() - options.chartPeriod),
labels: {
enabled: false
},
title: {
text: null
},
startOnTick: false,
endOnTick: false,
tickPositions: [],
},
yAxis: {
labels: {
enabled: false
},
title: {
text: null
},
endOnTick: false,
startOnTick: false,
tickPositions: [0],
},
legend: {
enabled: false,
},
tooltip: {
enabled: false,
},
plotOptions: {
series: {
animation: false,
lineWidth: 1,
shadow: false,
states: {
hover: {
lineWidth: 1
}
},
marker: {
radius: 1,
states: {
hover: {
radius: 2
}
}
},
fillOpacity: 0.25
},
column: {
negativeColor: '#910000',
borderColor: 'silver'
},
},
},
};
$scope.charts.battery = _.defaultsDeep({
yAxis: {
min: 0,
max: 100,
},
series: [{
data: [],
color: '#FFFFFF',
}],
}, $scope.charts.template);
$scope.charts.memory = _.defaultsDeep({
yAxis: {
min: 0,
max: null, // Gets corrected on next stats cycle
},
series: [{
data: [],
color: '#FFFFFF',
}],
}, $scope.charts.template);
$scope.charts.cpu = _.defaultsDeep({
yAxis: {
min: 0,
max: 100,
},
series: [{
data: [],
color: '#FFFFFF',
}],
}, $scope.charts.template);
$scope.charts.io = _.defaultsDeep({
yAxis: {
min: 0,
max: null,
},
series: [{
data: [],
color: '#FFFFFF',
}],
}, $scope.charts.template);
// }}}
console.log('Theme controller loaded');
});