public
Description: Free text geocoder
Homepage: http://fetegeo.org/
Clone URL: git://github.com/ltratt/fetegeo.git
fetegeo / fetegeos
100755 281 lines (196 sloc) 8.556 kb
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
#! /usr/bin/env python
 
# Copyright (C) 2008 Laurence Tratt http://tratt.net/laurie/
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to
# deal in the Software without restriction, including without limitation the
# rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
# sell copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
# FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
# IN THE SOFTWARE.
 
 
import imp, re, os, socket, SocketServer, sys, xml.dom.minidom as minidom
 
try:
    import psycopg2 as dbmod
    import psycopg2.extensions
    psycopg2.extensions.register_type(psycopg2.extensions.UNICODE)
except ImportError:
    import pgdb as dbmod
 
 
import Geo.Queryier
 
 
 
 
_DEFAULT_HOST = ""
_DEFAULT_PORT = 8263
 
_CONF_DIRS = ["/etc/", sys.path[0]]
_CONF_LEAF = "fetegeos.conf"
 
_RE_QUERY_END = re.compile("</(?:geo|country)query>")
 
_RE_TRUE = re.compile("true")
_RE_FALSE = re.compile("false")
 
_SOCK_BUF = 1024
 
 
 
 
class Fetegeos_Handler(SocketServer.BaseRequestHandler):
 
    def __init__(self, req, client_addr, server):
 
        if dbmod.threadsafety == 2 or dbmod.threadsafety == 3:
            # Connections can be shared between threads safely, so reuse the main server connection.
            self._db = server.db
        else:
            # Connections can't be shared between threads safely, so for every thread we have to
            # make a new connection.
            self._db = dbmod.connect(user="root", database="fetegeo")
            try:
                self.db.set_client_encoding('utf-8')
            except:
                pass
 
        SocketServer.BaseRequestHandler.__init__(self, req, client_addr, server)
 
 
 
    def _error(self, msg):
 
        self.request.send("<error>%s</error>" % msg)
        self.request.close()
        # We now kill this thread only.
        sys.exit(0)
 
 
 
    def handle(self):
 
        buf = ""
        while True:
            data = self.request.recv(_SOCK_BUF)
            buf += data
            m = _RE_QUERY_END.search(buf)
            if m is not None:
                break
 
        self._dom = minidom.parseString(buf)
 
        q_type = self._dom.firstChild.tagName.lower()
        if q_type == "geoquery":
            self._q_geo()
        elif q_type == "countryquery":
            self._q_ctry()
        else:
            self._error("Unknown query type '%s'." % n.tagName)
            return
 
 
 
    def _get_qe(self, name, default=None):
 
        r = self._dom.getElementsByTagName(name)
        if len(r) == 0:
            return default
        elif len(r) == 1:
            assert len(r[0].childNodes) == 1
            return r[0].childNodes[0].data
        else:
            XXX
 
 
 
    def _get_country_id(self, iso):
 
        c = self._db.cursor()
        c.execute("SELECT id FROM country WHERE iso2=%(iso)s OR iso3=%(iso)s", dict(iso=iso.upper()))
        assert c.rowcount < 2
        if c.rowcount == 1:
            return c.fetchone()[0]
 
        return None
 
 
 
    def _get_lang_ids(self):
 
        c = self._db.cursor()
        r = self._dom.getElementsByTagName("lang")
        lang_ids = []
        for e in r:
            iso639_1 = e.childNodes[0].data
            c.execute("SELECT id FROM lang WHERE iso639_1=%(iso639_1)s", dict(iso639_1=iso639_1))
            assert c.rowcount < 2
            if c.rowcount == 0:
                self._error("Unknown language '%s'." % e.childNodes[0].data)
            lang_ids.append(c.fetchone()[0])
 
        return lang_ids
 
 
 
    def _q_geo(self):
 
        fa_txt = self._dom.firstChild.getAttribute("find_all")
        if _RE_TRUE.match(fa_txt):
            find_all = True
        elif _RE_FALSE.match(fa_txt):
            find_all = False
        else:
            self._error("Unknown value '%s' for find_all attribute." % ra_txt)
 
        ad_txt = self._dom.firstChild.getAttribute("allow_dangling")
        if _RE_TRUE.match(ad_txt):
            allow_dangling = True
        elif _RE_FALSE.match(ad_txt):
            allow_dangling = False
        else:
            self._error("Unknown value '%s' for allow_dangling attribute." % ra_txt)
 
        lang_ids = self._get_lang_ids()
        country_iso = self._get_qe("country")
        if country_iso is None:
            country_id = None
        else:
            country_id = self._get_country_id(country_iso)
        qs = self._get_qe("qs")
        results = self.server.queryier.name_to_lat_long(self._db, lang_ids, find_all, \
          allow_dangling, qs, country_id)
 
        self.request.sendall("<results>\n%s\n</results>" % "\n".join([x.to_xml().encode("utf-8") for x in results]))
 
        self.request.close()
 
 
 
    def _q_ctry(self):
 
        lang_ids = self._get_lang_ids()
 
        qs = self._get_qe("qs")
 
        c = self._db.cursor()
        c.execute("SELECT id FROM country WHERE iso2=%(qs)s OR iso3=%(qs)s", dict(qs=qs.upper()))
        assert c.rowcount < 2
        if c.rowcount == 1:
            cntry_id = c.fetchone()[0]
        else:
            # No match found.
            self.request.send("<country></country>")
            return
 
        c.execute("""SELECT name FROM country_name
WHERE country_id=%(cntry_id)s AND lang_id=%(lang_id)s AND is_official=TRUE""",
          dict(cntry_id=cntry_id, lang_id=lang_ids[0]))
        assert c.rowcount == 1
 
        self.request.sendall("<result><country><name>%s</name></country></result>" % c.fetchone()[0])
 
        self.request.close()
 
 
 
 
 
