c5d469e9feb14b2976addac2086c5b3ef04b4a73
[frenchie/icalparse.git] / icalparse.py
1 #!/usr/bin/python3
2 #
3 # Copyright (c) 2013 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, os
24 from urllib import (request, error, parse)
25 import vobject
26 from cgi import parse_header
27
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).
31         '''
32
33         encoding = '' # If we don't populate this, the script will assume UTF-8
34
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)
39
40         if stdin:
41                 content = sys.stdin.read()
42                 return (content, encoding)
43
44         if not parsedURL[0]: url = 'file://' + os.path.abspath(url)
45
46         # If we've survived, use python's generic URL opening library to handle it
47         try:
48                 res = request.urlopen(url)
49                 content = res.read()
50                 ct = res.info().getplist()
51                 res.close()
52         except (error.URLError, OSError) as e:
53                 sys.stderr.write('%s\n'%e)
54                 sys.exit(1)
55
56         for param in ct:
57                 if 'charset' in param:
58                         encoding = param.split('=')[1]
59                         break
60
61         return (content, encoding)
62
63
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.'''
67
68         try:
69                 import httplib2
70         except ImportError:
71             pass
72
73         if not url: return ('','')
74
75         if not 'http' in parse.urlparse(url)[0]: return ('','')
76
77         if 'httplib2' in sys.modules:
78                 try: h = httplib2.Http()
79                 except OSError: h = httplib2.Http()
80         else: h = False
81
82         if h:
83                 try:
84                         req = h.request(url)
85                 except ValueError as e:
86                         sys.stderr.write('%s\n'%e)
87                         sys.exit(1)
88
89                 resp, content = req
90                 if 'content-type' in resp:
91                         ct = 'Content-Type: %s'%req[0]['content-type']
92                         ct = parse_header(ct)
93                         if 'charset' in ct[1]: encoding = ct[1]['charset']
94                         else: encoding = ''
95                 else:
96                         ct = ''
97                         encoding = ''
98
99         else:
100                 try:
101                         req = request.urlopen(url)
102                 except error.URLError as e:
103                         sys.stderr.write('%s\n'%e)
104                         sys.exit(1)
105
106                 content = req.read()
107                 ct = req.info().getplist()
108                 for param in ct:
109                         if 'charset' in param:
110                                 encoding = param.split('=')[1]
111                                 break
112
113         return (content, encoding)
114
115
116 def generateRules(ruleConfig):
117         '''Attempts to load a series of rules into a list'''
118         try:
119                 import parserrules
120         except ImportError:
121                 return []
122
123         for conf in ruleConfig:
124                 parserrules.ruleConfig[conf] = ruleConfig[conf]
125
126         rules = [getattr(parserrules, rule) for rule in dir(parserrules) if callable(getattr(parserrules, rule))]
127         return rules
128
129
130 def applyRules(cal, rules=[], verbose=False):
131         'Runs a series of rules on the lines in ical and mangles its output'
132
133         for rule in rules:
134                 cal = rule(cal)
135
136         return cal
137
138
139 def writeOutput(cal, outfile=''):
140         '''Takes a list of lines and outputs to the specified file'''
141
142         if not cal:
143                 sys.stderr.write('Refusing to write out an empty file')
144                 sys.exit(0)
145
146         if not outfile:
147                 out = sys.stdout
148         else:
149                 try:
150                         out = open(outfile, 'w')
151                 except (IOError, OSError) as e:
152                         sys.stderr.write('%s\n'%e)
153                         sys.exit(1)
154
155         cal.serialize(out)
156
157         if not out == sys.stdout:
158                 out.close()
159
160
161 def runLocal():
162         '''Main run function if this script is called locally'''
163
164         from optparse import OptionParser
165
166         parser = OptionParser('usage: %prog [options] url')
167         parser.add_option('-s', '--stdin', action='store_true', dest='stdin',
168                 default=False, help='Take a calendar from standard input')
169         parser.add_option('-v', '--verbose', action='store_true', dest='verbose',
170                 default=False, help='Be verbose when rules are being applied')
171         parser.add_option('-o', '--output', dest='outfile', default='',
172                 help='Specify output file (defaults to standard output)')
173         parser.add_option('-m','--encoding', dest='encoding', default='',
174                 help='Specify a different character encoding'
175                 '(ignored if the remote server also specifies one)')
176         parser.add_option('-t','--timezone', dest='timezone', default='',
177                 help='Specify a timezone to use if the remote calendar doesn\'t set it properly')
178
179         (options, args) = parser.parse_args()
180         ruleConfig["defaultTZ"] = options.timezone or ruleConfig["defaultTZ"]
181
182         # If the user passed us a 'stdin' argument, we'll go with that,
183         # otherwise we'll try for a url opener
184         if not args and not options.stdin:
185                 parser.print_usage()
186                 sys.exit(0)
187         elif not options.stdin:
188                 url = args[0]
189         else:
190                 url = ''
191
192         (content, encoding) = getContent(url, options.stdin)
193         encoding = encoding or options.encoding or 'utf-8'
194
195         cal = vobject.readOne(str(content, encoding))
196         cal = applyRules(cal, generateRules(ruleConfig), options.verbose)
197
198         writeOutput(cal, options.outfile)
199
200
201 def exitQuiet(exitstate=0):
202         '''When called as a CGI script, exit quietly if theres any errors'''
203         print('Content-Type: text/html\n')
204         sys.exit(exitstate)
205
206
207 def runCGI():
208         '''Main run function if this script is called as a CGI script
209         to process facebook ical files'''
210         import cgi
211         import re
212         import cgitb; cgitb.enable()
213
214         ruleConfig["facebook"] = True
215
216         form = cgi.FieldStorage()
217         if "uid" not in form or "key" not in form:
218             print('Content-Type: text/calendar\n')
219             sys.exit(0)
220         try:
221             # UID should be numeric, if it's not we have someone playing games
222             uid = int(form['uid'].value)
223         except:
224             exitQuiet()
225
226         # The user's key will be a 16 character string
227         key = form['key'].value
228         re.search('[&?]+', key) and exitQuiet()
229         len(key) == 16 or exitQuiet()
230
231         # Historically facebook has been notoriously bad at setting timzeones
232         # in their stuff so this should be a user setting. If it is set in
233         # their calendar it'll  be used otherwise if the user feeds crap or
234         # nothing just assume they want Australia/Perth
235         tz = ""
236         if "tz" in form:
237             from pytz import timezone
238             try:
239                 timezone(form['tz'].value)
240                 tz = form['tz'].value
241             except: pass
242
243         ruleConfig["defaultTZ"] = tz or ruleConfig["defaultTZ"]
244
245         # Okay, we're happy that the input is sane, lets serve up some data
246         url = 'https://www.facebook.com/events/ical/upcoming/?uid=%s&key=%s'%(uid,key)
247         (content, encoding) = getHTTPContent(url)
248
249         cal = vobject.readOne(str(content, encoding))
250         cal = applyRules(cal, generateRules(ruleConfig), False)
251
252         print(('Content-Type: text/calendar; charset=%s\n'%encoding))
253         writeOutput(cal)
254
255
256 if __name__ == '__main__':
257         # Ensure the rules process using the desired timezone
258         ruleConfig = {}
259         ruleConfig["defaultTZ"] = 'Australia/Perth'
260
261         # Detect if this script has been called by CGI and proceed accordingly
262         if 'REQUEST_METHOD' in os.environ:
263                 runCGI()
264         else:
265                 runLocal()

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