File: ical.py

package info (click to toggle)
taskcoach 1.4.1-4
  • links: PTS, VCS
  • area: main
  • in suites: jessie, jessie-kfreebsd
  • size: 32,496 kB
  • ctags: 17,810
  • sloc: python: 72,170; makefile: 254; ansic: 120; xml: 29; sh: 16
file content (374 lines) | stat: -rw-r--r-- 14,940 bytes parent folder | download
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
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
'''
Task Coach - Your friendly task manager
Copyright (C) 2004-2014 Task Coach developers <developers@taskcoach.org>

Task Coach is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.

Task Coach is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
GNU General Public License for more details.

You should have received a copy of the GNU General Public License
along with this program.  If not, see <http://www.gnu.org/licenses/>.
'''

'''
This module defines classes and functions to handle the VCalendar
format.
''' # pylint: disable=W0105

from taskcoachlib.domain.base import Object
from taskcoachlib.domain import date
from taskcoachlib.i18n import _

import time, calendar, datetime

#{ Utility functions

def parseDateTime(fulldate):
    ''' Parses a datetime as seen in iCalendar files into a 
    L{taskcoachlib.domain.date.DateTime} object. '''

    try:
        dt, tm = fulldate.split('T')
        year, month, day = int(dt[:4]), int(dt[4:6]), int(dt[6:8])
        hour, minute, second = int(tm[:2]), int(tm[2:4]), int(tm[4:6])

        if fulldate.endswith('Z'):
            # GMT. Convert this to local time.
            localTime = time.localtime(calendar.timegm((year, month, day, hour, minute, second, 0, 0, -1)))
            year, month, day, hour, minute, second = localTime[:6]
    except Exception, e:
        raise ValueError('Malformed date: %s (%s)' % (fulldate, str(e)))

    return date.DateTime(year, month, day, hour, minute, second)

def fmtDateTime(dt):
    ''' Formats a L{taskcoachlib.domain.date.DateTime} object to a string
    suitable for inclusion in an iCalendar file. '''
    dt = dt.utcfromtimestamp(time.mktime(dt.timetuple()))
    return '%04d%02d%02dT%02d%02d%02dZ' % (dt.year, dt.month, dt.day,
                                           dt.hour, dt.minute, dt.second)

def quoteString(s):
    ''' The 'quoted-printable' codec doesn't encode \n, but tries to
    fold lines with \n instead of CRLF and generally does strange
    things that ScheduleWorld does not understand (me neither, to an
    extent). Same thing with \r. This function works around this. '''

    s = s.encode('UTF-8').encode('quoted-printable')
    s = s.replace('=\r', '')
    s = s.replace('=\n', '')
    s = s.replace('\r', '=0D')
    s = s.replace('\n', '=0A')
    return s

#}

#{ Parsing iCalendar files

