-
Notifications
You must be signed in to change notification settings - Fork 10
Expand file tree
/
Copy pathmake.js
More file actions
1507 lines (1347 loc) · 49.6 KB
/
Copy pathmake.js
File metadata and controls
1507 lines (1347 loc) · 49.6 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';
const fs = require('fs');
const { execSync, spawn } = require('child_process');
const readlineSync = require('readline-sync');
const path = require('path');
const express = require('express');
const favicon = require('serve-favicon');
const WebSocket = require('ws');
const archiver = require ('archiver');
class AppMessage {
static mtInfo = "info";
static mtTiming = "timing";
static mtCommandResponse = "commandresponse";
static mtRunning = "running";
static mtComplete = "complete";
static mtCommand = "command";
static mtSettings = "settings";
static mtDownload = "download";
static mtConnection = "connection";
static mtCommandPackage = "commandpackage";
static mtExistingDb = "existingdb";
constructor(msgtype) {
this.type = msgtype;
this.css = [];
this.payload = "";
this.rowindex = -1;
this.completed = false;
this.items = [];
this.filename = "";
this.getexisting = false;
this.dbfilename = "";
this.uid = "";
}
}
class MakeCommand {
constructor(command, chart, rowindex, chartname, layertype) {
this.command = command;
this.chart = chart;
this.rowindex = rowindex;
this.chartname = chartname;
this.layertype = layertype;
}
}
class ProcessTime {
constructor(processName) {
this.processname = processName.replaceAll("_", " ");
this.startdate = new Date(new Date().toLocaleString());
this.totaltime = "";
this.logtime = "";
}
calculateProcessTime() {
let pt = ProcessTime.reportProcessingTime(this.startdate);
this.totaltime = `time: ${pt}`;
}
static reportProcessingTime(startdate) {
let date2 = new Date(new Date().toLocaleString());
if (date2 < startdate) {
date2.setDate(date2.getDate() + 1);
}
let msec = date2 - startdate;
let hh = Math.floor(msec / 1000 / 60 / 60);
msec -= hh * 1000 * 60 * 60;
let mm = Math.floor(msec / 1000 / 60);
msec -= mm * 1000 * 60;
let ss = Math.floor(msec / 1000);
msec -= ss * 1000;
let phh = pad2(hh);
let pmm = pad2(mm);
let pss = pad2(ss);
let ttime = `${phh}:${pmm}:${pss}`;
logEntry(`Start time: ${startdate}, End time: ${date2}, Total time: ${ttime}`);
return ttime;
}
};
// create websocket variables
var connections = new Map();
var inMakeLoop = false;
var pingSenderId = 0;
// set the base application folder, this will change if running in docker
let appdir = __dirname;
/**
* Utility to see if we are in a docker container
* @returns boolean
*/
let isdocker = isRunningInDocker();
function isRunningInDocker() {
let indocker = false;
try {
let r = execSync(`cat /proc/1/cgroup`, {encoding: "utf8"});
indocker = (r.search("/docker/") > -1);
}
catch {}
if (indocker) {
console.log("Running in docker!");
appdir = "/chartmaker";
}
return indocker;
}
/**
* Handle all prompting for input
*/
function processPrompt(message) {
return readlineSync.question(message);
}
const settings = JSON.parse(fs.readFileSync(path.join(appdir, "settings.json"), "utf-8")).settings;
var useWebServer = settings.webservermode;
var timings = new Map();
/**
* Set the time zone of this process to the value in settings if it exists.
* See https://en.wikipedia.org/wiki/List_of_tz_database_time_zones for
* for an exhaustive list of valid timezone string values.
*/
if (settings.timezone != "") {
process.env.TZ = settings.timezone;
}
/**
* Get the number of available processes
* @returns integer
*/
function getProcessCount() {
let pc = 4; // default
try {
let r = execSync(`grep -c "^processor" /proc/cpuinfo`, { encoding: 'utf8'});
pc = Number(r.replace('\n', ""));
logEntry(`Processor count = ${pc}`)
}
catch {}
return pc;
}
// logging
let logfd = 0;
const setupDebugLog = function(logfolder) {
if (settings.logtofile) {
logfd = fs.openSync(path.join(logfolder, "debug.log"), 'w', 0o666);
}
}
const logEntry = function(entry) {
if (settings.logtofile) {
fs.writeSync(logfd, `${entry}\n`)
}
else {
console.log(entry);
}
}
function pad2(n) {
let nn = `${n}`;
if (n < 10) {
nn = `0${nn}`;
}
return nn;
}
// Get the current chart date from the chartdates.json file
let expiredate = "";
const chartdate = getBestChartDate();
const remotemenu = JSON.parse(fs.readFileSync(path.join(appdir, "remotemenu.json"), "utf-8"));
const users = JSON.parse(fs.readFileSync(path.join(appdir, "users.json"), "utf-8")).users;
const zipfilename = settings.zipfilename;
const zipfilepath = path.join(appdir, "public", "charts", chartdate, zipfilename);
// used for process timing
const startdate = new Date(new Date().toLocaleString());
// make sure these base level folders exist
let workarea = path.join(appdir, "workarea");
if (settings.renameworkarea) workarea += `_${chartdate}`;
if (!fs.existsSync(workarea)) fs.mkdirSync(workarea)
let chartcache = path.join(appdir, "chartcache");
if (!fs.existsSync(chartcache)) fs.mkdirSync(chartcache);
let chartsfolder = path.join(appdir, "public", "charts");
if (!fs.existsSync(chartsfolder)) fs.mkdirSync(chartsfolder)
let dbfolder = path.join(chartsfolder, chartdate);
if (!fs.existsSync(dbfolder)) fs.mkdirSync(dbfolder)
if (isdocker) {
//see if we have an external chart folder volume
let extcharts = path.join(appdir, "externalcharts");
if (fs.existsSync(extcharts)) {
dbfolder = extcharts;
}
}
let imageformat = settings.tiledrivers[settings.tiledriverindex];
let chartlayertype = settings.layertypes[settings.layertypeindex];
let chartworkname = "";
let chartname = "";
let charturl = "";
let clippedShapeFolder = "";
let cmd = "";
let chartfolder = "";
let dir_1_unzipped = "";
let dir_2_expanded = "";
let dir_3_clipped = "";
let dir_4_tiled = "";
let dir_5_merged = "";
let dir_6_quantized = "";
let isifrchart = false;
let wgsbounds = [];
let addmetabounds = false;
/**
* Chart processing starts here
*/
let parray = [];
let nm = 0;
const processes = getProcessCount();
const arg = process.argv.slice(2);
if (useWebServer === false) {
if (arg.length >= 1) {
let chart = "";
let sarg = arg[0].toLowerCase();
if (sarg.startsWith("-s")) {
// output settings.json
console.log("\r\n\r\n----------------------------------------------------------------------------------\r\n" +
"Settings.json\r\n" +
"----------------------------------------------------------------------------------\r\n");
console.log(settings);
console.log("\r\n\r\n\r\n");
process.exit();
}
else if (sarg.startsWith("-h")) {
console.log("Command line options:\r\n" +
"----------------------------------------------------------------------------------\r\n" +
"-h, --help Show this help\r\n" +
"-s, --settings Show all values in settings.json\r\n" +
"-w, --webserver Start the web server" +
"----------------------------------------------------------------------------------\r\n" +
"area-single=X Process one area chart where X is the index in the area chart list\r\n" +
"area-all Process all 53 area VFR charts individually\r\n" +
"full-single=X Process one full chart where X is an index in the full chart list\r\n" +
"full-all Process all of the full charts in the full chart list\r\n" +
"----------------------------------------------------------------------------------\r\n");
process.exit();
}
else if (sarg.startsWith("-w")) {
enterWebserverMode();
}
else if (sarg === "area-all") {
processAllAreas();
}
else if (sarg === "full-all") {
processAllFull();
}
else if (sarg.search("area-single") > -1) {
try {
nm = Number(arg[0].split("=")[1]);
chart = settings.areachartlist[nm][1].replace("_", " ");
console.log(`Processing area chart: ${chart}`);
parray.push(nm);
processSingles();
}
catch {
console.log("Index error in argument, format is: area-single=X where X is a valid vfr chart index number (see settings.json.) Exiting chartmaker!");
process.exit();
}
}
else if (sarg.search("full-single") > -1) {
try {
nm = Number(arg[0].split("=")[1]);
chart = settings.fullchartlist[nm][0].replace("_", " ");
if (chart === "DDECUS") chart = settings.fullchartlist[nm][2].replace("_", " ");
console.log(`Processing full chart: ${chart}`);
parray.push(nm);
processFulls();
}
catch {
console.log("Index error in argument, format is: full-single=X where X is a valid full chart index number (see settings.json.) Exiting chartmaker!");
process.exit();
}
}
}
else {
let response = processPrompt("Select:\r\n" +
"--------------------------------------------------------------------\r\n" +
"1 = Process a single area VFR chart\r\n" +
"2 = Process all 53 area VFR charts individually\r\n" +
"3 = Process a single full chart from the full chart list\r\n" +
"4 = Process all of the full charts in the full chart list\r\n" +
"5 = Put chartmaker into webserver mode (new feature)\r\n" +
"6 = Output the settings.json file to the console\r\n" +
"---------------------------------------------------------------------\r\n\r\n" +
"Your selection: ");
switch (response) {
case "1":
processOneArea();
break;
case "2":
processAllAreas();
break;
case "3":
processOneFull();
break;
case "4":
parray = settings.chartprocessindexes;
processFulls();
break;
case "5":
enterWebserverMode();
break;
case "6":
console.log(settings);
console.log("\r\n\r\n\r\n");
process.exit();
default:
console.log("Exiting chartmaker!");
break;
}
}
}
function processOneArea(area = -1) {
if (area == -1) {
let lst = "\nSelect the chart number you want to process from this list\r\n\r\n";
for (var i = 0; i < settings.areachartlist.length; i++) {
lst += `${i} ${settings.areachartlist[i].split("_").join(" ")}\r\n`;
}
lst += "--------------------------------------------\r\nYour selection: ";
let response = processPrompt(lst);
nm = +response;
}
else {
nm = +area;
}
try {
if (nm >= 0 && nm < settings.areachartlist.length) {
parray.push(nm);
processSingles();
}
else {
console.log("Invalid response, exiting chartmaker!");
process.exit();
}
}
catch(err) {
console.error(err);
}
}
function processAllAreas() {
console.log("\r\nProcessing all 53 chart areas...\r\n");
for (var i = 0; i < 53; i++) {
parray.push(i);
}
processSingles();
}
function processSingles(msgid = -1) {
addmetabounds = true;
for (let idx = 0; idx < parray.length; idx++) {
let doProcessing = true;
chartworkname = settings.areachartlist[parray[idx]];
chartname = chartworkname;
clippedShapeFolder = path.join(appdir, "clipshapes", "sectional");
chartlayertype = settings.layertypes[settings.layertypeindex];
chartfolder = path.join(workarea, chartworkname);
charturl = `${settings.vfrindividualtemplate.replace("<chartdate>", chartdate).replace("<charttype>", chartworkname)}`;
console.log(charturl);
let cpt = new ProcessTime(chartname);
timings.set(chartname, cpt);
let chartdbfile = path.join(dbfolder, `${chartname}.${settings.dbextension}`);
if (fs.existsSync(chartdbfile)) {
let stat = fs.statSync(chartdbfile);
const birthDate = stat.birthtime;
const year = birthDate.getFullYear();
const month = String(birthDate.getMonth() + 1).padStart(2, '0'); // Month is 0-indexed
const day = String(birthDate.getDate()).padStart(2, '0');
const formattedDate = `${month}-${day}-${year}`;
if (formattedDate === chartdate) {
// Current version of this chart exists, no processing needed
doProcessing = false;
cpt.totaltime = "Download:";
}
}
if (doProcessing) {
runProcessing();
}
console.log(`${cpt.totaltime}\r\n`);
// if this was a single chart process request,
// return the resulting timing class object
if (msgid > -1) {
return cpt;
}
}
}
function processOneFull() {
let lst = "\nSelect the full chart number you want to process from this list\r\n\r\n";
let i = 0;
settings.fullchartlist.forEach((fullchart) => {
let cname = fullchart[0] === "DDECUS" ? fullchart[2] : fullchart[0];
lst += `${i} ${cname.split("_").join(" ")}\r\n`;
i++;
});
lst += "--------------------------------------------\r\nYour selection: ";
let response = processPrompt(lst);
nm = Number(response);
if (nm >= 0 && nm < settings.fullchartlist.length) {
parray.push(nm);
}
else {
console.log("Invalid response, exiting!");
process.exit();
}
processFulls();
}
function processFulls(msgid = -1) {
addmetabounds = true;
for (let idx = 0; idx < parray.length; idx++) {
let chart = settings.fullchartlist[parray[idx]];
let lcasename = chart[0].toLowerCase();
let charttype = chart[1];
chartworkname = chart[0];
if (charttype === "ifr") {
isifrchart = true;
lcasename = chart[2].toLowerCase();
charturl = settings.ifrdownloadtemplate.replace("<chartdate>", chartdate).replace("<charttype>", chartworkname);
clippedShapeFolder = path.join(appdir, "clipshapes", lcasename);
chartname = settings.fullchartlist[idx][2]; // use alias value for IFR
chartfolder = path.join(workarea, chartname);
}
else { // vfr
if (lcasename === "us_vfr_wall_planning") {
charturl = `${settings.usvfrwallplanningtemplate.replace("<chartdate>", chartdate).replace("<charttype>", chartworkname)}`;
}
else {
charturl = settings.vfrdownloadtemplate.replace("<chartdate>", chartdate).replace("<charttype>", chartworkname);
}
clippedShapeFolder = path.join(appdir, "clipshapes", lcasename);
chartname = chartworkname;
chartfolder = path.join(workarea, chartworkname);
}
let cpt = new ProcessTime(chartname);
timings.set(chartname, cpt);
console.log(`${cpt.totaltime}\n`);
let chartdbfile = path.join(dbfolder, `${chartname}.${settings.dbextension}`);
if (!fs.existsSync(chartdbfile)) {
runProcessing();
}
if (msgid > -1) {
return cpt;
}
};
}
function generateGeoTIFF() {
let question = "Enter the full path and filename of your mbtiles file: ";
let mbtilesfile = processPrompt(question);
if (fs.existsSync(mbtilesfile)) {
question = "Enter the full path and filename of the geoTIFF that will be created: "
let geotiff = processPrompt(question);
cmd = `gdal_translate -of GTiff -co BIGTIFF=YES ${mbtilesfile} ${geotiff}`;
executeCommand(cmd);
}
else {
console.log("ERROR: The specified mbtiles file does not exist, exiting chartmaker!");
}
}
function runProcessing() {
dir_1_unzipped = path.join(chartfolder, "1_unzipped");
dir_2_expanded = path.join(chartfolder, "2_expanded");
dir_3_clipped = path.join(chartfolder, "3_clipped");
dir_4_tiled = path.join(chartfolder, "4_tiled");
dir_5_merged = path.join(chartfolder, "5_merged");
dir_6_quantized = path.join(chartfolder, "6_quantized");
setupEnvironment();
downloadCharts();
unzipCharts();
normalizeChartNames();
processImages();
mergeAndQuantize();
makeMbTiles();
if (settings.cleanprocessfolders === true) {
cmd = `rm -rf ${workarea}`
executeCommand(cmd);
cmd = `mkdir ${workarea}`
executeCommand(cmd);
}
}
if (!useWebServer) {
ProcessTime.reportProcessingTime(startdate);
}
/**
* Generate all of the working folders for image processing
*/
function setupEnvironment() {
// make sure the working folder for this chart is cleared out
if (fs.existsSync(chartfolder)) {
fs.rmSync(chartfolder, { recursive: true, force: true });
}
// Create the base workarea chart folder
fs.mkdirSync(chartfolder);
// OK, now create all of the workarea sub folders
if (!fs.existsSync(dir_1_unzipped)) fs.mkdirSync(dir_1_unzipped);
if (!fs.existsSync(dir_2_expanded)) fs.mkdirSync(dir_2_expanded);
if (!fs.existsSync(dir_3_clipped)) fs.mkdirSync(dir_3_clipped);
if (!fs.existsSync(dir_4_tiled)) fs.mkdirSync(dir_4_tiled);
if (!fs.existsSync(dir_5_merged)) fs.mkdirSync(dir_5_merged);
if (!fs.existsSync(dir_6_quantized)) fs.mkdirSync(dir_6_quantized);
if (settings.logtofile) setupDebugLog(chartfolder);
logEntry("Created all workarea subfolders");
}
/**
* Get the desired chart zip file from the FAA's digital sources URL
*/
function downloadCharts() {
let chartzip = path.join(chartcache, `${chartworkname}-${chartdate}.zip`);
if (fs.existsSync(chartzip)) {
logEntry(`Using cached ${chartzip}`);
return;
}
else {
let oldfiles = fs.readdirSync(chartcache);
for (var i = 0; i < oldfiles.length; i++) {
if (oldfiles[i].startsWith(chartworkname)) {
fs.rmSync(path.join(chartcache, oldfiles[i]));
break;
}
}
logEntry(`Downloading ${chartzip}`);
cmd = `curl ${charturl} -v -o ${chartzip}`;
executeCommand(cmd, true);
}
}
/**
* Unzip chart file
*/
function unzipCharts() {
let chartzip = path.join(chartcache, `${chartworkname}-${chartdate}.zip`);
cmd = `unzip -o ${chartzip} -x '*.htm' -d ${dir_1_unzipped}`;
executeCommand(cmd);
if (isifrchart) { // we now have a work area full of IFR zip files
let zipfiles = fs.readdirSync(dir_1_unzipped);
zipfiles.forEach(zipfile => {
let srchstr = chartname === "Enroute_High" ? "ENR_H" : "ENR_L" // only unzip the indicated type
if (zipfile.search(srchstr) > -1) {
cmd = `unzip -o ${path.join(dir_1_unzipped, zipfile)} -d ${dir_1_unzipped}`;
executeCommand(cmd);
}
});
}
// now clean out all of the irrelevant files...
cmd = `rm -r -f ${path.join(dir_1_unzipped, "*.pdf")}`;
executeCommand(cmd);
cmd = `rm -r -f ${path.join(dir_1_unzipped, "*.htm")}`;
executeCommand(cmd);
cmd = `rm -r -f ${path.join(dir_1_unzipped, "*.zip")}`;
executeCommand(cmd);
// This chart is a recent addition to the zip file from the FAA.
// It does not have a processing option, but as it is included
// in the .zip file, it has no matching .tfw file with wsgbounds
// and crashes the process, so we will just eliminate it.
// Maybe in the future it could be added as a separate option.
cmd = `rm -r -f "${path.join(dir_1_unzipped, 'Caribbean Planning Chart.tif')}"`;
executeCommand(cmd);
}
/**
* Clean up chart tif names by converting spaces and dashes to underscores
*/
function normalizeChartNames() {
let files = fs.readdirSync(dir_1_unzipped);
files.forEach((file) => {
if (file.endsWith(".tif") || file.endsWith(".tfw") || file.endsWith(".tfwx")) {
let newfile = normalizeFileName(file);
fs.renameSync(path.join(dir_1_unzipped, file), path.join(dir_1_unzipped, newfile));
}
});
}
/**
* Perform GDAL operations on all the unzipped chart tif images
*/
function processImages() {
/*-----------------------------------------------------------------------
1) GDAL_TRANSLATE: Expand color table to RGBA
2) GDALWARP: Warp chart to EPSG:4326 and clip off the borders and legend
3) GDALADDO: Generate overviews of the VRT for all zoom levels
4) GDAL2TILES: Convert overviews into tiled PNG images
-------------------------------------------------------------------------*/
let chartareas = buildChartNameArray();
let cblend = settings.blendpixels;
chartareas.forEach((area) => {
logEntry(`* chart ${area}`);
let shpfile = `${area}.shp`;
let vrtfile = `${area}.vrt`;
let srcfile = `${area}.tif`;
let shapefile = path.join(clippedShapeFolder, shpfile);
let clipped = path.join(dir_3_clipped, vrtfile);
let sourcetif = path.join(dir_1_unzipped, srcfile);
let expanded = path.join(dir_2_expanded, vrtfile);
let tiled = path.join(dir_4_tiled, area);
let expandopt = "";
// determine if RGB expansion is required
cmd = `gdalinfo -json "${sourcetif}"`;
let infojson = JSON.parse(execSync(cmd));
if (infojson.bands.length === 1) {
if (settings.outputgrayscale) {
expandopt = "-expand gray";
}
else {
expandopt = "-expand rgb";
}
}
wgsbounds = infojson.wgs84Extent.coordinates[0];
logEntry(`>> gdal_translate ${sourcetif}`);
cmd = `gdal_translate -strict -of vrt -ovr NONE ${expandopt} ${sourcetif} ${expanded}`;
executeCommand(cmd);
logEntry(`>> gdalwarp warping and clipping ${clipped} using shapefile ${shapefile}`);
cmd = `gdalwarp -t_srs EPSG:3857 -dstalpha --config GDAL_CACHEMAX 256 -multi -cblend ${cblend} -cutline ${shapefile} -crop_to_cutline ${expanded} ${clipped}`;
executeCommand(cmd);
// If user specified grayscale but left the imageformat as
// webp, then force the imageformat to a default of png.
if (settings.outputgrayscale && imageformat === "webp") {
imageformat = "png";
}
// setup formatting arguments for overviews
let formatargs = `--tiledriver=${imageformat.toUpperCase()} `;
let configargs = "";
switch (imageformat) {
case "webp":
configargs = `--config WEBP_LOSSLESS_OVERVIEW YES --config WEBP_LEVEL_OVERVIEW ${settings.tileimagequality}`;
formatargs += `--webp-quality=${settings.tileimagequality} --webp-lossless`;
break;
case "jpeg":
configargs = `--config JPEG_QUALITY_OVERVIEW ${settings.tileimagequality}`;
break;
default:
// no adjustments for PNG images
break;
}
if (settings.addoverviews) {
logEntry(`>> gdaladdo adding overviews to ${clipped}`);
cmd = `gdaladdo ${configargs} --config GDAL_NUM_THREADS ALL_CPUS ${clipped}`;
executeCommand(cmd)
}
logEntry(`>> gdal2tiles tiling ${clipped} into ${tiled}`);
cmd = `gdal2tiles.py --zoom=${settings.zoomrange} --processes=${processes} ${formatargs} --tmscompatible --webviewer=openlayers ${clipped} ${tiled}`;
executeCommand(cmd);
});
}
/**
* Merge all of the individual chart zoom folders into a single master chart folder
*/
function mergeAndQuantize() {
let ptm = new ProcessTime("mergetiles.pl");
let loc = path.join(appdir, "mergetiles.pl");
logEntry(`Executing mergetiles.pl Perl script to merge tiles into ${dir_5_merged}\n`);
cmd = `perl ${loc} ${dir_4_tiled} ${dir_5_merged}`;
executeCommand(cmd, true);
ptm.calculateProcessTime();
logEntry(`${ptm.totaltime}\n`);
// Only quantize png images, webp images are quantized via tiling option...
if (imageformat === "png" && settings.tileimagequality < 100) {
quantizePngImages();
}
}
/**
* Perform quantization of all .png images
*/
function quantizePngImages() {
let interimct = 0;
let i;
let qcmd = "";
let cmds = buildQuantizingCommandArray();
let quantcmd = `pngquant --strip --skip-if-larger --force --quality ${settings.tileimagequality}`;
logEntry(`quantizing ${cmds.length} png images at ${settings.tileimagequality}% --------------`);
for (i = 0; i < cmds.length; i++) {
qcmd = `${quantcmd} ${cmds[i][0]} --output ${cmds[i][1]}`;
try {
execSync(qcmd, { stdio: 'inherit' });
}
catch (error) {
// if there is a error quantizing, just copy the original image
let file0 = cmds[i][0];
let file1 = cmds[i][1];
qcmd = `cp -f ${file0} ${file1}`;
executeCommand(qcmd);
}
interimct++;
if (interimct >= 1000) {
logEntry(`${i + 1} of ${cmds.length} images processed`);
interimct = 0;
}
}
logEntry(`>> Total processed image count = ${cmds.length}`);
}
/**
* Create the mbtiles database
*/
function makeMbTiles() {
logEntry(`>> generating metadata json for ${chartname} database`);
let sourcefolder = dir_5_merged;
let zooms = settings.zoomrange.split("-");
let minzoom = zooms[0];
let maxzoom = zooms.length > 1 ? zooms[1] : zooms[0];
// if png and any quality below 100%, use the quantized workarea folder
if (imageformat === "png" && settings.tileimagequality < 100) {
sourcefolder = dir_6_quantized;
}
let chartdesc = chartname.split("_").join(" "); // normalize description
let addedbounds = "";
if (addmetabounds) {
let metabounds = calculateBounds();
addedbounds = `"bounds": "${metabounds[0]},${metabounds[1]},${metabounds[2]},${metabounds[3]}",` +
`"center": "${metabounds[4][0]},${metabounds[4][1]},${settings.centerzoomlevel}",`
}
let metajson = `{
"name": "${chartname}",
"description": "${chartdesc} Chart",
"type": "${chartlayertype}",
"format": "${imageformat}",
"minzoom": ${minzoom},
"maxzoom": ${maxzoom},
"attribution": "${settings.attribution}"
}`;
let fpath = path.join(sourcefolder, "metadata.json");
let fd = fs.openSync(fpath, 'w');
fs.writeSync(fd, metajson);
fs.closeSync(fd);
let mbtiles = path.join(dbfolder, `${chartname}.${settings.dbextension}`);
fs.rmSync(mbtiles, { force: true });
logEntry(`>> creating database: ${mbtiles}`);
cmd = `python3 ${path.join(appdir, "mbutil", "mb-util")} --image_format=${imageformat} --silent --scheme=tms ${sourcefolder} ${mbtiles}`;
executeCommand(cmd, false);
let cpt = timings.get(chartname);
cpt.calculateProcessTime();
}
/**
* Get the bounds of the processed GEOTIFF for database metadata
*/
function calculateBounds() {
try {
let lngdiff = (Math.abs(wgsbounds[0][0]) - Math.abs(wgsbounds[2][0])) / 2;
let latdiff = (Math.abs(wgsbounds[0][1]) - Math.abs(wgsbounds[2][1])) / 2;
let center = [wgsbounds[0][0] + lngdiff, wgsbounds[0][1] - latdiff];
return [`${wgsbounds[0][0]}`, `${wgsbounds[0][1]}`, `${wgsbounds[2][0]}`, `${wgsbounds[2][1]}`, `${center}`];
}
catch(error) {
console.log(error);
}
}
/**
* Called by processImages() so it can iterate through all unzipped chart names
* @returns array containing all of the chart names to be processed
*/
function buildChartNameArray() {
let files = fs.readdirSync(dir_1_unzipped);
let chartnames = [];
files.forEach((file) => {
if (file.search("new_york_vfr_plannings_.tif") === -1) {
let fname = file.toLowerCase();
if ((fname.endsWith(".tif")) &&
(fname.search("fly") === -1)) {
let cname = fname.replace(".tif", "");
chartnames.push(cname);
}
}
});
return chartnames;
}
/**
* Called by quantizePngImages() to build processing commands for the pngquant utility
* @returns array containing all pngquant commands
*/
function buildQuantizingCommandArray() {
let mergedfolders = fs.readdirSync(dir_5_merged);
let cmdarray = [];
mergedfolders.forEach((zoomlevel) => {
let zoomfolder = path.join(dir_5_merged, zoomlevel);
if (fs.statSync(zoomfolder).isDirectory()) {
let quantzoomfolder = path.join(dir_6_quantized, zoomlevel);
if (!fs.existsSync(quantzoomfolder)) {
fs.mkdirSync(quantzoomfolder);
}
let xfolders = fs.readdirSync(zoomfolder);
xfolders.forEach((x) => {
let y = path.join(zoomfolder, x);
let quantizedfolders = path.join(quantzoomfolder, x);
if (!fs.existsSync(quantizedfolders)) {
fs.mkdirSync(quantizedfolders);
}
// build an array of chart names
let images = fs.readdirSync(y);
images.forEach((image) => {
let imgpath = path.join(y, image);
let outpath = path.join(quantizedfolders, image);
let subarray = new Array(imgpath, outpath);
cmdarray.push(subarray);
});
});
}
});
return cmdarray;
}
/**
* Get rid of spaces and dashes in chart names and "normalize" with underscores
* @param {string} file
* @returns string with underscores instead of spaces or dashes
*/
function normalizeFileName(file) {
return file.toLowerCase()
.split(" ").join("_")
.split("'").join("")
.split("-").join("_")
.split("_sec").join("")
.split("_tac").join("")
.split("_chart").join("")
.split("u.s.").join("us");
}
/**
* Iterate through the chartdates.json file that contains chart publication dates
* @returns the closest date of currently available FAA published charts
*/
function getBestChartDate() {
let thisdate = new Date();
let thistime = thisdate.getTime();
let cdates = [];
let found = false;
let selectedDate = "";
let datedata = fs.readFileSync(path.join(appdir, "chartdates.json"), "utf-8");
let datelist = JSON.parse(datedata);
datelist.ChartDates.forEach((cdate) => {
cdates.push(new Date(cdate))
});
let sortedDates = cdates.sort((a, b) => b.date - a.date);
sortedDates.forEach((dateobj) => {
if (!found) {
let dtime = new Date(dateobj).getTime();
let tdiff = thistime - dtime;
let tdays = tdiff / (1000 * 3600 * 24);
let diffdays = parseInt(tdays.toFixed(0));
if (diffdays >= -20 && diffdays <= 36) {
let m = pad2(dateobj.getMonth() + 1); // months (0-11)
let d = pad2(dateobj.getDate()); // day (1-31)
let y = dateobj.getFullYear();
selectedDate = `${m}-${d}-${y}`;
found = true;
}
}
else {
if (expiredate === "") {
let m = pad2(dateobj.getMonth() + 1); // months (0-11)
let d = pad2(dateobj.getDate()); // day (1-31)
let y = dateobj.getFullYear();
expiredate = `${m}-${d}-${y}`;
}
}
});
if (!found) {
throw new Error("No suitable chart date was found!");
}
else {
return selectedDate;
}
}
/**
* Execute the passed in command and log the result
* @param {string} command
*/
function executeCommand(command, logstdout = null) {
try {
if (logstdout == null) {
logstdout = settings.debug;
}
const stdout = execSync(command).toString();
if (logstdout) {
logEntry(stdout);
}
}
catch (error) {
logEntry(error.message);
}
}
/**
* Utility to make sure clipping files are all lower-case
*/
function normalizeClipNames() {
let files = fs.readdirSync(clippedShapeFolder);
try {
files.forEach((file) => {
let oldname = path.join(clippedShapeFolder, file);
let newname = oldname.toLowerCase();
fs.renameSync(oldname, newname);
});
}
catch (err) {
logEntry(err.message);
}
}
/**
* Set the global useWebServer flag
*/
function enterWebserverMode() {
useWebServer = true;
console.log("Entering web server mode")
}
/**
* Iterate through any/all connected clients and send data
* @param {message} json message object
*/
async function sendMessageToClients(message, userid = "") {
[...connections.keys()].forEach((client) => {
if (userid === client.tag.uid || userid === "") {
client.send(JSON.stringify(message));
}
});
}
// Set up a periodic ping interval
function startPingSender() {
if (pingSenderId !== 0) {
return pingSenderId;