-
Notifications
You must be signed in to change notification settings - Fork 2
/
requestHandlers.js
312 lines (268 loc) · 8.25 KB
/
requestHandlers.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
var https = require("https");
var OAuth= require('oauth').OAuth;
var mongodb = require('mongodb');
var querystring = require('querystring');
// Mongo details
var mongoUri = process.env.MONGOHQ_URL || 'mongodb://localhost/ubdata';
var collection;
mongodb.Db.connect(mongoUri, function (err, db) {
db.collection('measurements', function(er, aCollection) {
collection = aCollection;
});
});
// Get the most recent data
var getData = function (callback) {
// Not sure this url will always work?
var options = {
host: 'dl.dropboxusercontent.com',
port: 443,
path: '/sh/9knt5t1vuhq2i1x/1S6hOJ5QQO/PM25.txt?token_hash=AAEJ3Aah6f0CwRAeJ58uBE6HD50gjD7T-iovsaUSOVhrmg'
};
var data = '';
https.get(options, function (res) {
res.on('data', function (chunk) {
data += chunk;
});
res.on('end', function () {
// Split on ';'
var components = data.split(';');
// Make sure we have valid data
if (components.length === 0) {
callback(undefined);
}
var measurement = {};
var times = components[1].split('-');
measurement.startTime = Date.parse(components[0] + ' ' + times[0]);
measurement.endTime = Date.parse(components[0] + ' ' + times[1]);
measurement.pm25 = components[2] * 1000;
var station = {
id: components[3],
latitude: parseFloat(components[4]),
longitude: parseFloat(components[5])
};
measurement.station = station;
// Update data every time we're getting new data
saveToDatabase(measurement);
callback(measurement);
});
}).on('error', function (e) {
console.log(e);
callback(undefined);
});
};
var getMostRecent = function (req, res) {
getData(function (data) {
if (data === undefined) {
res.end('{"results": {"error": "no data"}}');
} else {
res.end(JSON.stringify(data));
}
});
};
var getMostRecentMeasurements = function (callback) {
if (collection === undefined) {
return undefined;
}
collection.find({}).toArray(callback);
};
var getDailyMeasurements = function (callback) {
if (collection === undefined) {
return undefined;
}
// Get all the records
collection.find({}).toArray(function (err, records) {
// Take the average for a given day
var dailyRecords = [];
var lastDay;
var dayTotal = 0;
var count = 0;
var dayAverage = 0;
for (var i = 0; i < records.length; i++) {
var record = records[i];
var midpoint = (record.endTime - record.startTime) * 0.5 + record.startTime;
midpoint += (60000 * new Date().getTimezoneOffset()); // convert it to mn time
midpoint = new Date(midpoint);
var day = new Date(midpoint.getFullYear(), midpoint.getMonth(), midpoint.getDate());
if (i === 0 || day.toString() === lastDay.toString()) {
// Add to previous total
dayTotal += record.pm25;
count++;
lastDay = day;
} else {
// New day, get average and push the value
dayAverage = dayTotal / count;
console.log(dayTotal, count);
dailyRecords.push({ date: Date.parse(lastDay), pm25: dayAverage });
count = 1;
dayTotal = record.pm25;
lastDay = day;
}
}
// And add the last one
dayAverage = dayTotal / count;
dailyRecords.push({ date: Date.parse(lastDay), pm25: dayAverage });
callback(err, dailyRecords);
});
};
// Send out a tweet with the pollution info
var sendTweet = function (req, res) {
getData(function (data) {
// Make sure we have data
if (data === undefined) {
console.log("ERROR no data.");
return res.json(404, {"results": {"error": "no data"}});
}
// Make sure the pm value is good
if (isNaN(data.pm25)) {
console.log("ERROR pm is NaN");
return res.json(404, {"results": {"error": "bad pm value"}});
}
// Make sure the data is from within the last 3 hours
var dLocal = new Date();
var utcLocal = dLocal.getTime() + (dLocal.getTimezoneOffset() * 60000);
var mnLocal = new Date(utcLocal + (3600000*8));
var diff = mnLocal - data.endTime;
if (diff > 3 * 60 * 60 * 1000) {
console.log("ERROR data older than 3 hours.");
return res.json(404, {"results": {"error": "data older than 3hr"}});
}
////
// Build the string to tweet
////
var mnString = '';
var enString = '';
// Get the date
var date = new Date(((data.endTime - data.startTime) * 0.5) + data.startTime);
var startTime = new Date(data.startTime);
var endTime = new Date(data.endTime);
var dateString = date.getFullYear() + '-' + addZero((date.getMonth() + 1)) + '-' + addZero(date.getDate()) + '; ' + addZero(startTime.getHours()) + ':' + addZero(startTime.getMinutes()) + '-' + addZero(endTime.getHours()) + ':' + addZero(endTime.getMinutes());
mnString += dateString + '; ';
enString += dateString + '; ';
// Get pm value
enString += 'PM2.5=' + data.pm25.toFixed(0) + '\u00B5g/m\u00B3 [3hr avg]; ';
mnString += 'PM2.5=' + data.pm25.toFixed(0) + '\u00B5g/m\u00B3 [3цагийн дундаж]; ';
// Get AQI
enString += getAQIStrings(data.pm25).en + ' [for 24hr exposure at this level]';
mnString += getAQIStrings(data.pm25).mn;
console.log(enString);
console.log(mnString);
// console.log(enString.length);
// console.log(mnString.length);
// Tweet the English then tweet the Mongolian 30 seconds later to ensure it shows up in feeds
tweet(enString);
setTimeout( function () {
tweet(mnString);
}, 30000);
// Send to Facebook in English then in Mongolian after a delay
facebook(enString);
setTimeout( function () {
facebook(mnString);
}, 30000);
// End the request
res.end('{"results": {"success": "1"}}');
});
};
// The function to actually send the tweet given a message
var tweet = function(text) {
var tweeter = new OAuth(
"https://api.twitter.com/oauth/request_token",
"https://api.twitter.com/oauth/access_token",
process.env.CONSUMER_KEY,
process.env.CONSUMER_SECRET,
"1.0",
null,
"HMAC-SHA1"
);
var body = ({'status': text, 'lat': 47.920709, 'long': 106.905848});
tweeter.post("https://api.twitter.com/1.1/statuses/update.json",
process.env.TWITTER_TOKEN, process.env.TWITTER_SECRET, body, "application/json",
function (error, data, response) {
if (error) {
console.log('{"results": {"error": ' + JSON.stringify(error) + '}}');
}
});
};
var facebook = function(text) {
var postData = {
'access_token': process.env.FACEBOOK_ACCESS_TOKEN,
'message': text
};
postData = querystring.stringify(postData);
var options = {
host: 'graph.facebook.com',
port: 443,
path: '/' + process.env.FACEBOOK_PAGE + '/feed',
method: 'POST',
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
'Conent-Length': postData.length
}
};
var req = https.request(options, function (res) {
var data = '';
res.on('data', function (d) {
data += d;
});
res.on('end', function () {
data = JSON.parse(data);
console.log(data);
});
});
req.write(postData);
req.end();
};
Array.prototype.sum = function() {
for (var i = 0, L = this.length, sum = 0; i < L; sum += this[i++]);
return sum;
};
var saveToDatabase = function (data) {
// Make sure we have a valid collection
if (!collection) {
return;
}
// Update the record, making sure a measurement is unique on startTime.
collection.update( { startTime: data.startTime }, data, { upsert: true }, function(err) {
if (err) {
console.warn(err.message);
} else {
console.log('successfully updated');
}
});
};
var getAQIStrings = function (pm25) {
var aqi = {};
if (pm25 <= 15.4) {
aqi.en = 'Good';
aqi.mn = 'Агаарын чанар сайн';
} else if (pm25 <= 40.4) {
aqi.en = 'Moderate';
aqi.mn = 'Хэвийн';
} else if (pm25 <= 65.4) {
aqi.en = 'Unhealthy for sensitive groups';
aqi.mn = 'Эмзэг бүлгийн эрүүл мэндэд муу';
} else if (pm25 <= 150.4) {
aqi.en = 'Unhealthy';
aqi.mn = 'Эрүүл мэндэд муу нөлөөтэй';
} else if (pm25 <= 250.4) {
aqi.en = 'Very Unhealthy';
aqi.mn = 'Эрүүл мэндэд маш муу';
} else if (pm25 <= 500.4) {
aqi.en = 'Hazardous';
aqi.mn = 'Аюултай';
} else {
aqi.en = 'Beyond Index';
aqi.mn = 'Онц аюултай';
}
return aqi;
};
var addZero = function (num) {
if (num < 10) {
return '0' + num;
} else {
return num;
}
};
exports.getMostRecentMeasurements = getMostRecentMeasurements;
exports.getMostRecent = getMostRecent;
exports.sendTweet = sendTweet;
exports.getDailyMeasurements = getDailyMeasurements;