Varken/varken/helpers.py

76 lines
2.1 KiB
Python
Raw Normal View History

import os
import time
import tarfile
2018-12-02 19:59:46 -08:00
import hashlib
import geoip2.database
from json.decoder import JSONDecodeError
from os.path import abspath, join
from requests.exceptions import InvalidSchema, SSLError
from urllib.request import urlretrieve
2018-11-28 12:32:39 -08:00
def geoip_download():
2018-12-01 15:53:03 -08:00
tar_dbfile = abspath(join('.', 'data', 'GeoLite2-City.tar.gz'))
url = 'http://geolite.maxmind.com/download/geoip/database/GeoLite2-City.tar.gz'
urlretrieve(url, tar_dbfile)
tar = tarfile.open(tar_dbfile, "r:gz")
for files in tar.getmembers():
if 'GeoLite2-City.mmdb' in files.name:
files.name = os.path.basename(files.name)
2018-12-01 15:51:28 -08:00
tar.extract(files, abspath(join('.', 'data')))
os.remove(tar_dbfile)
2018-12-02 19:59:46 -08:00
def geo_lookup(ipaddress):
2018-12-01 15:54:47 -08:00
dbfile = abspath(join('.', 'data', 'GeoLite2-City.mmdb'))
now = time.time()
try:
dbinfo = os.stat(dbfile)
db_age = now - dbinfo.st_ctime
if db_age > (35 * 86400):
os.remove(dbfile)
geoip_download()
except FileNotFoundError:
geoip_download()
reader = geoip2.database.Reader(dbfile)
return reader.city(ipaddress)
2018-12-02 19:59:46 -08:00
def hashit(string):
encoded = string.encode()
hashed = hashlib.md5(encoded).hexdigest()
return hashed
def connection_handler(session, request, verify):
s = session
r = request
v = verify
return_json = False
try:
get = s.send(r, verify=v)
if get.status_code == 401:
print("Your api key is incorrect for {}".format(r.url))
elif get.status_code == 404:
print("This url doesnt even resolve: {}".format(r.url))
elif get.status_code == 200:
try:
return_json = get.json()
except JSONDecodeError:
print("No JSON response... BORKED! Let us know in discord")
except InvalidSchema:
print("You added http(s):// in the config file. Don't do that.")
except SSLError as e:
print("Either your host is unreachable or you have an ssl issue.")
print("The issue was: {}".format(e))
return return_json