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

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