]> git.ipfire.org Git - ipfire.org.git/blame - www/webapp/backend/geoip.py
fireinfo: Fix geoip information.
[ipfire.org.git] / www / webapp / backend / geoip.py
CommitLineData
940227cb
MT
1#!/usr/bin/python
2
3from databases import Databases
4from misc import Singleton
5
6class GeoIP(object):
7 __metaclass__ = Singleton
8
9 @property
10 def db(self):
11 return Databases().geoip
12
13 def __encode_ip(self, addr):
65afea2f
MT
14 # We get a tuple if there were proxy headers.
15 addr = addr.split(", ")
16 if addr:
17 addr = addr[-1]
18
940227cb
MT
19 # ip is calculated as described in http://ipinfodb.com/ip_database.php
20 a1, a2, a3, a4 = addr.split(".")
21
22 return int(((int(a1) * 256 + int(a2)) * 256 + int(a3)) * 256 + int(a4) + 100)
23
24 def get_country(self, addr):
25 return self.db.get("SELECT * FROM ip_group_country WHERE ip_start <= %s \
26 ORDER BY ip_start DESC LIMIT 1;", self.__encode_ip(addr)).country_code.lower()
27
28 def get_all(self, addr):
29 # XXX should be done with a join
30 location = self.db.get("SELECT location FROM ip_group_city WHERE ip_start <= %s \
31 ORDER BY ip_start DESC LIMIT 1;", self.__encode_ip(addr)).location
32
33 return self.db.get("SELECT * FROM locations WHERE id = %s", int(location))
34
35
36if __name__ == "__main__":
37 g = GeoIP()
38
39 print g.get_country("123.123.123.123")
40 print g.get_all("123.123.123.123")