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:
12 # The above copyright notice and this permission notice shall be included in
13 # all copies or substantial portions of the Software.
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
26 from cgi import parse_header
29 class InvalidICS(Exception): pass
30 class IncompleteICS(InvalidICS): pass
32 def lineJoiner(oldcal, encoding='utf-8'):
33 '''Takes a string containing a calendar and returns an array of its lines'''
35 oldcal = unicode(oldcal, encoding)
36 oldcal = oldcal.replace('\r\n ', '').replace('\r\n\t','')
37 except UnicodeDecodeError:
38 # This is probably a file with badly folded lines
39 oldcal = oldcal.replace('\r\n ', '').replace('\r\n\t','')
40 try: oldcal = unicode(oldcal, encoding)
41 except UnicodeDecodeError:
42 sys.stderr.write('Malformed File')
45 if not oldcal[0:15] == 'BEGIN:VCALENDAR':
46 raise InvalidICS, "Does not appear to be a valid ICS file"
48 if not 'END:VCALENDAR' in oldcal[-15:-1]:
49 raise IncompleteICS, "File appears to be incomplete"
51 if list(oldcal) == oldcal:
52 oldcal = '\r\n'.join(oldcal)
54 return oldcal.split('\r\n')
57 def lineFolder(oldcal, length=75):
58 '''Folds content lines to a specified length, returns a list'''
61 sys.stderr.write('WARN: lines > 75 octets are not RFC compliant\n')
67 line = uline.encode('utf-8')
69 # Line fits inside length, do nothing
70 if len(line) <= length:
77 ufold = unicode(line[0:ll], 'utf-8', 'ignore')
78 fold = ufold.encode('utf-8')
79 uline = uline.replace(ufold,u'',1)
80 line = uline.encode('utf-8')
81 foldedline.append(fold)
83 # Subsequent lines are shorter as they include a space
85 cal.append('\r\n '.join(foldedline))
91 '''Takes a list of lines in a calendar file and returns a list of tuples
92 as (key, value) pairs'''
96 # Check that we got 2 items on every line
97 for line in [tuple(x.split(':',1)) for x in cal]:
98 if not len(line) == 2 and line[0]:
99 raise InvalidICS, 'Unusual content line: %s'%line
106 def joinFields(ical):
107 '''Takes a list of tuples that make up a calendar file and returns it to a
110 return [':'.join(x) for x in ical]
113 def getContent(url='',stdin=False):
114 '''Generic content retriever, DO NOT use this function in a CGI script as
115 it can read from the local disk (which you probably don't want it to).
118 encoding = '' # If we don't populate this, the script will assume UTF-8
120 # Special case, if this is a HTTP url, return the data from it using
121 # the HTTP functions which attempt to play a bit nicer.
122 parsedURL = urlparse.urlparse(url)
123 if 'http' in parsedURL[0]: return getHTTPContent(url)
126 content = sys.stdin.read()
127 return (content, encoding)
129 if not parsedURL[0]: url = 'file://' + os.path.abspath(url)
131 # If we've survived, use python's generic URL opening library to handle it
134 res = urllib2.urlopen(url)
136 ct = res.info().getplist()
138 except (urllib2.URLError, OSError), e:
139 sys.stderr.write('%s\n'%e)
143 if 'charset' in param:
144 encoding = param.split('=')[1]
147 return (content, encoding)
150 def getHTTPContent(url='',cache='.httplib2-cache'):
151 '''This function attempts to play nice when retrieving content from HTTP
152 services. It's what you should use in a CGI script.'''
159 if not url: return ('','')
161 if not 'http' in urlparse.urlparse(url)[0]: return ('','')
163 if 'httplib2' in sys.modules:
164 try: h = httplib2.Http('.httplib2-cache')
165 except OSError: h = httplib2.Http()
171 except ValueError, e:
172 sys.stderr.write('%s\n'%e)
176 if 'content-type' in resp:
177 ct = 'Content-Type: %s'%req[0]['content-type']
178 ct = parse_header(ct)
179 if 'charset' in ct[1]: encoding = ct[1]['charset']
187 req = urllib2.urlopen(url)
188 except urllib2.URLError, e:
189 sys.stderr.write('%s\n'%e)
193 ct = req.info().getplist()
195 if 'charset' in param:
196 encoding = param.split('=')[1]
199 return (content, encoding)
203 '''Attempts to load a series of rules into a list'''
209 rules = [getattr(parserrules, rule) for rule in dir(parserrules) if callable(getattr(parserrules, rule))]
213 def applyRules(ical, rules=[], verbose=False):
214 'Runs a series of rules on the lines in ical and mangles its output'
218 if rule.__doc__ and verbose:
222 out = rule(line[0],line[1])
228 # Drop lines that are boolean False
229 if not out and not out == None: continue
231 # If the rule did something and is a tuple or a list we'll accept it
232 # otherwise, pay no attention to the man behind the curtain
234 if tuple(out) == out or list(out) == out and len(out) == 2:
235 output.append(tuple(out))
246 def writeOutput(cal, outfile=''):
247 '''Takes a list of lines and outputs to the specified file'''
250 sys.stderr.write('Refusing to write out an empty file')
257 out = open(outfile, 'w')
258 except (IOError, OSError), e:
259 sys.stderr.write('%s\n'%e)
262 if cal[-1]: cal.append('')
264 out.write('\r\n'.join(cal))
266 if not out == sys.stdout:
270 def vobjectRules(ics):
271 '''Applies rules to the ICS file before we have our way with it'''
276 sys.stderr.write('Vobject rules file could not be imported\n')
279 for rule in vobjectRules.runRules:
285 if __name__ == '__main__':
286 from optparse import OptionParser
287 # If the user passed us a 'stdin' argument, we'll go with that,
288 # otherwise we'll try for a url opener
290 parser = OptionParser('usage: %prog [options] url')
291 parser.add_option('-s', '--stdin', action='store_true', dest='stdin',
292 default=False, help='Take a calendar from standard input')
293 parser.add_option('-v', '--verbose', action='store_true', dest='verbose',
294 default=False, help='Be verbose when rules are being applied')
295 parser.add_option('-o', '--output', dest='outfile', default='',
296 help='Specify output file (defaults to standard output)')
297 parser.add_option('-m','--encoding', dest='encoding', default='',
298 help='Specify a different character encoding'
299 '(ignored if the remote server also specifies one)')
300 parser.add_option('-r','--vobject-rules',
301 action='store_true', dest='vobject',
302 help='Run rules written for vobject stored in vobjectRules.py')
304 (options, args) = parser.parse_args()
306 if not args and not options.stdin:
309 elif not options.stdin:
314 (content, encoding) = getContent(url, options.stdin)
315 encoding = encoding or options.encoding or 'utf-8'
316 if options.vobject: content = vobjectRules(content)
317 cal = lineJoiner(content, encoding)
318 ical = applyRules(splitFields(cal), generateRules(), options.verbose)
319 output = lineFolder(joinFields(ical))
320 writeOutput(output, options.outfile)