forked from fiorix/eventsocket
-
Notifications
You must be signed in to change notification settings - Fork 2
/
eventsocket.py
524 lines (404 loc) · 17.4 KB
/
eventsocket.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
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
# coding: utf-8
#
# Twisted protocol for the FreeSWITCH's Event Socket
#
# Version: MPL 1.1
#
# The contents of this file are subject to the Mozilla Public License Version
# 1.1 (the "License"); you may not use this file except in compliance with
# the License. You may obtain a copy of the License at
# http://www.mozilla.org/MPL/
#
# Software distributed under the License is distributed on an "AS IS" basis,
# WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
# for the specific language governing rights and limitations under the
# License.
"Twisted protocol for the FreeSWITCH Event Socket"
import types
import string
from cStringIO import StringIO
import _eventsocket_accell
from twisted.python import log
from twisted.protocols import basic
from twisted.internet import defer, reactor, protocol
__version__ = "0.1.4"
class EventError(Exception):
pass
class AuthError(Exception):
pass
class _O(dict):
"""Translates dictionary keys to instance attributes"""
def __setattr__(self, k, v):
dict.__setitem__(self, k, v)
def __delattr__(self, k):
dict.__delitem__(self, k)
def __getattribute__(self, k):
try:
return dict.__getitem__(self, k)
except KeyError:
return dict.__getattribute__(self, k)
class EventSocket(basic.LineReceiver):
delimiter = "\n"
def __init__(self):
self.__ctx = None
self.__rawlen = None
self.__io = StringIO()
self.__rawresponse = [
"api/response",
"text/disconnect-notice",
]
def send(self, cmd):
if isinstance(cmd, types.UnicodeType):
cmd = cmd.encode("utf-8")
self.transport.write(cmd+"\n\n")
def rawSend(self, stuff):
if isinstance(stuff, types.UnicodeType):
stuff = stuff.encode('utf-8')
self.transport.write(stuff)
def sendmsg(self, name, arg=None, uuid="", lock=False):
if isinstance(name, types.UnicodeType):
name = name.encode("utf-8")
if isinstance(arg, types.UnicodeType):
arg = arg.encode("utf-8")
self.transport.write("sendmsg %s\ncall-command: execute\n" % uuid)
self.transport.write("execute-app-name: %s\n" % name)
if arg:
self.transport.write("execute-app-arg: %s\n" % arg)
if lock is True:
self.transport.write("event-lock: true\n")
self.transport.write("\n\n")
def processLine(self, ev, line):
try:
k, v = _eventsocket_accell.processLine(line)
ev[k] = v
except:
pass
def parseEvent(self, isctx=False):
ev = _O()
self.__io.reset()
for line in self.__io:
if line == "\n":
break
self.processLine(ev, line)
if not isctx:
rawlength = ev.get("Content_Length")
if rawlength:
ev.rawresponse = self.__io.read(int(rawlength))
self.__io.reset()
self.__io.truncate()
return ev
def readRawResponse(self):
self.__io.reset()
chunk = self.__io.read(int(self.__ctx.Content_Length))
self.__io.reset()
self.__io.truncate()
return _O(rawresponse=chunk)
def dispatchEvent(self, ctx, event):
ctx.data = _O(event.copy())
reactor.callLater(0, self.eventReceived, _O(ctx.copy()))
self.__ctx = self.__rawlen = None
def eventReceived(self, ctx):
pass
def lineReceived(self, line):
if line:
self.__io.write(line+"\n")
else:
ctx = self.parseEvent(True)
rawlength = ctx.get("Content_Length")
if rawlength:
self.__ctx = ctx
self.__rawlen = int(rawlength)
self.setRawMode()
else:
self.dispatchEvent(ctx, _O())
def rawDataReceived(self, data):
if self.__rawlen is None:
rest = ""
else:
data, rest = data[:self.__rawlen], data[self.__rawlen:]
self.__rawlen -= len(data)
self.__io.write(data)
if self.__rawlen == 0:
if self.__ctx.get("Content_Type") in self.__rawresponse:
self.dispatchEvent(self.__ctx, self.readRawResponse())
else:
self.dispatchEvent(self.__ctx, self.parseEvent())
self.setLineMode(rest)
class EventProtocol(EventSocket):
def __init__(self):
EventSocket.__init__(self)
# our internal event queue
self.__EventQueue = []
# callbacks by event's content-type
self.__EventCallbacks = {
"auth/request": self.authRequest,
"api/response": self._apiResponse,
"command/reply": self._commandReply,
"text/event-plain": self._plainEvent,
"text/disconnect-notice": self.onDisconnect,
}
def __protocolSend(self, name, args=""):
deferred = defer.Deferred()
self.__EventQueue.append((name, deferred))
self.send("%s %s" % (name, args))
return deferred
def __protocolSendRaw(self, name, args=""):
deferred = defer.Deferred()
self.__EventQueue.append((name, deferred))
self.rawSend("%s %s" % (name, args))
return deferred
def __protocolSendmsg(self, name, args=None, uuid="", lock=False):
deferred = defer.Deferred()
self.__EventQueue.append((name, deferred))
self.sendmsg(name, args, uuid, lock)
return deferred
def eventReceived(self, ctx):
#log.msg("GOT EVENT: %s\n" % repr(ctx), logLevel=logging.DEBUG)
content_type = ctx.get("Content_Type", None)
if content_type:
method = self.__EventCallbacks.get(content_type, None)
if callable(method):
return method(ctx)
else:
return self.unknownContentType(content_type, ctx)
def authRequest(self, ctx):
pass
def onDisconnect(self, ctx):
pass
def _apiResponse(self, ctx):
cmd, deferred = self.__EventQueue.pop(0)
if cmd == "api":
deferred.callback(ctx)
else:
deferred.errback(EventError("apiResponse on '%s': out of sync?" % cmd))
def _commandReply(self, ctx):
cmd, deferred = self.__EventQueue.pop(0)
if ctx.Reply_Text.startswith("+OK"):
deferred.callback(ctx)
elif cmd == "auth":
deferred.errback(AuthError("invalid password"))
else:
deferred.errback(EventError(ctx))
def _plainEvent(self, ctx):
name = ctx.data.get("Event_Name")
if name:
evname = "on" + string.capwords(name, "_").replace("_", "")
method = getattr(self, evname, None)
if callable(method):
return method(ctx.data)
else:
return self.unboundEvent(ctx.data, evname)
def unknownContentType(self, content_type, ctx):
log.err("[eventsocket] unknown Content-Type: %s" % content_type,
logLevel=log.logging.DEBUG)
def unboundEvent(self, ctx, evname):
log.err("[eventsocket] unbound Event: %s" % evname,
logLevel=log.logging.DEBUG)
# EVENT SOCKET COMMANDS
def api(self, args):
"Please refer to http://wiki.freeswitch.org/wiki/Event_Socket#api"
return self.__protocolSend("api", args)
def sendevent(self, name, args=dict(),body=None):
"Please refer to http://wiki.freeswitch.org/wiki/Event_Socket#sendevent"
parsed_args = [name]
for k,v in args.iteritems():
parsed_args.append('%s: %s' % (k, v))
if body:
parsed_args.append('content-length: %s' % len(body))
parsed_args.append('')
parsed_args.append(body)
return self.__protocolSend("sendevent", '\n'.join(parsed_args))
def bgapi(self, args):
"Please refer to http://wiki.freeswitch.org/wiki/Event_Socket#bgapi"
return self.__protocolSend("bgapi", args)
def exit(self):
"Please refer to http://wiki.freeswitch.org/wiki/Event_Socket#exit"
return self.__protocolSend("exit")
def eventplain(self, args):
"Please refer to http://wiki.freeswitch.org/wiki/Event_Socket#event"
return self.__protocolSend('eventplain', args)
def event(self, args):
"Please refer to http://wiki.freeswitch.org/wiki/Event_Socket#event"
return self.__protocolSendmsg("event", args, lock=True)
def linger(self, args=None):
"Please refer to http://wiki.freeswitch.org/wiki/Event_Socket#event"
return self.__protocolSend("linger", args)
def filter(self, args):
"""Please refer to http://wiki.freeswitch.org/wiki/Event_Socket#filter
The user might pass any number of values to filter an event for. But, from the point
filter() is used, just the filtered events will come to the app - this is where this
function differs from event().
>>> filter('Event-Name MYEVENT')
>>> filter('Unique-ID 4f37c5eb-1937-45c6-b808-6fba2ffadb63')
"""
return self.__protocolSend('filter', args)
def filter_delete(self, args):
"""Please refer to http://wiki.freeswitch.org/wiki/Event_Socket#filter_delete
>>> filter_delete('Event-Name MYEVENT')
"""
return self.__protocolSend('filter delete', args)
def verbose_events(self):
"""Please refer to http://wiki.freeswitch.org/wiki/Misc._Dialplan_Tools_verbose_events
>>> verbose_events()
"""
return self.__protocolSendmsg('verbose_events', lock=True)
def auth(self, args):
"""Please refer to http://wiki.freeswitch.org/wiki/Event_Socket#auth
This method is allowed only for Inbound connections."""
return self.__protocolSend("auth", args)
def connect(self):
"Please refer to http://wiki.freeswitch.org/wiki/Event_Socket_Outbound#Using_Netcat"
return self.__protocolSend("connect")
def myevents(self):
"Please refer to http://wiki.freeswitch.org/wiki/Event_Socket#event"
return self.__protocolSend("myevents")
def answer(self):
"Please refer to http://wiki.freeswitch.org/wiki/Event_Socket_Outbound#Using_Netcat"
return self.__protocolSendmsg("answer", lock=True)
def bridge(self, args):
"""Please refer to http://wiki.freeswitch.org/wiki/Event_Socket_Outbound
>>> bridge("{ignore_early_media=true}sofia/gateway/myGW/177808")
"""
return self.__protocolSendmsg("bridge", args, lock=True)
def hangup(self, reason=""):
"""Hangup may be used by both Inbound and Outbound connections.
When used by Inbound connections, you may add the extra `reason`
argument. Please refer to http://wiki.freeswitch.org/wiki/Event_Socket#hangup
for details.
When used by Outbound connections, the `reason` argument must be ignored.
Please refer to http://wiki.freeswitch.org/wiki/Event_Socket_Outbound for
details.
"""
return self.__protocolSendmsg("hangup", reason, lock=True)
def sched_api(self, args):
"Please refer to http://wiki.freeswitch.org/wiki/Mod_commands#sched_api"
return self.__protocolSendmsg("sched_api", args, lock=True)
def ring_ready(self):
"Please refer to http://wiki.freeswitch.org/wiki/Misc._Dialplan_Tools_ring_ready"
return self.__protocolSendmsg("ring_ready")
def record_session(self, filename):
"""Please refer to http://wiki.freeswitch.org/wiki/Misc._Dialplan_Tools_record_session
>>> record_session("/tmp/dump.gsm")
"""
return self.__protocolSendmsg("record_session", filename, lock=True)
def read(self, args):
"""Please refer to http://wiki.freeswitch.org/wiki/Misc._Dialplan_Tools_read
>>> read("0 10 $${base_dir}/sounds/en/us/callie/conference/8000/conf-pin.wav res 10000 #")
"""
return self.__protocolSendmsg("read", args, lock=True)
def bind_meta_app(self, args):
"""Please refer to http://wiki.freeswitch.org/wiki/Misc._Dialplan_Tools_bind_meta_app
>>> bind_meta_app("2 ab s record_session::/tmp/dump.gsm")
"""
return self.__protocolSendmsg("bind_meta_app", args, lock=True)
def wait_for_silence(self, args):
"""Please refer to http://wiki.freeswitch.org/wiki/Misc._Dialplan_Tools_wait_for_silence
>>> wait_for_silence("200 15 10 5000")
"""
return self.__protocolSendmsg("wait_for_silence", args, lock=True)
def sleep(self, milliseconds):
"""Please refer to http://wiki.freeswitch.org/wiki/Misc._Dialplan_Tools_sleep
>>> sleep(5000)
>>> sleep("5000")
"""
return self.__protocolSendmsg("sleep", milliseconds, lock=True)
def vmd(self, args):
"""Please refer to http://wiki.freeswitch.org/wiki/Mod_vmd
>>> vmd("start")
>>> vmd("stop")
"""
return self.__protocolSendmsg("vmd", args, lock=True)
def set(self, args):
"""Please refer to http://wiki.freeswitch.org/wiki/Misc._Dialplan_Tools_set
>>> set("ringback=${us-ring}")
"""
return self.__protocolSendmsg("set", args, lock=True)
def set_global(self, args):
"""Please refer to http://wiki.freeswitch.org/wiki/Misc._Dialplan_Tools_set_global
>>> set_global("global_var=value")
"""
return self.__protocolSendmsg("set_global", args, lock=True)
def unset(self, args):
"""Please refer to http://wiki.freeswitch.org/wiki/Misc._Dialplan_Tools_unset
>>> unset("ringback")
"""
return self.__protocolSendmsg("unset", args, lock=True)
def start_dtmf(self):
"""Please refer to http://wiki.freeswitch.org/wiki/Misc._Dialplan_Tools_start_dtmf
>>> start_dtmf()
"""
return self.__protocolSendmsg("start_dtmf", lock=True)
def stop_dtmf(self):
"""Please refer to http://wiki.freeswitch.org/wiki/Misc._Dialplan_Tools_stop_dtmf
>>> stop_dtmf()
"""
return self.__protocolSendmsg("stop_dtmf", lock=True)
def start_dtmf_generate(self):
"""Please refer to http://wiki.freeswitch.org/wiki/Misc._Dialplan_Tools_start_dtmf_generate
>>> start_dtmf_generate()
"""
return self.__protocolSendmsg("start_dtmf_generate", "true", lock=True)
def stop_dtmf_generate(self):
"""Please refer to http://wiki.freeswitch.org/wiki/Misc._Dialplan_Tools_stop_dtmf_generate
>>> stop_dtmf_generate()
"""
return self.__protocolSendmsg("stop_dtmf_generate", lock=True)
def queue_dtmf(self, args):
"""Please refer to http://wiki.freeswitch.org/wiki/Misc._Dialplan_Tools_queue_dtmf
Enqueue each received dtmf, that'll be sent once the call is bridged.
>>> queue_dtmf("0123456789")
"""
return self.__protocolSendmsg("queue_dtmf", args, lock=True)
def flush_dtmf(self):
"""Please refer to http://wiki.freeswitch.org/wiki/Misc._Dialplan_Tools_flush_dtmf
>>> flush_dtmf()
"""
return self.__protocolSendmsg("flush_dtmf", lock=True)
def play_fsv(self, filename):
"""Please refer to http://wiki.freeswitch.org/wiki/Mod_fsv
>>> play_fsv("/tmp/video.fsv")
"""
return self.__protocolSendmsg("play_fsv", filename, lock=True)
def record_fsv(self, filename):
"""Please refer to http://wiki.freeswitch.org/wiki/Mod_fsv
>>> record_fsv("/tmp/video.fsv")
"""
return self.__protocolSendmsg("record_fsv", filename, lock=True)
def playback(self, filename, terminators=None, lock=True):
"""Please refer to http://wiki.freeswitch.org/wiki/Mod_playback
The optional argument `terminators` may contain a string with
the characters that will terminate the playback.
>>> playback("/tmp/dump.gsm", terminators="#8")
In this case, the audio playback is automatically terminated
by pressing either '#' or '8'.
"""
self.set("playback_terminators=%s" % terminators or "none")
return self.__protocolSendmsg("playback", filename, lock=lock)
def transfer(self, args):
"""Please refer to http://wiki.freeswitch.org/wiki/Misc._Dialplan_Tools_transfer
>>> transfer("3222 XML default")
"""
return self.__protocolSendmsg("transfer", args, lock=True)
def conference(self, args):
"""Please refer to http://wiki.freeswitch.org/wiki/Mod_conference#API_Reference
>>> conference("myconf")
"""
return self.__protocolSendmsg("conference", args, lock=True)
def att_xfer(self, url):
"""Please refer to http://wiki.freeswitch.org/wiki/Misc._Dialplan_Tools_att_xfer
>>> att_xfer("user/1001")
"""
return self.__protocolSendmsg("att_xfer", url, lock=True)
def send_break(self):
return self.__protocolSendmsg("break", lock=True)
def endless_playback(self, filename):
"""Please refer to http://wiki.freeswitch.org/wiki/Misc._Dialplan_Tools_endless_playback
>>> endless_playback("/tmp/dump.gsm")
"""
return self.__protocolSendmsg("endless_playback", filename, lock=True)
def execute(self, command, args):
"""Please refer to http://wiki.freeswitch.org/wiki/Event_Socket_Library#execute
>>> execute('voicemail', 'default $${domain} 1000')
"""
return self.__protocolSendmsg(command, args, lock=True)
__all__ = ['EventError', 'AuthError', 'EventSocket', 'EventProtocol']