]> git.ipfire.org Git - ipfire.org.git/blob - webapp/backend/geoip.py
43f92da3acf57d59dff1b65eaa7ca489f3973327
[ipfire.org.git] / webapp / backend / geoip.py
1 #!/usr/bin/python
2
3 import re
4
5 from databases import Databases
6 from memcached import Memcached
7 from misc import Singleton
8
9 class GeoIP(object):
10 __metaclass__ = Singleton
11
12 @property
13 def db(self):
14 return Databases().geoip
15
16 def _encode_ip(self, addr):
17 # We get a tuple if there were proxy headers.
18 addr = addr.split(", ")
19 if addr:
20 addr = addr[-1]
21
22 # ip is calculated as described in http://dev.maxmind.com/geoip/csv
23 a1, a2, a3, a4 = addr.split(".")
24
25 try:
26 a1 = int(a1)
27 a2 = int(a2)
28 a3 = int(a3)
29 a4 = int(a4)
30 except ValueError:
31 return 0
32
33 return (16777216 * a1) + (65536 * a2) + (256 * a3) + a4
34
35 def get_country(self, addr):
36 addr = self._encode_ip(addr)
37
38 ret = self.db.get("SELECT locations.country_code AS country_code FROM addresses \
39 JOIN locations ON locations.id = addresses.location \
40 WHERE %s BETWEEN start_ip_num AND end_ip_num LIMIT 1", addr)
41
42 if ret:
43 return ret.country_code
44
45 def get_all(self, addr):
46 addr = self._encode_ip(addr)
47 if not addr:
48 return
49
50 ret = self.db.get("SELECT locations.* FROM addresses \
51 JOIN locations ON locations.id = addresses.location \
52 WHERE %s BETWEEN start_ip_num AND end_ip_num LIMIT 1", addr)
53
54 if not ret:
55 return
56
57 # If location was not determinable
58 if ret.latitude == 0 and ret.longitude == 0:
59 return None
60
61 return ret
62
63 def get_country_name(self, code):
64 name = "Unkown"
65
66 codes = {
67 "A1" : "Anonymous Proxy",
68 "A2" : "Satellite Provider",
69 "EU" : "Europe",
70 "AP" : "Asia/Pacific Region",
71 }
72
73 # Return description of some exceptional codes.
74 try:
75 return codes[code]
76 except KeyError:
77 pass
78
79 ret = self.db.get("SELECT name FROM iso3166_countries WHERE code = %s LIMIT 1", code)
80 if ret:
81 name = ret.name
82
83 # Fix some weird strings
84 name = re.sub(r"(.*) (.* Republic of)", r"\2 \1", name)
85
86 return name
87
88
89 if __name__ == "__main__":
90 g = GeoIP()
91
92 print g.get_country("123.123.123.123")
93 print g.get_all("123.123.123.123")