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
28 class InvalidICS(Exception): pass
29 class IncompleteICS(InvalidICS): pass
31 def lineJoiner(oldcal, encoding='utf-8'):
32 '''Takes a string containing a calendar and returns an array of its lines'''
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')
44 if not oldcal[0:15] == 'BEGIN:VCALENDAR':
45 raise InvalidICS, "Does not appear to be a valid ICS file"
47 if not 'END:VCALENDAR' in oldcal[-15:-1]:
48 raise IncompleteICS, "File appears to be incomplete"
50 if list(oldcal) == oldcal:
51 oldcal = '\r\n'.join(oldcal)
53 return oldcal.split('\r\n')
56 def lineFolder(oldcal, length=75):
57 '''Folds content lines to a specified length, returns a list'''
60 sys.stderr.write('WARN: lines > 75 octets are not RFC compliant\n')
66 line = uline.encode('utf-8')
68 # Line fits inside length, do nothing
69 if len(line) <= length:
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)
82 # Subsequent lines are shorter as they include a space
84 cal.append('\r\n '.join(foldedline))
90 '''Takes a list of lines in a calendar file and returns a list of tuples
91 as (key, value) pairs'''
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
105 def joinFields(ical):
106 '''Takes a list of tuples that make up a calendar file and returns it to a
109 return [':'.join(x) for x in ical]
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).
117 encoding = '' # If we don't populate this, the script will assume UTF-8
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)
125 content = sys.stdin.read()
126 return (content, encoding)
129 try: content = open(os.path.abspath(url),'r').read()
130 except (IOError, OSError), e:
131 sys.stderr.write('%s\n'%e)
133 return (content, encoding)
135 # If we've survived, use python's generic URL opening library to handle it
138 res = urllib2.urlopen(url)
141 except (urllib2.URLError, OSError), e:
142 sys.stderr.write('%s\n'%e)
144 return (content, encoding)
147 def getHTTPContent(url='',cache='.httplib2-cache'):
148 '''This function attempts to play nice when retrieving content from HTTP
149 services. It's what you should use in a CGI script.'''
156 if not url: return ''
158 encoding = '' # If we don't populate this, the script will assume UTF-8
160 if 'httplib2' in sys.modules:
161 try: h = httplib2.Http('.httplib2-cache')
162 except OSError: h = httplib2.Http()
169 if 'content-type' in req[0]:
170 for ct in req[0]['content-type'].split(';'):
173 encoding = ct.split('=')[1].strip()
174 return (content, encoding)
175 except ValueError, e:
176 sys.stderr.write('%s\n'%e)
180 content = urllib2.urlopen(url).read()
181 return (content, encoding)
182 except (urllib2.URLError, OSError), e:
183 sys.stderr.write('%s\n'%e)
190 '''Attempts to load a series of rules into a list'''
196 rules = [getattr(parserrules, rule) for rule in dir(parserrules) if callable(getattr(parserrules, rule))]
200 def applyRules(ical, rules=[], verbose=False):
201 'Runs a series of rules on the lines in ical and mangles its output'
205 if rule.__doc__ and verbose:
209 out = rule(line[0],line[1])
215 # Drop lines that are boolean False
216 if not out and not out == None: continue
218 # If the rule did something and is a tuple or a list we'll accept it
219 # otherwise, pay no attention to the man behind the curtain
221 if tuple(out) == out or list(out) == out and len(out) == 2:
222 output.append(tuple(out))
233 def writeOutput(cal, outfile=''):
234 '''Takes a list of lines and outputs to the specified file'''
237 sys.stderr.write('Refusing to write out an empty file')
244 out = open(outfile, 'w')
245 except (IOError, OSError), e:
246 sys.stderr.write('%s\n'%e)
249 if cal[-1]: cal.append('')
251 out.write('\r\n'.join(cal))
253 if not out == sys.stdout:
257 if __name__ == '__main__':
258 from optparse import OptionParser
259 # If the user passed us a 'stdin' argument, we'll go with that,
260 # otherwise we'll try for a url opener
262 parser = OptionParser('usage: %prog [options] url')
263 parser.add_option('-s', '--stdin', action='store_true', dest='stdin',
264 default=False, help='Take a calendar from standard input')
265 parser.add_option('-v', '--verbose', action='store_true', dest='verbose',
266 default=False, help='Be verbose when rules are being applied')
267 parser.add_option('-o', '--output', dest='outfile', default='',
268 help='Specify output file (defaults to standard output)')
269 parser.add_option('-m','--encoding', dest='encoding', default='',
270 help='Specify a different character encoding'
271 '(ignored if the remote server also specifies one)')
273 (options, args) = parser.parse_args()
275 if not args and not options.stdin:
278 elif not options.stdin:
283 (content, encoding) = getContent(url, options.stdin)
284 encoding = encoding or options.encoding or 'utf-8'
285 cal = lineJoiner(content, encoding)
286 ical = applyRules(splitFields(cal), generateRules(), options.verbose)
287 output = lineFolder(joinFields(ical))
288 writeOutput(output, options.outfile)