class VCalendarParser(object):
    ''' Base parser class for iCalendar files. This uses the State
    pattern (in its Python incarnation, replacing the class of an
    object at runtime) in order to parse different objects in the
    VCALENDAR. Other states are

     - VTodoParser: parses VTODO objects.

    @ivar kwargs: While parsing, the keyword arguments for the
        domain object creation for the current (parsed) object.
    @ivar tasks: A list of dictionaries suitable to use as
        keyword arguments for task creation, representing all
        VTODO object in the parsed file. ''' # pylint: disable=W0511

    def __init__(self, *args, **kwargs):
        super(VCalendarParser, self).__init__(*args, **kwargs)
        self.stateMap = { 'VCALENDAR': VCalendarParser,
                          'VTODO':     VTodoParser,
                          'VNOTE':     VNoteParser }
        self.tasks = []
        self.notes = []
        self.init()

    def init(self):
        ''' Called after a state change. '''
        self.kwargs = {} # pylint: disable=W0201

    def setState(self, state):
        ''' Sets the state (class) of the parser object. '''
        self.__class__ = state
        self.init()

    def parse(self, lines):
        ''' Actually parses the file.
        @param lines: A list of lines. '''

        # TODO: avoid using indexes here, just iterate. This way the
        # method can accept a file object as argument.

        currentLine = lines[0]

        for line in lines[1:]:
            if line.startswith(' ') or line.startswith('\t'):
                currentLine += line[1:]
            else:
                if self.handleLine(currentLine):
                    return
                currentLine = line

        self.handleLine(currentLine)

    def handleLine(self, line):
        ''' Called by L{parse} for each line to parse. L{parse} is
        supposed to have handled the unfolding. '''

        if line.startswith('BEGIN:'):
            try:
                self.setState(self.stateMap[line[6:]])
            except KeyError:
                raise TypeError, 'Unrecognized vcal type: %s' % line[6:]
        elif line.startswith('END:'):
            if line[4:] == 'VCALENDAR':
                return True
            else:
                self.onFinish()
                self.setState(VCalendarParser)
        else:
            try:
                idx = line.index(':')
            except ValueError:
                raise RuntimeError, 'Malformed vcal line: %s' % line

            details, value = line[:idx].split(';'), line[idx + 1:]
            name, specs = details[0], details[1:]
            specs = dict([tuple(v.split('=')) for v in specs])

            if specs.has_key('ENCODING'):
                value = value.decode(specs['ENCODING'].lower())
            if specs.has_key('CHARSET'):
                value = value.decode(specs['CHARSET'].lower())
            else:
                # Some  servers only  specify CHARSET  when  there are
                # non-ASCII characters :)
                # More, Horde encodes in UTF-8 without specifying the charset.
                value = value.decode('UTF-8')

            # If  an item  name ends  with  'TMPL', it's  part of  the
            # template system and has to be eval()ed.

            if name.endswith('TMPL'):
                name = name[:-4]
                context = dict()
                context.update(datetime.__dict__)
                context.update(date.__dict__)
                context['_'] = _
                value = eval(value, context)
                if isinstance(value, datetime.datetime):
                    value = fmtDateTime(value)

            self.acceptItem(name, value)

        return False

    def onFinish(self):
        ''' This method is called when the current object ends. '''
        raise NotImplementedError

    def acceptItem(self, name, value):
        ''' Called on each new 'item', i.e. key/value pair. Default
        behaviour is to store the pair in the 'kwargs' instance
        variable (which is emptied in L{init}). '''
        if name in ('CREATED', 'DCREATED'):
            self.kwargs['creationDateTime'] = parseDateTime(value)
        elif name == 'LAST-MODIFIED':
            self.kwargs['modificationDateTime'] = parseDateTime(value)
        elif name == 'SUMMARY':
            self.kwargs['subject'] = value
        elif name == 'CATEGORIES':
            # Horde escapes the comma, even though it's an actual separator.
            # I didn't found any way to include an actual comma in a Horde
            # "tag".
            self.kwargs['categories'] = map(lambda x: x.rstrip('\\').lstrip(), value.split(','))
        elif name == 'DESCRIPTION':
            self.kwargs['description'] = value.replace('\\n', '\n')
        else:
            self.kwargs[name.lower()] = value


class VTodoParser(VCalendarParser):
    ''' This is the state responsible for parsing VTODO objects. ''' # pylint: disable=W0511

    def onFinish(self):
        if not self.kwargs.has_key('plannedStartDateTime'):
            # This means no planned start date, but the task constructor will
            # take today by default, so force.
            self.kwargs['plannedStartDateTime'] = date.DateTime()

        if self.kwargs.has_key('vcardStatus'):
            if self.kwargs['vcardStatus'] == 'COMPLETED' and \
                   not self.kwargs.has_key('completionDateTime'):
                # Some servers only give the status, and not the date (SW)
                if self.kwargs.has_key('last-modified'):
                    self.kwargs['completionDateTime'] = parseDateTime(self.kwargs['last-modified'])
                else:
                    self.kwargs['completionDateTime'] = date.Now()

        self.kwargs['status'] = Object.STATUS_NONE
        self.tasks.append(self.kwargs)

    def acceptItem(self, name, value):
        if name == 'DTSTART':
            self.kwargs['plannedStartDateTime'] = parseDateTime(value)
        elif name == 'DUE':
            self.kwargs['dueDateTime'] = parseDateTime(value)
        elif name == 'COMPLETED':
            self.kwargs['completionDateTime'] = parseDateTime(value)
        elif name == 'PERCENT-COMPLETE':
            self.kwargs['percentageComplete'] = int(value)
        elif name == 'UID':
            self.kwargs['id'] = value.decode('UTF-8')
        elif name == 'PRIORITY':
            # Okay. Seems that in vcal,  the priority ranges from 1 to
            # 3, but what it means depends on the other client...

            self.kwargs['priority'] = int(value) - 1
        elif name == 'STATUS':
            self.kwargs['vcardStatus'] = value
        else:
            super(VTodoParser, self).acceptItem(name, value)


class VNoteParser(VCalendarParser):
    '''Parse VNote objects.'''

    def onFinish(self):
        # Summary is not mandatory.
        if not self.kwargs.has_key('subject'):
            if 'description' in self.kwargs:
                self.kwargs['subject'] = self.kwargs['description'].split('\n')[0]
            else:
                self.kwargs['subject'] = ''
        self.kwargs['status'] = Object.STATUS_NONE
        self.notes.append(self.kwargs)

    def acceptItem(self, name, value):
        if name == 'X-IRMC-LUID':
            self.kwargs['id'] = value.decode('UTF-8')
        elif name == 'BODY':
            self.kwargs['description'] = value.replace('\\n', '\n')
        elif name == 'CLASS':
            pass
        else:
            super(VNoteParser, self).acceptItem(name, value)

#}

#==============================================================================
#{ Generating iCalendar files.

