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

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