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
27 from cgi import parse_header
29 def getContent(url='',stdin=False):
30 '''Generic content retriever, DO NOT use this function in a CGI script as
31 it can read from the local disk (which you probably don't want it to).
34 encoding = '' # If we don't populate this, the script will assume UTF-8
36 # Special case, if this is a HTTP url, return the data from it using
37 # the HTTP functions which attempt to play a bit nicer.
38 parsedURL = urlparse.urlparse(url)
39 if 'http' in parsedURL[0]: return getHTTPContent(url)
42 content = sys.stdin.read()
43 return (content, encoding)
45 if not parsedURL[0]: url = 'file://' + os.path.abspath(url)
47 # If we've survived, use python's generic URL opening library to handle it
50 res = urllib2.urlopen(url)
52 ct = res.info().getplist()
54 except (urllib2.URLError, OSError), e:
55 sys.stderr.write('%s\n'%e)
59 if 'charset' in param:
60 encoding = param.split('=')[1]
63 return (content, encoding)
66 def getHTTPContent(url='',cache='.httplib2-cache'):
67 '''This function attempts to play nice when retrieving content from HTTP
68 services. It's what you should use in a CGI script.'''
75 if not url: return ('','')
77 if not 'http' in urlparse.urlparse(url)[0]: return ('','')
79 if 'httplib2' in sys.modules:
80 try: h = httplib2.Http('.httplib2-cache')
81 except OSError: h = httplib2.Http()
88 sys.stderr.write('%s\n'%e)
92 if 'content-type' in resp:
93 ct = 'Content-Type: %s'%req[0]['content-type']
95 if 'charset' in ct[1]: encoding = ct[1]['charset']
103 req = urllib2.urlopen(url)
104 except urllib2.URLError, e:
105 sys.stderr.write('%s\n'%e)
109 ct = req.info().getplist()
111 if 'charset' in param:
112 encoding = param.split('=')[1]
115 return (content, encoding)
118 def generateRules(ruleConfig):
119 '''Attempts to load a series of rules into a list'''
125 for conf in ruleConfig:
126 parserrules.ruleConfig[conf] = ruleConfig[conf]
128 rules = [getattr(parserrules, rule) for rule in dir(parserrules) if callable(getattr(parserrules, rule))]
132 def applyRules(cal, rules=[], verbose=False):
133 'Runs a series of rules on the lines in ical and mangles its output'
140 def writeOutput(cal, outfile=''):
141 '''Takes a list of lines and outputs to the specified file'''
144 sys.stderr.write('Refusing to write out an empty file')
151 out = open(outfile, 'w')
152 except (IOError, OSError), e:
153 sys.stderr.write('%s\n'%e)
158 if not out == sys.stdout:
161 def exitQuiet(exitstate=0):
162 '''When called as a CGI script, exit quietly if theres any errors'''
163 print('Content-Type: text/html\n')
167 '''Main run function if this script is called locally'''
169 from optparse import OptionParser
171 parser = OptionParser('usage: %prog [options] url')
172 parser.add_option('-s', '--stdin', action='store_true', dest='stdin',
173 default=False, help='Take a calendar from standard input')
174 parser.add_option('-v', '--verbose', action='store_true', dest='verbose',
175 default=False, help='Be verbose when rules are being applied')
176 parser.add_option('-o', '--output', dest='outfile', default='',
177 help='Specify output file (defaults to standard output)')
178 parser.add_option('-m','--encoding', dest='encoding', default='',
179 help='Specify a different character encoding'
180 '(ignored if the remote server also specifies one)')
181 parser.add_option('-t','--timezone', dest='timezone', default=ruleConfig["defaultTZ"],
182 help='Specify a timezone to use if the remote calendar doesn\'t set it properly')
184 (options, args) = parser.parse_args()
185 ruleConfig["defaultTZ"] = options.timezone
187 # If the user passed us a 'stdin' argument, we'll go with that,
188 # otherwise we'll try for a url opener
189 if not args and not options.stdin:
192 elif not options.stdin:
197 (content, encoding) = getContent(url, options.stdin)
198 encoding = encoding or options.encoding or 'utf-8'
200 cal = vobject.readOne(unicode(content, encoding))
201 cal = applyRules(cal, generateRules(ruleConfig), options.verbose)
203 writeOutput(cal, options.outfile)
207 '''Main run function if this script is called as a CGI script'''
210 if __name__ == '__main__':
211 # Ensure the rules process using the desired timezone
213 ruleConfig["defaultTZ"] = 'Australia/Perth'
215 # Detect if this script has been called by CGI and proceed accordingly
216 if 'REQUEST_METHOD' in os.environ: