]> git.ipfire.org Git - people/shoehn/ipfire.org.git/blob - www/webapp/backend/geoip.py
Add more information to the geo table.
[people/shoehn/ipfire.org.git] / www / webapp / backend / geoip.py
1 #!/usr/bin/python
2
3 import re
4
5 from databases import Databases
6 from misc import Singleton
7
8 class GeoIP(object):
9 __metaclass__ = Singleton
10
11 def __init__(self):
12 self.__country_codes = self.db.query("SELECT code, name FROM iso3166_countries")
13
14 @property
15 def db(self):
16 return Databases().geoip
17
18 def __encode_ip(self, addr):
19 # We get a tuple if there were proxy headers.
20 addr = addr.split(", ")
21 if addr:
22 addr = addr[-1]
23
24 # ip is calculated as described in http://ipinfodb.com/ip_database.php
25 a1, a2, a3, a4 = addr.split(".")
26
27 return int(((int(a1) * 256 + int(a2)) * 256 + int(a3)) * 256 + int(a4) + 100)
28
29 def get_country(self, addr):
30 return self.db.get("SELECT * FROM ip_group_country WHERE ip_start <= %s \
31 ORDER BY ip_start DESC LIMIT 1;", self.__encode_ip(addr)).country_code.lower()
32
33 def get_all(self, addr):
34 # XXX should be done with a join
35 location = self.db.get("SELECT location FROM ip_group_city WHERE ip_start <= %s \
36 ORDER BY ip_start DESC LIMIT 1;", self.__encode_ip(addr)).location
37
38 return self.db.get("SELECT * FROM locations WHERE id = %s", int(location))
39
40 def get_country_name(self, code):
41 name = "Unknown"
42
43 code = code.upper()
44 for country in self.__country_codes:
45 if country.code == code:
46 name = country.name
47 break
48
49 # Fix some weird strings
50 name = re.sub(r"(.*) (.* Republic of)", r"\2 \1", name)
51
52 return name
53
54
55 if __name__ == "__main__":
56 g = GeoIP()
57
58 print g.get_country("123.123.123.123")
59 print g.get_all("123.123.123.123")