[Merge] lp:~openerp-dev/openobject-addons/trunk-import_google-backlog2_import_meeting-jam
[odoo/odoo.git] / addons / import_google / wizard / google_contact_import.py
1 # -*- coding: utf-8 -*-
2 ##############################################################################
3 #
4 #    OpenERP, Open Source Management Solution
5 #    Copyright (C) 2004-2010 Tiny SPRL (<http://tiny.be>).
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 import datetime
22
23 try:
24     import gdata
25     import gdata.contacts.service
26     import gdata.contacts
27 except ImportError:
28     raise osv.except_osv(_('Google Contacts Import Error!'), _('Please install gdata-python-client from http://code.google.com/p/gdata-python-client/downloads/list'))
29 from osv import fields
30 from osv import osv
31 from tools.translate import _
32 from import_google import import_contact
33
34 class google_login_contact(osv.osv_memory):
35     _inherit = 'google.login'
36     _name = 'google.login.contact'
37
38     def _get_next_action(self, cr, uid, context):
39         data_obj = self.pool.get('ir.model.data')
40         data_id = data_obj._get_id(cr, uid, 'import_google', 'view_synchronize_google_contact_import_form')
41
42         view_id = False
43         if data_id:
44             view_id = data_obj.browse(cr, uid, data_id, context=context).res_id
45         value = {
46             'name': _('Import Contact'),
47             'view_type': 'form',
48             'view_mode': 'form,tree',
49             'res_model': 'synchronize.google.contact.import',
50             'view_id': False,
51             'context': context,
52             'views': [(view_id, 'form')],
53             'type': 'ir.actions.act_window',
54             'target': 'new',
55         }
56         return value
57 google_login_contact()
58
59 class synchronize_google_contact(osv.osv_memory):
60     _name = 'synchronize.google.contact.import'
61
62     def _get_group(self, cr, uid, context=None):
63         user_obj = self.pool.get('res.users').browse(cr, uid, uid)
64         google=self.pool.get('google.login')
65         if not user_obj.gmail_user or not user_obj.gmail_password:
66             raise osv.except_osv(_('Warning !'), _("No Google Username or password Defined for user.\nPlease define in user view"))
67         gd_client = google.google_login(user_obj.gmail_user,user_obj.gmail_password,type='group')
68         if not gd_client:
69             raise osv.except_osv(_('Error'), _("Authentication fail check the user and password !"))
70
71         res = []
72         query = gdata.contacts.service.GroupsQuery(feed='/m8/feeds/groups/default/full')
73         if gd_client:
74             groups = gd_client.GetFeed(query.ToUri())
75             for grp in groups.entry:
76                 res.append((grp.id.text, grp.title.text))
77         res.append(('all','All Groups'))
78         return res
79
80     _columns = {
81         'create_partner': fields.selection([('create_all','Create partner for each contact'),('create_address','Import only address')],'Options'),
82         'customer': fields.boolean('Customer', help="Check this box to set newly created partner as Customer."),
83         'supplier': fields.boolean('Supplier', help="Check this box to set newly created partner as Supplier."),
84         'group_name': fields.selection(_get_group, "Group Name", size=32,help="Choose which group to import, By default it takes all."),
85      }
86
87     _defaults = {
88         'create_partner': 'create_all',
89         'group_name': 'all',
90     }
91 #
92 #    def create_partner(self, cr, uid, data={}, context=None):
93 #        if context == None:
94 #            context = {}
95 #        if not data:
96 #            return False
97 #        name = data.get("company") or data.get('name','')
98 #        partner_pool = self.pool.get('res.partner')
99 #        partner_id = partner_pool.create(cr, uid, {
100 #                                                  'name': name,
101 #                                                  'user_id': uid,
102 #                                                  'address' : [(6, 0, [data['address_id']])],
103 #                                                  'customer': data.get('customer', False),
104 #                                                  'supplier': data.get('supplier', False)
105 #                                        }, context=context)
106 #        return partner_id
107 #
108 #    def set_partner(self, cr, uid, name, address_id, context=None):
109 #        partner_pool = self.pool.get('res.partner')
110 #        partner_ids = partner_pool.search(cr, uid, [('name', '=', name)], context=context)
111 #        if partner_ids:
112 #            address_pool = self.pool.get('res.partner.address')#TODO create partner of find the one with the same name
113 #            data = {'partner_id' : partner_ids[0]}
114 #            address_pool.write(cr, uid, [address_id], data, context=context)
115 #            return partner_ids[0]
116 #        return False
117
118     def import_contact_all(self, cr, uid, ids, context=None):
119         tables = ['contact']
120         obj = self.browse(cr, uid, ids, context=context)[0]
121         user_obj = self.pool.get('res.users').browse(cr, uid, uid)
122         google = self.pool.get('google.login')
123         
124         gmail_user = user_obj.gmail_user
125         gmail_pwd = user_obj.gmail_password
126         context = {}
127         gd_client = google.google_login(gmail_user, gmail_pwd, type='contact')
128         context.update({'user': gmail_user,'password': gmail_pwd,'gd_client':gd_client})
129         
130         imp = import_contact(self, cr, uid,'google', "synchronize_google_contact", context=context)
131         imp.set_table_list(tables)
132         imp.start()
133         return {'type': 'ir.actions.act_window_close'}
134 #
135 #        if not gd_client:
136 #            raise osv.except_osv(_('Error'), _("Please specify correct user and password !"))
137 #       
138 #        if obj.group_name not in ['all']:
139 #            query = gdata.contacts.service.ContactsQuery()
140 #            query.group = obj.group_name
141 #            contact = gd_client.GetContactsFeed(query.ToUri())
142 #        else:
143 #            contact = gd_client.GetContactsFeed()
144 #
145 #        ids = self.create_contact(cr, uid, ids, gd_client, contact, option=obj.create_partner,context=context)
146 #        if not ids:
147 #            return {'type': 'ir.actions.act_window_close'}
148 #
149 #        return {
150 #                'name': _(obj.create_partner =='create_all' and 'Partners') or _('Contacts'),
151 #                'domain': "[('id','in', ["+','.join(map(str,ids))+"])]",
152 #                'view_type': 'form',
153 #                'view_mode': 'tree,form',
154 #                'res_model': obj.create_partner =='create_all' and 'res.partner' or 'res.partner.address',
155 #                'context': context,
156 #                'views': [(False, 'tree'),(False, 'form')],
157 #                'type': 'ir.actions.act_window',
158 #        }
159
160
161 #    def create_contact(self, cr, uid, ids, gd_client, contact, option,context=None):
162 #        model_obj = self.pool.get('ir.model.data')
163 #        addresss_obj = self.pool.get('res.partner.address')
164 #        company_pool = self.pool.get('res.company')
165 #        addresses = []
166 #        partner_ids = []
167 #        contact_ids = []
168 #        if 'tz' in context and context['tz']:
169 #            time_zone = context['tz']
170 #        else:
171 #            time_zone = tools.get_server_timezone()
172 #        au_tz = timezone(time_zone)
173 #        while contact:
174 #            for entry in contact.entry:
175 #                data = self._retreive_data(entry)
176 #                google_id = data.pop('id')
177 #                model_data = {
178 #                    'name':  google_id,
179 #                    'model': 'res.partner.address',
180 #                    'module': 'sync_google_contact',
181 #                    'noupdate': True
182 #                }
183 #
184 #                data_ids = model_obj.search(cr, uid, [('model','=','res.partner.address'), ('name','=', google_id)])
185 #                if data_ids:
186 #                    contact_ids = [model_obj.browse(cr, uid, data_ids[0], context=context).res_id]
187 #                elif data['email']:
188 #                    contact_ids = addresss_obj.search(cr, uid, [('email', 'ilike', data['email'])])
189 #
190 #                if contact_ids:
191 #                    addresses.append(contact_ids[0])
192 #                    address = addresss_obj.browse(cr, uid, contact_ids[0], context=context)
193 #                    google_updated = entry.updated.text
194 #                    utime = dateutil.parser.parse(google_updated)
195 #                    au_dt = au_tz.normalize(utime.astimezone(au_tz))
196 #                    updated_dt = datetime.datetime(*au_dt.timetuple()[:6]).strftime('%Y-%m-%d %H:%M:%S')
197 #                    if address.write_date < updated_dt:
198 #                        self.update_contact(cr, uid, contact_ids, data, context=context)
199 #                    res_id = contact_ids[0]
200 #                if not contact_ids:
201 #                    #create or link to an existing partner only if it's a new contact
202 #                    data.update({'type': 'default'})
203 #                    res_id = addresss_obj.create(cr, uid, data, context=context)
204 #                    data['address_id'] = res_id
205 #                    if option == 'create_all':
206 #                        obj = self.browse(cr, uid, ids, context=context)[0]
207 #                        data['customer'] = obj.customer
208 #                        data['supplier'] = obj.supplier
209 #                        res = False
210 #                        if 'company' in data:
211 #                            res = self.set_partner(cr, uid, data.get('company'), res_id, context=context)
212 #                            if res:
213 #                                partner_ids.append(res)
214 #                        if not res:
215 #                            partner_id = self.create_partner(cr, uid, data, context=context)
216 #                            partner_ids.append(partner_id)
217 #                    addresses.append(res_id)
218 #
219 #                if not data_ids: #link to google_id if it was not the case before
220 #                    model_data.update({'res_id': res_id})
221 #                    model_obj.create(cr, uid, model_data, context=context)
222 #
223 #            next = contact.GetNextLink()
224 #            contact = next and gd_client.GetContactsFeed(next.href) or None
225 #
226 #        if option == 'create_all':
227 #            return partner_ids
228 #        else:
229 #            return addresses
230
231 #    def _retreive_data(self, entry):
232 #        data = {}
233 #        data['id'] = entry.id.text
234 #        name = tools.ustr(entry.title.text)
235 #        if name == "None":
236 #            name = entry.email[0].address
237 #        data['name'] = name
238 #        emails = ','.join(email.address for email in entry.email)
239 #        data['email'] = emails
240 #        if entry.organization:
241 #            if entry.organization.org_name:
242 #                data.update({'company': entry.organization.org_name.text})
243 #            if entry.organization.org_title:
244 #                data.update ({'function': entry.organization.org_title.text})
245 #
246 #
247 #        if entry.phone_number:
248 #            for phone in entry.phone_number:
249 #                if phone.rel == gdata.contacts.REL_WORK:
250 #                    data['phone'] = phone.text
251 #                if phone.rel == gdata.contacts.PHONE_MOBILE:
252 #                    data['mobile'] = phone.text
253 #                if phone.rel == gdata.contacts.PHONE_WORK_FAX:
254 #                    data['fax'] = phone.text
255 #        return data
256
257 #    def update_contact(self, cr, uid, contact_ids, data, context=None):
258 #        addresss_obj = self.pool.get('res.partner.address')
259 #        vals = {}
260 #        addr = addresss_obj.browse(cr,uid,contact_ids)[0]
261 #        name = str((addr.name or addr.partner_id and addr.partner_id.name or '').encode('utf-8'))
262 #
263 #        if name != data.get('name'):
264 #            vals['name'] = data.get('name','')
265 #        if addr.email != data.get('email'):
266 #            vals['email'] = data.get('email','')
267 #        if addr.mobile != data.get('mobile'):
268 #            vals['mobile'] = data.get('mobile','')
269 #        if addr.phone != data.get('phone'):
270 #            vals['phone'] = data.get('phone','')
271 #        if addr.fax != data.get('fax'):
272 #            vals['fax'] = data.get('fax','')
273 #
274 #        addresss_obj.write(cr, uid, contact_ids, vals, context=context)
275 #        return {'type': 'ir.actions.act_window_close'}
276
277 synchronize_google_contact()
278
279
280 class google_login_calendar(osv.osv_memory):
281     """Gdata Login Object for Google Calendar Import"""
282     _inherit = 'google.login'
283     _name = 'google.login'
284
285     def _get_next_action(self, cr, uid, context):
286         data_obj = self.pool.get('ir.model.data')
287         data_id = data_obj._get_id(cr, uid, 'import_google', 'view_synchronize_google_calendar_import_form')
288
289         view_id = False
290         if data_id:
291             view_id = data_obj.browse(cr, uid, data_id, context=context).res_id
292         value = {
293             'name': _('Import Events'),
294             'view_type': 'form',
295             'view_mode': 'form,tree',
296             'res_model': 'synchronize.google.calendar',
297             'view_id': False,
298             'context': context,
299             'views': [(view_id, 'form')],
300             'type': 'ir.actions.act_window',
301             'target': 'new',
302         }
303         return value
304 google_login_calendar()
305
306
307 class synchronize_google_calendar_events(osv.osv_memory):
308     """
309     Wizard to initiate import specific calendar or all calendars
310     """
311     _name = 'synchronize.google.calendar'
312
313     def _get_calendars(self, cr, uid, context=None):
314         user_obj = self.pool.get('res.users').browse(cr, uid, uid)
315         google = self.pool.get('google.login')
316         res = []
317         try:
318             gd_client = google.google_login(user_obj.gmail_user, user_obj.gmail_password, type='calendar')
319             calendars = gd_client.GetAllCalendarsFeed()
320             for cal in calendars.entry:
321                 res.append((cal.id.text, cal.title.text))
322         except Exception, e:
323             raise osv.except_osv('Error !', e.args[0].get('body'))
324         res.append(('all', 'All Calendars'))
325         return res
326
327     _columns = {
328         'calendar_name': fields.selection(_get_calendars, "Calendar Name", size=32),
329     }
330
331     _defaults = {
332         'calendar_name': 'all',
333     }
334
335     def import_calendar_events(self, cr, uid, ids, context=None):
336         if context == None:
337             context = {}
338         if not ids:
339             return {'type': 'ir.actions.act_window_close'}
340         table = ['Events']
341         user_obj = self.pool.get('res.users').browse(cr, uid, uid)
342         gmail_user = user_obj.gmail_user
343         gmail_pwd = user_obj.gmail_password
344         if not gmail_user or not gmail_pwd:
345             raise osv.except_osv(_('Error'), _("Invalid login detail !\n Specify Username/Password."))
346         current_rec = self.browse(cr, uid, ids, context=context)
347         calendars = False
348         for rec in current_rec:
349             if rec.calendar_name != 'all':
350                 calendars = [rec.calendar_name]
351             else:
352                 calendars = map(lambda x: x[0], [cal for cal in self._get_calendars(cr, uid, context) if cal[0] != 'all'])
353         context.update({'user': gmail_user,
354                         'password': gmail_pwd,
355                         'calendars': calendars,
356                         'instance': 'calendar'})
357         imp = import_contact(self, cr, uid, 'import_google', "import_google_calendar", [gmail_user], context)
358         imp.set_table_list(table)
359         imp.start()
360         return {}
361
362 synchronize_google_calendar_events()
363 # vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4: