forked from ampledata/python3-pjsip
-
Notifications
You must be signed in to change notification settings - Fork 0
/
pjsua.py
2962 lines (2425 loc) · 95.6 KB
/
pjsua.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
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# $Id: pjsua.py 4810 2014-04-07 06:56:06Z ming $
#
# Object oriented PJSUA wrapper.
#
# Copyright (C) 2016 Matthew Williams <[email protected]>
# Copyright (C) 2003-2008 Benny Prijono <[email protected]>
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
#
"""Multimedia communication client library based on SIP protocol.
This implements a fully featured multimedia communication client
library based on PJSIP stack (http://www.pjsip.org)
1. FEATURES
- Session Initiation Protocol (SIP) features:
- Basic registration and call
- Multiple accounts
- Call hold, attended and unattended call transfer
- Presence
- Instant messaging
- Multiple SIP accounts
- Media features:
- Audio
- Conferencing
- Narrowband and wideband
- Codecs: PCMA, PCMU, GSM, iLBC, Speex, G.722, L16
- RTP/RTCP
- Secure RTP (SRTP)
- WAV playback, recording, and playlist
- NAT traversal features
- Symmetric RTP
- STUN
- TURN
- ICE
2. USING
See http://www.pjsip.org/trac/wiki/Python_SIP_Tutorial for a more thorough
tutorial. The paragraphs below explain basic tasks on using this module.
"""
import _pjsua
import _thread
import threading
import weakref
import time
class Error(BaseException):
"""Error exception class.
Member documentation:
op_name -- name of the operation that generated this error.
obj -- the object that generated this error.
err_code -- the error code.
"""
op_name = ""
obj = None
err_code = -1
_err_msg = ""
def __init__(self, op_name, obj, err_code, err_msg=""):
self.op_name = op_name
self.obj = obj
self.err_code = err_code
self._err_msg = err_msg
def err_msg(self):
"Retrieve the description of the error."
if self._err_msg != "":
return self._err_msg
self._err_msg = Lib.strerror(self.err_code)
return self._err_msg
def __str__(self):
return "Object: " + str(self.obj) + ", operation=" + self.op_name + \
", error=" + str(self.err_msg())
#
# Constants
#
class TransportType:
"""SIP transport type constants.
Member documentation:
UNSPECIFIED -- transport type is unknown or unspecified
UDP -- UDP transport
TCP -- TCP transport
TLS -- TLS transport
IPV6 -- this is not a transport type but rather a flag
to select the IPv6 version of a transport
UDP_IPV6 -- IPv6 UDP transport
TCP_IPV6 -- IPv6 TCP transport
"""
UNSPECIFIED = 0
UDP = 1
TCP = 2
TLS = 3
IPV6 = 128
UDP_IPV6 = UDP + IPV6
TCP_IPV6 = TCP + IPV6
class TransportFlag:
"""Transport flags to indicate the characteristics of the transport.
Member documentation:
RELIABLE -- transport is reliable.
SECURE -- transport is secure.
DATAGRAM -- transport is datagram based.
"""
RELIABLE = 1
SECURE = 2
DATAGRAM = 4
class CallRole:
"""Call role constants.
Member documentation:
CALLER -- role is caller
CALLEE -- role is callee
"""
CALLER = 0
CALLEE = 1
class CallState:
"""Call state constants.
Member documentation:
NULL -- call is not initialized.
CALLING -- initial INVITE is sent.
INCOMING -- initial INVITE is received.
EARLY -- provisional response has been sent or received.
CONNECTING -- 200/OK response has been sent or received.
CONFIRMED -- ACK has been sent or received.
DISCONNECTED -- call is disconnected.
"""
NULL = 0
CALLING = 1
INCOMING = 2
EARLY = 3
CONNECTING = 4
CONFIRMED = 5
DISCONNECTED = 6
class MediaState:
"""Call media state constants.
Member documentation:
NULL -- media is not available.
ACTIVE -- media is active.
LOCAL_HOLD -- media is put on-hold by local party.
REMOTE_HOLD -- media is put on-hold by remote party.
ERROR -- media error (e.g. ICE negotiation failure).
"""
NULL = 0
ACTIVE = 1
LOCAL_HOLD = 2
REMOTE_HOLD = 3
ERROR = 4
class MediaDir:
"""Media direction constants.
Member documentation:
NULL -- media is not active
ENCODING -- media is active in transmit/encoding direction only.
DECODING -- media is active in receive/decoding direction only
ENCODING_DECODING -- media is active in both directions.
"""
NULL = 0
ENCODING = 1
DECODING = 2
ENCODING_DECODING = 3
class PresenceActivity:
"""Presence activities constants.
Member documentation:
UNKNOWN -- the person activity is unknown
AWAY -- the person is currently away
BUSY -- the person is currently engaging in other activity
"""
UNKNOWN = 0
AWAY = 1
BUSY = 2
class SubscriptionState:
"""Presence subscription state constants.
"""
NULL = 0
SENT = 1
ACCEPTED = 2
PENDING = 3
ACTIVE = 4
TERMINATED = 5
UNKNOWN = 6
class TURNConnType:
"""These constants specifies the connection type to TURN server.
Member documentation:
UDP -- use UDP transport.
TCP -- use TCP transport.
TLS -- use TLS transport.
"""
UDP = 17
TCP = 6
TLS = 255
class UAConfig:
"""User agent configuration to be specified in Lib.init().
Member documentation:
max_calls -- maximum number of calls to be supported.
nameserver -- list of nameserver hostnames or IP addresses. Nameserver
must be configured if DNS SRV resolution is desired.
stun_domain -- if nameserver is configured, this can be used to query
the STUN server with DNS SRV.
stun_host -- the hostname or IP address of the STUN server. This will
also be used if DNS SRV resolution for stun_domain fails.
user_agent -- Optionally specify the user agent name.
"""
max_calls = 4
nameserver = []
stun_domain = ""
stun_host = ""
user_agent = "pjsip python"
def _cvt_from_pjsua(self, cfg):
self.max_calls = cfg.max_calls
self.thread_cnt = cfg.thread_cnt
self.nameserver = cfg.nameserver
self.stun_domain = cfg.stun_domain
self.stun_host = cfg.stun_host
self.user_agent = cfg.user_agent
def _cvt_to_pjsua(self):
cfg = _pjsua.config_default()
cfg.max_calls = self.max_calls
cfg.thread_cnt = 0
cfg.nameserver = self.nameserver
cfg.stun_domain = self.stun_domain
cfg.stun_host = self.stun_host
cfg.user_agent = self.user_agent
return cfg
class LogConfig:
"""Logging configuration to be specified in Lib.init().
Member documentation:
msg_logging -- specify if SIP messages should be logged. Set to
True.
level -- specify the input verbosity level.
console_level -- specify the output verbosity level.
decor -- specify log decoration.
filename -- specify the log filename.
callback -- specify callback to be called to write the logging
messages. Sample function:
def log_cb(level, str, len):
print str,
"""
msg_logging = True
level = 5
console_level = 5
decor = 0
filename = ""
callback = None
def __init__(self, level=-1, filename="", callback=None,
console_level=-1):
self._cvt_from_pjsua(_pjsua.logging_config_default())
if level != -1:
self.level = level
if filename != "":
self.filename = filename
if callback != None:
self.callback = callback
if console_level != -1:
self.console_level = console_level
def _cvt_from_pjsua(self, cfg):
self.msg_logging = cfg.msg_logging
self.level = cfg.level
self.console_level = cfg.console_level
self.decor = cfg.decor
self.filename = cfg.log_filename
self.callback = cfg.cb
def _cvt_to_pjsua(self):
cfg = _pjsua.logging_config_default()
cfg.msg_logging = self.msg_logging
cfg.level = self.level
cfg.console_level = self.console_level
cfg.decor = self.decor
cfg.log_filename = self.filename
cfg.cb = self.callback
return cfg
class MediaConfig:
"""Media configuration to be specified in Lib.init().
Member documentation:
clock_rate -- specify the core clock rate of the audio,
most notably the conference bridge.
snd_clock_rate -- optionally specify different clock rate for
the sound device.
snd_auto_close_time -- specify the duration in seconds when the
sound device should be closed after inactivity
period.
channel_count -- specify the number of channels to open the sound
device and the conference bridge.
audio_frame_ptime -- specify the length of audio frames in millisecond.
max_media_ports -- specify maximum number of audio ports to be
supported by the conference bridge.
quality -- specify the audio quality setting (1-10)
ptime -- specify the audio packet length of transmitted
RTP packet.
no_vad -- disable Voice Activity Detector (VAD) or Silence
Detector (SD)
ilbc_mode -- specify iLBC codec mode (must be 30 for now)
tx_drop_pct -- randomly drop transmitted RTP packets (for
simulation). Number is in percent.
rx_drop_pct -- randomly drop received RTP packets (for
simulation). Number is in percent.
ec_options -- Echo Canceller option (specify zero).
ec_tail_len -- specify Echo Canceller tail length in milliseconds.
Value zero will disable the echo canceller.
jb_min -- specify the minimum jitter buffer size in
milliseconds. Put -1 for default.
jb_max -- specify the maximum jitter buffer size in
milliseconds. Put -1 for default.
enable_ice -- enable Interactive Connectivity Establishment (ICE)
enable_turn -- enable TURN relay. TURN server settings must also
be configured.
turn_server -- specify the domain or hostname or IP address of
the TURN server, in "host[:port]" format.
turn_conn_type -- specify connection type to the TURN server, from
the TURNConnType constant.
turn_cred -- specify AuthCred for the TURN credential.
"""
clock_rate = 16000
snd_clock_rate = 0
snd_auto_close_time = 5
channel_count = 1
audio_frame_ptime = 20
max_media_ports = 32
quality = 6
ptime = 0
no_vad = False
ilbc_mode = 30
tx_drop_pct = 0
rx_drop_pct = 0
ec_options = 0
ec_tail_len = 256
jb_min = -1
jb_max = -1
enable_ice = True
enable_turn = False
turn_server = ""
turn_conn_type = TURNConnType.UDP
turn_cred = None
def __init__(self):
default = _pjsua.media_config_default()
self._cvt_from_pjsua(default)
def _cvt_from_pjsua(self, cfg):
self.clock_rate = cfg.clock_rate
self.snd_clock_rate = cfg.snd_clock_rate
self.snd_auto_close_time = cfg.snd_auto_close_time
self.channel_count = cfg.channel_count
self.audio_frame_ptime = cfg.audio_frame_ptime
self.max_media_ports = cfg.max_media_ports
self.quality = cfg.quality
self.ptime = cfg.ptime
self.no_vad = cfg.no_vad
self.ilbc_mode = cfg.ilbc_mode
self.tx_drop_pct = cfg.tx_drop_pct
self.rx_drop_pct = cfg.rx_drop_pct
self.ec_options = cfg.ec_options
self.ec_tail_len = cfg.ec_tail_len
self.jb_min = cfg.jb_min
self.jb_max = cfg.jb_max
self.enable_ice = cfg.enable_ice
self.enable_turn = cfg.enable_turn
self.turn_server = cfg.turn_server
self.turn_conn_type = cfg.turn_conn_type
if cfg.turn_username:
self.turn_cred = AuthCred(cfg.turn_realm, cfg.turn_username,
cfg.turn_passwd, cfg.turn_passwd_type)
else:
self.turn_cred = None
def _cvt_to_pjsua(self):
cfg = _pjsua.media_config_default()
cfg.clock_rate = self.clock_rate
cfg.snd_clock_rate = self.snd_clock_rate
cfg.snd_auto_close_time = self.snd_auto_close_time
cfg.channel_count = self.channel_count
cfg.audio_frame_ptime = self.audio_frame_ptime
cfg.max_media_ports = self.max_media_ports
cfg.quality = self.quality
cfg.ptime = self.ptime
cfg.no_vad = self.no_vad
cfg.ilbc_mode = self.ilbc_mode
cfg.tx_drop_pct = self.tx_drop_pct
cfg.rx_drop_pct = self.rx_drop_pct
cfg.ec_options = self.ec_options
cfg.ec_tail_len = self.ec_tail_len
cfg.jb_min = self.jb_min
cfg.jb_max = self.jb_max
cfg.enable_ice = self.enable_ice
cfg.enable_turn = self.enable_turn
cfg.turn_server = self.turn_server
cfg.turn_conn_type = self.turn_conn_type
if self.turn_cred:
cfg.turn_realm = self.turn_cred.realm
cfg.turn_username = self.turn_cred.username
cfg.turn_passwd_type = self.turn_cred.passwd_type
cfg.turn_passwd = self.turn_cred.passwd
return cfg
class TransportConfig:
"""SIP transport configuration class.
Member configuration:
port -- port number.
bound_addr -- optionally specify the address to bind the socket to.
Default is empty to bind to INADDR_ANY.
public_addr -- optionally override the published address for this
transport. If empty, the default behavior is to get
the public address from STUN or from the selected
local interface. Format is "host:port".
qos_type -- High level traffic classification.
Enumerator:
0: PJ_QOS_TYPE_BEST_EFFORT
Best effort traffic (default value). Any QoS function calls with
specifying this value are effectively no-op
1: PJ_QOS_TYPE_BACKGROUND
Background traffic.
2: PJ_QOS_TYPE_VIDEO
Video traffic.
3: PJ_QOS_TYPE_VOICE
Voice traffic.
4: PJ_QOS_TYPE_CONTROL
Control traffic.
qos_params_flags -- Determines which values to set, bitmask of pj_qos_flag.
PJ_QOS_PARAM_HAS_DSCP = 1
PJ_QOS_PARAM_HAS_SO_PRIO = 2
PJ_QOS_PARAM_HAS_WMM = 4
qos_params_dscp_val -- The 6 bits DSCP value to set.
qos_params_so_prio -- Socket SO_PRIORITY value.
qos_params_wmm_prio -- Standard WMM priorities.
Enumerator:
0: PJ_QOS_WMM_PRIO_BULK_EFFORT: Bulk effort priority
1: PJ_QOS_WMM_PRIO_BULK: Bulk priority.
2: PJ_QOS_WMM_PRIO_VIDEO: Video priority
3: PJ_QOS_WMM_PRIO_VOICE: Voice priority.
"""
port = 0
bound_addr = ""
public_addr = ""
qos_type = 0
qos_params_flags = 0
qos_params_dscp_val = 0
qos_params_so_prio = 0
qos_params_wmm_prio = 0
def __init__(self, port=0,
bound_addr="", public_addr=""):
self.port = port
self.bound_addr = bound_addr
self.public_addr = public_addr
def _cvt_from_pjsua(self, cfg):
self.port = cfg.port
self.bound_addr = cfg.bound_addr
self.public_addr = cfg.public_addr
self.qos_type = cfg.qos_type
self.qos_params_flags = cfg.qos_params_flags
self.qos_params_dscp_val = cfg.qos_params_dscp_val
self.qos_params_so_prio = cfg.qos_params_so_prio
self.qos_params_wmm_prio = cfg.qos_params_wmm_prio
def _cvt_to_pjsua(self):
cfg = _pjsua.transport_config_default()
cfg.port = self.port
cfg.bound_addr = self.bound_addr
cfg.public_addr = self.public_addr
cfg.qos_type = self.qos_type
cfg.qos_params_flags = self.qos_params_flags
cfg.qos_params_dscp_val = self.qos_params_dscp_val
cfg.qos_params_so_prio = self.qos_params_so_prio
cfg.qos_params_wmm_prio = self.qos_params_wmm_prio
return cfg
class TransportInfo:
"""SIP transport info.
Member documentation:
type -- transport type, from TransportType constants.
description -- longer description for this transport.
is_reliable -- True if transport is reliable.
is_secure -- True if transport is secure.
is_datagram -- True if transport is datagram based.
host -- the IP address of this transport.
port -- the port number.
ref_cnt -- number of objects referencing this transport.
"""
type = ""
description = ""
is_reliable = False
is_secure = False
is_datagram = False
host = ""
port = 0
ref_cnt = 0
def __init__(self, ti):
self.type = ti.type_name
self.description = ti.info
self.is_reliable = (ti.flag & TransportFlag.RELIABLE)
self.is_secure = (ti.flag & TransportFlag.SECURE)
self.is_datagram = (ti.flag & TransportFlag.DATAGRAM)
self.host = ti.addr
self.port = ti.port
self.ref_cnt = ti.usage_count
class Transport:
"SIP transport class."
_id = -1
_lib = None
_obj_name = ""
def __init__(self, lib, id):
self._lib = weakref.proxy(lib)
self._id = id
self._obj_name = "{Transport " + self.info().description + "}"
_Trace((self, 'created'))
def __del__(self):
_Trace((self, 'destroyed'))
def __str__(self):
return self._obj_name
def info(self):
"""Get TransportInfo.
"""
lck = self._lib.auto_lock()
ti = _pjsua.transport_get_info(self._id)
if not ti:
self._lib._err_check("info()", self, -1, "Invalid transport")
return TransportInfo(ti)
def enable(self):
"""Enable this transport."""
lck = self._lib.auto_lock()
err = _pjsua.transport_set_enable(self._id, True)
self._lib._err_check("enable()", self, err)
def disable(self):
"""Disable this transport."""
lck = self._lib.auto_lock()
err = _pjsua.transport_set_enable(self._id, 0)
self._lib._err_check("disable()", self, err)
def close(self, force=False):
"""Close and destroy this transport.
Keyword argument:
force -- force deletion of this transport (not recommended).
"""
lck = self._lib.auto_lock()
err = _pjsua.transport_close(self._id, force)
self._lib._err_check("close()", self, err)
class SIPUri:
"""Helper class to parse the most important components of SIP URI.
Member documentation:
scheme -- URI scheme ("sip" or "sips")
user -- user part of the URI (may be empty)
host -- host name part
port -- optional port number (zero if port is not specified).
transport -- transport parameter, or empty if transport is not
specified.
"""
scheme = ""
user = ""
host = ""
port = 0
transport = ""
def __init__(self, uri=None):
if uri:
self.decode(uri)
def decode(self, uri):
"""Parse SIP URL.
Keyword argument:
uri -- the URI string.
"""
self.scheme, self.user, self.host, self.port, self.transport = \
_pjsua.parse_simple_uri(uri)
def encode(self):
"""Encode this object into SIP URI string.
Return:
URI string.
"""
output = self.scheme + ":"
if self.user and len(self.user):
output = output + self.user + "@"
output = output + self.host
if self.port:
output = output + ":" + output(self.port)
if self.transport:
output = output + ";transport=" + self.transport
return output
class AuthCred:
"""Authentication credential for SIP or TURN account.
Member documentation:
scheme -- authentication scheme (default is "Digest")
realm -- realm
username -- username
passwd_type -- password encoding (zero for plain-text)
passwd -- the password
"""
scheme = "Digest"
realm = "*"
username = ""
passwd_type = 0
passwd = ""
def __init__(self, realm, username, passwd, scheme="Digest", passwd_type=0):
self.scheme = scheme
self.realm = realm
self.username = username
self.passwd_type = passwd_type
self.passwd = passwd
class AccountConfig:
""" This describes account configuration to create an account.
Member documentation:
priority -- account priority for matching incoming
messages.
id -- SIP URI of this account. This setting is
mandatory.
force_contact -- force to use this URI as Contact URI. Setting
this value is generally not recommended.
reg_uri -- specify the registrar URI. Mandatory if
registration is required.
reg_timeout -- specify the SIP registration refresh interval
in seconds.
require_100rel -- specify if reliable provisional response is
to be enforced (with Require header).
publish_enabled -- specify if PUBLISH should be used. When
enabled, the PUBLISH will be sent to the
registrar.
pidf_tuple_id -- optionally specify the tuple ID in outgoing
PIDF document.
proxy -- list of proxy URI.
auth_cred -- list of AuthCred containing credentials to
authenticate against the registrars and
the proxies.
auth_initial_send -- specify if empty Authorization header should be
sent. May be needed for IMS.
auth_initial_algorithm -- when auth_initial_send is enabled, optionally
specify the authentication algorithm to use.
Valid values are "md5", "akav1-md5", or
"akav2-md5".
transport_id -- optionally specify the transport ID to be used
by this account. Shouldn't be needed unless
for specific requirements (e.g. in multi-homed
scenario).
allow_contact_rewrite -- specify whether the account should learn its
Contact address from REGISTER response and
update the registration accordingly. Default is
True.
ka_interval -- specify the interval to send NAT keep-alive
packet.
ka_data -- specify the NAT keep-alive packet contents.
use_srtp -- specify the SRTP usage policy. Valid values
are: 0=disable, 1=optional, 2=mandatory.
Default is 0.
srtp_secure_signaling -- specify the signaling security level required
by SRTP. Valid values are: 0=no secure
transport is required, 1=hop-by-hop secure
transport such as TLS is required, 2=end-to-
end secure transport is required (i.e. "sips").
rtp_transport_cfg -- the rtp-transport-configuration that is usede, when
a rtp-connection is being established.
"""
priority = 0
id = ""
force_contact = ""
reg_uri = ""
reg_timeout = 0
require_100rel = False
publish_enabled = False
pidf_tuple_id = ""
proxy = []
auth_cred = []
auth_initial_send = False
auth_initial_algorithm = ""
transport_id = -1
allow_contact_rewrite = True
ka_interval = 15
ka_data = "\r\n"
use_srtp = 0
srtp_secure_signaling = 1
rtp_transport_cfg = None
mwi_enabled = False
def __init__(self, domain="", username="", password="",
display="", registrar="", proxy=""):
"""
Construct account config. If domain argument is specified,
a typical configuration will be built.
Keyword arguments:
domain -- domain name of the server.
username -- user name.
password -- plain-text password.
display -- optional display name for the user name.
registrar -- the registrar URI. If domain name is specified
and this argument is empty, the registrar URI
will be constructed from the domain name.
proxy -- the proxy URI. If domain name is specified
and this argument is empty, the proxy URI
will be constructed from the domain name.
"""
default = _pjsua.acc_config_default()
self._cvt_from_pjsua(default)
if domain!="":
self.build_config(domain, username, password,
display, registrar, proxy)
self.rtp_transport_cfg = TransportConfig()
def build_config(self, domain, username, password, display="",
registrar="", proxy="", rtp_transport_cfg = None):
"""
Construct account config. If domain argument is specified,
a typical configuration will be built.
Keyword arguments:
domain -- domain name of the server.
username -- user name.
password -- plain-text password.
display -- optional display name for the user name.
registrar -- the registrar URI. If domain name is specified
and this argument is empty, the registrar URI
will be constructed from the domain name.
proxy -- the proxy URI. If domain name is specified
and this argument is empty, the proxy URI
will be constructed from the domain name.
"""
if display != "":
display = display + " "
userpart = username
if userpart != "":
userpart = userpart + "@"
self.id = display + "<sip:" + userpart + domain + ">"
self.reg_uri = registrar
if self.reg_uri == "":
self.reg_uri = "sip:" + domain
if proxy == "":
proxy = "sip:" + domain + ";lr"
if proxy.find(";lr") == -1:
proxy = proxy + ";lr"
self.proxy.append(proxy)
if username != "":
self.auth_cred.append(AuthCred("*", username, password))
if (rtp_transport_cfg is not None):
self.rtp_transport_cfg = rtp_transport_cfg
else:
self.rtp_transport_cfg = TransportConfig()
def _cvt_from_pjsua(self, cfg):
self.priority = cfg.priority
self.id = cfg.id
self.force_contact = cfg.force_contact
self.reg_uri = cfg.reg_uri
self.reg_timeout = cfg.reg_timeout
self.require_100rel = cfg.require_100rel
self.publish_enabled = cfg.publish_enabled
self.pidf_tuple_id = cfg.pidf_tuple_id
self.proxy = cfg.proxy
for cred in cfg.cred_info:
self.auth_cred.append(AuthCred(cred.realm, cred.username,
cred.data, cred.scheme,
cred.data_type))
self.auth_initial_send = cfg.auth_initial_send
self.auth_initial_algorithm = cfg.auth_initial_algorithm
self.transport_id = cfg.transport_id
self.allow_contact_rewrite = cfg.allow_contact_rewrite
self.ka_interval = cfg.ka_interval
self.ka_data = cfg.ka_data
self.use_srtp = cfg.use_srtp
self.srtp_secure_signaling = cfg.srtp_secure_signaling
self.mwi_enabled = cfg.mwi_enabled
if (self.rtp_transport_cfg is not None):
self.rtp_transport_cfg._cvt_from_pjsua(cfg.rtp_transport_cfg)
def _cvt_to_pjsua(self):
cfg = _pjsua.acc_config_default()
cfg.priority = self.priority
cfg.id = self.id
cfg.force_contact = self.force_contact
cfg.reg_uri = self.reg_uri
cfg.reg_timeout = self.reg_timeout
cfg.require_100rel = self.require_100rel
cfg.publish_enabled = self.publish_enabled
cfg.pidf_tuple_id = self.pidf_tuple_id
cfg.proxy = self.proxy
for cred in self.auth_cred:
c = _pjsua.Pjsip_Cred_Info()
c.realm = cred.realm
c.scheme = cred.scheme
c.username = cred.username
c.data_type = cred.passwd_type
c.data = cred.passwd
cfg.cred_info.append(c)
cfg.auth_initial_send = self.auth_initial_send
cfg.auth_initial_algorithm = self.auth_initial_algorithm
cfg.transport_id = self.transport_id
cfg.allow_contact_rewrite = self.allow_contact_rewrite
cfg.ka_interval = self.ka_interval
cfg.ka_data = self.ka_data
cfg.use_srtp = self.use_srtp
cfg.srtp_secure_signaling = self.srtp_secure_signaling
cfg.mwi_enabled = self.mwi_enabled
if (self.rtp_transport_cfg is not None):
cfg.rtp_transport_cfg = self.rtp_transport_cfg._cvt_to_pjsua()
return cfg
# Account information
class AccountInfo:
"""This describes Account info. Application retrives account info
with Account.info().
Member documentation:
is_default -- True if this is the default account.
uri -- the account URI.
reg_active -- True if registration is active for this account.
reg_expires -- contains the current registration expiration value,
in seconds.
reg_status -- the registration status. If the value is less than
700, it specifies SIP status code. Value greater than
this specifies the error code.
reg_reason -- contains the registration status text (e.g. the
error message).
online_status -- the account's presence online status, True if it's
publishing itself as online.
online_text -- the account's presence status text.
"""
is_default = False
uri = ""
reg_active = False
reg_expires = -1
reg_status = 0
reg_reason = ""
online_status = False
online_text = ""
def __init__(self, ai):
self.is_default = ai.is_default
self.uri = ai.acc_uri
self.reg_active = ai.has_registration
self.reg_expires = ai.expires
self.reg_status = ai.status
self.reg_reason = ai.status_text
self.online_status = ai.online_status
self.online_text = ai.online_status_text
# Account callback
class AccountCallback:
"""Class to receive notifications on account's events.
Derive a class from this class and register it to the Account object
using Account.set_callback() to start receiving events from the Account
object.
Member documentation:
account -- the Account object.
"""
account = None
def __init__(self, account=None):
self._set_account(account)
def __del__(self):
pass
def _set_account(self, account):
if account:
self.account = weakref.proxy(account)
else:
self.account = None
def on_reg_state(self):
"""Notification that the registration status has changed.
"""
pass
def on_incoming_call(self, call):
"""Notification about incoming call.
Application should implement one of on_incoming_call() or
on_incoming_call2(), otherwise, the default behavior is to
reject the call with default status code. Note that if both are
implemented, only on_incoming_call2() will be called.
Keyword arguments:
call -- the new incoming call
"""
call.hangup()
def on_incoming_call2(self, call, rdata):
"""Notification about incoming call, with received SIP message info.
Application should implement one of on_incoming_call() or
on_incoming_call2(), otherwise, the default behavior is to