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
|
const fetch = require('node-fetch')
function AWDrone (options) {
if (!(this instanceof AWDrone))
return new AWDrone(options)
options = options || {}
if (!options.express)
throw new Error('Express not provided to AWDrone');
if (!options.config)
throw new Error('Configuration not provided to AWDrone');
const express = options.express
const router = express.Router()
const config = options.config
const db = options.db
router.get('/', function (req, res) {
update(db).then( () => {
res.sendStatus(200)
}).catch( (err) => {
res.sendStatus(500)
})
})
function refresh () {
setTimeout(refresh, 60 * 60 * 12)
update(db)
}
setTimeout(refresh, 60)
this._router = router
}
function update (db) {
return new Promise( (resolve, reject) => {
const type = 'drone'
const id = 'drone-statistics'
db.get(type).get(id).then( data => {
scrape().then( matches => {
if (matches.length !== 4) {
throw new Error('problem retrieving matches')
}
data.strikes = matches[0]
data.totalKilled = matches[1]
data.civiliansKilled = matches[2]
data.childrenKilled = matches[3]
const resource = db.get(type, id)
resource.update(id, data).then(function(updated) {
resolve()
}).fail( err => { throw err })
})
.catch( err => {
reject(err)
})
})
})
}
function scrape (cb) {
return fetch('https://www.thebureauinvestigates.com/projects/drone-war')
.then(response => {
return response.text()
})
.then(body => {
const statRegexp = new RegExp('stat__figure">([-0-9,]+)<', 'g')
const matches = getMatches(body, statRegexp)
return matches
})
.catch( err => {
return []
})
}
function getMatches(string, regex, index) {
index = index || 1
let matches = []
let match
while (match = regex.exec(string)) {
matches.push(match[index])
}
return matches
}
AWDrone.prototype.middleware = function () {
return this._router
}
module.exports = AWDrone
|