forked from isjeffcom/coronvirusFigureUK
-
Notifications
You must be signed in to change notification settings - Fork 0
/
robot.js
499 lines (369 loc) · 14.2 KB
/
robot.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
/**
* Develop By Jeff Wu
* 2020.03
* isjeff.com
**/
/**
* IMPORTANCE
* Functions are designed to be collected data from specific website, it could be change fast accroding to source website structure
* Keep monitoring the source's data structure and 'current_shadow' table
**/
/**
* VOIDS AND FUNCTIONS
* ENTRANCE:
* getData: get all data, main entrance
* getAreaData: main entrance for getting all area data
*
* HELPER
* getDataFromNHS: get cases data from Government website
* getDataFromWDM: get cases data from Worldometer website
* getEnglandFromNHS: get England's area data from Government website
* getScotlandFromNHS: get Scotland's area data from Government website
*
**/
// The code in this page could be change fast accroding to source website structure
// Keep Monitoring the data is important
// import
const superagent= require('superagent')
const cheerio = require('cheerio')
const utils = require('./utils')
const database = require('./database')
const { addSlashes } = require('slashes')
const csv = require('csv-parser')
const fs = require('fs');
const { http, https } = require('follow-redirects');
const struct = require('./struct.js')
const timeoutDefault = {
response: 0, //delay 0 second
deadline: 100000 // 10 second timeout
}
const figure = [
{
source: "NHS",
link: "https://www.gov.uk/guidance/coronavirus-covid-19-information-for-the-public",
more: "http://www.arcgis.com/sharing/rest/content/items/bc8ee90225644ef7a6f4dd1b13ea1d67/data",
id: "number-of-cases"
},
{
source: "Worldometers",
link: "https://www.worldometers.info/coronavirus/",
id: "main_table_countries"
}
]
const areaData = [
{
name: "england",
link: "http://www.arcgis.com/sharing/rest/content/items/b684319181f94875a6879bbc833ca3a6/data",
id: "download-csv-file"
},
{
name: "scotland",
link: "https://www.gov.scot/coronavirus-covid-19/",
id: "overview"
},
{
name: "northernIreland",
link: "https://www.publichealth.hscni.net/news/covid-19-coronavirus",
id: "situation-in-northern-ireland"
},
{
name: "wales",
link: "https://gov.wales/written-statement-coronavirus-covid-19-1",
id: "announcement-item__article"
}
]
function getData(){
return new Promise(resolve => {
getDataFromNHS(figure[0])
getMoreFromNHS(figure[0]) // Get death and 4 nations data
getDataFromWDM(figure[1])
getAreaData()
//getEnglandFromNHS(areaData[0])
//getScotlandFromNHS(areaData[1])
//getWales(areaData[3])
//getNIreland(areaData[2])
resolve(true)
})
}
async function getAreaData(){
const england = await getEnglandFromNHS(areaData[0])
const scotland = await getScotlandFromNHS(areaData[1])
const nIreland = await getNIreland(areaData[2])
const wales = await getWales(areaData[3])
if(england && scotland && nIreland && wales){
let res = england.concat(scotland)
// Wales and Northern Ireland are as one due to there is no regional data available
if(wales) res.push(wales)
if(nIreland) res.push(nIreland)
let ready = {
area: addSlashes(JSON.stringify(res))
}
if(ready.area != "" || ready.area.length > 0){
database.update(1, ready)
}
}
}
function getMoreFromNHS(data){
return new Promise(resolve => {
var ready = {
death: 0,
england: 0,
scotland: 0,
wales: 0,
nireland: 0
}
const readXlsxFile = require('read-excel-file/node');
const file = fs.createWriteStream("nation.xlsx");
const request = http.get(data.more, response => {
if(response.statusCode == 200){
response.pipe(file)
// Readable Stream.
readXlsxFile(fs.createReadStream('nation.xlsx')).then((rows) => {
if(rows.length > 0){
for(let i=0;i<rows[0].length;i++){
if(rows[0][i] == "TotalUKDeaths"){
ready.death = rows[1][i]
}
else if(rows[0][i] == "EnglandCases"){
ready.england = rows[1][i]
}
else if(rows[0][i] == "ScotlandCases"){
ready.scotland = rows[1][i]
}
else if(rows[0][i] == "WalesCases"){
ready.wales = rows[1][i]
}
else if(rows[0][i] == "NICases"){
ready.nireland = rows[1][i]
}
}
database.update(1, ready)
resolve(true)
} else {
resolve(false)
}
})
} else {
resolve(false)
}
}).on('error', err => {
console.error(err)
})
})
}
// get NHS offical data
function getDataFromNHS(data){
superagent.get(data.link).timeout(timeoutDefault).end((err, res) => {
var tmp = utils.deepCopy(struct.getStruct())
if (err) {
recordError(data.source, "timeout", err)
return
} else {
let $ = cheerio.load(res.text)
$(('h2#'+data.id)).each((idx, ele) => {
let next = $(ele).next()
let txt = next.text()
txt = txt.split(" ")
// Check word 'positive' for getting positive number, both confirm and death use the word 'positive'
let cMIdx = utils.idIdxsInArr("positive", txt) // return an array with position with word 'positive'
let nMIdx = utils.idIdxsInArr("negative", txt) // return an array with negative with word 'negative'
if(cMIdx != -1
&& nMIdx != -1
&& cMIdx.length > 0
&& nMIdx.length > 0
&& txt.length>0){
// Process and save to number
let confirmed = parseInt(txt[cMIdx[0] - 4].replace(/,/g, ""))
let negative = parseInt(txt[nMIdx[0] - 3].replace(/,/g, ""))
let death = 0
if(cMIdx.length > 1){
death = parseInt(txt[cMIdx[1]-4].replace(/,/g, "")) ? parseInt(txt[cMIdx[1]-4].replace(/,/g, "")) : utils.matchNum(txt[cMIdx[1]-4])
} else {
recordError(data.source, "no death", txt)
}
// Record if Error and return
if(isNaN(confirmed) || isNaN(negative) || isNaN(death)){
let errData = {
confirmed: confirmed,
negative: negative,
death: death
}
recordError(data.source, "source struct changed", errData)
return
}
// Final check and put into database
tmp.confirmed = confirmed ? confirmed : -1
tmp.negative = negative ? negative : -1
tmp.death = death ? death : -1
tmp.ts = utils.getTS()
database.update(1, tmp)
}
})
}
})
}
function getDataFromWDM(data){
var tmp = utils.deepCopy(struct.getStruct())
superagent.get(data.link).timeout(timeoutDefault).end((err, res) => {
if(err){
recordError(data.source, "timeout", err)
}else{
let $ = cheerio.load(res.text)
let trs = $('table#' + data.id + ' tbody tr')
trs.each(function (idx, value){
$value = $(value).find('td');
$value.each(function (idxx, single) {
if (0 === idxx) {
if($(single).text().indexOf("UK") != -1){
tmp.confirmed = parseInt($($value[idxx+1]).text().replace(/,/g, ""))
tmp.death = parseInt($($value[idxx+3]).text().replace(/,/g, ""))
tmp.cured = parseInt($($value[idxx+5]).text().replace(/,/g, ""))
tmp.ts = utils.getTS()
// Record if Error and return
if(isNaN(tmp.confirmed) || isNaN(tmp.death) || isNaN(tmp.cured)){
let errData = {
confirmed: tmp.confirmed,
death: tmp.death,
cured: tmp.cured,
}
recordError(data.source, "source struct changed", errData)
return
}
database.update(2, tmp)
return
}
}
})
})
}
})
}
function getEnglandFromNHS(data){
return new Promise(resolve => {
var results = []
const http = require('http');
const file = fs.createWriteStream("england_data.csv");
const request = http.get(data.link, function(response) {
if(response.statusCode == 200){
response.pipe(file)
fs.createReadStream('england_data.csv')
.pipe(csv())
.on('data', (data) => {
let tmp = {location: data.GSS_NM, number: data.TotalCases}
results.push(tmp)
})
.on('end', () => {
resolve(results)
})
} else {
resolve(false)
}
}).on("error", ()=>{
resolve(false)
})
})
}
function getScotlandFromNHS(data){
return new Promise(resolve => {
var result = []
superagent.get(data.link).timeout(timeoutDefault).end((err, res) => {
if(err){
recordError(data.source, "timeout", err)
resolve(false)
}else{
let $ = cheerio.load(res.text)
let trs = $('#' + data.id + ' table tbody tr')
trs.each(function (idx, value){
$value = $(value).find('td')
let tmpSingle = {}
$value.each(function (idxx, single) {
if(idxx == 0) tmpSingle.location = $(single).text()
if(idxx == 1) tmpSingle.number = parseInt($(single).text().replace(/,/g, ""))
})
result.push(tmpSingle)
})
resolve(result)
}
})
})
}
// As Wales gov didnt provided regional data (I couldt find it anyway, Wales was treat as a whole area)
// Only return wales number only
function getWales(data){
return new Promise(resolve => {
var result = 0
superagent.get(data.link).timeout(timeoutDefault).end((err, res) => {
if(err){
recordError(data.source, "timeout", res)
resolve(false)
}else{
let $ = cheerio.load(res.text)
let trs = $('#' + data.id + ' div')
let c = $($(trs)[0]).find('div')[2]
trs = ($(c).children()[2])
let txt = $(trs).text()
if(txt.indexOf("total") != -1){
txt = txt.split(" ")
let idx = txt.indexOf("cases")
result = parseInt(txt[idx+2])
} else {
result = null
}
/*trs.each(function (idx, value){
$value = $(value)
let tmpSingle = {}
$value.each(function (idxx, single) {
let txt = $(single).text()
if(txt.indexOf('total number of confirmed cases') != -1){
let txtBuff = txt.split(' ')
let txtBuffIndex = txtBuff.indexOf('cases')
result = parseInt(txtBuff[txtBuffIndex+4])
}
})
})*/
resolve({location: "Wales", number: result})
}
})
})
}
function getNIreland(data){
return new Promise(resolve => {
var result = 0
superagent.get(data.link).timeout(timeoutDefault).end((err, res) => {
if(err){
recordError(data.source, "timeout", res)
resolve(false)
}else{
let $ = cheerio.load(res.text)
let trs = $('h2#' + data.id).next().next()
let txt = $(trs).text()
txt = txt.split(" ")
let txtIndex = txt.indexOf("Ireland")
// Maybe with ending period, ready for not
//txtIndex = txtIndex == -1 ? txt.indexOf("positive.") : txtIndex
result = parseInt(txt[txtIndex+2])
resolve({location: "Northern Ireland", number: result})
}
})
})
}
function recordError(source, reason, data){
try{
let ready = {
source: source,
reason: reason,
detail: utils.isJson(data) ? JSON.stringify(data) : String(data)
}
// Prevent too long
if(ready.detail.length > 1000){
ready.detail = "too many, check: " + source
}
database.saveErr(ready)
} catch{
// do nothing...
// dont stop main thread
}
}
module.exports={
getData: getData
}