A step closer to real unicode support
[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):
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, 'utf-8') 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:75], '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         # Special case, if this is a HTTP url, return the data from it using
117         # the HTTP functions which attempt to play a bit nicer.
118         parsedURL = urlparse.urlparse(url)
119         if 'http' in parsedURL[0]: return getHTTPContent(url)
120
121         if stdin:
122                 content = sys.stdin.read()
123                 return content
124
125         if not parsedURL[0]:
126                 try: content = open(os.path.abspath(url),'r').read()
127                 except (IOError, OSError), e:
128                         sys.stderr.write('%s\n'%e)
129                         sys.exit(1)
130                 return content
131
132         # If we've survived, use python's generic URL opening library to handle it
133         import urllib2
134         try:
135                 res = urllib2.urlopen(url)
136                 content = res.read()
137                 res.close()
138         except (urllib2.URLError, OSError), e:
139                 sys.stderr.write('%s\n'%e)
140                 sys.exit(1)
141         return content
142
143
144 def getHTTPContent(url='',cache='.httplib2-cache'):
145         '''This function attempts to play nice when retrieving content from HTTP
146         services. It's what you should use in a CGI script.'''
147
148         try:
149                 import httplib2
150         except ImportError:
151                 import urllib2
152
153         if not url: return ''
154
155         if 'httplib2' in sys.modules:
156                 try: h = httplib2.Http('.httplib2-cache')
157                 except OSError: h = httplib2.Http()
158         else: h = False
159
160         try:
161                 if h: content = h.request(url)[1]
162                 return content
163         except ValueError, e:
164                 sys.stderr.write('%s\n'%e)
165                 sys.exit(1)
166
167         try:
168                 content = urllib2.urlopen(url).read()
169                 return content
170         except (urllib2.URLError, OSError), e:
171                 sys.stderr.write('%s\n'%e)
172                 sys.exit(1)
173
174         return ''
175
176
177 def generateRules():
178         '''Attempts to load a series of rules into a list'''
179         try:
180                 import parserrules
181         except ImportError:
182                 return []
183
184         rules = [getattr(parserrules, rule) for rule in dir(parserrules) if callable(getattr(parserrules, rule))]
185         return rules
186
187
188 def applyRules(ical, rules=[], verbose=False):
189         'Runs a series of rules on the lines in ical and mangles its output'
190
191         for rule in rules:
192                 output = []
193                 if rule.__doc__ and verbose:
194                         print(rule.__doc__)
195                 for line in ical:
196                         try:
197                                 out = rule(line[0],line[1])
198                         except TypeError, e:
199                                 output.append(line)
200                                 print(e)
201                                 continue
202
203                         # Drop lines that are boolean False
204                         if not out and not out == None: continue
205
206                         # If the rule did something and is a tuple or a list we'll accept it
207                         # otherwise, pay no attention to the man behind the curtain
208                         try:
209                                 if tuple(out) == out or list(out) == out and len(out) == 2:
210                                         output.append(tuple(out))
211                                 else:
212                                         output.append(line)
213                         except TypeError, e:
214                                 output.append(line)
215
216                 ical = output
217
218         return ical
219
220
221 def writeOutput(cal, outfile=''):
222         '''Takes a list of lines and outputs to the specified file'''
223
224         if not cal:
225                 sys.stderr.write('Refusing to write out an empty file')
226                 sys.exit(0)
227
228         if not outfile:
229                 out = sys.stdout
230         else:
231                 try:
232                         out = open(outfile, 'w')
233                 except (IOError, OSError), e:
234                         sys.stderr.write('%s\n'%e)
235                         sys.exit(1)
236
237         if cal[-1]: cal.append('')
238
239         out.write('\r\n'.join(cal))
240
241         if not out == sys.stdout:
242                 out.close()
243
244
245 if __name__ == '__main__':
246         from optparse import OptionParser
247         # If the user passed us a 'stdin' argument, we'll go with that,
248         # otherwise we'll try for a url opener
249
250         parser = OptionParser('usage: %prog [options] url')
251         parser.add_option('-s', '--stdin', action='store_true', dest='stdin',
252                 default=False, help='Take a calendar from standard input')
253         parser.add_option('-v', '--verbose', action='store_true', dest='verbose',
254                 default=False, help='Be verbose when rules are being applied')
255         parser.add_option('-o', '--output', dest='outfile', default='',
256                 help='Specify output file (defaults to standard output)')
257
258         (options, args) = parser.parse_args()
259
260         if not args and not options.stdin:
261                 parser.print_usage()
262                 sys.exit(0)
263         elif not options.stdin:
264                 url = args[0]
265         else:
266                 url = ''
267
268         content = getContent(url, options.stdin)
269         cal = lineJoiner(content)
270         ical = applyRules(splitFields(cal), generateRules(), options.verbose)
271         output = lineFolder(joinFields(ical))
272         writeOutput(output, options.outfile)

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