forked from jeztek/imok_appengine
-
Notifications
You must be signed in to change notification settings - Fork 1
/
twilio.py
467 lines (381 loc) · 16 KB
/
twilio.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
"""
Copyright (c) 2009 Twilio, Inc.
Permission is hereby granted, free of charge, to any person
obtaining a copy of this software and associated documentation
files (the "Software"), to deal in the Software without
restriction, including without limitation the rights to use,
copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the
Software is furnished to do so, subject to the following
conditions:
The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
OTHER DEALINGS IN THE SOFTWARE.
"""
__VERSION__ = "2.0.6"
import urllib, urllib2, base64, hmac
from hashlib import sha1
from xml.sax.saxutils import escape, quoteattr
try:
from google.appengine.api import urlfetch
APPENGINE = True
except:
APPENGINE = False
_TWILIO_API_URL = 'https://api.twilio.com'
class TwilioException(Exception): pass
# Twilio REST Helpers
# ===========================================================================
class HTTPErrorProcessor(urllib2.HTTPErrorProcessor):
def https_response(self, request, response):
code, msg, hdrs = response.code, response.msg, response.info()
if code >= 300:
response = self.parent.error(
'http', request, response, code, msg, hdrs)
return response
class HTTPErrorAppEngine(Exception): pass
class TwilioUrlRequest(urllib2.Request):
def get_method(self):
if getattr(self, 'http_method', None):
return self.http_method
return urllib2.Request.get_method(self)
class Account:
"""Twilio account object that provides helper functions for making
REST requests to the Twilio API. This helper library works both in
standalone python applications using the urllib/urlib2 libraries and
inside Google App Engine applications using urlfetch.
"""
def __init__(self, id, token):
"""initialize a twilio account object
id: Twilio account SID/ID
token: Twilio account token
returns a Twilio account object
"""
self.id = id
self.token = token
self.opener = None
def _build_get_uri(self, uri, params):
if params and len(params) > 0:
if uri.find('?') > 0:
if uri[-1] != '&':
uri += '&'
uri = uri + urllib.urlencode(params)
else:
uri = uri + '?' + urllib.urlencode(params)
return uri
def _urllib2_fetch(self, uri, params, method=None):
# install error processor to handle HTTP 201 response correctly
if self.opener == None:
self.opener = urllib2.build_opener(HTTPErrorProcessor)
urllib2.install_opener(self.opener)
if method and method == 'GET':
uri = self._build_get_uri(uri, params)
req = TwilioUrlRequest(uri)
else:
req = TwilioUrlRequest(uri, urllib.urlencode(params))
if method and (method == 'DELETE' or method == 'PUT'):
req.http_method = method
authstring = base64.encodestring('%s:%s' % (self.id, self.token))
authstring = authstring.replace('\n', '')
req.add_header("Authorization", "Basic %s" % authstring)
response = urllib2.urlopen(req)
return response.read()
def _appengine_fetch(self, uri, params, method):
if method == 'GET':
uri = self._build_get_uri(uri, params)
try:
httpmethod = getattr(urlfetch, method)
except AttributeError:
raise NotImplementedError(
"Google App Engine does not support method '%s'" % method)
authstring = base64.encodestring('%s:%s' % (self.id, self.token))
authstring = authstring.replace('\n', '')
r = urlfetch.fetch(url=uri, payload=urllib.urlencode(params),
method=httpmethod,
headers={'Content-Type': 'application/x-www-form-urlencoded',
'Authorization': 'Basic %s' % authstring})
if r.status_code >= 300:
raise HTTPErrorAppEngine("HTTP %s: %s" % \
(r.status_code, r.content))
return r.content
def request(self, path, method=None, vars={}):
"""sends a request and gets a response from the Twilio REST API
path: the URL (relative to the endpoint URL, after the /v1
url: the HTTP method to use, defaults to POST
vars: for POST or PUT, a dict of data to send
returns Twilio response in XML or raises an exception on error
"""
if not path or len(path) < 1:
raise ValueError('Invalid path parameter')
if method and method not in ['GET', 'POST', 'DELETE', 'PUT']:
raise NotImplementedError(
'HTTP %s method not implemented' % method)
if path[0] == '/':
uri = _TWILIO_API_URL + path
else:
uri = _TWILIO_API_URL + '/' + path
if APPENGINE:
return self._appengine_fetch(uri, vars, method)
return self._urllib2_fetch(uri, vars, method)
# TwiML Response Helpers
# ===========================================================================
class Verb:
"""Twilio basic verb object.
"""
def __init__(self, **kwargs):
self.name = self.__class__.__name__
self.body = None
self.nestables = None
self.verbs = []
self.attrs = {}
for k, v in kwargs.items():
if k == "sender": k = "from"
if v: self.attrs[k] = quoteattr(str(v))
def __repr__(self):
s = '<%s' % self.name
keys = self.attrs.keys()
keys.sort()
for a in keys:
s += ' %s=%s' % (a, self.attrs[a])
if self.body or len(self.verbs) > 0:
s += '>'
if self.body:
s += escape(self.body)
if len(self.verbs) > 0:
s += '\n'
for v in self.verbs:
for l in str(v)[:-1].split('\n'):
s += "\t%s\n" % l
s += '</%s>\n' % self.name
else:
s += '/>\n'
return s
def append(self, verb):
if not self.nestables:
raise TwilioException("%s is not nestable" % self.name)
if verb.name not in self.nestables:
raise TwilioException("%s is not nestable inside %s" % \
(verb.name, self.name))
self.verbs.append(verb)
return verb
def asUrl(self):
return urllib.quote(str(self))
def addSay(self, text, **kwargs):
return self.append(Say(text, **kwargs))
def addPlay(self, url, **kwargs):
return self.append(Play(url, **kwargs))
def addPause(self, **kwargs):
return self.append(Pause(**kwargs))
def addRedirect(self, url=None, **kwargs):
return self.append(Redirect(url, **kwargs))
def addHangup(self, **kwargs):
return self.append(Hangup(**kwargs))
def addGather(self, **kwargs):
return self.append(Gather(**kwargs))
def addNumber(self, number, **kwargs):
return self.append(Number(number, **kwargs))
def addDial(self, number=None, **kwargs):
return self.append(Dial(number, **kwargs))
def addRecord(self, **kwargs):
return self.append(Record(**kwargs))
def addConference(self, name, **kwargs):
return self.append(Conference(name, **kwargs))
def addSms(self, msg, **kwargs):
return self.append(Sms(msg, **kwargs))
class Response(Verb):
"""Twilio response object.
version: Twilio API version e.g. 2008-08-01
"""
def __init__(self, version=None, **kwargs):
Verb.__init__(self, version=version, **kwargs)
self.nestables = ['Say', 'Play', 'Gather', 'Record', 'Dial',
'Redirect', 'Pause', 'Hangup', 'Sms']
class Say(Verb):
"""Say text
text: text to say
voice: MAN or WOMAN
language: language to use
loop: number of times to say this text
"""
MAN = 'man'
WOMAN = 'woman'
ENGLISH = 'en'
SPANISH = 'es'
FRENCH = 'fr'
GERMAN = 'de'
def __init__(self, text, voice=None, language=None, loop=None, **kwargs):
Verb.__init__(self, voice=voice, language=language, loop=loop,
**kwargs)
self.body = text
if voice and (voice != self.MAN and voice != self.WOMAN):
raise TwilioException( \
"Invalid Say voice parameter, must be 'man' or 'woman'")
if voice and (voice != self.MAN and voice != self.WOMAN):
raise TwilioException( \
"Invalid Say language parameter, must be " + \
"'en', 'es', 'fr', or 'de'")
class Play(Verb):
"""Play audio file at a URL
url: url of audio file, MIME type on file must be set correctly
loop: number of time to say this text
"""
def __init__(self, url, loop=None, **kwargs):
Verb.__init__(self, loop=loop, **kwargs)
self.body = url
class Pause(Verb):
"""Pause the call
length: length of pause in seconds
"""
def __init__(self, length=None, **kwargs):
Verb.__init__(self, length=length, **kwargs)
class Redirect(Verb):
"""Redirect call flow to another URL
url: redirect url
"""
GET = 'GET'
POST = 'POST'
def __init__(self, url=None, method=None, **kwargs):
Verb.__init__(self, method=method, **kwargs)
if method and (method != self.GET and method != self.POST):
raise TwilioException( \
"Invalid method parameter, must be 'GET' or 'POST'")
self.body = url
class Hangup(Verb):
"""Hangup the call
"""
def __init__(self, **kwargs):
Verb.__init__(self)
class Gather(Verb):
"""Gather digits from the caller's keypad
action: URL to which the digits entered will be sent
method: submit to 'action' url using GET or POST
numDigits: how many digits to gather before returning
timeout: wait for this many seconds before returning
finishOnKey: key that triggers the end of caller input
"""
GET = 'GET'
POST = 'POST'
def __init__(self, action=None, method=None, numDigits=None, timeout=None,
finishOnKey=None, **kwargs):
Verb.__init__(self, action=action, method=method,
numDigits=numDigits, timeout=timeout, finishOnKey=finishOnKey,
**kwargs)
if method and (method != self.GET and method != self.POST):
raise TwilioException( \
"Invalid method parameter, must be 'GET' or 'POST'")
self.nestables = ['Say', 'Play', 'Pause']
class Number(Verb):
"""Specify phone number in a nested Dial element.
number: phone number to dial
sendDigits: key to press after connecting to the number
"""
def __init__(self, number, sendDigits=None, **kwargs):
Verb.__init__(self, sendDigits=sendDigits, **kwargs)
self.body = number
class Sms(Verb):
""" Send a Sms Message to a phone number
to: whom to send message to, defaults based on the direction of the call
sender: whom to send message from.
action: url to request after the message is queued
method: submit to 'action' url using GET or POST
statusCallback: url to hit when the message is actually sent
"""
GET = 'GET'
POST = 'POST'
def __init__(self, msg, to=None, sender=None, method=None, action=None,
statusCallback=None, **kwargs):
Verb.__init__(self, action=action, method=method, to=to, sender=sender,
statusCallback=statusCallback, **kwargs)
if method and (method != self.GET and method != self.POST):
raise TwilioException( \
"Invalid method parameter, must be GET or POST")
self.body = msg
class Conference(Verb):
"""Specify conference in a nested Dial element.
name: friendly name of conference
muted: keep this participant muted (bool)
beep: play a beep when this participant enters/leaves (bool)
startConferenceOnEnter: start conf when this participants joins (bool)
endConferenceOnExit: end conf when this participants leaves (bool)
waitUrl: TwiML url that executes before conference starts
waitMethod: HTTP method for waitUrl GET/POST
"""
GET = 'GET'
POST = 'POST'
def __init__(self, name, muted=None, beep=None,
startConferenceOnEnter=None, endConferenceOnExit=None, waitUrl=None,
waitMethod=None, **kwargs):
Verb.__init__(self, muted=muted, beep=beep,
startConferenceOnEnter=startConferenceOnEnter,
endConferenceOnExit=endConferenceOnExit, waitUrl=waitUrl,
waitMethod=waitMethod, **kwargs)
if waitMethod and (waitMethod != self.GET and waitMethod != self.POST):
raise TwilioException( \
"Invalid waitMethod parameter, must be GET or POST")
self.body = name
class Dial(Verb):
"""Dial another phone number and connect it to this call
action: submit the result of the dial to this URL
method: submit to 'action' url using GET or POST
"""
GET = 'GET'
POST = 'POST'
def __init__(self, number=None, action=None, method=None, **kwargs):
Verb.__init__(self, action=action, method=method, **kwargs)
self.nestables = ['Number', 'Conference']
if number and len(number.split(',')) > 1:
for n in number.split(','):
self.append(Number(n.strip()))
else:
self.body = number
if method and (method != self.GET and method != self.POST):
raise TwilioException( \
"Invalid method parameter, must be GET or POST")
class Record(Verb):
"""Record audio from caller
action: submit the result of the dial to this URL
method: submit to 'action' url using GET or POST
maxLength: maximum number of seconds to record
timeout: seconds of silence before considering the recording complete
"""
GET = 'GET'
POST = 'POST'
def __init__(self, action=None, method=None, maxLength=None,
timeout=None, **kwargs):
Verb.__init__(self, action=action, method=method, maxLength=maxLength,
timeout=timeout, **kwargs)
if method and (method != self.GET and method != self.POST):
raise TwilioException( \
"Invalid method parameter, must be GET or POST")
# Twilio Utility function and Request Validation
# ===========================================================================
class Utils:
def __init__(self, id, token):
"""initialize a twilio utility object
id: Twilio account SID/ID
token: Twilio account token
returns a Twilio util object
"""
self.id = id
self.token = token
def validateRequest(self, uri, postVars, expectedSignature):
"""validate a request from twilio
uri: the full URI that Twilio requested on your server
postVars: post vars that Twilio sent with the request
expectedSignature: signature in HTTP X-Twilio-Signature header
returns true if the request passes validation, false if not
"""
# append the POST variables sorted by key to the uri
s = uri
if len(postVars) > 0:
for k, v in sorted(postVars.items()):
s += k + v
# compute signature and compare signatures
return (base64.encodestring(hmac.new(self.token, s, sha1).digest()).\
strip() == expectedSignature)