iwla

iwla Git Source Tree

Root/plugins/post_analysis/ip_to_geo.py

1# -*- coding: utf-8 -*-
2#
3# Copyright Grégory Soutadé 2016
4
5# This file is part of iwla
6
7# iwla is free software: you can redistribute it and/or modify
8# it under the terms of the GNU General Public License as published by
9# the Free Software Foundation, either version 3 of the License, or
10# (at your option) any later version.
11#
12# iwla is distributed in the hope that it will be useful,
13# but WITHOUT ANY WARRANTY; without even the implied warranty of
14# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15# GNU General Public License for more details.
16#
17# You should have received a copy of the GNU General Public License
18# along with iwla. If not, see <http://www.gnu.org/licenses/>.
19#
20
21from iwla import IWLA
22from iplugin import IPlugin
23
24from iptogeo import IPToGeo
25
26"""
27Post analysis hook
28
29Get country code from IP address
30
31Plugin requirements :
32 None
33
34Conf values needed :
35 iptogeo_remote_addr*
36 iptogeo_remote_port*
37
38Output files :
39 None
40
41Statistics creation :
42 geo =>
43 country_code => count
44 None
45
46Statistics update :
47valid_visitors:
48 country_code
49
50Statistics deletion :
51 None
52"""
53
54class IWLAPostAnalysisIPToGeo(IPlugin):
55
56 def __init__(self, iwla):
57 super(IWLAPostAnalysisIPToGeo, self).__init__(iwla)
58 self.API_VERSION = 1
59
60 def load(self):
61 remote_addr = self.iwla.getConfValue('iptogeo_remote_addr',
62 None)
63 remote_port = self.iwla.getConfValue('iptogeo_remote_port',
64 None)
65
66 args = {}
67 if remote_addr: args['remote_addr'] = remote_addr
68 if remote_port: args['remote_port'] = remote_port
69 self.iptogeo = IPToGeo(**args)
70
71 return True
72
73 def hook(self):
74 visitors = self.iwla.getCurrentVisits()
75 month_stats = self.iwla.getMonthStats()
76
77 geo = month_stats.get('geo', {})
78
79 for (ip, visitor) in visitors.items():
80 if visitor.get('country_code', False): continue
81 try:
82 (_, cc) = self.iptogeo.ip_to_geo(ip)
83 cc = cc and cc or 'ip'
84 visitor['country_code'] = cc
85 if not self.iwla.isValidVisitor(visitor):
86 continue
87 if cc in geo.keys():
88 geo[cc] += 1
89 else:
90 geo[cc] = 1
91 except Exception, e:
92 print e
93
94 month_stats['geo'] = geo

Archive Download this file

Branches

Tags