-
Notifications
You must be signed in to change notification settings - Fork 28
/
app.js
519 lines (468 loc) · 16 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
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
//----------DEFAULT VARIABLES----------
var usingFiles = false; //True if the user uploaded his own JSON
var failCount = 0; //Counts how many times getData tries the request if there is a failure
var rawEfficencyData; //contains the efficiency's data (first 3 chart)
var rawActivityData; //contains the activities's data (last chart)
//objects that will be used for the requests with default values
var queries = {
activities: {
perspective: 'rank',
restrict_kind: 'activity'
},
efficiency: {
perspective: 'interval',
restrict_kind: 'efficiency',
}
};
$("document").ready(function() {
$('#fileEfficency').on('change', fileUploaded);
$('#fileActivity').on('change', fileUploaded);
//redraw the efficiency chart when the value change
$('#trendLineSpinner').on('change', function(event) {
fullEfficiencyChart(rawEfficencyData);
});
$('#activitiesNumberSpinner').on('change', function(event) {
activityChart(rawActivityData);
});
});
function init() {
var key = document.getElementById('api_key').value;
if (key.length > 5) {
usingFiles = false;
queries.efficiency.key = queries.activities.key = key;
queries.efficiency.restrict_begin = queries.activities.restrict_begin = document.getElementById('from').value;
queries.efficiency.restrict_end = queries.activities.restrict_end = document.getElementById('to').value;
queries.efficiency.interval = queries.activities.interval = 'hour';
queries.efficiency.format = queries.activities.format = 'json';
//activities data
getData(queries.activities);
//efficiency data
getData(queries.efficiency);
$('#downloadSection').empty();
$('.spinner').show();
$('.chart').show();
} else {
alert('Please insert your api key');
}
}
function getData(params) {
var rescuetimeAPI = 'https://www.rescuetime.com/anapi/data?';
$.getJSON('https://allow-any-origin.appspot.com/' + rescuetimeAPI, {
key: params.key,
perspective: params.perspective,
restrict_kind: params.restrict_kind,
interval: params.interval,
restrict_begin: params.restrict_begin,
restrict_end: params.restrict_end,
format: params.format
})
.done(function(data) {
if (data.error) {
alert(data.messages);
}
if (params.restrict_kind === 'efficiency') {
fullEfficiencyChart(data.rows);
combinedCharts(data.rows);
rawEfficencyData = data.rows;
} else if (params.restrict_kind === 'activity') {
activityChart(data.rows);
rawActivityData = data.rows;
}
if (document.getElementById('download').checked) {
startDownload(data, params.restrict_kind);
}
$('.spinner').hide();
}).fail(function(jqxhr, textStatus, error) {
failCount++;
if (failCount < 3) {
setTimeout(getData(params), failCount * 300);
} else {
var modal = $('<div class="modal fade bs-modal-sm" tabindex="-1" role="dialog"> <div class="modal-dialog modal-sm"> <div class="modal-content">Error retriving your data. Please try again later. If you keep getting this error please open an issue on GitHub or send an email to davide.bonte@gmail.com </div></div></div>');
modal.modal('show');
}
// jqxhr.status
//TODO: add retry for 403 over quota?
var err = textStatus + ', ' + error;
console.log('Request Failed: ' + err);
});
}
function checkFiles() {
$(".chart").show();
usingFiles = true;
$("#act-display").empty();
// TODO: add check per vedere se ho effetivamente caricato dei file e vedere se sono validi
if (rawEfficencyData) {
fullEfficiencyChart(rawEfficencyData);
combinedCharts(rawEfficencyData);
}
if (rawActivityData) {
activityChart(rawActivityData);
}
}
function fileUploaded(event) {
var file = event.target.files[0];
var reader = new FileReader();
reader.onload = function(e) {
if (event.target.id === 'fileEfficency') {
rawEfficencyData = (JSON.parse(e.target.result)).rows;
} else if (event.target.id === 'fileActivity') {
rawActivityData = (JSON.parse(e.target.result)).rows;
}
};
reader.readAsText(file);
}
//add and automatically start the download for the files
function startDownload(data, type) {
var JSONString = JSON.stringify(data);
var file = "text/json;charset=utf-8," + encodeURIComponent(JSONString);
$('<a href="data:' + file + '" download="' + type + '+' + document.getElementById('from').value + ' to ' + document.getElementById('to').value + '.json" id="download' + type + '">Download ' + type + ' Data</a> <br>').appendTo('#downloadSection');
$('#download' + type).get(0).click();
}
/***************
*****CHARTS****
***************/
function fullEfficiencyChart(data) {
var normalizedData = [];
data.forEach(function(point) {
normalizedData.push([new Date(point[0]).getTime(), (point[4] * point[1]) / 3600]);
// normalizedData.push([new Date(point[0]).getTime(), point[4]]);
});
$('#efficiency_chart').highcharts('StockChart', {
chart: {
height: Math.max(window.innerHeight - 100, 350)
},
rangeSelector: {
buttons: [{
type: 'day',
count: 1,
text: '1D'
}, {
type: 'week',
count: 1,
text: '1W'
}, {
type: 'month',
count: 1,
text: '1M'
}, {
type: 'year',
count: 1,
text: '1Y'
}, {
type: 'all',
count: 1,
text: 'All'
}],
selected: 5,
inputEnabled: true
},
title: {
text: 'Productivity for the selected range'
},
series: [{
name: 'Efficiency',
type: 'scatter',
pointWith: 1,
data: normalizedData,
color: '#D6DCEA',
tooltip: {
valueDecimals: 2
},
regression: true,
regressionSettings: {
type: 'loess',
color: '#1111cc',
loessSmooth: parseInt(document.getElementById("trendLineSpinner").value)
},
}]
});
Highcharts.setOptions(Highcharts.theme);
}
function combinedCharts(data) {
var hours = initializeArray(24);
var days = initializeArray(7);
var hour = 0;
var day = 0;
data.forEach(function(element) {
hour = parseInt(element[0].substr(11, 2)); //note: I can't use Date() because rescuetime log the date based on user's system time which is in GMT but when using Date() on the string in the JSON is converted in UTC :(
day = new Date(element[0].substr(0, 10)).getDay();
hours[hour].totalTime += element[1]; //sum of the total time for a given hour
hours[hour].totalEfficency += (element[4] * element[1]) / 3600; //normalize the data
hours[hour].count++; //how many entries for a given hour. Used to calculate the average efficency
days[day].totalTime += element[1];
days[day].totalEfficency += (element[4] * element[1]) / 3600;
days[day].count++;
});
displayCombined('#combo_hour_chart', calcAvg(hours));
displayCombined('#combo_day_chart', calcAvg(days));
}
//inizialize the array with the default object
function initializeArray(length) {
var array = [];
for (var i = 0; i < length; i++) {
array.push({
totalTime: 0,
totalEfficency: 0,
avgEfficency: 0,
count: 0
});
}
return array;
}
//calculate the average efficency for the given period (day or hour)
function calcAvg(array) {
array.forEach(function(element) {
element.avgEfficency = element.totalEfficency / element.count;
});
return array;
}
//create the chart with total time and average efficency
function displayCombined(DOMChart, data) {
var totalTime = [];
data.forEach(function(item) {
totalTime.push(item.totalTime / 3600);
});
var avgEfficency = [];
data.forEach(function(item) {
avgEfficency.push(item.avgEfficency || 0);
});
var categories = [];
if (avgEfficency.length === 7) {
categories = ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'];
}
$(DOMChart).highcharts({
chart: {
zoomType: 'xy'
},
xAxis: [{
categories: categories,
crosshair: true
}],
yAxis: [{ // Primary yAxis
labels: {
format: '{value}%',
style: {
color: Highcharts.getOptions().colors[1]
}
},
title: {
text: 'Efficiency',
style: {
color: Highcharts.getOptions().colors[1]
}
},
min: 0,
max: 100
}, { // Secondary yAxis
title: {
text: 'Total Time',
style: {
color: Highcharts.getOptions().colors[0]
}
},
labels: {
format: '{value} H',
style: {
color: Highcharts.getOptions().colors[0]
}
},
opposite: true
}],
tooltip: {
shared: true
},
legend: {
layout: 'vertical',
align: 'left',
x: 50,
verticalAlign: 'top',
y: 50,
floating: true,
backgroundColor: (Highcharts.theme && Highcharts.theme.legendBackgroundColor) || '#FFFFFF'
},
series: [{
name: 'Total Time',
type: 'column',
yAxis: 1,
data: totalTime,
tooltip: {
pointFormat: 'Total Time: {point.y:.2f} hh<br>'
}
}, {
name: 'Efficiency',
type: 'spline',
data: avgEfficency,
tooltip: {
pointFormat: 'Efficiency: {point.y:.2f} %'
}
}]
});
}
//chart with the total time
function activityChart(data) {
// ["Rank", "Time Spent (seconds)", "Number of People", "Activity", "Category", "Productivity"]
var categories = {
veryDistracting: {
total: 0,
color: '#C5392F'
},
distracting: {
total: 0,
color: '#92343B'
},
neutral: {
total: 0,
color: '#655568'
},
productive: {
total: 0,
color: '#395B96'
},
veryProductive: {
total: 0,
color: '#2F78BD'
}
};
var activityData = [];
var totalSeconds = 0;
//colors the bars
data.forEach(function(activity) {
totalSeconds += activity[1];
switch (activity[5]) {
case -2:
activityData.push({
color: categories.veryDistracting.color,
y: activity[1],
name: activity[3]
});
categories.veryDistracting.total += activity[1];
break;
case -1:
activityData.push({
color: categories.distracting.color,
y: activity[1],
name: activity[3]
});
categories.distracting.total += activity[1];
break;
case 0:
activityData.push({
color: categories.neutral.color,
y: activity[1],
name: activity[3]
});
categories.neutral.total += activity[1];
break;
case 1:
activityData.push({
color: categories.productive.color,
y: activity[1],
name: activity[3]
});
categories.productive.total += activity[1];
break;
case 2:
activityData.push({
color: categories.veryProductive.color,
y: activity[1],
name: activity[3]
});
categories.veryProductive.total += activity[1];
break;
}
});
$('#act_chart').highcharts({
chart: {
height: (document.getElementById("activitiesNumberSpinner").value * 20)
},
title: {
text: 'Activities'
},
subtitle: {
text: '<strong>Total time recorded (hh:mm:ss) : ' + timeFormatter(totalSeconds) + '<br>' +avgPerDay(totalSeconds)+'</strong>'
},
tooltip: {
formatter: function() {
return 'Total: ' +
timeFormatter(this.y) + '<br>'+avgPerDay(this.y) ;
}
},
plotOptions: {
series: {
dataLabels: {
allowPointSelect: true,
enabled: true,
formatter: function() {
return timeFormatter(this.y);
}
}
}
},
xAxis: {
categories: function() {
var result = [];
return activityData.map(function(item) {
return item.name;
}).slice(0, parseInt(document.getElementById("activitiesNumberSpinner").value));
}
},
yAxis: {
labels: {
formatter: function() {
return timeFormatter(this.value);
}
}
},
series: [{
type: 'bar',
name: 'Activities',
data: activityData.slice(0, parseInt(document.getElementById("activitiesNumberSpinner").value)),
showInLegend: false
}, {
type: 'pie',
name: 'Total consumption',
data: [{
name: 'Very Productive',
y: categories.veryProductive.total,
color: categories.veryProductive.color
}, {
name: 'Productive',
y: categories.productive.total,
color: categories.productive.color
}, {
name: 'Neutral',
y: categories.neutral.total,
color: categories.neutral.color
}, {
name: 'Distracting',
y: categories.distracting.total,
color: categories.distracting.color
}, {
name: 'Very Distracting',
y: categories.veryDistracting.total,
color: categories.veryDistracting.color
}],
center: ['85%', '70%'],
size: 200,
showInLegend: true
}]
});
}
function avgPerDay(time){
if(!usingFiles){
var fromDate = new Date(document.getElementById('from').value);
var toDate = new Date(document.getElementById('to').value);
var timeDiff = Math.abs(toDate.getTime() - fromDate.getTime());
var diffDays = Math.ceil(timeDiff / (1000 * 3600 * 24));
var avgPerDay = time / diffDays;
return 'Average time per day: ' + timeFormatter(Math.ceil(avgPerDay));
}
return '';
}
//seconds to a readable format
function timeFormatter(totalSeconds) {
var hours = parseInt(totalSeconds / 3600);
var minutes = parseInt(totalSeconds / 60) % 60;
var seconds = totalSeconds % 60;
return (hours < 10 ? '0' + hours : hours) + ':' + (minutes < 10 ? '0' + minutes : minutes) + ':' + (seconds < 10 ? '0' + seconds : seconds);
}