def VCalFromTask(task, encoding=True, doFold=True):
    ''' This function returns a string representing the task in
        iCalendar format. '''

    encoding = ';ENCODING=QUOTED-PRINTABLE;CHARSET=UTF-8' if encoding else ''
    quote = quoteString if encoding else lambda s: s

    components = []
    components.append('BEGIN:VTODO') # pylint: disable=W0511
    components.append('UID:%s' % task.id().encode('UTF-8'))
    
    if task.creationDateTime() > date.DateTime.min:
        components.append('CREATED:%s' % fmtDateTime(task.creationDateTime()))
        
    if task.modificationDateTime() > date.DateTime.min:
        components.append('LAST-MODIFIED:%s' % fmtDateTime(task.modificationDateTime()))

    if task.plannedStartDateTime() != date.DateTime():
        components.append('DTSTART:%s' % fmtDateTime(task.plannedStartDateTime()))

    if task.dueDateTime() != date.DateTime():
        components.append('DUE:%s' % fmtDateTime(task.dueDateTime()))

    if task.completionDateTime() != date.DateTime():
        components.append('COMPLETED:%s' % fmtDateTime(task.completionDateTime()))

    if task.categories(recursive=True, upwards=True):
        categories = ','.join([quote(unicode(c)) for c in task.categories(recursive=True, upwards=True)])
        components.append('CATEGORIES%s:%s' % (encoding, categories))

    if task.completed():
        components.append('STATUS:COMPLETED')
    elif task.active():
        components.append('STATUS:NEEDS-ACTION')
    else:
        components.append('STATUS:CANCELLED') # Hum...

    components.append('DESCRIPTION%s:%s' % (encoding, quote(task.description())))
    components.append('PRIORITY:%d' % min(3, task.priority() + 1))
    components.append('PERCENT-COMPLETE:%d' % task.percentageComplete())
    components.append('SUMMARY%s:%s' % (encoding, quote(task.subject())))
    components.append('END:VTODO')  # pylint: disable=W0511
    if doFold:
        return fold(components)
    return '\r\n'.join(components) + '\r\n'


def VCalFromEffort(effort, encoding=True, doFold=True):
    encoding = ';ENCODING=QUOTED-PRINTABLE;CHARSET=UTF-8' if encoding else ''
    quote = quoteString if encoding else lambda s: s
    components = []
    components.append('BEGIN:VEVENT')
    components.append('UID:%s' % effort.id().encode('UTF-8'))
    components.append('SUMMARY%s:%s'%(encoding, quote(effort.subject())))
    components.append('DESCRIPTION%s:%s'%(encoding, quote(effort.description())))
    components.append('DTSTART:%s'%fmtDateTime(effort.getStart()))
    if effort.getStop():
        components.append('DTEND:%s'%fmtDateTime(effort.getStop()))
    components.append('END:VEVENT')
    if doFold:
        return fold(components)
    return '\r\n'.join(components) + '\r\n'


def VNoteFromNote(note, encoding=True, doFold=True):
    encoding = ';ENCODING=QUOTED-PRINTABLE;CHARSET=UTF-8' if encoding else ''
    quote = quoteString if encoding else lambda s: s
    components = []
    components.append('BEGIN:VNOTE')
    components.append('X-IRMC-LUID: %s' % note.id().encode('UTF-8'))
    components.append('SUMMARY%s: %s' % (encoding, quote(note.subject())))
    components.append('BODY%s:%s' % (encoding, quote(note.description())))
    components.append('END:VNOTE')
    if note.categories(recursive=True, upwards=True):
        categories = ','.join([quote(unicode(c)) for c in note.categories(recursive=True, upwards=True)])
        components.append('CATEGORIES%s:%s'%(encoding, categories))
    if doFold:
        return fold(components)
    return '\r\n'.join(components) + '\r\n'

#}

def fold(components, linewidth=75, eol='\r\n', indent=' '):
    lines = []
    # The iCalendar standard doesn't clearly state whether the maximum line 
    # width includes the indentation or not. We keep on the safe side:
    indentedlinewidth = linewidth - len(indent)
    for component in components:
        componentLines = component.split('\n')
        firstLine = componentLines[0]
        firstLine, remainderFirstLine = firstLine[:linewidth], firstLine[linewidth:]
        lines.append(firstLine)
        while remainderFirstLine:
            nextLine, remainderFirstLine = remainderFirstLine[:indentedlinewidth], remainderFirstLine[indentedlinewidth:]
            lines.append(indent + nextLine)
        for line in componentLines[1:]:
            nextLine, remainder = line[:linewidth], line[linewidth:]
            lines.append(indent + nextLine)
            while remainder:
                nextLine, remainder = remainder[:indentedlinewidth], remainder[indentedlinewidth:]
                lines.append(indent + nextLine)
    return eol.join(lines) + eol if lines else ''