-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapp.js
More file actions
345 lines (307 loc) · 10.2 KB
/
app.js
File metadata and controls
345 lines (307 loc) · 10.2 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
/**
* @constant {module} - Swagger Express module
*/
const swaggerUi = require('swagger-ui-express');
/**
* @constant {module} - The swagger api documentation saved in a json object
*/
const {
apiDocumentation
} = require('./doc/api/apidoc.js');
/**
* @constant {module} - The express module
*/
const express = require('express');
/**
* @constant {module} - The path module
*/
const path = require('path');
/**
* @constant {module} - The multer module
*/
const multer = require('multer');
/**
* @constant {module} - The body-parser module
*/
const bodyParser = require('body-parser');
/**
* @constant {module} - The fs module
*/
const fs = require('fs');
/**
* @constant {Object} - The functions from the ./useR_AOI_TD.js file
* @see ./useR_AOI_TD.js
*/
const {
getData,
validateTrainingData
} = require('./useR_AOI_TD');
/**
* @constant {Object} - The function from the ./useR_ML_AOA.js file
* @see ./useR_ML_AOA.js
*/
const {
calculateAOA
} = require('./useR_ML_AOA');
/**
* @constant {module} - The cors module
*/
var cors = require('cors');
/**
* @constant {module} - The R-integration module
*/
const R = require('r-integration');
/**
* @constant {module} - The https module
*/
const https = require('https')
/**
* @constant {module} - The resolveSoa function from the dns module
*/
const {
resolveSoa
} = require('dns');
/**
* @constant {number} - The port of the express server. If a port iss specified in the environment variable PORT, the port is overwritten, else
* the port is set to 8781
*/
const PORT = process.env.PORT || 8781;
/**
* The storage for the files send to multer
*/
let storage = multer.diskStorage({
destination: (req, file, cb) => {
cb(null, "./public/uploads");
},
filename: (req, file, cb) => {
cb(null, file.originalname)
}
});
let upload = multer({
storage: storage
});
/**
* @constant {Express} - The express app
*/
const app = express();
app.use(express.static(path.join(__dirname, 'doc')));
//Setting up the app
app.use(express.json());
app.use(bodyParser.json());
app.use(express.urlencoded({
extended: true
}));
app.use(cors());
app.post('/start', async (req, res, next) => {
if (req.body.areyouatest) {
//copy files to uplaods
fs.copyFile(__dirname + '/R/test_data/model.RDS', __dirname + '/public/uploads/model.RDS', (err) => {
if (err) throw err;
console.log('model for testrun copied to destination');
});
fs.copyFile(__dirname + '/R/test_data/trainingsdaten_muenster_32632.gpkg', __dirname + '/public/uploads/trainingsdaten_muenster_32632.gpkg', (err) => {
if (err) throw err;
console.log('training data for testrun copied to destination');
});
}
/**
* Formatting all needed incomingData in the way the getData function needs them.
*/
if (req.body.whereareyoufrom == "demo") {
console.log("demo");
console.log(req.body);
// copy aoiTIF to destination
fs.copyFile(__dirname + '/R/demo_input/demo_aoi.tif', __dirname + '/R/processed_sentinel_images/aoi.tif', (err) => {
if (err) throw err;
console.log('/R/demo_aoi.tif was copied to /R/processed_sentinel_images/aoi.tif');
});
// copy TrainingDataTIF to destination
fs.copyFile(__dirname + '/R/demo_input/demo_trainingData.tif', __dirname + '/R/processed_sentinel_images/trainingData.tif', (err) => {
if (err) throw err;
console.log('/R/demo_input/demo_trainingData.tif was copied to /R/processed_sentinel_images/trainingData.tif');
});
// copy Model to destination
fs.copyFile(__dirname + '/R/demo_input/demo_model.RDS', __dirname + '/public/uploads/model.RDS', (err) => {
if (err) throw err;
console.log('/R/demo_input/demo_model.RDS was copied to /public/uploads/model.RDS');
});
// copy Model to destination
fs.copyFile(__dirname + '/R/demo_input/demo_model.RDS', __dirname + '/R/model/model.RDS', (err) => {
if (err) throw err;
console.log('/R/demo_input/demo_model.RDS was copied to /R/model/model.RDS');
});
let response = await calculateAOA(req.body);
res.send(response);
} else {
console.log(req.body);
let response = {}
response.stac = await getData(req.body);
if (response.stac.status === "error") {
res.status(402).send(response);
console.log("/start 400", response);
} else {
response.aoa = await calculateAOA(req.body);
if (response.aoa.status === "error") {
res.status(403).send(response);
console.log("/start 400", response)
} else {
console.log("/start 200", response);
res.send(response);
}
}
}
});
// route to return uploaded file
// DEFAULT
app.get('/file/:name', (req, res, next) => {
const filePath = path.join(__dirname, 'public/uploads', req.params.name);
checkFileNotFound(filePath, res);
res.sendFile(filePath);
})
app.get('/model/:name', (req, res, next) => {
const filePath = path.join(__dirname, './R/model/', req.params.name);
checkFileNotFound(filePath, res);
res.sendFile(filePath);
})
// Prediction and AOA
app.get('/predictionaoa/:name', (req, res, next) => {
const filePath = path.join(__dirname, './R/prediction_and_aoa/', req.params.name);
checkFileNotFound(filePath, res);
res.sendFile(filePath);
})
// Sentinel images
app.get('/processedsentinelimages/:name', (req, res, next) => {
const filePath = path.join(__dirname, './R/processed_sentinel_images/', req.params.name);
checkFileNotFound(filePath, res);
res.sendFile(filePath);
})
// Further train areas
app.get('/furthertrainareas/:name', (req, res, next) => {
const filePath = path.join(__dirname, './R/further_train_areas/', req.params.name);
checkFileNotFound(filePath, res);
res.sendFile(filePath);
})
// training polygons
app.get('/trainingdata/:name', (req, res, next) => {
const filePath = path.join(__dirname, './public/uploads/', req.params.name);
checkFileNotFound(filePath, res);
res.sendFile(filePath);
})
app.get('/marker', (req, res, next) => {
res.sendFile(path.join(__dirname, './public/marker.png'));
})
// route to upload file only for multer
app.post('/upload', upload.single('file'), async function (req, res) {
let filename = req.file.filename
let extension = filename.split('.').pop()
if (!req.file) {
console.log("No file is available!");
return res.send({
success: false
});
} else if (filename.split('.').pop() === 'RDS'){
console.log('File is available!');
console.log(filename)
return res.send({
success: true
})
} else if (extension === 'geojson' || extension === 'gpkg') {
console.log('File is available!');
console.log(filename)
let path = "./public/uploads/" + req.file.originalname;
let valid = await validateTrainingData(path);
if (valid.status === "error") {
console.log("Invalid training data uploaded")
await deleteFiles(__dirname + "/public/uploads", "dummy");
res.status(401).send({
status: "error",
message: 'Invalid training data',
error: valid
});
return
}
return res.send({
success: true
})
}
});
app.post("/deleteFiles", async (req, res) => {
console.log("delete files from public/uploads");
console.log(req.body.file)
let json = {
text: "The files were deleted successfully"
}
try {
await deleteFiles(__dirname + "/public/uploads", req.body.file);
res.status(200).send(json);
} catch (err) {
console.log(err);
res.status(500).send({
"text": "Error while deleting files",
"error": err
});
}
});
app.post("/getGeoJSON", async (req, res) => {
console.log(req.body)
try {
let output = await R.callMethodAsync(__dirname + "/R/ConvertGeoPackageToGeoJson.R", "convertGeoPackageToGeoJson", {filename: req.body.filename, filepath: req.body.filepath})
console.log(output);
res.send(output);
} catch (error) {
console.error(error);
res.status(400).send(error);
}
});
/**
* Checking if the file at the given path actual exists. If not the function send a 404 error to the given response object.
* If the file exists, the function does nothing and returns void.
* @param {String} filePath - The path were the function looking for the possible file. The path should be given absolute.
* @param {Response} res - The response object were the function sends the error if the file does not exist.
* @returns {void} - The function returns void.
*/
function checkFileNotFound(filePath, res) {
fs.access(filePath, fs.constants.F_OK, (err) => {
if (err) {
res.status(404).send({
status: "error",
message: 'File not found'
});
return;
}
});
}
/**
* Test function for async calls
* @code function callMethodAsync(path, method, args) { test(); }
* @param {Test} dirPath
* @param {Test} fileName
* @returns
*/
function deleteFiles(dirPath, fileName) {
return new Promise((resolve, reject) => {
fs.readdir(dirPath, (err, files) => {
if (err) {
reject(err);
} else {
for (const file of files) {
if (file !== fileName && file !== ".gitignore") {
fs.unlink(path.join(dirPath, file), err => {
if (err) {
reject(err);
} else {
console.log("file deleted: ", file);
}
});
}
}
resolve();
}
});
});
}
app.use('/api', swaggerUi.serve, swaggerUi.setup(apiDocumentation));
app.listen(PORT, () => {
console.log(`Example app listening on port ${PORT}`)
});
module.exports = app;