2020-04-15 13:25:51 +02:00
|
|
|
import json
|
|
|
|
import time
|
|
|
|
import urllib.request
|
|
|
|
|
|
|
|
__document = None
|
|
|
|
__data = {}
|
|
|
|
__next = 0
|
|
|
|
|
|
|
|
__sources = [
|
2020-05-03 11:15:52 +02:00
|
|
|
{
|
|
|
|
"url": "http://free.ipwhois.io/json/",
|
|
|
|
"mapping": {
|
|
|
|
"latitude": "latitude",
|
|
|
|
"longitude": "longitude",
|
|
|
|
"country": "country",
|
|
|
|
"ip": "public_ip",
|
2020-04-15 13:25:51 +02:00
|
|
|
},
|
2020-05-03 11:15:52 +02:00
|
|
|
},
|
|
|
|
{
|
|
|
|
"url": "http://ipapi.co/json",
|
|
|
|
"mapping": {
|
|
|
|
"latitude": "latitude",
|
|
|
|
"longitude": "longitude",
|
|
|
|
"country_name": "country",
|
|
|
|
"ip": "public_ip",
|
|
|
|
},
|
|
|
|
},
|
2020-04-15 13:25:51 +02:00
|
|
|
]
|
|
|
|
|
2020-05-03 11:15:52 +02:00
|
|
|
|
2020-04-15 13:25:51 +02:00
|
|
|
def __expired():
|
|
|
|
global __next
|
|
|
|
return __next <= time.time()
|
|
|
|
|
2020-05-03 11:15:52 +02:00
|
|
|
|
2020-04-15 13:25:51 +02:00
|
|
|
def __load():
|
|
|
|
global __data
|
|
|
|
global __next
|
|
|
|
|
|
|
|
__data = {}
|
|
|
|
for src in __sources:
|
|
|
|
try:
|
2020-05-03 11:15:52 +02:00
|
|
|
tmp = json.loads(urllib.request.urlopen(src["url"]).read())
|
|
|
|
for k, v in src["mapping"].items():
|
2020-04-15 13:25:51 +02:00
|
|
|
__data[v] = tmp.get(k, None)
|
2020-05-03 11:15:52 +02:00
|
|
|
__next = time.time() + 60 * 60 * 12 # update once every 12h
|
2020-04-15 13:25:51 +02:00
|
|
|
return
|
|
|
|
except Exception as e:
|
|
|
|
pass
|
2020-05-03 11:15:52 +02:00
|
|
|
__next = time.time() + 60 * 30 # error - try again every 30m
|
|
|
|
|
2020-04-15 13:25:51 +02:00
|
|
|
|
|
|
|
def __get(name, default=None):
|
|
|
|
global __data
|
|
|
|
if not __data or __expired():
|
|
|
|
__load()
|
|
|
|
return __data.get(name, default)
|
|
|
|
|
2020-05-03 11:15:52 +02:00
|
|
|
|
2020-04-15 13:25:51 +02:00
|
|
|
def reset():
|
|
|
|
global __next
|
|
|
|
__next = 0
|
|
|
|
|
2020-05-03 11:15:52 +02:00
|
|
|
|
2020-04-15 13:25:51 +02:00
|
|
|
def coordinates():
|
2020-05-03 11:15:52 +02:00
|
|
|
return __get("latitude"), __get("longitude")
|
|
|
|
|
2020-04-15 13:25:51 +02:00
|
|
|
|
|
|
|
def country():
|
2020-05-03 11:15:52 +02:00
|
|
|
return __get("country")
|
|
|
|
|
2020-04-15 13:25:51 +02:00
|
|
|
|
|
|
|
def public_ip():
|
2020-05-03 11:15:52 +02:00
|
|
|
return __get("public_ip")
|
|
|
|
|
2020-04-15 13:25:51 +02:00
|
|
|
|
|
|
|
# vim: tabstop=8 expandtab shiftwidth=4 softtabstop=4
|