-
Notifications
You must be signed in to change notification settings - Fork 0
/
app.js
310 lines (246 loc) · 8.96 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
var fs = require('fs');
var async = require('async');
var upload = require('mapbox-upload');
var shpwrite = require('shp-write');
var sys = require('sys')
var exec = require('child_process').exec;
var mergeGeoJSON = require('./custom_modules/merge-geojson');
var queryOverpass = require('./custom_modules/bbox-query-overpass');
//var queryOverpass = require('./custom_modules/read-files.js'); // for test purposes
var calcLength = require('./custom_modules/calc-line-length');
//TODO: covert these to command line args
var runAsCronJob = true;
var saveStatsToDB = true;
var pushToMapBox = false;
//var cronTime = '00 * * * * *'; //once a minute - for testing only
var cronTime = '00 00 00 * * *'; //every night at midnight
//polyfill startsWith
if (!String.prototype.startsWith) {
String.prototype.startsWith = function(searchString, position) {
position = position || 0;
return this.indexOf(searchString, position) === position;
};
}
function run(dataUpdatedCallback){
if(saveStatsToDB){
var knex = require('./connection');
}
var overpassQL = '[out:json][timeout:25];' +
'(' +
'way["highway"="track"]["access"="forestry"]( {{bbox}} );' +
'way["highway"="track"]["access"="agriculture"]( {{bbox}} );' +
'way["abandoned:highway"="track"]["access"="forestry"]( {{bbox}} );' +
'way["abandoned:highway"="track"]["access"="agricultural"]( {{bbox}} );' +
');' +
'out body;' +
'>;' +
'out skel qt;';
var inFiles = {
drc: __dirname + '/data/drc_project_areas.geojson',
car: __dirname + '/data/car_project_areas.geojson',
cog: __dirname + '/data/cog_project_areas.geojson',
cmr: __dirname + '/data/cmr_project_areas.geojson'
};
var roadLengthFile = __dirname + '/data/km_roads_by_project.json';
queryOverpass(inFiles, overpassQL, function(err, geojsonObj){
if(err) throw err;
var roadLengths = {};
var totalRoadLength = 0;
var roadCount = 0;
var roadWithTagCount = 0;
// given an array of project logging road geojson feature collections
// 1. calculate their length
//1. b) convert OSM tags to geoJSON properties
// 2. write each to file
// 3. write calculated lengths to file
// 4. merge and write that to a file
// 5. upload the merged file to MapBox
async.each(Object.keys(geojsonObj), function(key, callback){
// 1. calculate length
var geojson = geojsonObj[key];
roadLengths[key] = calcLength(geojson);
totalRoadLength += roadLengths[key];
roadCount += geojson.features.length;
//1. b) convert OSM tags to geoJSON properties
geojson.features.forEach(function(feature){
var tags = feature.properties.tags;
if(typeof tags === 'object'){
Object.keys(tags).map(function (key) {
var val = tags[key];
if(typeof val === 'object' ){
val = JSON.stringify(val);
}
feature.properties[key] = val;
});
if(feature.properties.start_date
&& feature.properties.start_date != ''
&& feature.properties.start_date != 'unknown'){
roadWithTagCount++;
}else{
//assign a value so it is easier to style in the map
feature.properties.start_date = 'unknown';
}
//remove bad tags
if(feature.properties.start_date
&& feature.properties.start_date.startsWith('before')
&& feature.properties.start_date != 'before 2000'){
feature.properties.start_date = 'unknown';
}
}
//delete feature.properties.tags;
});
// 2. write to file
writeJSON(__dirname + '/data/' + key + '_logging_roads.geojson', geojson);
callback();
}, function(err){
if(err) throw err
// 3. write road lengths to file
writeJSON(roadLengthFile, roadLengths);
});
// 4. merge geojsons and write to file
var allRoads = mergeGeoJSON(geojsonObj);
// var allRoadsFileName = __dirname + '/data/' + Object.keys(geojsonObj).join('_') + '_logging_roads.geojson';
var allRoadsFileName = __dirname + '/output/roads.geojson';
if(saveStatsToDB){
//save counts to database
knex('logging.stats')
.where({key: 'totalRoads'})
.update({ value: roadCount})
.catch(function (err) {
console.log(err);
});
knex('logging.stats')
.where({key: 'taggedRoads'})
.update({ value: roadWithTagCount})
.catch(function (err) {
console.log(err);
});
knex('logging.stats')
.where({key: 'totalRoadLength'})
.update({ value: round(totalRoadLength)})
.catch(function (err) {
console.log(err);
});
}
writeJSON(allRoadsFileName, allRoads, function(err){
if (err) throw err;
if(pushToMapBox) {
// 5. upload to MapBox
var progress = upload({
file: allRoadsFileName,
account: 'crowdcover', // Mapbox user account.
accesstoken: 'sk.eyJ1IjoiY3Jvd2Rjb3ZlciIsImEiOiJsemhCUzljIn0.uIgOj_SkXD99320QU5ejuQ', // A valid Mapbox API secret token with the uploads:write scope enabled.
mapid: 'crowdcover.e06eb11a' // The identifier of the map to create or update.
});
progress.on('error', function(err){
if (err) throw err;
});
progress.once('finished', function(){
console.log('Uploaded to mapbox complete for file: ' + allRoadsFileName);
});
}
//remove unknown
var allRoadsWithTags = {
"type":"FeatureCollection",
"features":[]
};
allRoads.features.forEach(function(feature){
if(feature.properties.start_date
&& feature.properties.start_date == 'before 2000'){
feature.properties.start_date = '2000';
}
if(feature.properties.start_date
&& feature.properties.start_date == 'after 2013'){
feature.properties.start_date = '2014';
}
if(feature.properties.start_date
&& feature.properties.start_date != 'unknown'){
allRoadsWithTags.features.push(feature);
}
});
var allRoadsWithTagFileName = __dirname + '/data/all_roads_withstartdate.geojson';
writeJSON(allRoadsWithTagFileName, allRoadsWithTags, function(err){
if(err) console.log(err);
var options = {
folder: 'loggingroads',
types: {
line: 'roads',
polyline: 'roads'
}
}
console.log("Creating Shapefile");
var shapefile = shpwrite.zip(allRoads, options);
var shapeFileName = __dirname + '/data/roads.shp.zip';
fs.writeFile(shapeFileName, shapefile, function(err){
if(err) console.log(err);
console.log('successfully wrote file: ' + shapeFileName);
//rezip the shapefile with the OS since the node package is not compressing
var cmd = 'unzip -d ' + __dirname + ' ' + __dirname + '/data/roads.shp.zip';
console.log(cmd);
exec(cmd, function (error, stdout, stderr) {
console.log('stdout: ' + stdout);
console.log('stderr: ' + stderr);
var cmd2 = 'zip -r -m ' + __dirname + '/output/roads.shp.zip '+ __dirname +'/loggingroads';
console.log(cmd2);
exec(cmd2, function (error, stdout, stderr) {
console.log('stdout: ' + stdout);
console.log('stderr: ' + stderr);
dataUpdatedCallback();
if (error !== null) {
console.log('exec error: ' + error);
}
});
if (error !== null) {
console.log('exec error: ' + error);
}
});
});
});
});
});
function writeJSON(outFile, json, callback){
try {
json = JSON.stringify(json) + '\n';
}catch(err){
console.log(err);
}
fs.writeFile(outFile, json, function(err){
if(err) console.log(err);
console.log('successfully wrote file: ' + outFile);
if(callback) callback();
});
}
} //end run()
if(runAsCronJob){
var CronJob = require('cron').CronJob;
var job = new CronJob({
cronTime: cronTime,
onTick: function() {
try{
console.log('Started: ' + new Date().toLocaleString());
run(function(){
console.log('Finished: ' + new Date().toLocaleString());
exec("pm2 restart tessera", function (error, stdout, stderr) {
console.log('stdout: ' + stdout);
console.log('stderr: ' + stderr);
if (error !== null) {
console.log('exec error: ' + error);
}
});
});
} catch(error){
console.log(error.toString());
}
//restart vector tile service to load new data
},
start: false,
timeZone: 'America/New_York'
});
job.start();
} else {
//just run once
console.log('Started: ' + new Date().toLocaleString());
run(function(){
console.log('Finished: ' + new Date().toLocaleString());
});
}