[FIX] website_forum: post edition working again
[odoo/odoo.git] / addons / base_geolocalize / models / res_partner.py
1 # -*- coding: utf-8 -*-
2 ##############################################################################
3 #
4 #    OpenERP, Open Source Management Solution
5 #    Copyright (C) 2013_Today OpenERP SA (<http://www.openerp.com>).
6 #
7 #    This program is free software: you can redistribute it and/or modify
8 #    it under the terms of the GNU Affero General Public License as
9 #    published by the Free Software Foundation, either version 3 of the
10 #    License, or (at your option) any later version.
11 #
12 #    This program 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 Affero General Public License for more details.
16 #
17 #    You should have received a copy of the GNU Affero General Public License
18 #    along with this program.  If not, see <http://www.gnu.org/licenses/>.
19 #
20 ##############################################################################
21
22 try:
23     import simplejson as json
24 except ImportError:
25     import json     # noqa
26 import urllib
27
28 from openerp.osv import osv, fields
29 from openerp import tools
30 from openerp.tools.translate import _
31
32
33 def geo_find(addr):
34     url = 'https://maps.googleapis.com/maps/api/geocode/json?sensor=false&address='
35     url += urllib.quote(addr.encode('utf8'))
36
37     try:
38         result = json.load(urllib.urlopen(url))
39     except Exception, e:
40         raise osv.except_osv(_('Network error'),
41                              _('Cannot contact geolocation servers. Please make sure that your internet connection is up and running (%s).') % e)
42     if result['status'] != 'OK':
43         return None
44
45     try:
46         geo = result['results'][0]['geometry']['location']
47         return float(geo['lat']), float(geo['lng'])
48     except (KeyError, ValueError):
49         return None
50
51
52 def geo_query_address(street=None, zip=None, city=None, state=None, country=None):
53     if country and ',' in country and (country.endswith(' of') or country.endswith(' of the')):
54         # put country qualifier in front, otherwise GMap gives wrong results,
55         # e.g. 'Congo, Democratic Republic of the' => 'Democratic Republic of the Congo'
56         country = '{1} {0}'.format(*country.split(',', 1))
57     return tools.ustr(', '.join(filter(None, [street,
58                                               ("%s %s" % (zip or '', city or '')).strip(),
59                                               state,
60                                               country])))
61
62
63 class res_partner(osv.osv):
64     _inherit = "res.partner"
65
66     _columns = {
67         'partner_latitude': fields.float('Geo Latitude'),
68         'partner_longitude': fields.float('Geo Longitude'),
69         'date_localization': fields.date('Geo Localization Date'),
70     }
71
72     def geo_localize(self, cr, uid, ids, context=None):
73         # Don't pass context to browse()! We need country names in english below
74         for partner in self.browse(cr, uid, ids):
75             if not partner:
76                 continue
77             result = geo_find(geo_query_address(street=partner.street,
78                                                 zip=partner.zip,
79                                                 city=partner.city,
80                                                 state=partner.state_id.name,
81                                                 country=partner.country_id.name))
82             if result:
83                 self.write(cr, uid, [partner.id], {
84                     'partner_latitude': result[0],
85                     'partner_longitude': result[1],
86                     'date_localization': fields.date.context_today(self, cr, uid, context=context)
87                 }, context=context)
88         return True