-
Notifications
You must be signed in to change notification settings - Fork 4
/
sip-session3
executable file
·3765 lines (3165 loc) · 174 KB
/
sip-session3
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
#!/usr/bin/env python3
import hashlib
import glob
import os
import re
import signal
import json
import sys
import urllib.request, urllib.parse, urllib.error
import random
import requests
import uuid
import pgpy
import subprocess
from collections import defaultdict
from datetime import datetime, timedelta
from dateutil.tz import tzlocal
from itertools import chain
from lxml import html
from optparse import OptionParser
from pathlib import Path
from threading import Event, Thread
from time import sleep
from application import log
from application.system import makedirs
from application.notification import IObserver, NotificationCenter, NotificationData
from application.python.queue import EventQueue
from application.python import Null
from eventlib import api
from gnutls.errors import GNUTLSError
from gnutls.crypto import X509Certificate, X509PrivateKey
from twisted.internet import reactor
from zope.interface import implementer
from otr import OTRTransport, OTRState, SMPStatus
from otr.exceptions import IgnoreMessage, UnencryptedMessage, EncryptedMessageError, OTRError, OTRFinishedError
from sipsimple.core import Engine, FromHeader, Message, RouteHeader, SIPCoreError, SIPURI, ToHeader
from sipsimple.account import Account, AccountManager, BonjourAccount
from sipsimple.application import SIPApplication
from sipsimple.audio import WavePlayer
from sipsimple.configuration import ConfigurationError
from sipsimple.configuration.settings import SIPSimpleSettings
from sipsimple.core import Route
from sipsimple.core import CORE_REVISION, PJ_VERSION, PJ_SVN_REVISION
from sipsimple import __version__ as version
from sipsimple.lookup import DNSLookup
from sipsimple.payloads.iscomposing import IsComposingMessage, IsComposingDocument
from sipsimple.session import IllegalStateError, Session
from sipsimple.streams import MediaStreamRegistry
from sipsimple.streams.msrp.filetransfer import FileSelector
from sipsimple.streams.msrp.chat import CPIMPayload, CPIMHeader, CPIMNamespace, SimplePayload, CPIMParserError, ChatIdentity, OTREncryption
from sipsimple.payloads.imdn import IMDNDocument, DisplayNotification, DeliveryNotification
from sipsimple.storage import FileStorage
from sipsimple.threading.green import run_in_green_thread
from sipsimple.util import ISOTimestamp
from sipclient.configuration import config_directory
from sipclient.configuration.account import AccountExtension, BonjourAccountExtension
from sipclient.configuration.datatypes import ResourcePath
from sipclient.configuration.settings import SIPSimpleSettingsExtension
from sipclient.log import Logger
from sipclient.system import IPAddressMonitor, copy_default_certificates
from sipclient.ui import Prompt, Question, RichText, UI
# This is a helper function for sending formatted notice messages
def show_notice(text, bold=True):
ui = UI()
if isinstance(text, list):
ui.writelines([RichText(line, bold=bold) if not isinstance(line, RichText) else line for line in text])
elif isinstance(text, RichText):
ui.write(text)
else:
ui.write(RichText(text, bold=bold))
# Utility classes
#
class BonjourNeighbour(object):
def __init__(self, neighbour, uri, display_name, host):
self.display_name = display_name
self.host = host
self.neighbour = neighbour
self.uri = uri
class RTPStatisticsThread(Thread):
def __init__(self):
Thread.__init__(self)
self.setDaemon(True)
self.stopped = False
def run(self):
application = SIPSessionApplication()
while not self.stopped:
if application.active_session is not None and application.active_session.streams:
audio_stream = next((stream for stream in application.active_session.streams if stream.type == 'audio'), None)
if audio_stream is not None:
stats = audio_stream.statistics
if stats is not None:
reactor.callFromThread(show_notice, '%s RTP statistics: RTT=%d ms, packet loss=%.1f%%, jitter RX/TX=%d/%d ms' %
(datetime.now().replace(microsecond=0),
stats['rtt']['avg'] / 1000,
100.0 * stats['rx']['packets_lost'] / stats['rx']['packets'] if stats['rx']['packets'] else 0,
stats['rx']['jitter']['avg'] / 1000,
stats['tx']['jitter']['avg'] / 1000))
sleep(10)
def stop(self):
self.stopped = True
class QueuedMessage(object):
def __init__(self, msg_id, content, content_type='text/plain', call_id=None):
self.id = msg_id
self.content = content
self.timestamp = None
self.content_type = content_type
self.encrypted = False
self.call_id = None
class OTRInternalMessage(QueuedMessage):
def __init__(self, content):
super(OTRInternalMessage, self).__init__('OTR', content, 'text/plain')
@implementer(IObserver)
class MessageSession(object):
def __init__(self, account, target, route=None):
self.account = account
self.target = target
self.routes = None
self.msg_id = 0
self.started = False
self.msg_map = {}
self.route = None
self.ended = False
self.route = route
self.notification_center = NotificationCenter()
self.encryption = OTREncryption(self)
self.message_queue = EventQueue(self._send_message)
target = self.target
if '@' not in target:
target = '%s@%s' % (target, self.account.id.domain)
if not target.startswith('sip:') and not target.startswith('sips:'):
target = 'sip:' + target
self.remote_uri = str(target).split(":")[1]
try:
self.target_uri = SIPURI.parse(target)
except SIPCoreError:
show_notice('Illegal SIP URI: %s' % target)
self.target_uri = None
return
self.notification_center = NotificationCenter()
if self.route:
show_notice('Message session started with %s via %s' % (self.target, self.route))
else:
show_notice('Message session started with %s' % self.target)
def end(self):
show_notice('Ending message session to %s' % self.target)
if self.encryption.active:
self.encryption.stop()
self.notification_center = None
self.message_queue = None
self.encryption = None
self.ended = True
def start(self):
if self.ended:
return
if self.route:
self.routes = [self.route]
show_notice('%s Message session to %s will start via %s' % (datetime.now().replace(microsecond=0), self.remote_uri, self.routes[0]))
if not self.started:
self.message_queue.start()
if not self.encryption.active:
self.encryption.start()
self.started = True
return
lookup = DNSLookup()
self.notification_center.add_observer(self, sender=lookup)
settings = SIPSimpleSettings()
if isinstance(self.account, Account) and self.account.sip.outbound_proxy is not None:
uri = SIPURI(host=self.account.sip.outbound_proxy.host, port=self.account.sip.outbound_proxy.port, parameters={'transport': self.account.sip.outbound_proxy.transport})
tls_name = self.account.sip.tls_name or self.account.sip.outbound_proxy.host
elif isinstance(self.account, Account) and self.account.sip.always_use_my_proxy:
uri = SIPURI(host=self.account.id.domain)
tls_name = self.account.sip.tls_name or self.account.id.domain
else:
uri = self.remote_uri
tls_name = uri.host
if self.account is not BonjourAccount():
if self.account.id.domain == uri.host.decode():
tls_name = self.account.sip.tls_name or self.account.id.domain
elif "isfocus" in str(uri) and uri.host.decode().endswith(self.account.id.domain):
tls_name = self.account.conference.tls_name or self.account.sip.tls_name or self.account.id.domain
else:
is_ip_address = re.match("^\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}$", uri.host.decode()) or ":" in uri.host.decode()
if "isfocus" in str(uri) and self.account.conference.tls_name:
tls_name = self.account.conference.tls_name
elif is_ip_address and self.account.sip.tls_name:
tls_name = self.account.sip.tls_name
lookup.lookup_sip_proxy(uri, settings.sip.transport_list, tls_name=tls_name)
def handle_notification(self, notification):
if self.ended:
return
handler = getattr(self, '_NH_%s' % notification.name, Null)
handler(notification)
def inject_otr_message(self, data):
if not self.encryption.active:
ui = UI()
ui.status = 'Negotiating OTR encryption...'
messageObject = OTRInternalMessage(data)
self.send_message(messageObject)
def _NH_DNSLookupDidSucceed(self, notification):
self.notification_center.remove_observer(self, sender=notification.sender)
self.routes = notification.data.result
show_notice('%s Message session to %s will start via %s' % (datetime.now().replace(microsecond=0), self.remote_uri, self.routes[0]))
if not self.started:
self.message_queue.start()
if not self.encryption.active and self.account.sms.enable_otr:
self.encryption.start()
self.started = True
def _NH_DNSLookupDidFail(self, notification):
self.notification_center.remove_observer(self, sender=notification.sender)
show_notice('%s Message session to %s failed: DNS lookup failed' % (datetime.now().replace(microsecond=0), self.remote_uri))
self.message_queue.stop()
if not self.routes:
self.start()
self.msg_id = self.msg_id + 1
if not isinstance(message, OTRInternalMessage):
messageObject = QueuedMessage(self.msg_id , message, content_type)
self.message_queue.put(messageObject)
else:
self.message_queue.put(message)
return self.msg_id
def send_message(self, message, content_type='text/plain'):
if not self.routes:
self.start()
self.msg_id = self.msg_id + 1
if not isinstance(message, OTRInternalMessage):
messageObject = QueuedMessage(self.msg_id , message, content_type)
self.message_queue.put(messageObject)
else:
self.message_queue.put(message)
return self.msg_id
@run_in_green_thread
def send_imdn_notification(self, imdn_id, imdn_timestamp, recipient, sender_identity, event):
show_notice('Send %s notification for %s' % (event, imdn_id))
if event == 'delivered':
notification = DeliveryNotification('delivered')
elif event == 'displayed':
notification = DisplayNotification(event)
else:
return
content = IMDNDocument.create(message_id=imdn_id, datetime=imdn_timestamp, recipient_uri=recipient, notification=notification)
self.send_message(content.decode(), content_type=IMDNDocument.content_type)
@run_in_green_thread
def _send_message(self, message):
if not self.routes:
return
if not self.route:
self.route = self.routes.pop(0)
identity = str(self.account.uri)
if self.account.display_name:
identity = '"%s" <%s>' % (self.account.display_name, identity)
if isinstance(message.content, str):
charset = 'utf8'
message.content = message.content.encode(charset)
else:
charset = None
what_type = None
if not isinstance(message, OTRInternalMessage):
if message.content_type not in (IsComposingDocument.content_type, IMDNDocument.content_type):
try:
message.content = self.encryption.otr_session.handle_output(message.content, message.content_type)
except OTRError as e:
if 'has ended the private conversation' in str(e):
show_notice('Encryption has been disabled by remote party, please resend the message again')
self.encryption.stop()
else:
show_notice('Failed to encrypt outgoing message: %s' % str(e))
return
except OTRFinishedError:
show_notice('Encryption has finished, please resend the message again')
return
if self.encryption.active and not message.content.startswith(b'?OTR:'):
show_notice('Encryption has been disabled by remote party, please resend the message again')
self.encryption.stop()
return None
else:
what_type = 'OTR'
if message.timestamp is None:
message.timestamp = ISOTimestamp.now()
additional_cpim_headers = []
additional_sip_headers = []
if self.account.sms.use_cpim:
if self.account.sms.enable_imdn and message.content_type != IsComposingDocument.content_type:
ns = CPIMNamespace('urn:ietf:params:imdn', 'imdn')
additional_cpim_headers = [CPIMHeader('Message-ID', ns, str(uuid.uuid4()))]
if message.content_type != IsComposingDocument.content_type:
# request IMDN
additional_cpim_headers.append(CPIMHeader('Disposition-Notification', ns, 'positive-delivery, display'))
content_type = 'message/cpim'
payload = CPIMPayload(message.content,
message.content_type,
charset='utf-8',
timestamp=message.timestamp,
sender=ChatIdentity(self.account.uri, self.account.display_name),
recipients=[ChatIdentity(self.remote_uri, None)],
additional_headers=additional_cpim_headers)
else:
payload = SimplePayload(message.content, message.content_type, charset)
content, content_type = payload.encode()
from_uri = self.account.uri
if self.account is BonjourAccount():
settings = SIPSimpleSettings()
from_uri.parameters['instance_id'] = settings.instance_id
message_request = Message(FromHeader(from_uri, self.account.display_name),
ToHeader(self.target_uri),
RouteHeader(self.route.uri),
content_type,
content,
credentials=self.account.credentials,
extra_headers=additional_sip_headers)
self.notification_center.add_observer(self, sender=message_request)
self.msg_map[str(message_request)] = message
message_request.send(15)
call_id = message_request._request.call_id.decode()
message.call_id = call_id
ui = UI()
if message.id != 'OTR':
if '?OTR:' in content:
if message.content_type not in (IsComposingDocument.content_type, IMDNDocument.content_type):
ui.status = 'Encrypted message sent to %s' % self.route.uri
reactor.callLater(2, setattr, ui, 'status', None)
message.encrypted = True
else:
if message.content_type not in (IsComposingDocument.content_type, IMDNDocument.content_type):
ui.status = 'Message sent to %s' % (self.route.uri)
reactor.callLater(3, setattr, ui, 'status', None)
else:
ui.status = 'OTR message %s sent' % call_id
reactor.callLater(3, setattr, ui, 'status', None)
def handle_incoming_message(self, from_header, content_type, data, call_id):
self.msg_id = self.msg_id + 1
cpim_imdn_events = None
imdn_timestamp = None
imdn_id = None
from_header = FromHeader.new(from_header)
identity = '%s@%s' % (from_header.uri.user.decode(), from_header.uri.host.decode())
if content_type == 'message/cpim':
try:
cpim_message = CPIMPayload.decode(data)
except CPIMParserError as e:
show_notice('CPIM parse error: %s' % str(e))
return None
else:
content = cpim_message.content
payload = cpim_message
content_type = cpim_message.content_type
#if cpim_message.sender:
# identity = '%s@%s' % (cpim_message.sender.uri.user.decode(), cpim_message.sender.uri.host.decode())
# if from_header.uri == cpim_message.sender.uri:
# if cpim_message.sender.display_name:
# identity = '"%s" <%s>' % (cpim_message.sender.display_name, identity)
# elif from_header.display_name:
# identity = '"%s" <%s>' % (from_header.display_name, identity)
#else:
# identity = from_header
sender_identity = cpim_message.sender or from_header
imdn_timestamp = cpim_message.timestamp
for h in cpim_message.additional_headers:
if h.name == "Message-ID":
imdn_id = h.value
if h.name == "Disposition-Notification":
cpim_imdn_events = h.value
if content_type == IMDNDocument.content_type and content_type not in ('text/pgp-private-key', 'text/pgp-public-key'):
document = IMDNDocument.parse(content)
imdn_message_id = document.message_id.value
imdn_status = document.notification.status.__str__()
ui = UI()
msg = "Message %s was %s" % (imdn_message_id, imdn_status)
ui.status = msg
reactor.callLater(2, setattr, ui, 'status', None)
show_notice(msg)
return
else:
payload = SimplePayload.decode(data, content_type)
from_header = FromHeader.new(from_header)
identity = '%s@%s' % (from_header.uri.user.decode(), from_header.uri.host.decode())
content = payload.content
content_type = payload.content_type
if cpim_imdn_events and imdn_timestamp and content_type not in ('text/pgp-private-key', 'text/pgp-public-key', 'application/sylk-file-transfer'):
if self.account.sms.enable_imdn:
if 'delivery' in cpim_imdn_events:
self.send_imdn_notification(imdn_id, imdn_timestamp, identity, sender_identity, 'delivered')
if 'display' in cpim_imdn_events:
self.send_imdn_notification(imdn_id, imdn_timestamp, identity, sender_identity, 'displayed')
# if content_type not in (IsComposingDocument.content_type, IMDNDocument.content_type):
try:
content = self.encryption.otr_session.handle_input(content, content_type)
except IgnoreMessage:
show_notice('OTR message %s received' % call_id)
return None
except UnencryptedMessage:
encrypted = False
encryption_active = True
except EncryptedMessageError as e:
show_notice('OTP encrypted message error: %s' % str(e))
return None
except (OTRError, OTRFinishedError) as e:
show_notice('OTP error: %s' % str(e))
return None
else:
encrypted = encryption_active = self.encryption.active
if payload.charset is not None:
content = content.decode(payload.charset)
elif payload.content_type.startswith('text/'):
content.decode('utf8')
return (content_type, content, identity, self.msg_id, encrypted)
def _NH_SIPMessageDidSucceed(self, notification):
self.notification_center.remove_observer(self, sender=notification.sender)
try:
message = self.msg_map[str(notification.sender)]
except KeyError:
message = None
else:
del(self.msg_map[str(notification.sender)])
if not message:
return
if message.id in (None, 'OTR'):
return
if message.content_type in (IsComposingDocument.content_type, IMDNDocument.content_type):
return
ui = UI()
if notification.data.code == 202:
ui.status = 'Message %s to %s will be delivered later by the server' % (message.id, self.remote_uri)
reactor.callLater(4, setattr, ui, 'status', None)
elif notification.data.code == 200:
ui.status = 'Message %s received by %s' % (message.id, self.remote_uri)
reactor.callLater(4, setattr, ui, 'status', None)
else:
ui.status = 'Message %s received by %s (code %d)' % (message.id, self.remote_uri, notification.data.code)
reactor.callLater(4, setattr, ui, 'status', None)
def _NH_SIPMessageDidFail(self, notification):
self.notification_center.remove_observer(self, sender=notification.sender)
try:
message = self.msg_map[str(notification.sender)]
except KeyError:
message = None
else:
del(self.msg_map[str(notification.sender)])
if not message:
return
if message.id in (None, 'OTR'):
return
if hasattr(notification.data, 'headers'):
server = notification.data.headers.get('Server', Null).body
client = notification.data.headers.get('Client', Null).body
else:
server = 'local'
client = 'local'
if notification.data.code == 408 and self.routes:
pass
# self.route = self.routes.pop(0)
# TO DO retry
if message.encrypted:
show_notice('%s Encrypted message %s to %s failed on %s: %s (%d)' % (datetime.now().replace(microsecond=0), message.id, self.remote_uri, server or client, notification.data.reason.decode(), notification.data.code))
else:
show_notice('%s Message %s to %s failed on %s: %s (%d)' % (datetime.now().replace(microsecond=0), message.id, self.remote_uri, server or client, notification.data.reason.decode() if isinstance(notification.data.reason, bytes) else notification.data.reason, notification.data.code))
OTRTransport.register(MessageSession)
@implementer(IObserver)
class OutgoingCallInitializer(object):
def __init__(self, account, target, audio=False, chat=False, video=False, play_file=None, auto_reconnect=False):
self.account = account
self.target = target
self.auto_reconnect = auto_reconnect
self.streams = []
self.play_file = play_file
self.playback_wave_player = None
self.play_file = play_file
application = SIPSessionApplication()
self.playback_dir = application.playback_dir
self.remote_identity = None
if video:
self.streams.append(MediaStreamRegistry.VideoStream())
if audio:
audio_stream = MediaStreamRegistry.AudioStream()
self.streams.append(audio_stream)
if self.play_file:
notification_center = NotificationCenter()
notification_center.add_observer(self, sender=audio_stream)
if chat:
self.streams.append(MediaStreamRegistry.ChatStream())
self.wave_ringtone = None
def start(self):
if self.play_file:
lock_file = "%s/playback.lock" % self.playback_dir
Path(lock_file).touch()
show_notice("Lock file %s created" % lock_file)
if isinstance(self.account, BonjourAccount) and '@' not in self.target:
show_notice('Bonjour mode requires a host in the destination address')
return
if '@' not in self.target:
self.target = '%s@%s' % (self.target, self.account.id.domain)
if not self.target.startswith('sip:') and not self.target.startswith('sips:'):
self.target = 'sip:' + self.target
try:
self.target = SIPURI.parse(self.target)
except SIPCoreError:
show_notice('Illegal SIP URI: %s' % self.target)
else:
if '.' not in self.target.host.decode() and not isinstance(self.account, BonjourAccount):
self.target.host = '%s.%s' % (self.target.host, self.account.id.domain)
lookup = DNSLookup()
notification_center = NotificationCenter()
notification_center.add_observer(self, sender=lookup)
settings = SIPSimpleSettings()
if isinstance(self.account, Account) and self.account.sip.outbound_proxy is not None:
uri = SIPURI(host=self.account.sip.outbound_proxy.host, port=self.account.sip.outbound_proxy.port, parameters={'transport': self.account.sip.outbound_proxy.transport})
tls_name = self.account.sip.tls_name or self.account.sip.outbound_proxy.host
elif isinstance(self.account, Account) and self.account.sip.always_use_my_proxy:
uri = SIPURI(host=self.account.id.domain)
tls_name = self.account.sip.tls_name or self.account.id.domain
else:
uri = self.target
tls_name = uri.host
if self.account is not BonjourAccount():
if self.account.id.domain == uri.host.decode():
tls_name = self.account.sip.tls_name or self.account.id.domain
elif "isfocus" in str(uri) and uri.host.decode().endswith(self.account.id.domain):
tls_name = self.account.conference.tls_name or self.account.sip.tls_name or self.account.id.domain
else:
is_ip_address = re.match("^\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}$", uri.host.decode()) or ":" in uri.host.decode()
if "isfocus" in str(uri) and self.account.conference.tls_name:
tls_name = self.account.conference.tls_name
elif is_ip_address and self.account.sip.tls_name:
tls_name = self.account.sip.tls_name
show_notice('DNS lookup for %s' % uri)
lookup.lookup_sip_proxy(uri, settings.sip.transport_list, tls_name=tls_name)
def reconnect(self, after=5):
if not self.auto_reconnect:
return
api.sleep(after)
notification_center = NotificationCenter()
notification_center.post_notification('SessionMustReconnect', data=NotificationData(target=str(self.target)))
def handle_notification(self, notification):
handler = getattr(self, '_NH_%s' % notification.name, Null)
handler(notification)
def _NH_DNSLookupDidSucceed(self, notification):
notification_center = NotificationCenter()
notification_center.remove_observer(self, sender=notification.sender)
session = Session(self.account)
notification_center.add_observer(self, sender=session)
session.connect(ToHeader(self.target), routes=notification.data.result, streams=self.streams)
application = SIPSessionApplication()
application.outgoing_session = session
def _NH_DNSLookupDidFail(self, notification):
show_notice('Call to %s failed: DNS lookup error: %s' % (self.target, notification.data.error))
notification_center = NotificationCenter()
notification_center.remove_observer(self, sender=notification.sender)
self._playback_end(failed_reason='outgoing-failed-DNS')
self.reconnect(10)
def _NH_SIPSessionNewOutgoing(self, notification):
session = notification.sender
local_identity = str(session.local_identity.uri)
if session.local_identity.display_name:
local_identity = '"%s" <%s>' % (session.local_identity.display_name, local_identity)
remote_identity = str(session.remote_identity.uri)
self.remote_identity = remote_identity.split(":")[1]
if session.remote_identity.display_name:
remote_identity = '"%s" <%s>' % (session.remote_identity.display_name, remote_identity)
show_notice("Initiating SIP session from %s to %s via %s..." % (local_identity, remote_identity, session.route))
self.message_session_to = None
def _NH_SIPSessionGotRingIndication(self, notification):
settings = SIPSimpleSettings()
ui = UI()
ringtone = settings.sounds.audio_outbound
if ringtone and self.wave_ringtone is None and not self.play_file:
self.wave_ringtone = WavePlayer(SIPApplication.voice_audio_mixer, ringtone.path.normalized, volume=ringtone.volume, loop_count=0, pause_time=2)
SIPApplication.voice_audio_bridge.add(self.wave_ringtone)
self.wave_ringtone.start()
ui.status = 'Ringing...'
def _NH_SIPSessionWillStart(self, notification):
ui = UI()
if self.wave_ringtone:
self.wave_ringtone.stop()
SIPApplication.voice_audio_bridge.remove(self.wave_ringtone)
self.wave_ringtone = None
ui.status = 'Connecting...'
def _NH_SIPSessionDidEnd(self, notification):
self._playback_end()
session = notification.sender
show_notice('Session ended by %s' % notification.data.originator)
identity = str(session.remote_identity.uri)
notification_center = NotificationCenter()
notification_center.remove_observer(self, sender=session)
if session.remote_identity.display_name:
identity = '"%s" <%s>' % (session.remote_identity.display_name, identity)
if notification.data.originator == 'remote':
self.reconnect(5)
def _NH_SIPSessionDidStart(self, notification):
notification_center = NotificationCenter()
ui = UI()
session = notification.sender
ui.status = 'Connected'
reactor.callLater(2, setattr, ui, 'status', None)
application = SIPSessionApplication()
for stream in notification.data.streams:
if application.auto_record:
settings = SIPSimpleSettings()
if stream.type == 'audio':
direction = session.direction
remote = "%s@%s" % (session.remote_identity.uri.user, session.remote_identity.uri.host)
filename = "%s-%s-%s.wav" % (datetime.now().strftime("%Y%m%d-%H%M%S"), remote, direction)
path = os.path.join(settings.audio.directory.normalized, session.account.id, datetime.now().strftime("%Y%m%d"))
makedirs(path)
stream.start_recording(os.path.join(path, filename))
if stream.type in ('audio', 'video'):
show_notice('%s session established using %s codec at %sHz' % (stream.type.title(), stream.codec.capitalize(), stream.sample_rate))
if stream.ice_active:
show_notice('%s RTP endpoints %s:%d (ICE type %s) <-> %s:%d (ICE type %s)' % (stream.type.title(),
stream.local_rtp_address,
stream.local_rtp_port,
stream.local_rtp_candidate.type.lower(),
stream.remote_rtp_address,
stream.remote_rtp_port,
stream.remote_rtp_candidate.type.lower()
)
)
else:
show_notice('%s RTP endpoints %s:%d <-> %s:%d' % (stream.type.title(), stream.local_rtp_address, stream.local_rtp_port, stream.remote_rtp_address, stream.remote_rtp_port))
if session.remote_user_agent is not None:
show_notice('Remote SIP User Agent is "%s"' % session.remote_user_agent)
def _NH_MediaStreamDidStart(self, notification):
stream = notification.sender
if stream.type == 'audio' and self.play_file:
script = "%s/scripts/%s-playback-start" % (self.playback_dir, self.remote_identity)
if os.path.exists(script):
show_notice("Running script %s" % script)
p = subprocess.Popen(script)
else:
pass
#show_notice("Script does not exist %s" % script)
file = ResourcePath(self.play_file).normalized
show_notice("Playback file %s\n" % file)
self.playback_wave_player = WavePlayer(SIPApplication.voice_audio_mixer, file)
notification_center = NotificationCenter()
notification_center.add_observer(self, sender=self.playback_wave_player)
stream.bridge.add(self.playback_wave_player)
#SIPApplication.voice_audio_bridge.add(self.playback_wave_player)
self.playback_wave_player.start()
def _NH_WavePlayerDidEnd(self, notification):
notification_center = NotificationCenter()
notification_center.remove_observer(self, sender=notification.sender)
show_notice("Playback finished")
if notification.sender == self.playback_wave_player:
application = SIPSessionApplication()
if application.outgoing_session:
application.outgoing_session.end()
def _NH_WavePlayerDidFail(self, notification):
notification_center = NotificationCenter()
notification_center.remove_observer(self, sender=notification.sender)
show_notice('Playback %s failed: %s' % (notification.sender.filename, notification.data.error))
if notification.sender == self.playback_wave_player or self.play_file:
application = SIPSessionApplication()
if application.outgoing_session:
application.outgoing_session.end()
self._playback_end(failed_reason='outgoing-failed-playback')
def _NH_SIPSessionDidFail(self, notification):
code = notification.data.code
self._playback_end(failed_reason='outgoing-failed-' + str(code))
notification_center = NotificationCenter()
session = notification.sender
notification_center.remove_observer(self, sender=session)
if self.playback_wave_player:
SIPApplication.voice_audio_bridge.remove(self.playback_wave_player)
ui = UI()
ui.status = None
application = SIPSessionApplication()
application.outgoing_session = None
if self.wave_ringtone:
self.wave_ringtone.stop()
SIPApplication.voice_audio_bridge.remove(self.wave_ringtone)
self.wave_ringtone = None
if notification.data.failure_reason == 'user request' and code == 487:
show_notice('SIP session cancelled')
elif notification.data.failure_reason == 'user request':
show_notice('SIP session rejected by user (%d %s)' % (code, notification.data.reason))
else:
pass
#show_notice('SIP session failed: %s' % notification.data.failure_reason)
self.reconnect(15)
def _remove_lock(self):
# used by external audio recorder to know if we are in call
lock_file = "%s/playback.lock" % self.playback_dir
if os.path.exists(lock_file):
os.remove(lock_file)
def _playback_end(self, failed_reason=None):
reactor.callLater(0.1, self._remove_lock)
if not self.play_file:
return
settings = SIPSimpleSettings()
application = SIPSessionApplication()
if failed_reason or not application.auto_record:
save_path = os.path.join(settings.audio.directory.normalized, self.account.id, datetime.now().strftime("%Y%m%d"))
makedirs(save_path)
base = Path(self.play_file).stem
ext = Path(self.play_file).suffix
save_path = save_path + '/' + base + '-' + (failed_reason or 'outgoing') + ext
show_notice("Saved playback file to %s\n" % save_path)
os.rename(self.play_file, save_path)
if not failed_reason:
settings = SIPSimpleSettings()
api.sleep(0.2)
rogertone = settings.sounds.roger_beep
roger_tone = WavePlayer(SIPApplication.voice_audio_mixer, rogertone.path.normalized)
show_notice("Play roger beep")
SIPApplication.voice_audio_bridge.add(roger_tone)
roger_tone.start()
else:
api.sleep(0.2)
hangup_tone = WavePlayer(SIPApplication.voice_audio_mixer, ResourcePath('sounds/hangup_tone.wav').normalized)
SIPApplication.voice_audio_bridge.add(hangup_tone)
hangup_tone.start()
script = "%s/scripts/%s-playback-end" % (self.playback_dir, self.remote_identity)
if os.path.exists(script):
show_notice("Running script %s\n" % script)
p = subprocess.Popen(script)
if os.path.exists(self.play_file):
try:
os.remove(self.play_file)
except OSError:
pass
self.play_file = None
@implementer(IObserver)
class IncomingCallInitializer(object):
sessions = 0
tone_ringtone = None
def __init__(self, session, auto_answer_interval=None):
self.session = session
self.auto_answer_interval = auto_answer_interval
self.question = None
def start(self):
IncomingCallInitializer.sessions += 1
notification_center = NotificationCenter()
notification_center.add_observer(self, sender=self.session)
# start auto-answer
self.answer_timer = None
if self.auto_answer_interval == 0:
self.session.accept(self.session.proposed_streams)
return
elif self.auto_answer_interval and self.auto_answer_interval > 0:
self.answer_timer = reactor.callFromThread(reactor.callLater, self.auto_answer_interval, self.session.accept, self.session.proposed_streams)
# start ringing
application = SIPSessionApplication()
self.wave_ringtone = None
if application.active_session is None:
if IncomingCallInitializer.sessions == 1:
ringtone = self.session.account.sounds.audio_inbound.sound_file if self.session.account.sounds.audio_inbound is not None else None
if ringtone:
self.wave_ringtone = WavePlayer(SIPApplication.alert_audio_mixer, ringtone.path.normalized, volume=ringtone.volume, loop_count=0, pause_time=2)
SIPApplication.alert_audio_bridge.add(self.wave_ringtone)
self.wave_ringtone.start()
elif IncomingCallInitializer.tone_ringtone is None:
IncomingCallInitializer.tone_ringtone = WavePlayer(SIPApplication.voice_audio_mixer, ResourcePath('sounds/ring_tone.wav').normalized, loop_count=0, pause_time=6)
SIPApplication.voice_audio_bridge.add(IncomingCallInitializer.tone_ringtone)
IncomingCallInitializer.tone_ringtone.start()
self.session.send_ring_indication()
# ask question
identity = str(self.session.remote_identity.uri)
if self.session.remote_identity.display_name:
identity = '"%s" <%s>' % (self.session.remote_identity.display_name, identity)
streams = '/'.join(stream.type for stream in self.session.proposed_streams)
self.question = Question("Incoming %s from %s, do you want to accept? (a)ccept/(r)eject/(b)usy" % (streams, identity), 'arbi', bold=True)
notification_center.add_observer(self, sender=self.question)
ui = UI()
ui.add_question(self.question)
def handle_notification(self, notification):
handler = getattr(self, '_NH_%s' % notification.name, Null)
handler(notification)
def _NH_UIQuestionGotAnswer(self, notification):
notification_center = NotificationCenter()
ui = UI()
application = SIPSessionApplication()
notification_center.remove_observer(self, sender=notification.sender)
answer = notification.data.answer
self.question = None
show_notice('Got answer %s' % answer)
if answer == 'a':
if application.received_private_key:
self.question = Question("Please enter the pincode to decrypt the key...", 'ar', bold=True)
ui.add_question(self.question)
return
self.session.accept(self.session.proposed_streams)
ui.status = 'Accepting...'
elif answer == 'r':
if application.received_private_key:
application.received_private_key = None
return
self.session.reject()
ui.status = 'Rejected'
reactor.callLater(3, setattr, ui, 'status', None)
elif answer == 'b':
self.session.reject(486)
ui.status = 'Sent Busy Here'
reactor.callLater(3, setattr, ui, 'status', None)
if self.wave_ringtone:
self.wave_ringtone.stop()
self.wave_ringtone = None
if IncomingCallInitializer.sessions > 1:
if IncomingCallInitializer.tone_ringtone is None:
IncomingCallInitializer.tone_ringtone = WavePlayer(SIPApplication.voice_audio_mixer, ResourcePath('sounds/ring_tone.wav').normalized, loop_count=0, pause_time=6)
SIPApplication.voice_audio_bridge.add(IncomingCallInitializer.tone_ringtone)
IncomingCallInitializer.tone_ringtone.start()
elif IncomingCallInitializer.tone_ringtone:
IncomingCallInitializer.tone_ringtone.stop()
IncomingCallInitializer.tone_ringtone = None
if self.answer_timer is not None and self.answer_timer.active():
self.answer_timer.cancel()
def _NH_SIPSessionWillStart(self, notification):
ui = UI()
if self.question is not None:
notification_center = NotificationCenter()
notification_center.remove_observer(self, sender=self.question)
ui.remove_question(self.question)
self.question = None
ui.status = 'Connecting...'
def _NH_SIPSessionDidStart(self, notification):
notification_center = NotificationCenter()
session = notification.sender
notification_center.remove_observer(self, sender=session)
IncomingCallInitializer.sessions -= 1
ui = UI()
ui.status = 'Connected'
reactor.callLater(2, setattr, ui, 'status', None)
identity = str(session.remote_identity.uri)