d52ac7e0f476558db2cb4855ef27b8afe6f4a8b2
[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 urlparse
25 import os
26 from cgi import parse_header
27
28
29 class InvalidICS(Exception): pass
30 class IncompleteICS(InvalidICS): pass
31
32 def lineJoiner(oldcal, encoding='utf-8'):
33         '''Takes a string containing a calendar and returns an array of its lines'''
34         try:
35                 oldcal = unicode(oldcal, encoding)
36                 oldcal = oldcal.replace('\r\n ', '').replace('\r\n\t','')
37         except UnicodeDecodeError:
38                 # This is probably a file with badly folded lines
39                 oldcal = oldcal.replace('\r\n ', '').replace('\r\n\t','')
40                 try: oldcal = unicode(oldcal, encoding)
41                 except UnicodeDecodeError:
42                         sys.stderr.write('Malformed File')
43                         raise
44
45         if not oldcal[0:15] == 'BEGIN:VCALENDAR':
46                 raise InvalidICS, "Does not appear to be a valid ICS file"
47
48         if not 'END:VCALENDAR' in oldcal[-15:-1]:
49                 raise IncompleteICS, "File appears to be incomplete"
50
51         if list(oldcal) == oldcal:
52                 oldcal = '\r\n'.join(oldcal)
53
54         return oldcal.split('\r\n')
55
56
57 def lineFolder(oldcal, length=75):
58         '''Folds content lines to a specified length, returns a list'''
59
60         if length > 75:
61                 sys.stderr.write('WARN: lines > 75 octets are not RFC compliant\n')
62
63         cal = []
64         sl = length - 1
65
66         for uline in oldcal:
67                 line = uline.encode('utf-8')
68
69                 # Line fits inside length, do nothing
70                 if len(line) <= length:
71                         cal.append(line)
72
73                 else:
74                         ll = length
75                         foldedline = []
76                         while uline:
77                                 ufold = unicode(line[0:ll], 'utf-8', 'ignore')
78                                 fold = ufold.encode('utf-8')
79                                 uline = uline.replace(ufold,u'',1)
80                                 line = uline.encode('utf-8')
81                                 foldedline.append(fold)
82
83                                 # Subsequent lines are shorter as they include a space
84                                 ll = length - 1
85                         cal.append('\r\n '.join(foldedline))
86
87         return cal
88
89
90 def splitFields(cal):
91         '''Takes a list of lines in a calendar file and returns a list of tuples
92         as (key, value) pairs'''
93
94         ical = []
95
96         # Check that we got 2 items on every line
97         for line in [tuple(x.split(':',1)) for x in cal]:
98                 if not len(line) == 2 and line[0]:
99                         raise InvalidICS, 'Unusual content line: %s'%line
100                 elif line[0]:
101                         ical.append(line)
102
103         return ical
104
105
106 def joinFields(ical):
107         '''Takes a list of tuples that make up a calendar file and returns it to a
108         list of lines'''
109
110         return [':'.join(x) for x in ical]
111
112
113 def getContent(url='',stdin=False):
114         '''Generic content retriever, DO NOT use this function in a CGI script as
115         it can read from the local disk (which you probably don't want it to).
116         '''
117
118         encoding = '' # If we don't populate this, the script will assume UTF-8
119
120         # Special case, if this is a HTTP url, return the data from it using
121         # the HTTP functions which attempt to play a bit nicer.
122         parsedURL = urlparse.urlparse(url)
123         if 'http' in parsedURL[0]: return getHTTPContent(url)
124
125         if stdin:
126                 content = sys.stdin.read()
127                 return (content, encoding)
128
129         if not parsedURL[0]: url = 'file://' + os.path.abspath(url)
130
131         # If we've survived, use python's generic URL opening library to handle it
132         import urllib2
133         try:
134                 res = urllib2.urlopen(url)
135                 content = res.read()
136                 ct = res.info().getplist()
137                 res.close()
138         except (urllib2.URLError, OSError), e:
139                 sys.stderr.write('%s\n'%e)
140                 sys.exit(1)
141
142         for param in ct:
143                 if 'charset' in param:
144                         encoding = param.split('=')[1]
145                         break
146
147         return (content, encoding)
148
149
150 def getHTTPContent(url='',cache='.httplib2-cache'):
151         '''This function attempts to play nice when retrieving content from HTTP
152         services. It's what you should use in a CGI script.'''
153
154         try:
155                 import httplib2
156         except ImportError:
157                 import urllib2
158
159         if not url: return ('','')
160
161         if not 'http' in urlparse.urlparse(url)[0]: return ('','')
162
163         if 'httplib2' in sys.modules:
164                 try: h = httplib2.Http('.httplib2-cache')
165                 except OSError: h = httplib2.Http()
166         else: h = False
167
168         if h:
169                 try:
170                         req = h.request(url)
171                 except ValueError, e:
172                         sys.stderr.write('%s\n'%e)
173                         sys.exit(1)
174
175                 resp, content = req
176                 if 'content-type' in resp:
177                         ct = 'Content-Type: %s'%req[0]['content-type']
178                         ct = parse_header(ct)
179                         if 'charset' in ct[1]: encoding = ct[1]['charset']
180                         else: encoding = ''
181                 else:
182                         ct = ''
183                         encoding = ''
184
185         else:
186                 try:
187                         req = urllib2.urlopen(url)
188                 except urllib2.URLError, e:
189                         sys.stderr.write('%s\n'%e)
190                         sys.exit(1)
191
192                 content = req.read()
193                 ct = req.info().getplist()
194                 for param in ct:
195                         if 'charset' in param:
196                                 encoding = param.split('=')[1]
197                                 break
198
199         return (content, encoding)
200
201
202 def generateRules():
203         '''Attempts to load a series of rules into a list'''
204         try:
205                 import parserrules
206         except ImportError:
207                 return []
208
209         rules = [getattr(parserrules, rule) for rule in dir(parserrules) if callable(getattr(parserrules, rule))]
210         return rules
211
212
213 def applyRules(ical, rules=[], verbose=False):
214         'Runs a series of rules on the lines in ical and mangles its output'
215
216         for rule in rules:
217                 output = []
218                 if rule.__doc__ and verbose:
219                         print(rule.__doc__)
220                 for line in ical:
221                         try:
222                                 out = rule(line[0],line[1])
223                         except TypeError, e:
224                                 output.append(line)
225                                 print(e)
226                                 continue
227
228                         # Drop lines that are boolean False
229                         if not out and not out == None: continue
230
231                         # If the rule did something and is a tuple or a list we'll accept it
232                         # otherwise, pay no attention to the man behind the curtain
233                         try:
234                                 if tuple(out) == out or list(out) == out and len(out) == 2:
235                                         output.append(tuple(out))
236                                 else:
237                                         output.append(line)
238                         except TypeError, e:
239                                 output.append(line)
240
241                 ical = output
242
243         return ical
244
245
246 def writeOutput(cal, outfile=''):
247         '''Takes a list of lines and outputs to the specified file'''
248
249         if not cal:
250                 sys.stderr.write('Refusing to write out an empty file')
251                 sys.exit(0)
252
253         if not outfile:
254                 out = sys.stdout
255         else:
256                 try:
257                         out = open(outfile, 'w')
258                 except (IOError, OSError), e:
259                         sys.stderr.write('%s\n'%e)
260                         sys.exit(1)
261
262         if cal[-1]: cal.append('')
263
264         out.write('\r\n'.join(cal))
265
266         if not out == sys.stdout:
267                 out.close()
268
269
270 if __name__ == '__main__':
271         from optparse import OptionParser
272         # If the user passed us a 'stdin' argument, we'll go with that,
273         # otherwise we'll try for a url opener
274
275         parser = OptionParser('usage: %prog [options] url')
276         parser.add_option('-s', '--stdin', action='store_true', dest='stdin',
277                 default=False, help='Take a calendar from standard input')
278         parser.add_option('-v', '--verbose', action='store_true', dest='verbose',
279                 default=False, help='Be verbose when rules are being applied')
280         parser.add_option('-o', '--output', dest='outfile', default='',
281                 help='Specify output file (defaults to standard output)')
282         parser.add_option('-m','--encoding', dest='encoding', default='',
283                 help='Specify a different character encoding'
284                 '(ignored if the remote server also specifies one)')
285
286         (options, args) = parser.parse_args()
287
288         if not args and not options.stdin:
289                 parser.print_usage()
290                 sys.exit(0)
291         elif not options.stdin:
292                 url = args[0]
293         else:
294                 url = ''
295
296         (content, encoding) = getContent(url, options.stdin)
297         encoding = encoding or options.encoding or 'utf-8'
298         cal = lineJoiner(content, encoding)
299         ical = applyRules(splitFields(cal), generateRules(), options.verbose)
300         output = lineFolder(joinFields(ical))
301         writeOutput(output, options.outfile)

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