Replaced getopt with optparse (which will need to be replaced again)
[frenchie/icalparse.git] / icalparse.py
1 #!/usr/bin/python
2 #
3 # Copyright (c) 2010 James French <[email protected]>
4 #
5 # Permission is hereby granted, free of charge, to any person obtaining a copy
6 # of this software and associated documentation files (the "Software"), to deal
7 # in the Software without restriction, including without limitation the rights
8 # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9 # copies of the Software, and to permit persons to whom the Software is
10 # furnished to do so, subject to the following conditions:
11 #
12 # The above copyright notice and this permission notice shall be included in
13 # all copies or substantial portions of the Software.
14 #
15 # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16 # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17 # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18 # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19 # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20 # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
21 # THE SOFTWARE.
22
23 import sys
24 import re
25 from optparse import OptionParser
26
27 class InvalidICS(Exception): pass
28 class notJoined(Exception): pass
29
30 # RFC5545 and RFC5546 iCalendar registries contain upper case letters
31 # and dashes only and are separated from the value by a colon (:)
32 icalEntry = re.compile('^[A-Z\-]+:.*')
33
34 def lineJoiner(oldcal):
35         '''Unfolds a calendar so that items can be parsed'''
36
37         cal = []
38
39         # Strip newlines (
40         for line in oldcal:
41                 line = line.rstrip('\r\n')
42
43                 # Reassemble broken Lines
44                 if not line:
45                         if not cal: continue
46                         else: cal[-1] += '\\n'
47                 elif line[0] == ' ':
48                         if not cal: raise InvalidICS, 'First line of ICS must be element'
49                         line = line[1:len(line)]
50                         cal[-1] += line
51                 elif not icalEntry.match(line):
52                         if not cal: raise InvalidICS, 'First line of ICS must be element'
53                         cal[-1] += '\\n' + line
54                 else:
55                         if cal: cal[-1] += '\r\n'
56                         cal.append(line)
57
58         cal[-1] += '\r\n'
59
60         return cal
61
62 def lineSplitter(oldcal, length=75):
63         '''Folds content lines to a specified length, returns a list'''
64
65         cal = []
66         sl = length - 1
67
68         for line in oldcal:
69                 # Line & line ending line ending fit inside length, do nothing
70                 if len(line.rstrip()) <= length:
71                         cal.append(line)
72                 else:
73                         brokenline = [line[0:length] + '\r\n']
74                         ll = length
75                         while ll < len(line.rstrip('\r\n')) + 1:
76                                 brokenline.append(' ' + line[ll:sl+ll].rstrip('\r\n') + '\r\n')
77                                 ll += sl
78                         cal += brokenline
79
80         return cal
81
82 if __name__ == '__main__':
83         # If the user passed us a 'stdin' argument, we'll go with that,
84         # otherwise we'll try for a url opener
85
86         parser = OptionParser()
87         parser.add_option('-s', '--stdin', action='store_true', dest='stdin',
88                 default=False, help='Take a calendar from standard input')
89         parser.add_option('-o', '--output', dest='outfile', default='',
90                 help='Specify output file (defaults to standard output)')
91
92         (options, args) = parser.parse_args()
93
94         if not options.stdin:
95                 try:
96                         import httplib2
97                         urllib = False
98                 except ImportError:
99                         try:
100                                 import urllib
101                                 urllib = True
102                         except ImportError:
103                                 sys.stderr.write('Failed to find a suitable http downloader\n')
104                                 raise
105

UCC git Repository :: git.ucc.asn.au