2012-09-05 16:25:51 +12:00
import os . path
2012-09-06 00:13:13 +12:00
import json
2013-07-02 05:56:01 +12:00
import gzip
from StringIO import StringIO
2011-11-20 22:23:31 +13:00
2014-02-14 16:36:57 +13:00
import pygeoip
from util import hook , http
2012-09-06 00:13:13 +12:00
# load region database
with open ( " ./plugins/data/geoip_regions.json " , " rb " ) as f :
regions = json . loads ( f . read ( ) )
2012-09-05 20:56:50 +12:00
2013-07-02 05:56:01 +12:00
if os . path . isfile ( os . path . abspath ( " ./plugins/data/GeoLiteCity.dat " ) ) :
2014-02-14 16:49:41 +13:00
# initialise geolocation database
2013-07-02 05:56:01 +12:00
geo = pygeoip . GeoIP ( os . path . abspath ( " ./plugins/data/GeoLiteCity.dat " ) )
else :
download = http . get ( " http://geolite.maxmind.com/download/geoip/database/GeoLiteCity.dat.gz " )
string_io = StringIO ( download )
geoip_file = gzip . GzipFile ( fileobj = string_io , mode = ' rb ' )
2013-09-04 18:30:04 +08:00
output = open ( os . path . abspath ( " ./plugins/data/GeoLiteCity.dat " ) , ' wb ' )
2013-07-02 05:56:01 +12:00
output . write ( geoip_file . read ( ) )
output . close ( )
2013-07-15 23:01:01 +12:00
geo = pygeoip . GeoIP ( os . path . abspath ( " ./plugins/data/GeoLiteCity.dat " ) )
2012-09-05 20:56:50 +12:00
2011-11-20 22:23:31 +13:00
@hook.command
2012-09-05 16:25:51 +12:00
def geoip ( inp ) :
2013-09-04 18:30:04 +08:00
""" geoip <host/ip> -- Gets the location of <host/ip> """
2013-07-02 05:56:01 +12:00
2012-09-05 16:25:51 +12:00
try :
record = geo . record_by_name ( inp )
except :
return " Sorry, I can ' t locate that in my database. "
2012-05-07 11:58:29 +12:00
2012-09-05 20:56:50 +12:00
data = { }
if " region_name " in record :
# we try catching an exception here because the region DB is missing a few areas
# it's a lazy patch, but it should do the job
try :
data [ " region " ] = " , " + regions [ record [ " country_code " ] ] [ record [ " region_name " ] ]
except :
data [ " region " ] = " "
else :
data [ " region " ] = " "
data [ " cc " ] = record [ " country_code " ] or " N/A "
data [ " country " ] = record [ " country_name " ] or " Unknown "
data [ " city " ] = record [ " city " ] or " Unknown "
2014-03-18 16:20:12 +11:00
return u " \x02 Country: \x02 {country} ( {cc} ), \x02 City: \x02 {city} {region} " . format ( * * data )