]> git.ipfire.org Git - people/shoehn/ipfire.org.git/blob - webapp/backend/geoip.py
16159a5803a4b63694afcdd26e06a54416335cfc
[people/shoehn/ipfire.org.git] / webapp / backend / geoip.py
1 #!/usr/bin/python
2
3 import IPy
4 import re
5
6 import countries
7
8 from misc import Object
9
10 class GeoIP(Object):
11 def guess_address_family(self, addr):
12 if ":" in addr:
13 return 6
14
15 return 4
16
17 def get_country(self, addr):
18 ret = self.get_all(addr)
19
20 if ret:
21 return ret.country
22
23 def get_location(self, addr):
24 query = "SELECT * FROM geoip \
25 WHERE %s BETWEEN start_ip AND end_ip LIMIT 1"
26
27 ret = self.db.get(query, addr)
28
29 if ret:
30 if ret.city:
31 ret.city = ret.city.strip()
32
33 if ret.postal_code:
34 ret.postal_code = ret.postal_code.strip()
35
36 return ret
37
38 def get_asn(self, addr):
39 query = "SELECT asn FROM geoip_asn \
40 WHERE %s BETWEEN start_ip AND end_ip LIMIT 1"
41
42 ret = self.db.get(query, addr)
43
44 if ret:
45 return ret.asn
46
47 def get_all(self, addr):
48 location = self.get_location(addr)
49
50 if location:
51 location["asn"] = self.get_asn(addr)
52
53 return location
54
55 _countries = {
56 "A1" : "Anonymous Proxy",
57 "A2" : "Satellite Provider",
58 "AP" : "Asia/Pacific Region",
59 "EU" : "Europe",
60 }
61
62 def get_country_name(self, code):
63 # Return description of some exceptional codes.
64 try:
65 return self._countries[code]
66 except KeyError:
67 pass
68
69 country = countries.get_by_code(code)
70 if not country:
71 return code
72
73 return country