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

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