class Fetegeos_Server(SocketServer.TCPServer, SocketServer.ThreadingMixIn):
 
    def __init__(self, addr, rhc):
    
        # Load the config file
    
        for dir in _CONF_DIRS:
            conf_path = os.path.join(dir, _CONF_LEAF)
            if os.path.exists(conf_path):
                break
        else:
            sys.stderr.write("Error: No config file found.")
            sys.exit(1)
        
        f = open(conf_path, "r")
        # We fool load_source by pretending the config file comes from /dev/null,
        # which (because it's a filename without a "." in it, but which is
        # genuinely present) stops it trying to write a .pyc file. Otherwise for
        # a file fetegeos.conf, one ends up with a fetegeos.confc file, which is
        # plain ugly.
        self._config = imp.load_source("config", "/dev/null", f)
        f.close()
    
        # Setup the server
    
        self.allow_reuse_address = True # XXX
        SocketServer.TCPServer.__init__(self, addr, rhc)
        
        self.queryier = Geo.Queryier.Queryier()
        
        if dbmod.threadsafety == 2 or dbmod.threadsafety == 3:
            # Connections can be shared between threads safely so we connect only once.
            self.db = dbmod.connect(user="root", database="fetegeo")
            try:
                self.db.set_client_encoding('utf-8')
            except:
                pass
 
 
    def verify_request(self, requst, client_address):
    
        # Check that client_address is an IP address allowed to connect to fetegeos.
        # NOTE: This is rather IP4 specific at the moment.
    
        split_client_address = client_address[0].split(".")
        for addr in self._config.accept_connect:
            split_addr = addr.split(".")
            if len(split_addr) == len(split_client_address):
                match = True
                for i in range(len(split_addr)):
                    if split_addr[i] == "*":
                        continue
                    elif split_addr[i] != split_client_address[i]:
                        match = False
                        break
                
                if match:
                    return True
 
        return False
 
 
 
 
if __name__ == "__main__":
    s = Fetegeos_Server((_DEFAULT_HOST, _DEFAULT_PORT), Fetegeos_Handler)
    try:
        s.serve_forever()
    except KeyboardInterrupt:
        pass