edfca4c6ee7a70a4ae6c16e8124a6b5b4cd2270c
[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 line in oldcal:
57                 line = line.encode('utf-8')
58                 # Line fits inside length, do nothing
59                 if len(line.rstrip()) <= length:
60                         cal.append(line)
61                 else:
62                         brokenline = [line[0:length]]
63                         ll = length
64                         while ll < len(line) + 1:
65                                 brokenline.append(line[ll:sl+ll])
66                                 ll += sl
67                         brokenline = '\r\n '.join(brokenline)
68                         cal.append(brokenline)
69
70         return cal
71
72
73 def splitFields(cal):
74         '''Takes a list of lines in a calendar file and returns a list of tuples        
75         as (key, value) pairs'''
76
77         ical = [tuple(x.split(':',1)) for x in cal]
78
79         # Check that we got 2 items on every line
80         for line in ical:
81                 if not len(line) == 2:
82                         raise InvalidICS, "Didn't find a content key on: %s"%(line)
83
84         return ical
85
86
87 def joinFields(ical):
88         '''Takes a list of tuples that make up a calendar file and returns it to a
89         list of lines'''
90
91         return [':'.join(x) for x in ical]
92
93
94 def getContent(url='',stdin=False):
95         '''Generic content retriever, DO NOT use this function in a CGI script as
96         it can read from the local disk (which you probably don't want it to).
97         '''
98
99         # Special case, if this is a HTTP url, return the data from it using
100         # the HTTP functions which attempt to play a bit nicer.
101         parsedURL = urlparse.urlparse(url)
102         if 'http' in parsedURL[0]: return getHTTPContent(url)
103
104         if stdin:
105                 content = sys.stdin.read()
106                 return content
107
108         if not parsedURL[0]:
109                 try: content = open(os.path.abspath(url),'r').read()
110                 except (IOError, OSError), e:
111                         sys.stderr.write('%s\n'%e)
112                         sys.exit(1)
113                 return content
114
115         # If we've survived, use python's generic URL opening library to handle it
116         import urllib2
117         try:
118                 res = urllib2.urlopen(url)
119                 content = res.read()
120                 res.close()
121         except (urllib2.URLError, OSError), e:
122                 sys.stderr.write('%s\n'%e)
123                 sys.exit(1)
124         return content
125
126
127 def getHTTPContent(url='',cache='.httplib2-cache'):
128         '''This function attempts to play nice when retrieving content from HTTP
129         services. It's what you should use in a CGI script.'''
130
131         try:
132                 import httplib2
133         except ImportError:
134                 import urllib2
135
136         if not url: return ''
137
138         if 'httplib2' in sys.modules:
139                 try: h = httplib2.Http('.httplib2-cache')
140                 except OSError: h = httplib2.Http()
141         else: h = False
142
143         try:
144                 if h: content = h.request(url)[1]
145                 return content
146         except ValueError, e:
147                 sys.stderr.write('%s\n'%e)
148                 sys.exit(1)
149
150         try:
151                 content = urllib2.urlopen(url).read()
152                 return content
153         except (urllib2.URLError, OSError), e:
154                 sys.stderr.write('%s\n'%e)
155                 sys.exit(1)
156
157         return ''
158
159
160 def generateRules():
161         '''Attempts to load a series of rules into a list'''
162         try:
163                 import parserrules
164         except ImportError:
165                 return []
166
167         rules = [getattr(parserrules, rule) for rule in dir(parserrules) if callable(getattr(parserrules, rule))]
168         return rules
169
170
171 def applyRules(ical, rules=[], verbose=False):
172         'Runs a series of rules on the lines in ical and mangles its output'
173
174         for rule in rules:
175                 output = []
176                 if rule.__doc__ and verbose:
177                         print(rule.__doc__)
178                 for line in ical:
179                         try:
180                                 out = rule(line[0],line[1])
181                         except TypeError, e:
182                                 output.append(line)
183                                 print(e)
184                                 continue
185
186                         # Drop lines that are boolean False
187                         if not out and not out == None: continue
188
189                         # If the rule did something and is a tuple or a list we'll accept it
190                         # otherwise, pay no attention to the man behind the curtain
191                         try:
192                                 if tuple(out) == out or list(out) == out and len(out) == 2:
193                                         output.append(tuple(out))
194                                 else:
195                                         output.append(line)
196                         except TypeError, e:
197                                 output.append(line)
198
199                 ical = output
200
201         return ical
202
203
204 def writeOutput(cal, outfile=''):
205         '''Takes a list of lines and outputs to the specified file'''
206
207         if not cal:
208                 sys.stderr.write('Refusing to write out an empty file')
209                 sys.exit(0)
210
211         if not outfile:
212                 out = sys.stdout
213         else:
214                 try:
215                         out = open(outfile, 'w')
216                 except (IOError, OSError), e:
217                         sys.stderr.write('%s\n'%e)
218                         sys.exit(1)
219
220         if cal[-1]: cal.append('')
221
222         out.write('\r\n'.join(cal))
223
224         if not out == sys.stdout:
225                 out.close()
226
227
228 if __name__ == '__main__':
229         from optparse import OptionParser
230         # If the user passed us a 'stdin' argument, we'll go with that,
231         # otherwise we'll try for a url opener
232
233         parser = OptionParser('usage: %prog [options] url')
234         parser.add_option('-s', '--stdin', action='store_true', dest='stdin',
235                 default=False, help='Take a calendar from standard input')
236         parser.add_option('-v', '--verbose', action='store_true', dest='verbose',
237                 default=False, help='Be verbose when rules are being applied')
238         parser.add_option('-o', '--output', dest='outfile', default='',
239                 help='Specify output file (defaults to standard output)')
240
241         (options, args) = parser.parse_args()
242
243         if not args and not options.stdin:
244                 parser.print_usage()
245                 sys.exit(0)
246         elif not options.stdin:
247                 url = args[0]
248         else:
249                 url = ''
250
251         content = getContent(url, options.stdin)
252         cal = lineJoiner(content)
253         ical = applyRules(splitFields(cal), generateRules(), options.verbose)
254         output = lineFolder(joinFields(ical))
255         writeOutput(output, options.outfile)

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