Debian Codegraph @

Xpjproject/pjsip-apps/src/confbot/confbot.py

raw symbols SCIP
1 #
2 # SIP Conference Bot
3 #
4 # Copyright (C) 2008-2009 Teluu Inc. (http://www.teluu.com)
5 #
6 # This program is free software; you can redistribute it and/or modify
7 # it under the terms of the GNU General Public License as published by
8 # the Free Software Foundation; either version 2 of the License, or
9 # (at your option) any later version.
10 #
11 # This program is distributed in the hope that it will be useful,
12 # but WITHOUT ANY WARRANTY; without even the implied warranty of
13 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 # GNU General Public License for more details.
15 #
16 # You should have received a copy of the GNU General Public License
17 # along with this program; if not, write to the Free Software
18 # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
19 #
20 import pjsua as pj
21 import string
22 import sys
23
24 CFG_FILE = "config"
25
26 INFO = 1
27 TRACE = 2
28
29 # Call callback. This would just forward the event to the Member class
30 class CallCb(pj.CallCallback):
31 def __init__(self, member, call=None):
32 pj.CallCallback.__init__(self, call)
33 self.member = member
34
35 def on_state(self):
36 self.member.on_call_state(self.call)
37
38 def on_media_state(self):
39 self.member.on_call_media_state(self.call)
40
41 def on_dtmf_digit(self, digits):
42 self.member.on_call_dtmf_digit(self.call, digits)
43
44 def on_transfer_request(self, dst, code):
45 return self.member.on_call_transfer_request(self.call, dst, code)
46
47 def on_transfer_status(self, code, reason, final, cont):
48 return self.member.on_call_transfer_status(self.call, code, reason, final, cont)
49
50 def on_replace_request(self, code, reason):
51 return self.member.on_call_replace_request(self.call, code, reason)
52
53 def on_replaced(self, new_call):
54 self.member.on_call_replaced(self.call, new_call)
55
56 def on_typing(self, is_typing):
57 self.member.on_typing(is_typing, call=self.call)
58
59 def on_pager(self, mime_type, body):
60 self.member.on_pager(mime_type, body, call=self.call)
61
62 def on_pager_status(self, body, im_id, code, reason):
63 self.member.on_pager_status(body, im_id, code, reason, call=self.call)
64
65 # Buddy callback. This would just forward the event to Member class
66 class BuddyCb(pj.BuddyCallback):
67 def __init__(self, member, buddy=None):
68 pj.BuddyCallback.__init__(self, buddy)
69 self.member = member
70
71 def on_pager(self, mime_type, body):
72 self.member.on_pager(mime_type, body, buddy=self.buddy)
73
74 def on_pager_status(self, body, im_id, code, reason):
75 self.member.on_pager_status(body, im_id, code, reason, buddy=self.buddy)
76
77 def on_state(self):
78 self.member.on_pres_state(self.buddy)
79
80 def on_typing(self, is_typing):
81 self.member.on_typing(is_typing, buddy=self.buddy)
82
83
84
85
86 ##############################################################################
87 #
88 #
89 # This class represents individual room member (either/both chat and voice conf)
90 #
91 #
92 class Member:
93 def __init__(self, bot, uri):
94 self.uri = uri
95 self.bot = bot
96 self.call = None
97 self.buddy = None
98 self.bi = pj.BuddyInfo()
99 self.in_chat = False
100 self.in_voice = False
101 self.im_error = False
102 self.html = False
103
104 def __str__(self):
105 str = string.ljust(self.uri, 30) + " -- "
106 if self.buddy:
107 bi = self.buddy.info()
108 str = str + bi.online_text
109 else:
110 str = str + "Offline"
111 str = str + " ["
112 if (self.in_voice):
113 str = str + " voice"
114 if (self.in_chat):
115 str = str + " chat"
116 if (self.html):
117 str = str + " html"
118 else:
119 str = str + " plain"
120
121 if (self.im_error):
122 str = str + " im_error"
123 str = str + "]"
124 return str
125
126 def join_call(self, call):
127 if self.call:
128 self.call.hangup(603, "You have been disconnected for making another call")
129 self.call = call
130 call.set_callback(CallCb(self, call))
131 msg = "%(uri)s is attempting to join the voice conference" % \
132 {'uri': self.uri}
133 self.bot.DEBUG(msg + "\n", INFO)
134 self.bot.broadcast_pager(None, msg)
135
136 def join_chat(self):
137 if not self.buddy:
138 self.bot.DEBUG(self.uri + " joining chatroom...\n", INFO)
139 self.buddy = self.bot.acc.add_buddy(self.uri)
140 self.buddy.set_callback(BuddyCb(self, self.buddy))
141 self.buddy.subscribe()
142 else:
143 self.bot.DEBUG(self.uri + " already in chatroom, resubscribing..\n", INFO)
144 self.buddy.subscribe()
145
146 def send_pager(self, body, mime="text/plain"):
147 self.bot.DEBUG("send_pager() to " + self.uri)
148 if self.in_chat and not self.im_error and self.buddy:
149 if self.html:
150 #This will make us receive html!
151 #mime = "text/html"
152 body = body.replace("<", "&lt;")
153 body = body.replace(">", "&gt;")
154 body = body.replace('"', "&quot;")
155 body = body.replace("\n", "<BR>\n")
156 self.buddy.send_pager(body, content_type=mime)
157 self.bot.DEBUG("..sent\n")
158 else:
159 self.bot.DEBUG("..not sent!\n")
160
161 def on_call_state(self, call):
162 ci = call.info()
163 if ci.state==pj.CallState.DISCONNECTED:
164 if self.in_voice:
165 msg = "%(uri)s has left the voice conference (%(1)d/%(2)s)" % \
166 {'uri': self.uri, '1': ci.last_code, '2': ci.last_reason}
167 self.bot.DEBUG(msg + "\n", INFO)
168 self.bot.broadcast_pager(None, msg)
169 self.in_voice = False
170 self.call = None
171 self.bot.on_member_left(self)
172 elif ci.state==pj.CallState.CONFIRMED:
173 msg = "%(uri)s has joined the voice conference" % \
174 {'uri': self.uri}
175 self.bot.DEBUG(msg + "\n", INFO)
176 self.bot.broadcast_pager(None, msg)
177
178 def on_call_media_state(self, call):
179 self.bot.DEBUG("Member.on_call_media_state\n")
180 ci = call.info()
181 if ci.conf_slot!=-1:
182 if not self.in_voice:
183 msg = self.uri + " call media is active"
184 self.bot.broadcast_pager(None, msg)
185 self.in_voice = True
186 self.bot.add_to_voice_conf(self)
187 else:
188 if self.in_voice:
189 msg = self.uri + " call media is inactive"
190 self.bot.broadcast_pager(None, msg)
191 self.in_voice = False
192
193 def on_call_dtmf_digit(self, call, digits):
194 msg = "%(uri)s sent DTMF digits %(dig)s" % \
195 {'uri': self.uri, 'dig': digits}
196 self.bot.broadcast_pager(None, msg)
197
198 def on_call_transfer_request(self, call, dst, code):
199 msg = "%(uri)s is transferring the call to %(dst)s" % \
200 {'uri': self.uri, 'dst': dst}
201 self.bot.broadcast_pager(None, msg)
202 return 202
203
204 def on_call_transfer_status(self, call, code, reason, final, cont):
205 msg = "%(uri)s call transfer status is %(code)d/%(res)s" % \
206 {'uri': self.uri, 'code': code, 'res': reason}
207 self.bot.broadcast_pager(None, msg)
208 return True
209
210 def on_call_replace_request(self, call, code, reason):
211 msg = "%(uri)s is requesting call replace" % \
212 {'uri': self.uri}
213 self.bot.broadcast_pager(None, msg)
214 return (code, reason)
215
216 def on_call_replaced(self, call, new_call):
217 msg = "%(uri)s call is replaced" % \
218 {'uri': self.uri}
219 self.bot.broadcast_pager(None, msg)
220
221 def on_pres_state(self, buddy):
222 old_bi = self.bi
223 self.bi = buddy.info()
224 msg = "%(uri)s status is %(st)s" % \
225 {'uri': self.uri, 'st': self.bi.online_text}
226 self.bot.DEBUG(msg + "\n", INFO)
227 self.bot.broadcast_pager(self, msg)
228
229 if self.bi.sub_state==pj.SubscriptionState.ACTIVE:
230 if not self.in_chat:
231 self.in_chat = True
232 buddy.send_pager("Welcome to chatroom")
233 self.bot.broadcast_pager(self, self.uri + " has joined the chat room")
234 else:
235 self.in_chat = True
236 elif self.bi.sub_state==pj.SubscriptionState.NULL or \
237 self.bi.sub_state==pj.SubscriptionState.TERMINATED or \
238 self.bi.sub_state==pj.SubscriptionState.UNKNOWN:
239 self.buddy.delete()
240 self.buddy = None
241 if self.in_chat:
242 self.in_chat = False
243 self.bot.broadcast_pager(self, self.uri + " has left the chat room")
244 else:
245 self.in_chat = False
246 self.bot.on_member_left(self)
247
248 def on_typing(self, is_typing, call=None, buddy=None):
249 if is_typing:
250 msg = self.uri + " is typing..."
251 else:
252 msg = self.uri + " has stopped typing"
253 self.bot.broadcast_pager(self, msg)
254
255 def on_pager(self, mime_type, body, call=None, buddy=None):
256 if not self.bot.handle_cmd(self, None, body):
257 msg = self.uri + ": " + body
258 self.bot.broadcast_pager(self, msg, mime_type)
259
260 def on_pager_status(self, body, im_id, code, reason, call=None, buddy=None):
261 self.im_error = (code/100 != 2)
262
263
264
265 ##############################################################################
266 #
267 #
268 # The Bot instance (singleton)
269 #
270 #
271 class Bot(pj.AccountCallback):
272 def __init__(self):
273 pj.AccountCallback.__init__(self, None)
274 self.lib = pj.Lib()
275 self.acc = None
276 self.calls = []
277 self.members = {}
278 self.cfg = None
279
280 def DEBUG(self, msg, level=TRACE):
281 print msg,
282
283 def helpstring(self):
284 return """
285 --h[elp] Display this help screen
286 --j[oin] Join the chat room
287 --html on|off Set to receive HTML or plain text
288
289 Participant commands:
290 --s[how] Show confbot settings
291 --leave Leave the chatroom
292 --l[ist] List all members
293
294 Admin commands:
295 --a[dmin] <CMD> Where <CMD> are:
296 list List the admins
297 add <URI> Add URI as admin
298 del <URI> Remove URI as admin
299 rr Reregister account to server
300 call <URI> Make call to the URI and add to voice conf
301 dc <URI> Disconnect call to URI
302 hold <URI> Hold call with that URI
303 update <URI> Send UPDATE to call with that URI
304 reinvite <URI> Send re-INVITE to call with that URI
305 """
306
307 def listmembers(self):
308 msg = ""
309 for uri, m in self.members.iteritems():
310 msg = msg + str(m) + "\n"
311 return msg
312
313 def showsettings(self):
314 ai = self.acc.info()
315 msg = """
316 ConfBot status and settings:
317 URI: %(uri)s
318 Status: %(pres)s
319 Reg Status: %(reg_st)d
320 Reg Reason: %(reg_res)s
321 """ % {'uri': ai.uri, 'pres': ai.online_text, \
322 'reg_st': ai.reg_status, 'reg_res': ai.reg_reason}
323 return msg
324
325 def main(self, cfg_file):
326 try:
327 cfg = self.cfg = __import__(cfg_file)
328
329 self.lib.init(ua_cfg=cfg.ua_cfg, log_cfg=cfg.log_cfg, media_cfg=cfg.media_cfg)
330 self.lib.set_null_snd_dev()
331
332 transport = None
333 if cfg.udp_cfg:
334 transport = self.lib.create_transport(pj.TransportType.UDP, cfg.udp_cfg)
335 if cfg.tcp_cfg:
336 t = self.lib.create_transport(pj.TransportType.TCP, cfg.tcp_cfg)
337 if not transport:
338 transport = t
339
340 self.lib.start()
341
342 if cfg.acc_cfg:
343 self.DEBUG("Creating account %(uri)s..\n" % {'uri': cfg.acc_cfg.id}, INFO)
344 self.acc = self.lib.create_account(cfg.acc_cfg, cb=self)
345 else:
346 self.DEBUG("Creating account for %(t)s..\n" % \
347 {'t': transport.info().description}, INFO)
348 self.acc = self.lib.create_account_for_transport(transport, cb=self)
349
350 self.acc.set_basic_status(True)
351
352 # Wait for ENTER before quitting
353 print "Press q to quit or --help/--h for help"
354 while True:
355 input = sys.stdin.readline().strip(" \t\r\n")
356 if not self.handle_cmd(None, None, input):
357 if input=="q":
358 break
359
360 self.lib.destroy()
361 self.lib = None
362
363 except pj.Error, e:
364 print "Exception: " + str(e)
365 if self.lib:
366 self.lib.destroy()
367 self.lib = None
368
369 def broadcast_pager(self, exclude_member, body, mime_type="text/plain"):
370 self.DEBUG("Broadcast: " + body + "\n")
371 for uri, m in self.members.iteritems():
372 if m != exclude_member:
373 m.send_pager(body, mime_type)
374
375 def add_to_voice_conf(self, member):
376 if not member.call:
377 return
378 src_ci = member.call.info()
379 self.DEBUG("bot.add_to_voice_conf\n")
380 for uri, m in self.members.iteritems():
381 if m==member:
382 continue
383 if not m.call:
384 continue
385 dst_ci = m.call.info()
386 if dst_ci.media_state==pj.MediaState.ACTIVE and dst_ci.conf_slot!=-1:
387 self.lib.conf_connect(src_ci.conf_slot, dst_ci.conf_slot)
388 self.lib.conf_connect(dst_ci.conf_slot, src_ci.conf_slot)
389
390 def on_member_left(self, member):
391 if not member.call and not member.buddy:
392 del self.members[member.uri]
393 del member
394
395 def handle_admin_cmd(self, member, body):
396 if member and self.cfg.admins and not member.uri in self.cfg.admins:
397 member.send_pager("You are not admin")
398 return
399 args = body.split()
400 msg = ""
401
402 if len(args)==1:
403 args.append(" ")
404
405 if args[1]=="list":
406 if not self.cfg.admins:
407 msg = "Everyone is admin!"
408 else:
409 msg = str(self.cfg.admins)
410 elif args[1]=="add":
411 if len(args)!=3:
412 msg = "Usage: add <URI>"
413 else:
414 self.cfg.admins.append(args[2])
415 msg = args[2] + " added as admin"
416 elif args[1]=="del":
417 if len(args)!=3:
418 msg = "Usage: del <URI>"
419 elif args[2] not in self.cfg.admins:
420 msg = args[2] + " is not admin"
421 else:
422 self.cfg.admins.remove(args[2])
423 msg = args[2] + " has been removed from admins"
424 elif args[1]=="rr":
425 msg = "Reregistering.."
426 self.acc.set_registration(True)
427 elif args[1]=="call":
428 if len(args)!=3:
429 msg = "Usage: call <URI>"
430 else:
431 uri = args[2]
432 try:
433 call = self.acc.make_call(uri)
434 except pj.Error, e:
435 msg = "Error: " + str(e)
436 call = None
437
438 if call:
439 if not uri in self.members:
440 m = Member(self, uri)
441 self.members[m.uri] = m
442 else:
443 m = self.members[uri]
444 msg = "Adding " + m.uri + " to voice conference.."
445 m.join_call(call)
446 elif args[1]=="dc" or args[1]=="hold" or args[1]=="update" or args[1]=="reinvite":
447 if len(args)!=3:
448 msg = "Usage: " + args[1] + " <URI>"
449 else:
450 uri = args[2]
451 if not uri in self.members:
452 msg = "Member not found/URI doesn't match (note: case matters!)"
453 else:
454 m = self.members[uri]
455 if m.call:
456 if args[1]=="dc":
457 msg = "Disconnecting.."
458 m.call.hangup(603, "You're disconnected by admin")
459 elif args[1]=="hold":
460 msg = "Holding the call"
461 m.call.hold()
462 elif args[1]=="update":
463 msg = "Sending UPDATE"
464 m.call.update()
465 elif args[1]=="reinvite":
466 msg = "Sending re-INVITE"
467 m.call.reinvite()
468 else:
469 msg = "He is not in call"
470 else:
471 msg = "Unknown admin command " + body
472
473 #print "msg is '%(msg)s'" % {'msg': msg}
474
475 if True:
476 if member:
477 member.send_pager(msg)
478 else:
479 print msg
480
481 def handle_cmd(self, member, from_uri, body):
482 body = body.strip(" \t\r\n")
483 msg = ""
484 handled = True
485 if body=="--l" or body=="--list":
486 msg = self.listmembers()
487 if msg=="":
488 msg = "Nobody is here"
489 elif body[0:3]=="--s":
490 msg = self.showsettings()
491 elif body[0:6]=="--html" and member:
492 if body[8:11]=="off":
493 member.html = False
494 else:
495 member.html = True
496 elif body=="--h" or body=="--help":
497 msg = self.helpstring()
498 elif body=="--leave":
499 if not member or not member.buddy:
500 msg = "You are not in chatroom"
501 else:
502 member.buddy.unsubscribe()
503 elif body[0:3]=="--j":
504 if not from_uri in self.members:
505 m = Member(self, from_uri)
506 self.members[m.uri] = m
507 self.DEBUG("Adding " + m.uri + " to chatroom\n")
508 m.join_chat()
509 else:
510 m = self.members[from_uri]
511 self.DEBUG("Adding " + m.uri + " to chatroom\n")
512 m.join_chat()
513 elif body[0:3]=="--a":
514 self.handle_admin_cmd(member, body)
515 handled = True
516 else:
517 handled = False
518
519 if msg:
520 if member:
521 member.send_pager(msg)
522 elif from_uri:
523 self.acc.send_pager(from_uri, msg);
524 else:
525 print msg
526 return handled
527
528 def on_incoming_call(self, call):
529 self.DEBUG("on_incoming_call from %(uri)s\n" % {'uri': call.info().remote_uri}, INFO)
530 ci = call.info()
531 if not ci.remote_uri in self.members:
532 m = Member(self, ci.remote_uri)
533 self.members[m.uri] = m
534 m.join_call(call)
535 else:
536 m = self.members[ci.remote_uri]
537 m.join_call(call)
538 call.answer(200)
539
540 def on_incoming_subscribe(self, buddy, from_uri, contact_uri, pres_obj):
541 self.DEBUG("on_incoming_subscribe from %(uri)s\n" % from_uri, INFO)
542 return (200, 'OK')
543
544 def on_reg_state(self):
545 ai = self.acc.info()
546 self.DEBUG("Registration state: %(code)d/%(reason)s\n" % \
547 {'code': ai.reg_status, 'reason': ai.reg_reason}, INFO)
548 if ai.reg_status/100==2 and ai.reg_expires > 0:
549 self.acc.set_basic_status(True)
550
551 def on_pager(self, from_uri, contact, mime_type, body):
552 body = body.strip(" \t\r\n")
553 if not self.handle_cmd(None, from_uri, body):
554 self.acc.send_pager(from_uri, "You have not joined the chat room. Type '--join' to join or '--help' for the help")
555
556 def on_pager_status(self, to_uri, body, im_id, code, reason):
557 pass
558
559 def on_typing(self, from_uri, contact, is_typing):
560 pass
561
562
563
564
565 ##############################################################################
566 #
567 #
568 # main()
569 #
570 #
571 if __name__ == "__main__":
572 bot = Bot()
573 bot.main(CFG_FILE)
574