]> git.ipfire.org Git - ipfire.org.git/blame - webapp/backend/geoip.py
Move everything to the root of the repository.
[ipfire.org.git] / webapp / backend / geoip.py
CommitLineData
940227cb
MT
1#!/usr/bin/python
2
638e9782
MT
3import re
4
940227cb 5from databases import Databases
0673d1b0 6from memcached import Memcached
940227cb
MT
7from misc import Singleton
8
9class GeoIP(object):
10 __metaclass__ = Singleton
11
12 @property
13 def db(self):
14 return Databases().geoip
15
119f55d7 16 def _encode_ip(self, addr):
65afea2f
MT
17 # We get a tuple if there were proxy headers.
18 addr = addr.split(", ")
19 if addr:
20 addr = addr[-1]
21
119f55d7 22 # ip is calculated as described in http://dev.maxmind.com/geoip/csv
940227cb
MT
23 a1, a2, a3, a4 = addr.split(".")
24
119f55d7
MT
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
940227cb
MT
34
35 def get_country(self, addr):
119f55d7 36 addr = self._encode_ip(addr)
0673d1b0 37
119f55d7
MT
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)
0673d1b0 41
119f55d7
MT
42 if ret:
43 return ret.country_code
940227cb
MT
44
45 def get_all(self, addr):
119f55d7 46 addr = self._encode_ip(addr)
3d0049b3
MT
47 if not addr:
48 return
0673d1b0 49
119f55d7
MT
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)
0673d1b0
MT
53
54 if not ret:
119f55d7 55 return
0673d1b0
MT
56
57 # If location was not determinable
58 if ret.latitude == 0 and ret.longitude == 0:
59 return None
60
61 return ret
940227cb 62
638e9782 63 def get_country_name(self, code):
119f55d7
MT
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
638e9782
MT
82
83 # Fix some weird strings
84 name = re.sub(r"(.*) (.* Republic of)", r"\2 \1", name)
85
86 return name
87
940227cb
MT
88
89if __name__ == "__main__":
90 g = GeoIP()
91
92 print g.get_country("123.123.123.123")
93 print g.get_all("123.123.123.123")