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
24 from urllib import (request, error, parse)
26 from cgi import parse_header
28 def getContent(url='',stdin=False):
29 '''Generic content retriever, DO NOT use this function in a CGI script as
30 it can read from the local disk (which you probably don't want it to).
33 encoding = '' # If we don't populate this, the script will assume UTF-8
35 # Special case, if this is a HTTP url, return the data from it using
36 # the HTTP functions which attempt to play a bit nicer.
37 parsedURL = parse.urlparse(url)
38 if 'http' in parsedURL[0]: return getHTTPContent(url)
41 content = sys.stdin.read()
42 return (content, encoding)
44 if not parsedURL[0]: url = 'file://' + os.path.abspath(url)
46 # If we've survived, use python's generic URL opening library to handle it
48 res = request.urlopen(url)
50 ct = res.info().getplist()
52 except (error.URLError, OSError) as e:
53 sys.stderr.write('%s\n'%e)
57 if 'charset' in param:
58 encoding = param.split('=')[1]
61 return (content, encoding)
64 def getHTTPContent(url=''):
65 '''This function attempts to play nice when retrieving content from HTTP
66 services. It's what you should use in a CGI script.'''
73 if not url: return ('','')
75 if not 'http' in parse.urlparse(url)[0]: return ('','')
77 if 'httplib2' in sys.modules:
78 try: h = httplib2.Http()
79 except OSError: h = httplib2.Http()
85 except ValueError as e:
86 sys.stderr.write('%s\n'%e)
90 if 'content-type' in resp:
91 ct = 'Content-Type: %s'%req[0]['content-type']
93 if 'charset' in ct[1]: encoding = ct[1]['charset']
101 req = request.urlopen(url)
102 except error.URLError as e:
103 sys.stderr.write('%s\n'%e)
107 ct = req.info().getplist()
109 if 'charset' in param:
110 encoding = param.split('=')[1]
113 return (content, encoding)
116 def generateRules(ruleConfig):
117 '''Attempts to load a series of rules into a list'''
123 for conf in ruleConfig:
124 parserrules.ruleConfig[conf] = ruleConfig[conf]
126 rules = [getattr(parserrules, rule) for rule in dir(parserrules) if callable(getattr(parserrules, rule))]
131 def applyRules(cal, rules=[], verbose=False):
132 '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) as e:
153 sys.stderr.write('%s\n'%e)
158 if not out == sys.stdout:
163 '''Main run function if this script is called locally'''
165 from optparse import OptionParser
167 parser = OptionParser('usage: %prog [options] url')
168 parser.add_option('-s', '--stdin', action='store_true', dest='stdin',
169 default=False, help='Take a calendar from standard input')
170 parser.add_option('-v', '--verbose', action='store_true', dest='verbose',
171 default=False, help='Be verbose when rules are being applied')
172 parser.add_option('-o', '--output', dest='outfile', default='',
173 help='Specify output file (defaults to standard output)')
174 parser.add_option('-m','--encoding', dest='encoding', default='',
175 help='Specify a different character encoding'
176 '(ignored if the remote server also specifies one)')
177 parser.add_option('-t','--timezone', dest='timezone', default='',
178 help='Specify a timezone to use if the remote calendar doesn\'t set it properly')
180 (options, args) = parser.parse_args()
181 ruleConfig["defaultTZ"] = options.timezone or ruleConfig["defaultTZ"]
183 # If the user passed us a 'stdin' argument, we'll go with that,
184 # otherwise we'll try for a url opener
185 if not args and not options.stdin:
188 elif not options.stdin:
193 (content, encoding) = getContent(url, options.stdin)
194 encoding = encoding or options.encoding or 'utf-8'
196 cal = vobject.readOne(str(content, encoding))
197 cal = applyRules(cal, generateRules(ruleConfig), options.verbose)
199 writeOutput(cal, options.outfile)
202 def exitQuiet(exitstate=0):
203 '''When called as a CGI script, exit quietly if theres any errors'''
204 print('Content-Type: text/html\n')
209 '''Main run function if this script is called as a CGI script
210 to process facebook ical files'''
213 import cgitb; cgitb.enable()
215 ruleConfig["facebook"] = True
217 form = cgi.FieldStorage()
218 if "uid" not in form or "key" not in form:
219 print('Content-Type: text/calendar\n')
222 # UID should be numeric, if it's not we have someone playing games
223 uid = int(form['uid'].value)
227 # The user's key will be a 16 character string
228 key = form['key'].value
229 re.search('[&?]+', key) and exitQuiet()
230 len(key) == 16 or exitQuiet()
232 # Historically facebook has been notoriously bad at setting timzeones
233 # in their stuff so this should be a user setting. If it is set in
234 # their calendar it'll be used otherwise if the user feeds crap or
235 # nothing just assume they want Australia/Perth
238 from pytz import timezone
240 timezone(form['tz'].value)
241 tz = form['tz'].value
244 ruleConfig["defaultTZ"] = tz or ruleConfig["defaultTZ"]
246 # Okay, we're happy that the input is sane, lets serve up some data
247 url = 'https://www.facebook.com/events/ical/upcoming/?uid=%s&key=%s'%(uid,key)
248 (content, encoding) = getHTTPContent(url)
250 cal = vobject.readOne(str(content, encoding))
251 cal = applyRules(cal, generateRules(ruleConfig), False)
253 print(('Content-Type: text/calendar; charset=%s\n'%encoding))
257 if __name__ == '__main__':
258 # Ensure the rules process using the desired timezone
260 ruleConfig["defaultTZ"] = 'Australia/Perth'
262 # Detect if this script has been called by CGI and proceed accordingly
263 if 'REQUEST_METHOD' in os.environ: