1 | |
---|
2 | GeoIp = { |
---|
3 | cache: {}, |
---|
4 | pending: {}, |
---|
5 | |
---|
6 | get: function(ip, callback){ |
---|
7 | if (!GeoIp.storageInit && window.localStorage) { |
---|
8 | GeoIp.storageInit = true; |
---|
9 | var cache = localStorage.getItem("freegeoip"); |
---|
10 | if (cache) { |
---|
11 | cache = JSON.parse(cache); |
---|
12 | for (var key in cache) { |
---|
13 | var data = cache[key]; |
---|
14 | if ( (new Date()).getTime() - data.reqTime > 36 * 3600000) |
---|
15 | delete cache[key]; |
---|
16 | } |
---|
17 | GeoIp.cache = cache; |
---|
18 | } |
---|
19 | jQuery(window).on("unload", function() { |
---|
20 | localStorage.setItem("freegeoip", JSON.stringify(GeoIp.cache) ); |
---|
21 | } ); |
---|
22 | } |
---|
23 | |
---|
24 | if (GeoIp.cache.hasOwnProperty(ip)) |
---|
25 | callback(GeoIp.cache[ip]); |
---|
26 | else if (GeoIp.pending[ip]) |
---|
27 | GeoIp.pending[ip].push(callback); |
---|
28 | else { |
---|
29 | GeoIp.pending[ip] = [callback]; |
---|
30 | jQuery.ajax( { |
---|
31 | url: "http://freegeoip.net/json/" + ip, |
---|
32 | dataType: "jsonp", |
---|
33 | cache: true, |
---|
34 | timeout: 5000, |
---|
35 | success: function(data) { |
---|
36 | data.reqTime = (new Date()).getTime(); |
---|
37 | var res=[]; |
---|
38 | if (data.city) res.push(data.city); |
---|
39 | if (data.region_name) res.push(data.region_name); |
---|
40 | if (data.country_name) res.push(data.country_name); |
---|
41 | data.fullName = res.join(", "); |
---|
42 | |
---|
43 | GeoIp.cache[ip] = data; |
---|
44 | var callbacks = GeoIp.pending[ip]; |
---|
45 | delete GeoIp.pending[ip]; |
---|
46 | for (var i=0; i<callbacks.length; i++) |
---|
47 | callbacks[i].call(null, data); |
---|
48 | }, |
---|
49 | |
---|
50 | error: function() { |
---|
51 | var data = {ip:ip, reqTime: (new Date()).getTime()}; |
---|
52 | |
---|
53 | GeoIp.cache[ip] = data; |
---|
54 | var callbacks = GeoIp.pending[ip]; |
---|
55 | delete GeoIp.pending[ip]; |
---|
56 | for (var i=0; i<callbacks.length; i++) |
---|
57 | callbacks[i].call(null, data); |
---|
58 | } |
---|
59 | }); |
---|
60 | } |
---|
61 | } |
---|
62 | } |
---|