forked from bdotdub/hummingbird
/
locations.js
64 lines (49 loc) · 1.58 KB
/
locations.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
var http = require('http');
var locationCache = {};
var LocationsMetric = {
name: 'Location',
initialData: {location: []},
interval: 500,
incrementCallback: function(view) {
var remoteAddress,
metric = this,
host = "ipinfodb.com",
client = http.createClient(80, host);
if(view.env.ip === "127.0.0.1") {
remoteAddress = "";
} else {
remoteAddress = view.env.ip;
}
if(locationCache[remoteAddress]) {
console.log('cache hit');
metric.data.location.push(locationCache[remoteAddress]);
}
client.on('error', function(exception) {
console.log("IP Lookup exception:");
console.log(JSON.stringify(exception, null, 2));
});
var request = client.request("GET", "/ip_query.php?ip=" + remoteAddress + "&timezone=false", {host: host});
request.end();
request.on('response', function(resp) {
var buffer = '';
resp.on('data', function(chunk) { buffer += chunk; });
resp.on('end', function() {
var lat, lon, city;
if(resp.statusCode < 300) {
lat = /<Latitude>([0-9\.\-]+)<\/Latitude>/.exec(buffer);
lon = /<Longitude>([0-9\.\-]+)<\/Longitude>/.exec(buffer);
city = /<City>(.*)<\/City>/.exec(buffer);
}
var location = {
latitude: lat ? lat[1] : 0,
longitude: lon ? lon[1] : 0,
city: city ? city[1] : "Unknown"
};
locationCache[remoteAddress] = location;
metric.data.location.push(location);
});
});
}
}
for (var i in LocationsMetric)
exports[i] = LocationsMetric[i];