Skip to content

Commit

Permalink
Move to use ip-api for geolocation
Browse files Browse the repository at this point in the history
  • Loading branch information
cdown committed Sep 6, 2015
1 parent c9688e0 commit 9f39ad3
Show file tree
Hide file tree
Showing 2 changed files with 12 additions and 21 deletions.
1 change: 0 additions & 1 deletion requirements.txt
@@ -1,2 +1 @@
maxminddb-geolite2
requests
32 changes: 12 additions & 20 deletions tzupdate.py
Expand Up @@ -10,29 +10,27 @@
import os
import sys
import requests
from geolite2 import geolite2


class TimezoneUpdateException(Exception): pass
class TimezoneNotLocallyAvailableError(TimezoneUpdateException): exit_code = 1
class NoTimezoneAvailableError(TimezoneUpdateException): exit_code = 2
class DirectoryTraversalError(TimezoneUpdateException): exit_code = 3


def get_public_ip():
ipify_handle = requests.get('https://api.ipify.org')
return ipify_handle.text
class IPAPIError(TimezoneUpdateException): exit_code = 4


def get_timezone_for_ip(ip):
geoip = geolite2.reader()
ip_info = geoip.get(ip)
timezone = ip_info['location'].get('time_zone')

if timezone is None:
raise NoTimezoneAvailableError('No timezone found for this IP.')

return timezone
api_url = 'http://ip-api.com/json/{ip}'.format(ip=ip or '')
api_response = requests.get(api_url).json()
try:
return api_response['timezone']
except KeyError:
if api_response.get('status') == 'success':
raise NoTimezoneAvailableError('No timezone found for this IP.')
else:
raise IPAPIError(
api_response.get('message', 'Unspecified API error.'),
)


def check_directory_traversal(base_dir, requested_path):
Expand Down Expand Up @@ -83,12 +81,6 @@ def parse_args(argv):
help='path to localtime symlink (default: %(default)s)'
)
args = parser.parse_args(argv)

# We do this here instead of in "default" to avoid running it when we
# already have an IP address manually specified.
if args.ip is None:
args.ip = get_public_ip()

return args


Expand Down

0 comments on commit 9f39ad3

Please sign in to comment.