#!/usr/bin/env python
# http://www.braggtown.com
# Gets ip address, geolocates it with call to hostip.info, returns latitude and longitude of ip address for use in Google Maps API.
import string, os, cgi, cgitb; cgitb.enable()
from urllib import urlopen
from time import time, gmtime, strftime
from socket import gethostbyaddr
# printDebug. Simple debug function to print the geocode variables to web page.
def printDebug(data_list, new):
if new:
message = "Welcome. This is your first visit. A data point has been created for you." + "
"
addr, country, code, city, lat, lng, guess = data_list
host = resolveAddr(addr)
message += "You are visiting from %s (%s) in %s, %s. Your latitude is %s and your longitude is %s." % (host, addr, city, country, lat, lng)
else:
host = resolveAddr(data_list) # overloaded. It's a string, not a list. Contains ip addr.
message = "Welcome back. A data point has already been created for %s (%s)." % (host, data_list)
tstamp = strftime("%B %d %Y %H:%M UTC", gmtime(time()))
message += "
Report generated: %s" % (tstamp)
return message
# passToJS. Pass latitude and longitude to javascript page via url. This approach sucks- probably won't use it.
def passToJS(lat, lng):
print "Content-Type: text/html\n"
print '
'
print '' % (lat, lng)
print ''
# geocodeIP. Send IP address to hostip.info for geocoding, pack return data into list.
def geocodeIP(addr):
url = "http://api.hostip.info/rough.php?ip=%s&position=true" % (addr) # geolocate ip address
data = urlopen(url).read()
data = data.split('\n')
data_list = []
data_list.append(addr) # addr; country; country code; city, state; lattitude;longitude; guess
for field in data:
name, value = field.split(':')
data_list.append(value.strip()) # strip out leading and trailing whitespace
return data_list
# checkIfIgnore. Check if ip address is on ignore list.
def checkIfIgnore(addr):
ignoring_addresses = ['152.1.24.80']
if addr in ignoring_addresses:
return True
else:
return False
# checkIfNew. Check if ip address has already been recorded, add if not.
def checkIfNew(addr):
f = open('maps/ipaddresses', 'r+')
lines = f.readlines()
f.close()
if not (addr + '\n') in lines: # If address isn't in file: it's new: return true
return True
else:
return False # Is in file: returning visitor: return true
# recordVisitor. Append the ip address of new visitor to ipaddresses file.
def recordVisitor(addr):
f = open('maps/ipaddresses', 'a')
addr = str(addr) + "\n"
f.write(addr)
# createMarker. Create data marker for Google Maps API in example.xml data point file.
def createMarker(lng, lat, city, addr):
tstamp = strftime("%B %d %Y %H:%M UTC", gmtime(time()))
host = resolveAddr(addr)
closing_tag = ""
new_line = ' \n%s' % (lat, lng, city, host, tstamp, city, closing_tag)
xmlfile = open('maps/example.xml' ,'r')
new_file = []
for line in xmlfile.readlines():
if line == closing_tag or line == closing_tag + '\n':
new_file.append(new_line)
else:
new_file.append(line)
xmlfile.close()
xmlfile = open('maps/example.xml' ,'w')
for line in new_file:
xmlfile.write(line)
xmlfile.close()
# resolveAddr. Resolve domain name from IP address after stripping off hostname to preserve privacy of visitor.
def resolveAddr(addr):
host = gethostbyaddr(addr)[0]
host = host.split('.', 1)[1]
return host
# main application logic
def main():
addr = os.environ['REMOTE_ADDR']
ignore = checkIfIgnore(addr)
if not ignore:
new = checkIfNew(addr)
if new:
data_list = geocodeIP(addr)
addr, country, code, city, lat, lng, guess = data_list
recordVisitor(addr)
createMarker(lng, lat, city, addr)
message = printDebug(data_list, new)
else:
message = printDebug(addr, new)
else:
message = "Ignoring address %s" % (addr)
map_page = open('maps/index.html', 'r')
map_contents = map_page.read()
map_page.close()
print "Content-Type: text/html\n"
print map_contents.replace('$message', message)
### Call main function
if (__name__ == "__main__"):
main()