[IMP]: base_calendar, caldav: Improvement and Fixed problems in import/export .ics
[odoo/odoo.git] / addons / caldav / caldav.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
22 from datetime import datetime, timedelta
23 from datetime import datetime, timedelta
24 from dateutil import parser
25 from osv import fields, osv
26 from base_calendar import base_calendar
27 from service import web_services
28 from tools.translate import _
29 import base64
30 import pooler
31 import re
32 import time
33
34 months = {
35         1:"January", 2:"February", 3:"March", 4:"April", \
36         5:"May", 6:"June", 7:"July", 8:"August", 9:"September", \
37         10:"October", 11:"November", 12:"December"}
38
39 def caldav_id2real_id(caldav_id=None, with_date=False):
40     if caldav_id and isinstance(caldav_id, (str, unicode)):
41         res = caldav_id.split('-')
42         if len(res) >= 2:
43             real_id = res[0]
44             if with_date:
45                 real_date = time.strftime("%Y-%m-%d %H:%M:%S", \
46                                  time.strptime(res[1], "%Y%m%d%H%M%S"))
47                 start = datetime.strptime(real_date, "%Y-%m-%d %H:%M:%S")
48                 end = start + timedelta(hours=with_date)
49                 return (int(real_id), real_date, end.strftime("%Y-%m-%d %H:%M:%S"))
50             return int(real_id)
51     return caldav_id and int(caldav_id) or caldav_id
52
53 def real_id2caldav_id(real_id, recurrent_date):
54     if real_id and recurrent_date:
55         recurrent_date = time.strftime("%Y%m%d%H%M%S", \
56                          time.strptime(recurrent_date, "%Y-%m-%d %H:%M:%S"))
57         return '%d-%s' % (real_id, recurrent_date)
58     return real_id
59
60
61 def _links_get(self, cr, uid, context={}):
62     obj = self.pool.get('res.request.link')
63     ids = obj.search(cr, uid, [])
64     res = obj.read(cr, uid, ids, ['object', 'name'], context)
65     return [(r['object'], r['name']) for r in res]
66
67 class calendar_attendee(osv.osv):
68     _name = 'calendar.attendee'
69     _description = 'Attendee information'
70     _rec_name = 'cutype'
71
72     __attribute__ = {}
73
74     def _get_address(self, name=None, email=None):
75         if name and email:
76             name += ':'
77         return (name or '') + (email and ('MAILTO:' + email) or '')
78
79     def _compute_data(self, cr, uid, ids, name, arg, context):
80         name = name[0]
81         result = {}
82
83         def get_delegate_data(user):
84             email = user.address_id and user.address_id.email or ''
85             return self._get_address(user.name, email)
86
87         for attdata in self.browse(cr, uid, ids, context=context):
88             id = attdata.id
89             result[id] = {}
90             if name == 'sent_by':
91                 if not attdata.sent_by_uid:
92                     result[id][name] = ''
93                     continue
94                 else:
95                     result[id][name] =  self._get_address(attdata.sent_by_uid.name, \
96                                         attdata.sent_by_uid.address_id.email)
97             if name == 'cn':
98                 if attdata.user_id:
99                     result[id][name] = self._get_address(attdata.user_id.name, attdata.email)
100                 elif attdata.partner_address_id:
101                     result[id][name] = self._get_address(attdata.partner_id.name, attdata.email)
102                 else:
103                     result[id][name] = self._get_address(None, attdata.email)
104             if name == 'delegated_to':
105                 user_obj = self.pool.get('res.users')
106                 todata = map(get_delegate_data, attdata.del_to_user_ids)
107                 result[id][name] = ', '.join(todata)
108             if name == 'delegated_from':
109                 dstring = []
110                 user_obj = self.pool.get('res.users')
111                 fromdata = map(get_delegate_data, attdata.del_from_user_ids)
112                 result[id][name] = ', '.join(fromdata)
113             if name == 'event_date':
114                 # TO fix date for project task
115                 if attdata.ref:
116                     model, res_id = tuple(attdata.ref.split(','))
117                     model_obj = self.pool.get(model)
118                     obj = model_obj.read(cr, uid, res_id, ['date'])[0]
119                     result[id][name] = None#obj['date']
120                 else:
121                     result[id][name] = None
122             if name == 'event_end_date':
123                 if attdata.ref:
124                     model, res_id = tuple(attdata.ref.split(','))
125                     model_obj = self.pool.get(model)
126                     obj = model_obj.read(cr, uid, res_id, ['date_deadline'])[0]
127                     result[id][name] = obj['date_deadline']
128                 else:
129                     result[id][name] = None
130             if name == 'sent_by_uid':
131                 if attdata.ref:
132                     model, res_id = tuple(attdata.ref.split(','))
133                     model_obj = self.pool.get(model)
134                     obj = model_obj.read(cr, uid, res_id, ['user_id'])[0]
135                     result[id][name] = obj['user_id']
136                 else:
137                     result[id][name] = uid
138         return result
139
140     def _links_get(self, cr, uid, context={}):
141         obj = self.pool.get('res.request.link')
142         ids = obj.search(cr, uid, [])
143         res = obj.read(cr, uid, ids, ['object', 'name'], context)
144         return [(r['object'], r['name']) for r in res]
145
146     def _lang_get(self, cr, uid, context={}):
147         obj = self.pool.get('res.lang')
148         ids = obj.search(cr, uid, [])
149         res = obj.read(cr, uid, ids, ['code', 'name'], context)
150         res = [((r['code']).replace('_', '-'), r['name']) for r in res]
151         return res
152
153     _columns = {
154         'cutype': fields.selection([('individual', 'Individual'), \
155                     ('group', 'Group'), ('resource', 'Resource'), \
156                     ('room', 'Room'), ('unknown', 'Unknown') ], \
157                     'User Type', help="Specify the type of calendar user"), 
158         'member': fields.char('Member', size=124, 
159                     help="Indicate the groups that the attendee belongs to"), 
160         'role': fields.selection([('req-participant', 'Participation required'), \
161                     ('chair', 'Chair Person'), \
162                     ('opt-participant', 'Optional Participation'), \
163                     ('non-participant', 'For information Purpose')], 'Role', \
164                     help='Participation role for the calendar user'), 
165         'state': fields.selection([('tentative', 'Tentative'), 
166                         ('needs-action', 'Needs Action'), 
167                         ('accepted', 'Accepted'), 
168                         ('declined', 'Declined'), 
169                         ('delegated', 'Delegated')], 'State', readonly=True, 
170                         help="Status of the attendee's participation"), 
171         'rsvp':  fields.boolean('Required Reply?', 
172                     help="Indicats whether the favor of a reply is requested"), 
173         'delegated_to': fields.function(_compute_data, method=True, \
174                 string='Delegated To', type="char", size=124, store=True, \
175                 multi='delegated_to', help="The users that the original \
176 request was delegated to"), 
177         'del_to_user_ids': fields.many2many('res.users', 'att_del_to_user_rel', 
178                                   'attendee_id', 'user_id', 'Users'), 
179         'delegated_from': fields.function(_compute_data, method=True, string=\
180             'Delegated From', type="char", store=True, size=124, multi='delegated_from'), 
181         'del_from_user_ids': fields.many2many('res.users', 'att_del_from_user_rel', \
182                                       'attendee_id', 'user_id', 'Users'), 
183         'sent_by': fields.function(_compute_data, method=True, string='Sent By', type="char", multi='sent_by', store=True, size=124, help="Specify the user that is acting on behalf of the calendar user"), 
184         'sent_by_uid': fields.many2one('res.users', 'Sent by User'), 
185         'cn': fields.function(_compute_data, method=True, string='Common name', type="char", size=124, multi='cn', store=True), 
186         'dir': fields.char('URI Reference', size=124, help="Reference to the URI that points to the directory information corresponding to the attendee."), 
187         'language': fields.selection(_lang_get, 'Language', 
188                                   help="To specify the language for text values in a property or property parameter."), 
189         'user_id': fields.many2one('res.users', 'User'), 
190         'partner_address_id': fields.many2one('res.partner.address', 'Contact'), 
191         'partner_id':fields.related('partner_address_id', 'partner_id', type='many2one', relation='res.partner', string='Partner'), 
192         'email': fields.char('Email', size=124), 
193         'event_date': fields.function(_compute_data, method=True, string='Event Date', type="datetime", multi='event_date'), 
194         'event_end_date': fields.function(_compute_data, method=True, string='Event End Date', type="datetime", multi='event_end_date'), 
195         'ref': fields.reference('Document Ref', selection=_links_get, size=128), 
196         'availability': fields.selection([('free', 'Free'), ('busy', 'Busy')], 'Free/Busy', readonly="True"), 
197      }
198     _defaults = {
199         'state':  lambda *x: 'needs-action', 
200     }
201
202     def onchange_user_id(self, cr, uid, ids, user_id, *args, **argv):
203         if not user_id:
204             return {'value': {'email': ''}}
205         usr_obj = self.pool.get('res.users')
206         user = usr_obj.browse(cr, uid, user_id, *args)
207         return {'value': {'email': user.address_id.email, 'availability':user.availability}}
208
209     def do_tentative(self, cr, uid, ids, context=None, *args):
210         self.write(cr, uid, ids, {'state': 'tentative'}, context)
211
212     def do_accept(self, cr, uid, ids, context=None, *args):
213         self.write(cr, uid, ids, {'state': 'accepted'}, context)
214
215     def do_decline(self, cr, uid, ids, context=None, *args):
216         self.write(cr, uid, ids, {'state': 'declined'}, context)
217
218 calendar_attendee()
219
220 class res_alarm(osv.osv):
221     _name = 'res.alarm'
222     _description = 'Basic Alarm Information'
223     _columns = {
224         'name':fields.char('Name', size=256, required=True), 
225         'trigger_occurs': fields.selection([('before', 'Before'), ('after', 'After')], \
226                                         'Triggers', required=True), 
227         'trigger_interval': fields.selection([('minutes', 'Minutes'), ('hours', 'Hours'), \
228                 ('days', 'Days')], 'Interval', required=True), 
229         'trigger_duration':  fields.integer('Duration', required=True), 
230         'trigger_related':  fields.selection([('start', 'The event starts'), ('end', \
231                                        'The event ends')], 'Related to', required=True), 
232         'duration': fields.integer('Duration', help="""Duration' and 'Repeat' \
233 are both optional, but if one occurs, so MUST the other"""), 
234         'repeat': fields.integer('Repeat'), 
235         'active': fields.boolean('Active', help="If the active field is set to true, it will allow you to hide the event alarm information without removing it."), 
236
237
238     }
239     _defaults = {
240         'trigger_interval':  lambda *x: 'minutes', 
241         'trigger_duration': lambda *x: 5, 
242         'trigger_occurs': lambda *x: 'before', 
243         'trigger_related': lambda *x: 'start', 
244         'active': lambda *x: 1, 
245     }
246
247     def do_alarm_create(self, cr, uid, ids, model, date, context={}):
248         alarm_obj = self.pool.get('calendar.alarm')
249         ir_obj = self.pool.get('ir.model')
250         model_id = ir_obj.search(cr, uid, [('model', '=', model)])[0]
251         
252         model_obj = self.pool.get(model)
253         for data in model_obj.browse(cr, uid, ids):
254             basic_alarm = data.alarm_id
255             self.do_alarm_unlink(cr, uid, [data.id], model)
256             if basic_alarm:
257                 vals = {
258                     'action': 'display', 
259                     'description': data.description, 
260                     'name': data.name, 
261                     'attendee_ids': [(6, 0, map(lambda x:x.id, data.attendee_ids))], 
262                     'trigger_related': basic_alarm.trigger_related, 
263                     'trigger_duration': basic_alarm.trigger_duration, 
264                     'trigger_occurs': basic_alarm.trigger_occurs, 
265                     'trigger_interval': basic_alarm.trigger_interval, 
266                     'duration': basic_alarm.duration, 
267                     'repeat': basic_alarm.repeat, 
268                     'state': 'run', 
269                     'event_date': data[date], 
270                     'res_id': data.id, 
271                     'model_id': model_id, 
272                     'user_id': uid
273                  }
274                 alarm_id = alarm_obj.create(cr, uid, vals)
275                 cr.execute('Update %s set caldav_alarm_id=%s, alarm_id=%s \
276                                         where id=%s' % (model_obj._table, \
277                                         alarm_id, basic_alarm.id, data.id))
278         cr.commit()
279         return True
280
281     def do_alarm_unlink(self, cr, uid, ids, model, context={}):
282         alarm_obj = self.pool.get('calendar.alarm')
283         ir_obj = self.pool.get('ir.model')
284         model_id = ir_obj.search(cr, uid, [('model', '=', model)])[0]
285         model_obj = self.pool.get(model)
286         for datas in model_obj.browse(cr, uid, ids):
287             alarm_ids = alarm_obj.search(cr, uid, [('model_id', '=', model_id), ('res_id', '=', datas.id)])
288             if alarm_ids and len(alarm_ids):
289                 alarm_obj.unlink(cr, uid, alarm_ids)
290                 cr.execute('Update %s set caldav_alarm_id=NULL, alarm_id=NULL\
291                              where id=%s' % (model_obj._table, datas.id))
292         cr.commit()
293         return True
294
295 res_alarm()
296
297 class calendar_alarm(osv.osv):
298     _name = 'calendar.alarm'
299     _description = 'Event alarm information'
300     _inherits = {'res.alarm': "alarm_id"}
301     __attribute__ = {}
302
303     _columns = {
304             'alarm_id': fields.many2one('res.alarm', 'Basic Alarm', ondelete='cascade'), 
305             'name': fields.char('Summary', size=124, help="""Contains the text to be used as the message subject for email
306 or contains the text to be used for display"""), 
307             'action': fields.selection([('audio', 'Audio'), ('display', 'Display'), \
308                     ('procedure', 'Procedure'), ('email', 'Email') ], 'Action', \
309                     required=True, help="Defines the action to be invoked when an alarm is triggered"), 
310             'description': fields.text('Description', help='Provides a more complete description of the calendar component, than that provided by the "SUMMARY" property'), 
311             'attendee_ids': fields.many2many('calendar.attendee', 'alarm_attendee_rel', \
312                                           'alarm_id', 'attendee_id', 'Attendees', readonly=True), 
313             'attach': fields.binary('Attachment', help="""* Points to a sound resource, which is rendered when the alarm is triggered for audio,
314 * File which is intended to be sent as message attachments for email,
315 * Points to a procedure resource, which is invoked when the alarm is triggered for procedure."""), 
316             'res_id': fields.integer('Resource ID'), 
317             'model_id': fields.many2one('ir.model', 'Model'), 
318             'user_id': fields.many2one('res.users', 'Owner'), 
319             'event_date': fields.datetime('Event Date'), 
320             'event_end_date': fields.datetime('Event End Date'), 
321             'trigger_date': fields.datetime('Trigger Date', readonly="True"), 
322             'state':fields.selection([
323                         ('draft', 'Draft'), 
324                         ('run', 'Run'), 
325                         ('stop', 'Stop'), 
326                         ('done', 'Done'), 
327                     ], 'State', select=True, readonly=True), 
328      }
329
330     _defaults = {
331         'action':  lambda *x: 'email', 
332         'state': lambda *x: 'run', 
333      }
334
335     def create(self, cr, uid, vals, context={}):
336         event_date = vals.get('event_date', False)
337         if event_date:
338             dtstart = datetime.strptime(vals['event_date'], "%Y-%m-%d %H:%M:%S")
339             if vals['trigger_interval'] == 'days':
340                 delta = timedelta(days=vals['trigger_duration'])
341             if vals['trigger_interval'] == 'hours':
342                 delta = timedelta(hours=vals['trigger_duration'])
343             if vals['trigger_interval'] == 'minutes':
344                 delta = timedelta(minutes=vals['trigger_duration'])
345             trigger_date =  dtstart + (vals['trigger_occurs'] == 'after' and delta or -delta)
346             vals['trigger_date'] = trigger_date
347         res = super(calendar_alarm, self).create(cr, uid, vals, context)
348         return res
349
350     def do_run_scheduler(self, cr, uid, automatic=False, use_new_cursor=False, \
351                        context=None):
352         if not context:
353             context = {}
354         current_datetime = datetime.now().strftime('%Y-%m-%d %H:%M:%S')
355         cr.execute("select alarm.id as id \
356                     from calendar_alarm alarm \
357                     where alarm.state = %s and alarm.trigger_date <= %s", ('run', current_datetime))
358         res = cr.dictfetchall()
359         alarm_ids = map(lambda x: x['id'], res)
360         attendee_obj = self.pool.get('calendar.attendee')
361         request_obj = self.pool.get('res.request')
362         mail_to = []
363         for alarm in self.browse(cr, uid, alarm_ids):
364             if alarm.action == 'display':
365                 value = {
366                    'name': alarm.name, 
367                    'act_from': alarm.user_id.id, 
368                    'act_to': alarm.user_id.id, 
369                    'body': alarm.description, 
370                    'trigger_date': alarm.trigger_date, 
371                    'ref_doc1':  '%s,%s'  % (alarm.model_id.model, alarm.res_id)
372                 }
373                 request_id = request_obj.create(cr, uid, value)
374                 request_ids = [request_id]
375                 for attendee in alarm.attendee_ids:
376                     value['act_to'] = attendee.user_id.id
377                     request_id = request_obj.create(cr, uid, value)
378                     request_ids.append(request_id)
379                 request_obj.request_send(cr, uid, request_ids)
380
381             if alarm.action == 'email':
382                 sub = '[Openobject Remainder] %s'  % (alarm.name)
383                 body = """
384                 Name: %s
385                 Date: %s
386                 Description: %s
387
388                 From:
389                       %s
390                       %s
391
392                 """  % (alarm.name, alarm.trigger_date, alarm.description, \
393                     alarm.user_id.name, alarm.user_id.sign)
394                 mail_to = [alarm.user_id.address_id.email]
395                 for att in alarm.attendee_ids:
396                     mail_to.append(att.user_id.address_id.email)
397
398                 tools.email_send(
399                     tools.confirm['from_mail'], 
400                     mail_to, 
401                     sub, 
402                     body
403                 )
404             self.write(cr, uid, [alarm.id], {'state':'done'})
405         return True
406
407 calendar_alarm()
408
409
410 class calendar_event(osv.osv):
411     _name = "calendar.event"
412     _description = "Calendar Event"
413     __attribute__ = {}
414
415     def onchange_rrule_type(self, cr, uid, ids, rtype, *args, **argv):
416         if rtype == 'none' or not rtype:
417             return {'value': {'rrule': ''}}
418         if rtype == 'custom':
419             return {}
420         rrule = self.pool.get('calendar.custom.rrule')
421         rrulestr = rrule.compute_rule_string(cr, uid, {'freq': rtype.upper(), \
422                                  'interval': 1})
423         return {'value': {'rrule': rrulestr}}
424     
425     def _get_duration(self, cr, uid, ids, name, arg, context):
426         res = {}
427         for event in self.browse(cr, uid, ids, context=context):
428             start = datetime.strptime(event.date, "%Y-%m-%d %H:%M:%S")
429             res[event.id] = 0
430             if event.date_deadline:
431                 end = datetime.strptime(event.date_deadline[:19], "%Y-%m-%d %H:%M:%S")
432                 diff = end - start
433                 duration =  float(diff.days)* 24 + (float(diff.seconds) / 3600)
434                 res[event.id] = round(duration, 2)
435         return res
436
437     def _set_duration(self, cr, uid, id, name, value, arg, context):
438         event = self.browse(cr, uid, id, context=context)
439         start = datetime.strptime(event.date, "%Y-%m-%d %H:%M:%S")
440         end = start + timedelta(hours=value)
441         cr.execute("UPDATE %s set date_deadline='%s' \
442                         where id=%s"% (self._table, end.strftime("%Y-%m-%d %H:%M:%S"), id))
443         return True
444     
445     _columns = {
446         'id': fields.integer('ID'), 
447         'name': fields.char('Description', size=64, required=True), 
448         'date': fields.datetime('Date'), 
449         'date_deadline': fields.datetime('Deadline'), 
450         'duration': fields.function(_get_duration, method=True, \
451                                     fnct_inv=_set_duration, string='Duration'), 
452         'description': fields.text('Your action'), 
453         'class': fields.selection([('public', 'Public'), ('private', 'Private'), \
454                  ('confidential', 'Confidential')], 'Mark as'), 
455         'location': fields.char('Location', size=264, help="Location of Event"), 
456         'show_as': fields.selection([('free', 'Free'), \
457                                   ('busy', 'Busy')], 
458                                    'Show as'), 
459         'caldav_url': fields.char('Caldav URL', size=264), 
460         'exdate': fields.text('Exception Date/Times', help="This property \
461 defines the list of date/time exceptions for arecurring calendar component."), 
462         'exrule': fields.char('Exception Rule', size=352, help="defines a \
463 rule or repeating pattern for anexception to a recurrence set"), 
464         'rrule': fields.char('Recurrent Rule', size=124), 
465         'rrule_type': fields.selection([('none', 'None'), ('daily', 'Daily'), \
466                             ('weekly', 'Weekly'), ('monthly', 'Monthly'), \
467                             ('yearly', 'Yearly'), ('custom', 'Custom')], 'Recurrency'), 
468         'alarm_id': fields.many2one('res.alarm', 'Alarm'), 
469         'caldav_alarm_id': fields.many2one('calendar.alarm', 'Alarm'), 
470         'recurrent_uid': fields.integer('Recurrent ID'), 
471         'recurrent_id': fields.datetime('Recurrent ID date'), 
472                 }
473     
474     _defaults = {
475          'class': lambda *a: 'public', 
476          'show_as': lambda *a: 'busy', 
477     }
478
479     def export_cal(self, cr, uid, ids, context={}):
480         ids = map(lambda x: caldav_id2real_id(x), ids)
481         event_data = self.read(cr, uid, ids)
482         event_obj = self.pool.get('basic.calendar.event')
483         ical = event_obj.export_ical(cr, uid, event_data, context={'model': self._name})
484         cal_val = ical.serialize()
485         cal_val = cal_val.replace('"', '').strip()
486         return cal_val
487
488     def import_cal(self, cr, uid, data, context={}):
489         file_content = base64.decodestring(data)
490         event_obj = self.pool.get('basic.calendar.event')
491         vals = event_obj.import_ical(cr, uid, file_content)
492         ids = []
493         for val in vals:
494             exists, r_id = base_calendar.uid2openobjectid(cr, val['id'], self._name, \
495                                                              val.get('recurrent_id'))
496             if val.has_key('create_date'): val.pop('create_date')
497             val['caldav_url'] = context.get('url') or ''
498             val.pop('id')
499             if exists and r_id:
500                 val.update({'recurrent_uid': exists})
501                 self.write(cr, uid, [r_id], val)
502                 ids.append(r_id)
503             elif exists:
504                 self.write(cr, uid, [exists], val)
505                 ids.append(exists)
506             else:
507                 event_id = self.create(cr, uid, val)
508                 ids.append(event_id)
509         return ids
510
511     def modify_this(self, cr, uid, ids, defaults, context=None, *args):
512         datas = self.read(cr, uid, ids[0], context=context)
513         date = datas.get('date')
514         defaults.update({
515                'recurrent_uid': caldav_id2real_id(datas['id']), 
516                'recurrent_id': defaults.get('date'), 
517                'rrule_type': 'none', 
518                'rrule': ''
519                     })
520         new_id = self.copy(cr, uid, ids[0], default=defaults, context=context)
521         return new_id
522
523     def get_recurrent_ids(self, cr, uid, select, base_start_date, base_until_date, limit=100):
524         if not limit:
525             limit = 100
526         if isinstance(select, (str, int, long)):
527             ids = [select]
528         else:
529             ids = select
530         result = []
531         if ids and (base_start_date or base_until_date):
532             cr.execute("select m.id, m.rrule, m.date, m.date_deadline, \
533                             m.exdate  from "  + self._table + \
534                             " m where m.id in ("\
535                             + ','.join(map(lambda x: str(x), ids))+")")
536
537             count = 0
538             for data in cr.dictfetchall():
539                 start_date = base_start_date and datetime.strptime(base_start_date, "%Y-%m-%d") or False
540                 until_date = base_until_date and datetime.strptime(base_until_date, "%Y-%m-%d") or False
541                 if count > limit:
542                     break
543                 event_date = datetime.strptime(data['date'], "%Y-%m-%d %H:%M:%S")
544                 if start_date and start_date <= event_date:
545                     start_date = event_date
546                 if not data['rrule']:
547                     if start_date and (event_date < start_date):
548                         continue
549                     if until_date and (event_date > until_date):
550                         continue
551                     idval = real_id2caldav_id(data['id'], data['date'])
552                     result.append(idval)
553                     count += 1
554                 else:
555                     exdate = data['exdate'] and data['exdate'].split(',') or []
556                     event_obj = self.pool.get('basic.calendar.event')
557                     rrule_str = data['rrule']
558                     new_rrule_str = []
559                     rrule_until_date = False
560                     is_until = False
561                     for rule in rrule_str.split(';'):
562                         name, value = rule.split('=')
563                         if name == "UNTIL":
564                             is_until = True
565                             value = parser.parse(value)
566                             rrule_until_date = parser.parse(value.strftime("%Y-%m-%d"))
567                             if until_date and until_date >= rrule_until_date:
568                                 until_date = rrule_until_date
569                             if until_date:
570                                 value = until_date.strftime("%Y%m%d%H%M%S")
571                         new_rule = '%s=%s' % (name, value)
572                         new_rrule_str.append(new_rule)
573                     if not is_until and until_date:
574                         value = until_date.strftime("%Y%m%d%H%M%S")
575                         name = "UNTIL"
576                         new_rule = '%s=%s' % (name, value)
577                         new_rrule_str.append(new_rule)
578                     new_rrule_str = ';'.join(new_rrule_str)
579                     start_date = datetime.strptime(data['date'], "%Y-%m-%d %H:%M:%S")
580                     rdates = event_obj.get_recurrent_dates(str(new_rrule_str), exdate, start_date)
581                     for rdate in rdates:
582                         r_date = datetime.strptime(rdate, "%Y-%m-%d %H:%M:%S")
583                         if start_date and r_date < start_date:
584                             continue
585                         if until_date and r_date > until_date:
586                             continue
587                         idval = real_id2caldav_id(data['id'], rdate)
588                         result.append(idval)
589                         count += 1
590         if result:
591             ids = result
592         if isinstance(select, (str, int, long)):
593             return ids and ids[0] or False
594         return ids
595
596     def search(self, cr, uid, args, offset=0, limit=100, order=None, 
597             context=None, count=False):
598         args_without_date = []
599         start_date = False
600         until_date = False
601         for arg in args:
602             if arg[0] not in ('date', unicode('date')):
603                 args_without_date.append(arg)
604             else:
605                 if arg[1] in ('>', '>='):
606                     start_date = arg[2]
607                 elif arg[1] in ('<', '<='):
608                     until_date = arg[2]
609         res = super(calendar_event, self).search(cr, uid, args_without_date, offset, 
610                 limit, order, context, count)
611         return self.get_recurrent_ids(cr, uid, res, start_date, until_date, limit)
612
613
614     def write(self, cr, uid, ids, vals, context=None, check=True, update_check=True):
615         if isinstance(ids, (str, int, long)):
616             select = [ids]
617         else:
618             select = ids
619         new_ids = []
620         for id in select:
621             id = caldav_id2real_id(id)
622             if not id in new_ids:
623                 new_ids.append(id)
624         res = super(calendar_event, self).write(cr, uid, new_ids, vals, context=context)
625         if vals.has_key('alarm_id'):
626             alarm_obj = self.pool.get('res.alarm')
627             alarm_obj.do_alarm_create(cr, uid, new_ids, self._name, 'date')
628         return res
629
630     def browse(self, cr, uid, ids, context=None, list_class=None, fields_process={}):
631         if isinstance(ids, (str, int, long)):
632             select = [ids]
633         else:
634             select = ids
635         select = map(lambda x: caldav_id2real_id(x), select)
636         res = super(calendar_event, self).browse(cr, uid, select, context, list_class, fields_process)
637         if isinstance(ids, (str, int, long)):
638             return res and res[0] or False
639         return res
640
641     def read(self, cr, uid, ids, fields=None, context={}, load='_classic_read'):
642         if isinstance(ids, (str, int, long)):
643             select = [ids]
644         else:
645             select = ids
646         select = map(lambda x: (x, caldav_id2real_id(x)), select)
647         result = []
648         if fields and 'date' not in fields:
649             fields.append('date')
650         for caldav_id, real_id in select:
651             res = super(calendar_event, self).read(cr, uid, real_id, fields=fields, context=context, \
652                                               load=load)
653             ls = caldav_id2real_id(caldav_id, with_date=res.get('duration', 0))
654             if not isinstance(ls, (str, int, long)) and len(ls) >= 2:
655                 res['date'] = ls[1]
656                 res['date_deadline'] = ls[2]
657             res['id'] = caldav_id
658
659             result.append(res)
660         if isinstance(ids, (str, int, long)):
661             return result and result[0] or False
662         return result
663
664     def copy(self, cr, uid, id, default=None, context={}):
665         res = super(calendar_event, self).copy(cr, uid, caldav_id2real_id(id), default, context)
666         alarm_obj = self.pool.get('res.alarm')
667         alarm_obj.do_alarm_create(cr, uid, [res], self._name, 'date')
668         return res
669
670     def unlink(self, cr, uid, ids, context=None):
671         res = False
672         for id in ids:
673             ls = caldav_id2real_id(id)
674             if not isinstance(ls, (str, int, long)) and len(ls) >= 2:
675                 date_new = ls[1]
676                 for record in self.read(cr, uid, [caldav_id2real_id(id)], \
677                                             ['date', 'rrule', 'exdate']):
678                     if record['rrule']:
679                         exdate = (record['exdate'] and (record['exdate'] + ',')  or '') + \
680                                     ''.join((re.compile('\d')).findall(date_new)) + 'Z'
681                         if record['date'] == date_new:
682                             res = self.write(cr, uid, [caldav_id2real_id(id)], {'exdate': exdate})
683                     else:
684                         ids = map(lambda x: caldav_id2real_id(x), ids)
685                         res = super(calendar_event, self).unlink(cr, uid, caldav_id2real_id(ids))
686                         alarm_obj = self.pool.get('res.alarm')
687                         alarm_obj.do_alarm_unlink(cr, uid, ids, self._name)
688             else:
689                 ids = map(lambda x: caldav_id2real_id(x), ids)
690                 res = super(calendar_event, self).unlink(cr, uid, ids)
691                 alarm_obj = self.pool.get('res.alarm')
692                 alarm_obj.do_alarm_unlink(cr, uid, ids, self._name)
693         return res
694
695     def create(self, cr, uid, vals, context={}):
696         res = super(calendar_event, self).create(cr, uid, vals, context)
697         alarm_obj = self.pool.get('res.alarm')
698         alarm_obj.do_alarm_create(cr, uid, [res], self._name, 'date')
699         return res
700
701 calendar_event()
702
703 class calendar_todo(osv.osv):
704     _name = "calendar.todo"
705     _inherit = "calendar.event"
706     _description = "Calendar Task"
707
708     def _get_date(self, cr, uid, ids, name, arg, context):
709         res = {}
710         for event in self.browse(cr, uid, ids, context=context):
711             res[event.id] = event.date_start
712         return res
713
714     def _set_date(self, cr, uid, id, name, value, arg, context):
715         event = self.browse(cr, uid, id, context=context)
716         cr.execute("UPDATE %s set date_start='%s' where id=%s"  \
717                            % (self._table, value, id))
718         return True
719
720     _columns = {
721         'date': fields.function(_get_date, method=True,   fnct_inv=_set_date, \
722                                         string='Duration', store=True, type='datetime'),
723         'duration': fields.integer('Duration'), 
724     }
725     
726     __attribute__ = {}
727     
728     def import_cal(self, cr, uid, data, context={}):
729         file_content = base64.decodestring(data)
730         todo_obj = self.pool.get('basic.calendar.todo')
731         vals = todo_obj.import_ical(cr, uid, file_content)
732         for val in vals:
733             obj_tm = self.pool.get('res.users').browse(cr, uid, uid, context).company_id.project_time_mode_id
734             if not val.has_key('planned_hours'):
735                 # 'Computes duration' in days
736                 start = datetime.strptime(val['date'], '%Y-%m-%d %H:%M:%S')
737                 end = datetime.strptime(val['date_deadline'], '%Y-%m-%d %H:%M:%S')
738                 diff = end - start
739                 plan = (diff.seconds/float(86400) + diff.days) * obj_tm.factor
740                 val['planned_hours'] = plan
741             else:
742                 # Converts timedelta into hours
743                 hours = (val['planned_hours'].seconds / float(3600)) + \
744                                         (val['planned_hours'].days * 24)
745                 val['planned_hours'] = hours
746             exists, r_id = base_calendar.uid2openobjectid(cr, val['id'], self._name, val.get('recurrent_id'))
747             val.pop('id')
748             if exists:
749                 self.write(cr, uid, [exists], val)
750             else:
751                 task_id = self.create(cr, uid, val)
752         return {'count': len(vals)}
753
754     def export_cal(self, cr, uid, ids, context={}):
755         task_datas = self.read(cr, uid, ids, [], context ={'read': True})
756         tasks = []
757         for task in task_datas:
758             if task.get('planned_hours', None) and task.get('date_deadline', None):
759                 task.pop('planned_hours')
760             tasks.append(task)
761         todo_obj = self.pool.get('basic.calendar.todo')
762         ical = todo_obj.export_ical(cr, uid, tasks, context={'model': self._name})
763         calendar_val = ical.serialize()
764         calendar_val = calendar_val.replace('"', '').strip()
765         return calendar_val
766
767 calendar_todo()
768  
769 class ir_attachment(osv.osv):
770     _name = 'ir.attachment'
771     _inherit = 'ir.attachment'
772
773     def search_count(self, cr, user, args, context=None):
774         args1 = []
775         for arg in args:
776             args1.append(map(lambda x:str(x).split('-')[0], arg))
777         return super(ir_attachment, self).search_count(cr, user, args1, context)
778
779     def search(self, cr, uid, args, offset=0, limit=None, order=None, 
780             context=None, count=False):
781         new_args = args
782         for i, arg in enumerate(new_args):
783             if arg[0] == 'res_id':
784                 new_args[i] = (arg[0], arg[1], caldav_id2real_id(arg[2]))
785         return super(ir_attachment, self).search(cr, uid, new_args, offset=offset, 
786                             limit=limit, order=order, 
787                             context=context, count=False)
788 ir_attachment()
789
790 class ir_values(osv.osv):
791     _inherit = 'ir.values'
792
793     def set(self, cr, uid, key, key2, name, models, value, replace=True, \
794             isobject=False, meta=False, preserve_user=False, company=False):
795         new_model = []
796         for data in models:
797             if type(data) in (list, tuple):
798                 new_model.append((data[0], caldav_id2real_id(data[1])))
799             else:
800                 new_model.append(data)
801         return super(ir_values, self).set(cr, uid, key, key2, name, new_model, \
802                     value, replace, isobject, meta, preserve_user, company)
803
804     def get(self, cr, uid, key, key2, models, meta=False, context={}, \
805              res_id_req=False, without_user=True, key2_req=True):
806         new_model = []
807         for data in models:
808             if type(data) in (list, tuple):
809                 new_model.append((data[0], caldav_id2real_id(data[1])))
810             else:
811                 new_model.append(data)
812         return super(ir_values, self).get(cr, uid, key, key2, new_model, \
813                          meta, context, res_id_req, without_user, key2_req)
814
815 ir_values()
816
817 class ir_model(osv.osv):
818
819     _inherit = 'ir.model'
820
821     def read(self, cr, uid, ids, fields=None, context={}, 
822             load='_classic_read'):
823         data = super(ir_model, self).read(cr, uid, ids, fields=fields, \
824                         context=context, load=load)
825         if data:
826             for val in data:
827                 val['id'] = caldav_id2real_id(val['id'])
828         return data
829
830 ir_model()
831
832 class virtual_report_spool(web_services.report_spool):
833
834     def exp_report(self, db, uid, object, ids, datas=None, context=None):
835         if object == 'printscreen.list':
836             return super(virtual_report_spool, self).exp_report(db, uid, \
837                             object, ids, datas, context)
838         new_ids = []
839         for id in ids:
840             new_ids.append(caldav_id2real_id(id))
841         datas['id'] = caldav_id2real_id(datas['id'])
842         super(virtual_report_spool, self).exp_report(db, uid, object, new_ids, datas, context)
843         return super(virtual_report_spool, self).exp_report(db, uid, object, new_ids, datas, context)
844
845 virtual_report_spool()
846
847 class calendar_custom_rrule(osv.osv):
848     _name = "calendar.custom.rrule"
849     _description = "Custom Recurrency Rule"
850
851     _columns = {
852         'freq': fields.selection([('None', 'No Repeat'), \
853                             ('secondly', 'Secondly'), \
854                             ('minutely', 'Minutely'), \
855                             ('hourly', 'Hourly'), \
856                             ('daily', 'Daily'), \
857                             ('weekly', 'Weekly'), \
858                             ('monthly', 'Monthly'), \
859                             ('yearly', 'Yearly')], 'Frequency', required=True), 
860         'interval': fields.integer('Interval'), 
861         'count': fields.integer('Count'), 
862         'mo': fields.boolean('Mon'), 
863         'tu': fields.boolean('Tue'), 
864         'we': fields.boolean('Wed'), 
865         'th': fields.boolean('Thu'), 
866         'fr': fields.boolean('Fri'), 
867         'sa': fields.boolean('Sat'), 
868         'su': fields.boolean('Sun'), 
869         'select1': fields.selection([('date', 'Date of month'), \
870                             ('day', 'Day of month')], 'Option'), 
871         'day': fields.integer('Date of month'), 
872         'week_list': fields.selection([('MO', 'Monday'), ('TU', 'Tuesday'), \
873                                    ('WE', 'Wednesday'), ('TH', 'Thursday'), \
874                                    ('FR', 'Friday'), ('SA', 'Saturday'), \
875                                    ('SU', 'Sunday')], 'Weekday'), 
876         'byday': fields.selection([('1', 'First'), ('2', 'Second'), \
877                                    ('3', 'Third'), ('4', 'Fourth'), \
878                                    ('5', 'Fifth'), ('-1', 'Last')], 'By day'), 
879         'month_list': fields.selection(months.items(), 'Month'), 
880         'end_date': fields.date('Repeat Until')
881     }
882
883     _defaults = {
884                  'freq':  lambda *x: 'daily', 
885                  'select1':  lambda *x: 'date', 
886                  'interval':  lambda *x: 1, 
887                  }
888
889     def compute_rule_string(self, cr, uid, datas, context=None, *args):
890         weekdays = ['mo', 'tu', 'we', 'th', 'fr', 'sa', 'su']
891         weekstring = ''
892         monthstring = ''
893         yearstring = ''
894
895 #    logic for computing rrule string
896
897         freq = datas.get('freq')
898         if freq == 'None':
899             obj.write(cr, uid, [res_obj.id], {'rrule': ''})
900             return {}
901
902         if freq == 'weekly':
903             byday = map(lambda x: x.upper(), filter(lambda x: datas.get(x) and x in weekdays, datas))
904             if byday:
905                 weekstring = ';BYDAY=' + ','.join(byday)
906
907         elif freq == 'monthly':
908             if datas.get('select1')=='date' and (datas.get('day') < 1 or datas.get('day') > 31):
909                 raise osv.except_osv(_('Error!'), ("Please select proper Day of month"))
910             if datas.get('select1')=='day':
911                 monthstring = ';BYDAY=' + datas.get('byday') + datas.get('week_list')
912             elif datas.get('select1')=='date':
913                 monthstring = ';BYMONTHDAY=' + str(datas.get('day'))
914
915         elif freq == 'yearly':
916             if datas.get('select1')=='date'  and (datas.get('day') < 1 or datas.get('day') > 31):
917                 raise osv.except_osv(_('Error!'), ("Please select proper Day of month"))
918             bymonth = ';BYMONTH=' + str(datas.get('month_list'))
919             if datas.get('select1')=='day':
920                 bystring = ';BYDAY=' + datas.get('byday') + datas.get('week_list')
921             elif datas.get('select1')=='date':
922                 bystring = ';BYMONTHDAY=' + str(datas.get('day'))
923             yearstring = bymonth + bystring
924
925         if datas.get('end_date'):
926             datas['end_date'] = ''.join((re.compile('\d')).findall(datas.get('end_date'))) + '235959Z'
927         enddate = (datas.get('count') and (';COUNT=' +  str(datas.get('count'))) or '') +\
928                              ((datas.get('end_date') and (';UNTIL=' + datas.get('end_date'))) or '')
929
930         rrule_string = 'FREQ=' + freq.upper() +  weekstring + ';INTERVAL=' + \
931                 str(datas.get('interval')) + enddate + monthstring + yearstring
932
933 #        End logic
934         return rrule_string
935
936     def do_add(self, cr, uid, ids, context={}):
937         datas = self.read(cr, uid, ids)[0]
938         if datas.get('interval') <= 0:
939             raise osv.except_osv(_('Error!'), ("Please select proper Interval"))
940
941
942         if not context or not context.get('model'):
943             return {}
944         else:
945             model = context.get('model')
946         obj = self.pool.get(model)
947         res_obj = obj.browse(cr, uid, context['active_id'])
948
949         rrule_string = self.compute_rule_string(cr, uid, datas)
950         obj.write(cr, uid, [res_obj.id], {'rrule': rrule_string})
951         return {}
952
953 calendar_custom_rrule()
954
955 class res_users(osv.osv):
956     _inherit = 'res.users'
957
958     def _get_user_avail(self, cr, uid, ids, context=None):
959         current_datetime = datetime.now().strftime('%Y-%m-%d %H:%M:%S')
960         res = {}
961         attendee_obj = self.pool.get('calendar.attendee')
962         attendee_ids = attendee_obj.search(cr, uid, [
963                     ('event_date', '<=', current_datetime), ('event_end_date', '<=', current_datetime), 
964                     ('state', '=', 'accepted'), ('user_id', 'in', ids)
965                     ])
966
967         result = cr.dictfetchall()
968         for attendee_data in attendee_obj.read(cr, uid, attendee_ids, ['user_id']):
969             user_id = attendee_data['user_id']
970             status = 'busy'
971             res.update({user_id:status})
972
973         #TOCHECK: Delegrated Event
974         #cr.execute("SELECT user_id,'busy' FROM att_del_to_user_rel where user_id = ANY(%s)", (ids,))
975         #res.update(cr.dictfetchall())
976         for user_id in ids:
977             if user_id not in res:
978                 res[user_id] = 'free'
979
980         return res
981
982     def _get_user_avail_fun(self, cr, uid, ids, name, args, context=None):
983         return self._get_user_avail(cr, uid, ids, context=context)
984
985     _columns = {
986             'availability': fields.function(_get_user_avail_fun, type='selection', \
987                     selection=[('free', 'Free'), ('busy', 'Busy')], \
988                     string='Free/Busy', method=True), 
989     }
990 res_users()
991
992 class invite_attendee_wizard(osv.osv_memory):
993     _name = "caldav.invite.attendee"
994     _description = "Invite Attendees"
995
996     _columns = {
997         'type': fields.selection([('internal', 'Internal User'), \
998               ('external', 'External Email'), \
999               ('partner', 'Partner Contacts')], 'Type', required=True), 
1000         'user_ids': fields.many2many('res.users', 'invite_user_rel', 
1001                                   'invite_id', 'user_id', 'Users'), 
1002         'partner_id': fields.many2one('res.partner', 'Partner'), 
1003         'email': fields.char('Email', size=124), 
1004         'contact_ids': fields.many2many('res.partner.address', 'invite_contact_rel', 
1005                                   'invite_id', 'contact_id', 'Contacts'), 
1006               }
1007
1008     def do_invite(self, cr, uid, ids, context={}):
1009         datas = self.read(cr, uid, ids)[0]
1010         if not context or not context.get('model'):
1011             return {}
1012         else:
1013             model = context.get('model')
1014         obj = self.pool.get(model)
1015         res_obj = obj.browse(cr, uid, context['active_id'])
1016         type = datas.get('type')
1017         att_obj = self.pool.get('calendar.attendee')
1018         vals = {'ref': '%s,%s' % (model, caldav_id2real_id(context['active_id']))}
1019         if type == 'internal':
1020             user_obj = self.pool.get('res.users')
1021             for user_id in datas.get('user_ids', []):
1022                 user = user_obj.browse(cr, uid, user_id)
1023                 if not user.address_id.email:
1024                     raise osv.except_osv(_('Error!'), \
1025                                     ("User does not have an email Address"))
1026                 vals.update({'user_id': user_id, 
1027                                      'email': user.address_id.email})
1028                 att_id = att_obj.create(cr, uid, vals)
1029                 obj.write(cr, uid, res_obj.id, {'attendee_ids': [(4, att_id)]})
1030
1031         elif  type == 'external' and datas.get('email'):
1032             vals.update({'email': datas['email']})
1033             att_id = att_obj.create(cr, uid, vals)
1034             obj.write(cr, uid, res_obj.id, {'attendee_ids': [(4, att_id)]})
1035         elif  type == 'partner':
1036             add_obj = self.pool.get('res.partner.address')
1037             for contact in  add_obj.browse(cr, uid, datas['contact_ids']):
1038                 vals.update({
1039                              'partner_address_id': contact.id, 
1040                              'email': contact.email})
1041                 att_id = att_obj.create(cr, uid, vals)
1042                 obj.write(cr, uid, res_obj.id, {'attendee_ids': [(4, att_id)]})
1043         return {}
1044
1045
1046     def onchange_partner_id(self, cr, uid, ids, partner_id, *args, **argv):
1047         if not partner_id:
1048             return {'value': {'contact_ids': []}}
1049         cr.execute('select id from res_partner_address \
1050                          where partner_id=%s' % (partner_id))
1051         contacts = map(lambda x: x[0], cr.fetchall())
1052         if not contacts:
1053             raise osv.except_osv(_('Error!'), \
1054                                 ("Partner does not have any Contacts"))
1055
1056         return {'value': {'contact_ids': contacts}}
1057
1058 invite_attendee_wizard()
1059
1060
1061 # vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4: