forked from minddog/twilio-emulator
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathtwilio-emulator.py
executable file
·365 lines (287 loc) · 9.29 KB
/
twilio-emulator.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
#!/usr/bin/python
import sys, signal, os
import urllib, urllib2
import urlparse
import readline
from StringIO import StringIO
from threading import Timer
from xml.dom.minidom import parseString
from xml.parsers.expat import ExpatError
from optparse import OptionParser
from datetime import datetime
class TwiMLSyntaxError(Exception):
def __init__(self, lineno, col, doc):
self.lineno = lineno
self.col = col
self.doc = doc
self.line = self.doc.split("\n")[self.lineno-2]
def __str__(self):
return "TwiMLSyntaxError at line %i col %i near %s" \
% (self.lineno, self.col, self.line)
class ResponseLogger(object):
def __init__(self, level=0, verbose=False, filename=None):
if not filename:
filename = "%s-twilio-log" % datetime.now()
self.buf = StringIO()
self.level = level
self.verbose = verbose
self.filename = filename
self.WARN_LEVEL = 2
self.NOTICE_LEVEL = 4
self.ERROR_LEVEL = 0
self.OUTPUT_LEVEL = 0
def __str__(self):
return self.buf.getvalue()
def log(self, log_level, str):
if(self.level > log_level):
self.write(str)
def warn(self, str):
self.log(self.WARN_LEVEL, str)
def notice(self, str):
self.log(self.NOTICE_LEVEL, str)
def error(self, str):
self.log(self.ERROR_LEVEL, str)
def output(self, str):
self.log(self.OUTPUT_LEVEL, str)
def write(self, str):
self.buf.write("[%s] %s\n" % (datetime.now(), str))
if self.verbose:
print str
def to_file(self):
f = open(self.filename, "w+")
f.write(str(self))
f.close()
def getResponse(url, method, digits):
data = None
if method == 'POST' and digits:
data = urllib.urlencode( {'Digits' : digits} )
elif method == 'GET' and digits:
purl = urlparse.urlparse(url)
url = "%s?%s&%s" % \
( purl.geturl(),
purl.query ,
urllib.urlencode(
{'Digits': digits}
)
)
logger.notice('[%s] %s \n%s' % (method, url, data))
try:
req = urllib2.Request(url, data)
fd = urllib2.urlopen(req)
except IOError, e:
logger.error('[Not Found] %s' % e)
exit_handler()
return fd.read()
def end_pause():
logger.notice("[End Pause]")
return None
def input_timeout(*args):
print
logger.notice("[Gather timed out]")
def exit_handler(*args):
logger.to_file()
sys.stdout.flush()
sys.exit(0)
def timed_input(prompt, timeout):
signal.alarm(timeout)
sys.stdout.write(prompt)
sys.stdout.flush()
try:
input = sys.stdin.readline()
except KeyboardInterrupt, e:
exit_handler()
except IOError, e:
input = None
signal.alarm(0)
return input
def Gather(node):
# See Verb Attributes
# Source: http://www.twilio.com/docs/api_reference/TwiML/gather
numDigits = -1
timeout = 5
method = "POST"
action = ""
finishOnKey = "#"
if node.attributes.has_key('numDigits'):
numDigits = node.attributes['numDigits'].value
if node.attributes.has_key('timeout'):
timeout = node.attributes['timeout'].value
if node.attributes.has_key('method'):
method = node.attributes['method'].value
if node.attributes.has_key('action'):
action = node.attributes['action'].value
if node.attributes.has_key('finishOnKey'):
finishOnkey = node.attributes['finishOnKey'].value
if node.hasChildNodes():
[processNode(child) for child in node.childNodes]
prompt = "[Gather timeout=%s numDigits=%s]> " % \
(timeout,
numDigits)
digits = timed_input(prompt, int(timeout))
if not digits:
return None
request = {
'action' : action,
'method' : method,
'digits' : digits
}
return request
def Say(node):
if not node.hasChildNodes():
logger.error("text node for <Say> not found.")
exit_handler()
if len(node.childNodes) != 1:
logger.error("Multiple child nodes for say illegal")
exit_handler()
logger.output("[Say] %s" % node.childNodes[0].data.strip())
return None
def Play(node):
if not node.hasChildNodes():
logger.error("text node for <Play> not found.")
exit_handler()
if len(node.childNodes) != 1:
logger.error("Multiple child nodes for play illegal")
exit_handler()
logger.output("[Play] %s" % node.childNodes[0].data)
return None
def Pause(node):
length = 1
if node.hasAttributes() and \
node.attributes.has_key('length'):
length = node.attributes['length'].value
logger.output("[Pause length=%s]" % length)
t = Timer(float(length), end_pause)
t.start()
return None
def Dial(node):
if not node.hasChildNodes():
logger.error("text node for <Play> not found.")
exit_handler()
if len(node.childNodes) == 1 and \
node.childNodes[0].nodeType == node.TEXT_NODE:
logger.notice("[Dial] %s" % node.childNodes[0].data.strip())
return None
logger.notice("[Dial with children]")
[processNode(child) for child in node.childNodes]
return None
def Number(node):
if not node.hasChildNodes():
logger.error("text node for <Number> not found.")
exit_handler()
logger.output("[Number] %s" % node.childNodes[0].data.encode('ascii').strip())
return None
def Redirect(node):
if len(node.childNodes) != 1:
logger.error("Redirect Syntax Error")
exit_handler()
logger.notice("[Redirect] %s" % node.childNodes[0].data)
request = {
'action' : node.childNodes[0].data,
'method' : 'GET',
'digits' : None
}
return request
def Record(node):
action = ""
method = "POST"
timeout = 5
finishOnKey = "123456789*#"
maxLength = 3600
if node.attributes.has_key('action'):
action = node.attributes['action'].value
if node.attributes.has_key('method'):
method = node.attributes['method'].value
if node.attributes.has_key('timeout'):
timeout = node.attributes['timeout'].value
if node.attributes.has_key('finishOnKey'):
finishOnKey = node.attributes['finishOnKey'].value
if node.attributes.has_key('maxLength'):
maxLength = node.attributes['maxLength'].value
prompt = "[Record maxLength=%s timeout=%s action=%s]" % \
(maxLength, timeout, action)
digits = timed_input(prompt, int(timeout))
request = {
'action' : action,
'method' : method,
'digits' : digits,
}
return request
def Hangup(node):
logger.output("[Hangup]")
exit_handler()
def processNode(node):
action = node.nodeName.encode('ascii')
if node.nodeType == node.TEXT_NODE:
logger.output(node.data.strip())
else:
return eval("%s(node)" % action)
return None
def emulate(url, method = 'GET', digits = None):
logger.notice('[Emulation Start] %s' % url)
response = getResponse(
url,
method,
digits)
if not response:
logger.error('[Emulation Failed to start]')
exit_handler()
try:
rdoc = parseString(response)
except ExpatError, e:
raise TwiMLSyntaxError(e.lineno, e.offset, response)
try:
respNode = rdoc.getElementsByTagName('Response')[0]
except IndexError, e:
logger.error('[No response node] exiting')
exit_handler()
if not respNode.hasChildNodes():
#hangup
logger.notice('Hanging up')
exit_handler()
nodes = respNode.childNodes
for node in nodes:
if node.nodeType == node.TEXT_NODE:
# ignore
pass
if node.nodeType == node.ELEMENT_NODE:
request = processNode(node)
if not request:
continue
try:
if(request['action'] == ''):
request['action'] = url
emulate(request['action'],
request['method'],
request['digits'])
except TwiMLSyntaxError, e:
logger.error(e)
exit_handler()
def main():
signal.signal(signal.SIGALRM, input_timeout)
signal.signal(signal.SIGINT, exit_handler)
usage = "usage: %prog [options] [url]"
parser = OptionParser(usage)
parser.add_option("-v", "--verbose",
action="store_true", dest="verbose",
help="Display notices")
parser.add_option("-o", "--log-output",
action="store", dest="filename",
help="Where to store log of phone call")
(options, args) = parser.parse_args(sys.argv)
if len(args) != 2:
parser.print_help()
exit_handler()
if options.verbose:
logger.level = 5
if options.filename:
logger.filename = options.filename
url = args[1]
try:
emulate(url)
except TwiMLSyntaxError, e:
logger.error(e)
exit_handler()
logger.notice('[Phone call ended]')
logger = ResponseLogger(1, True)
if __name__ == "__main__":
main()