-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.js
701 lines (620 loc) · 20.4 KB
/
main.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
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
const electron = require('electron');
const url = require('url');
const path = require('path');
const ipc = electron.ipcMain
const fileSystem = require('fs')
var bonjour = require('bonjour-hap')();
const portfinder = require('portfinder')
const http = require('http');
const formidable = require('formidable')
const dataRestore = require("./dataRestore")
const {app, BrowserWindow, Menu, dialog} = electron;
const EXPORT_DIRECTORY_NAME = "export"
const EXPORT_DIRECTORY = "./" + EXPORT_DIRECTORY_NAME
const UPLOAD_DIRECTORY = "./upload"
const DATA_DIRECTORY = "./data"
let mainWindow = null;
let workerWindow = null;
let loadedDBPath = ""
var fileTransferServer = undefined, sockets = {}, nextSocketId = 0
var shouldInterruptTrasnferring = false;
process.on("uncaughtException", (err) => {
// uncaught Exception will occur when user tries to force quit application while uploading database
const messageBoxOptions = {
type: "error",
title: "Error in Main process",
message: "Something failed"
};
console.log(err)
});
/**
* Create directory structure
*/
function initDirectoryStructure() {
if (!fileSystem.existsSync('./upload')) {
fileSystem.mkdirSync('./upload')
}
if (!fileSystem.existsSync('./export')) {
fileSystem.mkdirSync('./export')
}
if (!fileSystem.existsSync('./data')) {
fileSystem.mkdirSync('./data')
}
}
/**
* Deletes content of the given directory
* @param {String} directoryPath Path to the directory
*/
function emptyDirectory(directoryPath) {
fileSystem.readdir(directoryPath, (err, files) => {
if (err) throw err;
for (const file of files) {
fileSystem.unlinkSync(path.join(directoryPath, file))
}
});
}
/**
* Create new windows which is hidden and not used.
* It's renderer thread is used as worker thread.
*/
function makeHiddenWindow() {
workerWindow = new BrowserWindow({
webPreferences: {
nodeIntegration: true
},
minHeight: 700,
minWidth: 1100,
show: false
});
workerWindow.loadURL(url.format({
pathname: path.join(__dirname, 'workerWindow.html'),
protocol:'file:',
slashes: true
}));
}
/**
* Make windows which is used for graph visualization.
* @param {String} windowTitle title of the window
*/
function makeGraphdWindow(windowTitle) {
var graphWindow = new BrowserWindow({
webPreferences: {
nodeIntegration: true,
additionalArguments: [windowTitle]
},
minHeight: 700,
minWidth: 1100,
show: false
});
graphWindow.loadURL(url.format({
pathname: path.join(__dirname, 'graph.html'),
protocol:'file:',
slashes: true
}));
graphWindow.setMenu(null)
graphWindow.webContents.on('did-finish-load', function() {
graphWindow.show();
});
}
/**
* Empty all directories which are created by application.
*/
function emptyAllDirectories() {
try {
if (mainWindow != null) {
mainWindow.webContents.send('app-is-closing');
}
emptyDirectory(EXPORT_DIRECTORY)
emptyDirectory(UPLOAD_DIRECTORY)
emptyDirectory(DATA_DIRECTORY)
}
catch(err) {
console.log("Error ocurred while trying to delete directories")
}
}
/**
* Listen for app to be ready
*/
app.on('ready', function() {
initDirectoryStructure()
emptyAllDirectories()
// Create new window
mainWindow = new BrowserWindow({
webPreferences: {
nodeIntegration: true
},
icon: path.join(__dirname, '/img/icon.png'),
minHeight: 700,
minWidth: 1100,
show: false
});
mainWindow.on('close', function() {
workerWindow.close()
emptyAllDirectories()
});
// Load html into window
mainWindow.loadURL(url.format({
pathname: path.join(__dirname, 'index.html'),
protocol:'file:',
slashes: true
}));
mainWindow.webContents.on('did-finish-load', function() {
mainWindow.show();
});
makeHiddenWindow()
// Build menu from template
const mainMenu = Menu.buildFromTemplate(mainMenuTemplate);
// Insert menu
Menu.setApplicationMenu(mainMenu);
});
/**
* Create menu template
*/
const mainMenuTemplate = [
{
label: 'File',
submenu: [
{
label: 'Save as',
click() {
if (loadedDBPath === "") {
return;
}
const options = { defaultPath: app.getPath('documents') }
dialog.showSaveDialog(null, options, (destination) => {
if(typeof destination !== "undefined") {
copyFile(loadedDBPath, destination)
}
});
}
},
{
label: 'Convert to',
submenu : [
{
label: 'CSV',
click() {
if (loadedDBPath === "") {
return;
}
exportDatabase("csv")
}
},
{
label: 'JSON',
click() {
if (loadedDBPath === "") {
return;
}
exportDatabase("json")
}
}
]
},
{
type: 'separator'
},
{
label: 'Quit',
accelerator: process.platfrom == 'darwin' ? 'Command+Q' : 'Ctrl+Q',
click() {
app.quit();
}
}
]
},
{
label: 'View',
submenu: [
{
label: 'Home',
click() {
loadedDBPath = ""
shouldInterruptTrasnferring = true
clearDeviceSubmenu();
closeServer();
dataRestore.finish();
workerWindow.webContents.send('finishWorker');
mainWindow.webContents.send('show-home-page');
}
},
{
label: 'Visualize data',
submenu : [
{
label: "Location data",
click() {
if (loadedDBPath === "") {
return;
}
makeGraphdWindow('location_data');
}
},
{
label: "Sensor data",
submenu: []
}
]
},
{
role: 'togglefullscreen'
}
]
},
{
label: 'Window',
submenu: [
{
role: 'minimize'
},
{
role: 'close'
}
]
}
];
/**
* Add sub menu which consists of node ids of smartwatches.
* @param {String[]} deviceList list od node ids of smartwatches.
*/
function addDeviceSubMenu(deviceList) {
deviceSubmenu = []
for(var i = 0; i < deviceList.length; i++) {
const name = deviceList[i]
deviceSubmenu.push({ label: name, click() {
if (loadedDBPath === "") {
return;
}
makeGraphdWindow(name)
} })
}
mainMenuTemplate[1].submenu[1].submenu[1].submenu = deviceSubmenu
const mainMenu = Menu.buildFromTemplate(mainMenuTemplate);
Menu.setApplicationMenu(mainMenu);
}
/**
* Remove sub menu which constist of node ids of smarwatches.
*/
function clearDeviceSubmenu() {
mainMenuTemplate[1].submenu[1].submenu[1].submenu = []
const mainMenu = Menu.buildFromTemplate(mainMenuTemplate);
Menu.setApplicationMenu(mainMenu);
}
/**
* Copy file from source to destination.
* @param {String} source
* @param {String} destination
*/
function copyFile(source, destination) {
fileSystem.copyFile(source, destination, (err) => {
if (err) {
notifyUser("Save as failed! Please try again.")
}
});
}
var isConversionStarted = false
/**
* Convets database from sqlite to exportType
* @param {String} exportType exportType can take values: csv or json
*/
function exportDatabase(exportType) {
if (isConversionStarted) {
notifyUser("Can not start new conversion. Conversion is already in progress!")
return
}
emptyDirectory(EXPORT_DIRECTORY)
notifyUser("Conversion started!")
isConversionStarted = true
const SqliteConverter = require("./js/sqlite-converter");
let filePath = loadedDBPath;
let outputPath = EXPORT_DIRECTORY;
let logPath = EXPORT_DIRECTORY;
let sqliteConverter = new SqliteConverter()
.setFilePath(filePath)
.setOutputPath(outputPath)
.setLogPath(logPath);
if (exportType === "csv") {
sqliteConverter.convertToCSV().then((result) => {
notifyConversionIsDone()
isConversionStarted = false
}).catch((err) => {
notifyUser("Conversion failed!")
isConversionStarted = false
});
}
else if (exportType === "json") {
sqliteConverter.convertToJson().then((result) => {
notifyConversionIsDone()
isConversionStarted = false
}).catch((err) => {
notifyUser("Conversion failed!")
isConversionStarted = false
});
}
}
/**
* Show notification with messageBody to user
* @param {String} messageBody Text of the message
*/
function notifyUser(messageBody) {
const notifier = require('node-notifier')
notifier.notify({
title: 'Sensor Logger',
icon: path.join(__dirname, '/img/icon.png'),
message: messageBody
});
}
/**
* Show notification the converstion is done.
* This notification is different from other, because it has
* click callback and it will wait for user action
*/
function notifyConversionIsDone() {
const notifier = require('node-notifier')
notifier.notify({
title: 'Sensor Logger',
icon: path.join(__dirname, '/img/icon.png'),
message: 'Conversion is done!',
wait: true
});
notifier.on('click', function(notifierObject, options, event) {
require('child_process').exec('start "" ' + EXPORT_DIRECTORY_NAME);
});
}
var totalNumOfFiles = 100
var numOfTransfeeredFiles = 0
/**
* Send to main window's renderer process database upload status percentage.
*/
ipc.on('get-database-upload-status-percentage', function(event) {
event.sender.send('database-upload-status-percentage', calculateDatabaseTransferProgress())
})
/**
* Calculate database upload status percentage
* @return {Number} return upload status percentage
*/
function calculateDatabaseTransferProgress() {
return Math.floor((numOfTransfeeredFiles/totalNumOfFiles) * 100);
}
/**
* Send path of uploaded database to main window's renderer process
*/
ipc.on('get-database-path', (event, arg) => {
event.returnValue = loadedDBPath
})
/**
* When it receives database path from window's renderer process,
* it will add device submenu
*/
ipc.on('database-file-path', (event, arg) => {
loadedDBPath = arg;
db = require('better-sqlite3')(loadedDBPath);
device_id = []
node_ids = db.prepare('SELECT node_id FROM sensor_data GROUP BY node_id').all()
for (i = 0; i < node_ids.length; i++) {
device_id.push(node_ids[i].node_id)
}
db.close()
addDeviceSubMenu(device_id)
})
/**
* This ipc will be called when workerWindow's renderer process
* finishes with data restoring of one file
*/
ipc.on('restoring-done', (event, arg) => {
numOfTransfeeredFiles++
if (numOfTransfeeredFiles === totalNumOfFiles) {
closeServer();
dataRestore.finish();
workerWindow.webContents.send('finishWorker');
}
})
/**
* Receives command from main window's process to
* start loading database from binary files
*
* @param {String[]} arg List of files absolute paths
*/
ipc.on('load-database-from-folder', (event, arg) => {
shouldInterruptTrasnferring = false
numOfTransfeeredFiles = 0
const files = arg
totalNumOfFiles = files.length
event.sender.send('database-transfer-started');
workerWindow.webContents.send('initWorker');
dataRestore.init(true)
for(var i = 0; i < totalNumOfFiles; i++) {
if (shouldInterruptTrasnferring) {
dataRestore.finish();
break;
}
const _filePath = files[i]
var _fileType = 0;
if(_filePath.indexOf("json") > -1) {
_fileType = 0
}
else if(_filePath.indexOf("location") > -1) {
_fileType = 1
}
else if(_filePath.indexOf("device") > -1) {
_fileType = 2
}
if(i % 2 == 1) {
//if(_fileType === 2) {
workerWindow.webContents.send('restore', [_filePath, _fileType]);
continue;
}
const fileType = _fileType
const filePath = _filePath
setTimeout(function () {
if (shouldInterruptTrasnferring) {
return;
}
dataRestore.restore(filePath, fileType).then(() => {
numOfTransfeeredFiles++
if (numOfTransfeeredFiles === totalNumOfFiles) {
dataRestore.finish();
workerWindow.webContents.send('finishWorker');
}
})
.catch(err => {
dataRestore.finish();
workerWindow.webContents.send('finishWorker');
mainWindow.webContents.send('show-error', filePath)
})
}, i * 50)
}
})
/**
* Message is receives from workerWindows's renderer process
* when error is occured while data restoring
*
* @param {String} arg Path to the file which can't be restored
*/
ipc.on('data-restore-error', (event, arg) => {
dataRestore.finish();
workerWindow.webContents.send('finishWorker');
mainWindow.webContents.send('show-error', arg);
})
var packetsId = -1
/**
* When receives message from mainWindow's renderer process,
* it will create server and it start publishing dns-sd multicast
* messages
*/
ipc.on('publish-transfer-service', function(event) {
console.log('publish-transfer-service')
portfinder.getPort({port: 0, stopPort: 65535}, function (err, freePort) {
fileTransferServer = http.createServer(function (req, res) {
// if (req.url == '/upload' && req.method.toLowerCase() == 'post') {
// parse a file upload
var form = new formidable.IncomingForm();
form.uploadDir = UPLOAD_DIRECTORY
form.parse(req, function(err, fields, files) {
//console.log(req)
console.log("")
if (err) {
console.log('some error ', err)
closeServer()
mainWindow.webContents.send('database-transfer-error');
}
else if (!(Object.entries(fields).length === 0 && fields.constructor === Object)) {
totalNumOfFiles = Number(fields['numOfFiles'])
packetsId = fields['id']
numOfTransfeeredFiles = 0
console.log(totalNumOfFiles)
mainWindow.webContents.send('database-transfer-started');
dataRestore.init(true)
workerWindow.webContents.send('initWorker');
res.statusCode = 200;
res.setHeader('Content-Type', 'text/plain');
res.end('Hello World\n');
} else if (!files.file) {
console.log('no file received')
} else {
var messageId = url.parse(req.url, true).query.id
if (messageId !== packetsId) {
return;
}
var queryData = url.parse(req.url, true).query;
const fileType = Number(queryData.fileType);
///////////////////////////////////////////////////////////
if(numOfTransfeeredFiles % 2 == 1) {
//if(fileType === 2) {
res.statusCode = 200;
res.setHeader('Content-Type', 'text/plain');
res.end('Hello World\n');
workerWindow.webContents.send('restore', [files.file.path, fileType]);
return;
}
//////////////////////////////////////////////////////////
dataRestore.restore(files.file.path, fileType).then(() => {
numOfTransfeeredFiles++
if (numOfTransfeeredFiles === totalNumOfFiles) {
closeServer();
dataRestore.finish()
workerWindow.webContents.send('finishWorker');
}
})
var file = files.file
console.log('saved file to', file.path)
console.log('original name', file.name)
console.log('type', file.type)
console.log('size', file.size)
res.statusCode = 200;
res.setHeader('Content-Type', 'text/plain');
res.end('Hello World\n');
}
});
return;
//}
}).listen(freePort);
fileTransferServer.on('connection', function (socket) {
// Add a newly connected socket
var socketId = nextSocketId++;
sockets[socketId] = socket;
console.log('socket', socketId, 'opened');
// Remove the socket when it closes
socket.on('close', function () {
delete sockets[socketId];
});
});
txtRecord = {'ip' : getLocalWifiIpAddress()}
const hostname = require("os").hostname() + ".local."
const name = "SensorLoggerFileTransfer" + require("os").hostname()
bonjour.publish({ name: name, type: 'hap', port: freePort, host: hostname, txt: txtRecord })
});
})
/**
* Close server and stop sending dns-sd multicast
* messages. It will force close all existing connections.
*/
function closeServer() {
console.log('Server closing...')
for (var i = 0; i < 5; i++)
bonjour.unpublishAll();
if (typeof fileTransferServer !== "undefined") {
fileTransferServer.close(function () {
console.log('Server closed!'); });
// Destroy all open sockets
for (var socketId in sockets) {
console.log('socket', socketId, 'destroyed');
sockets[socketId].destroy();
}
}
}
/**
* Find ipv4 address of wifi interface. This
* is the only function that is os dependant,
* because wifi interface has different name on different
* operation systems.
*
* @return {String} ipv4 address
*/
function getLocalWifiIpAddress() {
var os = require('os');
var ifaces = os.networkInterfaces();
var address;
var wifiInterfaceName = "Wi-Fi"
if (os.platform() === 'darwin') {
wifiInterfaceName = "en0"
}
else if (os.platform() === 'linux') {
wifiInterfaceName = "eth"
}
Object.keys(ifaces).forEach(function (ifname) {
if (!(ifname === wifiInterfaceName))
return;
ifaces[ifname].forEach(function (iface) {
if ('IPv4' !== iface.family || iface.internal !== false) {
return;
}
address = iface.address
});
});
return address;
}
bonjour.find({ type: 'hap' }, function (service) {
console.log(service)
//console.log(service.referer.address)
})