2017-06-02 19:00:22 +10:00
|
|
|
import express = require('express');
|
|
|
|
import expresshb = require('express-handlebars');
|
2017-06-02 20:43:16 +10:00
|
|
|
import http = require('http');
|
|
|
|
import https = require('https');
|
2017-06-02 21:16:55 +10:00
|
|
|
import Promise = require('promise');
|
2017-06-02 21:47:17 +10:00
|
|
|
import HashMap = require('hashmap');
|
2017-06-02 20:43:16 +10:00
|
|
|
|
|
|
|
import { IPGeoJson } from './ip_geo';
|
2017-06-02 19:00:22 +10:00
|
|
|
|
|
|
|
var app = express();
|
2017-06-02 21:47:17 +10:00
|
|
|
var cache = new HashMap();
|
2017-06-02 19:00:22 +10:00
|
|
|
|
2017-06-02 19:07:34 +10:00
|
|
|
app.engine('handlebars', expresshb({ defaultLayout: 'main' }));
|
2017-06-02 19:00:22 +10:00
|
|
|
app.set('view engine', 'handlebars');
|
2017-06-02 19:07:34 +10:00
|
|
|
|
2017-06-02 19:00:22 +10:00
|
|
|
app.get('/', function (req, res) {
|
2017-06-02 21:16:55 +10:00
|
|
|
getIpInfo("::ffff:" + "119.17.156.106").done(function (geoinfo: IPGeoJson) {
|
2017-06-02 21:32:21 +10:00
|
|
|
res.render('home', {
|
|
|
|
helpers: {
|
2017-06-02 21:47:17 +10:00
|
|
|
ip: function () { return geoinfo.ip; },
|
|
|
|
city: function () { return geoinfo.city; },
|
|
|
|
region: function () { return geoinfo.region; },
|
|
|
|
country: function () { return geoinfo.country; },
|
|
|
|
loc: function () { return geoinfo.loc; },
|
|
|
|
postal: function () { return geoinfo.postal }
|
2017-06-02 21:32:21 +10:00
|
|
|
}
|
|
|
|
});
|
2017-06-02 21:16:55 +10:00
|
|
|
}); //replace with req.ip
|
2017-06-02 19:00:22 +10:00
|
|
|
});
|
|
|
|
|
2017-06-02 22:24:22 +10:00
|
|
|
app.listen(3000, 'localhost');
|
2017-06-02 20:43:16 +10:00
|
|
|
|
2017-06-02 21:16:55 +10:00
|
|
|
function getIpInfo(ip: String): Promise.IThenable<{}> {
|
|
|
|
return new Promise(function (resolve, reject) {
|
|
|
|
var options = {
|
|
|
|
host: 'ipinfo.io',
|
|
|
|
port: 443,
|
|
|
|
path: '/' + ip + '/geo',
|
|
|
|
method: 'GET',
|
|
|
|
headers: {
|
|
|
|
'Content-Type': 'application/json'
|
|
|
|
}
|
2017-06-02 20:43:16 +10:00
|
|
|
}
|
|
|
|
|
2017-06-02 21:16:55 +10:00
|
|
|
var callback = function (response: http.IncomingMessage) {
|
|
|
|
var str: string;
|
2017-06-02 20:43:16 +10:00
|
|
|
|
2017-06-02 21:16:55 +10:00
|
|
|
response.on('data', function (chunk) {
|
|
|
|
str += chunk;
|
|
|
|
});
|
2017-06-02 20:43:16 +10:00
|
|
|
|
2017-06-02 21:16:55 +10:00
|
|
|
response.on('end', function () {
|
2017-06-02 21:47:17 +10:00
|
|
|
var result = <IPGeoJson>JSON.parse(str.slice(9));
|
|
|
|
cache.set(ip, result);
|
|
|
|
resolve(result);
|
2017-06-02 21:16:55 +10:00
|
|
|
});
|
|
|
|
}
|
2017-06-02 20:43:16 +10:00
|
|
|
|
2017-06-02 21:47:17 +10:00
|
|
|
var cached = cache.get(ip);
|
|
|
|
if (cached != null) {
|
|
|
|
resolve(cached);
|
|
|
|
} else {
|
|
|
|
https.get(options, callback);
|
|
|
|
}
|
2017-06-02 21:16:55 +10:00
|
|
|
})
|
2017-06-02 20:43:16 +10:00
|
|
|
}
|