forked from CartoDB/madrid-traffic-connector
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcameras.js
96 lines (91 loc) · 2.85 KB
/
cameras.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
const config = require('./config');
const request = require('request');
const parseString = require('xml2js').parseString;
const store = require('./store');
class Cameras {
run() {
let p = new Promise((resolve, reject) => {
request(config.CAMERAS.URL, (error, response, body) => {
if (error) {
console.error('error:', error); // Print the error if one occurred
reject(error);
} else if (!response) {
let e = new Error('No response received');
console.error(e);
reject(e);
} else if (response.statusCode !== 200) {
let e = new Error(`Unexpected statusCode: ${response.statusCode}`);
console.error(e);
reject(e);
} else if (!response.body) {
let e = new Error(`Missing body`);
console.error(e);
reject(e);
} else {
this.parse(body).then((data) => {
store.query(this.buildSQL(data))
.then(d => resolve())
.catch(e => reject(e));
}).catch(reason => {
let e = new Error(`Error parsing KML: ${reason}`);
console.error(e);
reject(e);
});
}
});
});
return p;
}
parse (xml) {
let p = new Promise((resolve, reject) => {
parseString(xml, (err, result) => {
if (err) return reject(err);
let doc = result.kml.Document[0];
let placeMarks = doc.Placemark;
let data = [];
for (let p of placeMarks) {
try {
const cod_id = p.ExtendedData[0].Data[0].Value[0];
const name = p.ExtendedData[0].Data[1].Value[0].replace("'","\\'");
const coords = p.Point[0].coordinates[0];
const url = `${config.CAMERAS.URL_IMAGES}Camara${cod_id}.jpg`;
let o = {
the_geom: `ST_Force2D(ST_SetSRID(
ST_GeomFromKML('<Point><coordinates>${coords}</coordinates></Point>')
,4326))`,
name: name,
cod_id: cod_id,
url: url
};
data.push(o);
} catch (err) {
// Catch exception to avoid abort all the features
console.error(`Error parsing element: ${err}`);
}
}
if (!data.length) {
reject(new Error('No length after parser'));
}
resolve(data);
});
});
return p;
}
buildSQL (data) {
const q = [];
for (let d of data) {
q.push(`
INSERT INTO ${config.CAMERAS.TABLE}
(the_geom, name, cod_id, url, created_at)
VALUES
(${d.the_geom},E'${d.name}','${d.cod_id}','${d.url}',now());
`);
}
return `BEGIN;
DELETE FROM ${config.CAMERAS.TABLE};
${q.join(' ')}
COMMIT;
`;
}
}
module.exports = Cameras;