This repository has been archived by the owner on Apr 17, 2022. It is now read-only.
forked from AdyStudios/AlTracker
-
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathapp.js
693 lines (656 loc) · 19.8 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
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
/* Ace Logistics - JobTracker 1.1.0
@Authors: AdyStudios, Felix Waßmuth (D1strict-Development)
@License: GNU General Public License v3.0 - https://github.com/D1strict/AL-JobTracker/blob/main/LICENSE
@Website: https://ace-logistics.uk/
(c) 2021, Ace Logistics
*/
/* Dependencies */
var ETCarsClient = require('etcars-node-client');
const notifier = require('node-notifier');
var XMLHttpRequest = require("xmlhttprequest").XMLHttpRequest;
const fs = require('fs');
var etcars = new ETCarsClient();
etcars.connect();
var request = new XMLHttpRequest();
const http = require('http');
const https = require('https');
const rp = require('request-promise');
var open = require('open');
const SysTray = require('systray2').default;
const os = require('os');
var exec = require('child_process').execFile;
const exitHook = require('exit-hook');
const isOnline = require('is-online');
const isReachable = require('is-reachable');
/* Configuration */
etcars.enableDebug = true; /* to enable debug console.log and console.error */
var devmode = 0; /* Developer mode: 1 - Active - Advanced outputs in the console, 0 = Production mode (no outputs in the console). */
var version = 2; /* Versionnumber (not Semantic) */
const AlTPort = 10853; /* Port for the process check (should be a port which is not commonly) */
const AlTPath = '/AlT'; /* Random path. Should not contain special characters or umlauts. */
var apikey = ""; /* INSERT API-KEY */
const VTCName = "Ace Logistics";
const APPName = "JobTracker";
/* Removal of existing notifications */
var notifyIDS = ["100", "101", "102", "103", "104", "105", "106", "107"];
notifyIDS.forEach(notifyRemove);
function notifyRemove(item) {
notifier.notify({
'remove': item // to remove all group ID
});
}
/* Functions */
async function onlineCheck() {
isOnlineCheck = await isOnline();
isReachableCheck = await isReachable('api.d1strict.net/al/1-1-0/appversion.txt');
return;
}
/* Checking for - and installing updates */
async function updateCheck() {
await onlineCheck();
if ((isOnlineCheck == true) && (isReachableCheck == true)) {
var updateserver = new XMLHttpRequest();
if (updateserver) {
updateserver.onreadystatechange = function() {
if ((updateserver.readyState == 4) && (updateserver.status == 200)) {
if (updateserver.responseText > version) {
if (os.arch() == "x32") {
url = "https://d1strict.de/media/218/";
dest = os.tmpdir() + '\\Updated_ALJobTracker.exe';
} else if (os.arch() == "x64") {
url = "https://d1strict.de/media/220/";
dest = os.tmpdir() + '\\Updated_ALJobTracker.exe';
} else {
url = "https://d1strict.de/media/220/";
dest = os.tmpdir() + '\\Updated_ALJobTracker.exe';
}
downloadUpdate(url, dest);
notifier.notify({
title: APPName,
message: 'Info: Update available. Update is being downloaded.',
icon: "./assets/info.png",
timeout: 1,
appID: VTCName,
sound: true,
id: 100,
wait: true
});
} else {
notifier.notify({
title: APPName,
message: 'Info: The JobTracker is up to date.',
icon: "./assets/info.png",
timeout: 1,
appID: VTCName,
sound: true,
id: 100,
wait: true
});
console.log(updateserver.responseText);
}
}
};
updateserver.open("GET", "https://api.d1strict.net/al/1-1-0/appversion.txt");
updateserver.send();
}
} else {
notifier.notify({
title: APPName,
message: 'Error: It was not possible to check for updates because no connection could be established.\nPlease check your internet connection.',
icon: "./assets/error.png",
timeout: 1,
appID: VTCName,
sound: true,
id: 100,
wait: false
});
}
}
async function updateCheckSilent() {
await onlineCheck();
if ((isOnlineCheck == true) && (isReachableCheck == true)) {
var updateserverSilent = new XMLHttpRequest();
if (updateserverSilent) {
updateserverSilent.onreadystatechange = function() {
if ((updateserverSilent.readyState == 4) && (updateserverSilent.status == 200)) {
if (updateserverSilent.responseText > version) {
if (os.arch() == "x32") {
url = "https://d1strict.de/media/218/";
dest = os.tmpdir() + '\\Updated_ALJobTracker.exe';
} else if (os.arch() == "x64") {
url = "https://d1strict.de/media/220/";
dest = os.tmpdir() + '\\Updated_ALJobTracker.exe';
} else {
url = "https://d1strict.de/media/220/";
dest = os.tmpdir() + '\\Updated_ALJobTracker.exe';
}
downloadUpdate(url, dest);
notifier.notify({
title: APPName,
message: 'Info: Update available. Update is being downloaded.',
icon: "./assets/info.png",
timeout: 1,
appID: VTCName,
sound: true,
id: 100,
wait: true
});
}
}
updateserverSilent.open("GET", "https://api.d1strict.net/al/1-1-0/appversion.txt");
updateserverSilent.send();
};
}
}
}
async function downloadUpdate(url, dest, cb) {
await onlineCheck();
if ((isOnlineCheck == true) && (isReachableCheck == true)) {
var file = fs.createWriteStream(dest);
var request = https.get(url, function(response) {
response.pipe(file);
file.on('finish', function() {
file.close(cb); // close() is async, call cb after close completes.
notifier.notify({
title: APPName,
message: 'Success: The update has been downloaded successfully.\nThe installation routine will be started in a few moments.',
icon: "./assets/success.png",
timeout: 1,
appID: VTCName,
sound: true,
id: 101,
wait: false
});
exec(os.tmpdir() + '\\Updated_ALJobTracker.exe', function(err, data) {
if (devmode == 1) {
if (err) {
console.log(err);
return;
}
console.log(data.toString());
}
});
setTimeout(() => {
terminateDRP();
notifyIDS.forEach(notifyRemove);
systray.kill();
process.exit(1);
}, 5000);
});
}).on('error', function(err) { // Handle errors
fs.unlink(dest); // Delete the file async. (But we don't check the result)
if (cb && devmode == 1) cb(err.message);
notifier.notify({
title: APPName,
message: 'Error: An error has occurred. The update could not be downloaded. Try again later.',
icon: "./assets/error.png",
timeout: 1,
appID: VTCName,
sound: true,
id: 102,
wait: true
});
});
}
}
/* Submit of local-saved Jobs */
var submitJobsRunnning = false;
async function submitLocalJobs() {
if (!submitJobsRunnning) {
await onlineCheck();
if ((isOnlineCheck == true) && (isReachableCheck == true)) {
fs.readdir("./jobs/", (err, files) => {
if (err) throw err;
files.forEach(file => {
var jsondata = fs.readFileSync("./jobs/" + file + "", 'utf8');
if (files.length == 0) {
fs.unlink('./jobs/' + file + '', (err) => {
if (err && devmode == 1) {
console.log(err);
return;
}
});
} else {
setTimeout(() => {
content = JSON.parse(jsondata);
console.log(content);
var localjobsender = new XMLHttpRequest();
if (localjobsender) {
localjobsender.onreadystatechange = function() {
if ((localjobsender.readyState == 4) && (localjobsender.status == 200)) {
notifier.notify({
title: APPName,
message: 'Info: local Job submitted.',
icon: "./assets/success.png",
timeout: 1,
appID: VTCName,
sound: true,
id: 103,
wait: false
});
fs.writeFile(filedeletion, "", (err) => {
if (err) throw err;
if (devmode == 1) {
console.log("API connection successful:\n\n" + localjobsender.responseText + "\n\nLocal job is emptied and flagged for deletion.");
}
});
} else if ((localjobsender.readyState == 4) && (localjobsender.status !== 200)) {
notifier.notify({
title: APPName,
message: 'Error: Local jobs could not be submitted.',
icon: "./assets/error.png",
timeout: 1,
appID: VTCName,
sound: true,
id: 103,
wait: false
});
}
};
localjobsender.open('POST', 'https://api.d1strict.net/al/1-1-0/add?apikey=' + apikey + '&dcnotification=no', true); /* Open the request to the Job-API. */
localjobsender.setRequestHeader('Content-Type', 'application/json'); /* Sets the request header for the Job-API */
localjobsender.send(JSON.stringify(content)); /*Sends the JSON file to the API*/
}
if (devmode == 1) {
console.log('Job found, Connecting...');
}
filedeletion = './jobs/' + file + '';
}, 65000);
}
});
});
} else {
notifier.notify({
title: APPName,
message: 'Error: Local jobs could not be submitted.\nCheck your internet connection.',
icon: "./assets/error.png",
timeout: 1,
appID: VTCName,
sound: true,
id: 103,
wait: false
});
}
} else {
notifier.notify({
title: APPName,
message: 'Warning: Local jobs are already submitted.\nBe patient for a moment.',
icon: "./assets/warning.png",
timeout: 1,
appID: VTCName,
sound: true,
id: 103,
wait: false
});
}
}
/* Restart of the Discord-Rich Presence */
function restartDRP() {
require('child_process').exec('cmd /c RebootDRP.bat', function() {
if (devmode == 1) {
console.log("Restart DRP...");
}
});
}
/* Termination of the Discord-Rich Presence */
function terminateDRP() {
require('child_process').exec('cmd /c TerminateDRP.bat', function() {
if (devmode == 1) {
console.log("Terminate DRP...");
}
});
}
/* Process-Checking */
rp({
uri: `http://localhost:${AlTPort}${AlTPath}`,
resolveWithFullResponse: true
}).then(res => {
if (res.statusCode === 200) {
notifier.notify({
title: APPName,
message: 'Error: Tracker could not be started, it is already running.',
icon: "./assets/error.png",
timeout: 1,
appID: VTCName,
sound: true,
id: 105,
wait: false
});
setTimeout(() => {
systray.kill();
process.exit(1);
}, 2000);
} else {
throw new Error(`statusCode ${res.statusCode}`);
}
}).catch(err => {
const server = http.createServer((req, res) => {
if (req.url === AlTPath) {
res.statusCode = 200;
res.end("ok");
} else {
res.statusCode = 404;
res.end("err");
}
});
server.listen(AlTPort);
server.unref();
// StartUp
onlineCheck();
updateCheckSilent();
submitLocalJobs();
restartDRP();
apistatus = "false";
console.log("Tracker is running.");
if (devmode == 1) {
console.log("Process-Check successfully. Continue.");
}
notifier.notify({
title: APPName,
message: APPName + ' started.',
icon: "./assets/logo.png",
timeout: 1,
appID: VTCName,
sound: true,
id: 105,
wait: false
});
if (devmode == 1) {
setInterval(() => {
console.log(APPName + " still running");
}, 30000);
}
});
/* Data-Logging & Transmission */
etcars.on('data', function(data) {
if (devmode == 1) {
console.log('data received.');
}
jobStatus = data.jobData.status; /* 1 = In progress, 2 = Finished, 3 = Cancelled */
APISaving(data);
MapTransmitting(data);
});
async function MapTransmitting(data) {
await onlineCheck();
var isPaused = data.telemetry.game.paused; /* Return: Boolean */
var isDriving = data.telemetry.game.isDriving; /* Return:: Boolean */
var gameID = data.telemetry.game.gameID; /* Return: ets2 or ats */
var gameName = data.telemetry.game.gameName; /* Return: Euro Truck Simulator 2 or American Truck Simulator */
var truckMake = data.telemetry.truck.make; /* Return: String */
var truckModel = data.telemetry.truck.model; /* Return: String */
var truckPositionX = data.telemetry.truck.worldPlacement.x; /* X-Coordinate of the Truck */
var truckPositionY = data.telemetry.truck.worldPlacement.y; /* Y-Coordinate of the Truck */
var truckPositionZ = data.telemetry.truck.worldPlacement.z; /* Z-Coordinate of the Truck */
var jobRemainingTime = data.jobData.timeRemaining; /* Remaining time, until the delivery will be late */
var steamID = data.telemetry.user.steamID; /* Steam-UserID */
var steamUsername = data.telemetry.user.steamUsername; /* Steam-Username */
var currentSpeed = data.telemetry.truck.speed; /* Current Speed */
var currentJobDestination = data.telemetry.job.destinationCity; /* Current Job-Destination*/
var currentJobSource = data.telemetry.job.sourceCity; /* Current Job-Source */
var eta = data.telemetry.navigation.lowestDistance; /* ETA */
var currentFuel = data.telemetry.truck.fuel.currentLitres; /* Current fuel in l */
var map = new XMLHttpRequest();
if (map) {
map.onreadystatechange = function() {
if ((map.readyState == 4) && (map.status == 200)) {
if (devmode == 1) {
console.log("Position sent to MAP-API successful:");
console.log(request.responseText);
}
}
};
map.open('POST', 'https://api.d1strict.net/al/1-1-0/map', true); /* Open the request to the Map API. */
map.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded'); /* Sets the request header for the Map API */
map.send('game=' + gameName + '&x=' + truckPositionX + '&y=' + truckPositionY + '&z=' + truckPositionZ + '&isDriving=' + isDriving + '&isPaused=' + isPaused + '&jobRemainingTime=' + jobRemainingTime + '&steamID=' + steamID + '&steamUsername=' + steamUsername + '¤tSpeed=' + currentSpeed + '¤tDestination=' + currentJobDestination + '&eta=' + eta + '¤tFuel=' + currentFuel + '¤tSource=' + currentJobSource + '&gameID=' + gameID + '&truckMake=' + truckMake + '&truckModel=' + truckModel + '&apikey=' + apikey + ''); /* Sends data to the Map API. */
}
}
var ApiSavingRunning = false;
async function APISaving(data) {
await onlineCheck();
if (!ApiSavingRunning) {
if ((jobStatus == "1") && (apistatus == "false")) {
if ((isOnlineCheck == true) && (isReachableCheck == true)) {
if (devmode == 1) {
console.log('Job started, Connecting...\nJobInfo \n\n' + JSON.stringify(data) + '\n\nAuthentication with API key:' + apikey + '');
}
apistatus = "true";
var request = new XMLHttpRequest();
if (request) {
request.onreadystatechange = function() {
if ((request.readyState == 4) && (request.status == 200)) {
notifier.notify({
title: APPName,
message: 'Info: Job submitted.',
icon: "./assets/success.png",
timeout: 1,
appID: VTCName,
sound: true,
id: 106,
wait: false
});
if (devmode == 1) {
console.log("Connection successful:");
console.log(request.responseText);
}
}
};
request.open('POST', 'https://api.d1strict.net/al/1-1-0/add?apikey=' + apikey + '&jobstatus=' + jobStatus + '', true); /* Open the request to the Job-API. */
request.setRequestHeader('Content-Type', 'application/json; charset=UTF-8'); /* Sets the request header for the Job-API */
request.send(JSON.stringify(data)); /* Sends the JSON file to the API */
}
}
} else if (((jobStatus == "2") && (apistatus == "true")) || ((jobStatus == "3") && (apistatus == "true"))) /* Check if the job has not been sent yet and if it has been finished */ {
if ((isOnlineCheck == true) && (isReachableCheck == true)) {
if (devmode == 1) {
console.log('Job ended, Connecting...\nJobInfo \n\n' + JSON.stringify(data) + '\n\nAuthentication with API key:' + apikey + '');
}
var request = new XMLHttpRequest();
if (request) {
request.onreadystatechange = function() {
if ((request.readyState == 4) && (request.status == 200)) {
notifier.notify({
title: APPName,
message: 'Info: Job submitted.',
icon: "./assets/success.png",
timeout: 1,
appID: VTCName,
sound: true,
id: 106,
wait: false
});
if (devmode == 1) {
console.log("Connection successful:");
console.log(request.responseText);
}
} else if ((request.readyState == 4) && (request.status != 200)) {
var fileid = Math.random().toString(36).substring(7);
fs.writeFileSync('./jobs/' + fileid + '.json', JSON.stringify(data));
apistatus = "false";
notifier.notify({
title: APPName,
message: 'Info: Job locally saved.',
icon: "./assets/info.png",
timeout: 1,
appID: VTCName,
sound: true,
id: 106,
wait: false
});
}
};
request.open('POST', 'https://api.d1strict.net/al/1-1-0/add?apikey=' + apikey + '&jobstatus=' + jobStatus + '', true); /* Open the request to the Job-API. */
request.setRequestHeader('Content-Type', 'application/json; charset=UTF-8'); /* Sets the request header for the Job-API */
request.send(JSON.stringify(data)); /* Sends the JSON file to the API */
}
} else {
var fileid = Math.random().toString(36).substring(7);
fs.writeFileSync('./jobs/' + fileid + '.json', JSON.stringify(data));
retryCount = 0;
apistatus = "false";
}
}
}
}
etcars.on('connect', function(data) {
if (devmode == 1) {
console.log('connected');
}
});
etcars.on('error', function(data) {
if (devmode == 1) {
console.log('etcars error');
}
});
/* Systray */
const AboutMenu = {
title: 'About',
checked: false,
enabled: true,
items: [{
title: 'Website',
checked: false,
enabled: true,
click: () => {
open('https://ace-logistics.uk');
}
},
{
title: 'Support',
checked: false,
enabled: true,
click: () => {
open('https://discord.link/acelogisticsvtc');
}
},
{
title: 'Legal Notice',
checked: false,
enabled: true,
click: () => {
open('https://d1strict.de/legal-notice/');
}
},
{
title: 'Privacy Policy',
checked: false,
enabled: true,
click: () => {
open('https://d1strict.de/privacy-policy/');
}
},
{
title: 'Check for Updates',
checked: false,
enabled: true,
click: () => {
updateCheck();
}
},
]
};
const JobMenu = {
title: 'Jobs',
checked: false,
enabled: true,
items: [{
title: 'Submit a Job',
checked: false,
enabled: true,
click: () => {
open('https://d1strict.de/form-user-response/10-submit-a-job/');
}
},
{
title: 'Submit locally stored jobs',
checked: false,
enabled: true,
click: () => {
submitLocalJobs();
}
}
]
};
const RestartTrackerButton = {
title: 'Restart',
checked: false,
enabled: true,
click: () => {
RestartApplication();
}
};
const ExitTrackerButton = {
title: 'Exit',
checked: false,
enabled: true,
click: () => {
ExitApplication();
}
};
const systray = new SysTray({
menu: {
icon: 'systray.ico',
title: APPName,
tooltip: VTCName,
items: [
JobMenu,
RestartTrackerButton,
AboutMenu,
ExitTrackerButton,
]
},
debug: false,
copyDir: false
});
//Functions */
function ExitApplication() {
notifier.notify({
title: APPName,
message: 'Warning: The tracker has been terminated. Jobs are not logged until you start the' + APPName + ' again.',
icon: "./assets/warning.png",
timeout: 1,
appID: VTCName,
sound: true,
id: 107,
wait: false
});
setTimeout(() => {
terminateDRP();
notifyIDS.forEach(notifyRemove);
systray.kill();
process.exit(1);
}, 1000);
}
function RestartApplication() {
terminateDRP();
setTimeout(function() {
exitHook(() => {
require("child_process").spawn(process.argv.shift(), process.argv, {
cwd: process.cwd(),
detached: true,
stdio: "inherit"
});
});
notifyIDS.forEach(notifyRemove);
process.exit(1);
}, 3000);
}
systray.onClick(action => {
if (action.item.click != null) {
action.item.click();
}
});
exitHook(() => {
notifier.notify({
title: APPName,
message: 'Warning: The tracker has been terminated. Jobs are not logged until you start the' + APPName + ' again.',
icon: "./assets/warning.png",
timeout: 1,
appID: VTCName,
sound: true,
id: 107,
wait: false
});
notifyIDS.forEach(notifyRemove);
terminateDRP();
systray.kill();
});