forked from AGProjects/sipclients
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathsip-session
1967 lines (1718 loc) · 94.7 KB
/
sip-session
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 python
import os
import re
import signal
import sys
from datetime import datetime
from itertools import chain
from lxml import html
from optparse import OptionParser
from threading import Event, Thread
from time import sleep
from application import log
from application.notification import IObserver, NotificationCenter
from application.python import Null
from eventlib import api
from twisted.internet import reactor
from zope.interface import implements
from sipsimple.core import Engine, 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.lookup import DNSLookup
from sipsimple.session import IllegalStateError, Session
from sipsimple.streams import MediaStreamRegistry
from sipsimple.streams.msrp.filetransfer import FileSelector
from sipsimple.storage import FileStorage
from sipsimple.threading.green import run_in_green_thread
from sipclient.configuration import config_directory
from sipclient.configuration.account import AccountExtension
from sipclient.configuration.datatypes import ResourcePath
from sipclient.configuration.settings import SIPSimpleSettingsExtension
from sipclient.log import Logger
from sipclient.system import IPAddressMonitor
from sipclient.ui import Prompt, Question, RichText, UI
# This is a helper function for sending formatted notice messages
def send_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(send_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 OutgoingCallInitializer(object):
implements(IObserver)
def __init__(self, account, target, audio=False, chat=False):
self.account = account
self.target = target
self.streams = []
if audio:
self.streams.append(MediaStreamRegistry.AudioStream())
if chat:
self.streams.append(MediaStreamRegistry.ChatStream())
self.wave_ringtone = None
def start(self):
if isinstance(self.account, BonjourAccount) and '@' not in self.target:
send_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:
send_notice('Illegal SIP URI: %s' % self.target)
else:
if '.' not in self.target.host 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})
elif isinstance(self.account, Account) and self.account.sip.always_use_my_proxy:
uri = SIPURI(host=self.account.id.domain)
else:
uri = self.target
lookup.lookup_sip_proxy(uri, settings.sip.transport_list)
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):
send_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)
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)
if session.remote_identity.display_name:
remote_identity = '"%s" <%s>' % (session.remote_identity.display_name, remote_identity)
send_notice("Initiating SIP session from '%s' to '%s' via %s..." % (local_identity, remote_identity, session.route))
def _NH_SIPSessionGotRingIndication(self, notification):
settings = SIPSimpleSettings()
ui = UI()
ringtone = settings.sounds.audio_outbound
if ringtone and self.wave_ringtone is None:
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_SIPSessionDidStart(self, notification):
notification_center = NotificationCenter()
ui = UI()
session = notification.sender
notification_center.remove_observer(self, sender=session)
ui.status = 'Connected'
reactor.callLater(2, setattr, ui, 'status', None)
application = SIPSessionApplication()
application.outgoing_session = None
for stream in notification.data.streams:
if stream.type == 'audio':
send_notice('Audio session established using "%s" codec at %sHz' % (stream.codec, stream.sample_rate))
if stream.ice_active:
send_notice('Audio RTP endpoints %s:%d (ICE type %s) <-> %s:%d (ICE type %s)' % (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:
send_notice('Audio RTP endpoints %s:%d <-> %s:%d' % (stream.local_rtp_address, stream.local_rtp_port, stream.remote_rtp_address, stream.remote_rtp_port))
if stream.encryption.active:
send_notice('RTP audio stream is encrypted using %s (%s)\n' % (stream.encryption.type, stream.encryption.cipher))
if session.remote_user_agent is not None:
send_notice('Remote SIP User Agent is "%s"' % session.remote_user_agent)
def _NH_SIPSessionDidFail(self, notification):
notification_center = NotificationCenter()
session = notification.sender
notification_center.remove_observer(self, sender=session)
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 notification.data.code == 487:
send_notice('SIP session cancelled')
elif notification.data.failure_reason == 'user request':
send_notice('SIP session rejected by user (%d %s)' % (notification.data.code, notification.data.reason))
else:
send_notice('SIP session failed: %s' % notification.data.failure_reason)
class IncomingCallInitializer(object):
implements(IObserver)
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 > 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()
notification_center.remove_observer(self, sender=notification.sender)
answer = notification.data.answer
self.question = None
if answer == 'a':
self.session.accept(self.session.proposed_streams)
ui.status = 'Accepting...'
elif answer == 'r':
self.session.reject()
ui.status = 'Rejecting...'
elif answer == 'b':
self.session.reject(486)
ui.status = 'Sending Busy Here...'
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)
if session.remote_identity.display_name:
identity = '"%s" <%s>' % (session.remote_identity.display_name, identity)
send_notice("SIP session with '%s' established" % identity)
for stream in notification.data.streams:
if stream.type == 'audio':
send_notice('Audio stream using "%s" codec at %sHz' % (stream.codec, stream.sample_rate))
if stream.ice_active:
send_notice('Audio RTP endpoints %s:%d (ICE type %s) <-> %s:%d (ICE type %s)' % (stream.local_rtp_address, stream.local_rtp_port, stream.local_rtp_candidate_type, stream.remote_rtp_address, stream.remote_rtp_port, stream.remote_rtp_candidate_type))
else:
send_notice('Audio RTP endpoints %s:%d <-> %s:%d' % (stream.local_rtp_address, stream.local_rtp_port, stream.remote_rtp_address, stream.remote_rtp_port))
if stream.encryption.active:
send_notice('RTP audio stream is encrypted using %s (%s)\n' % (stream.encryption.type, stream.encryption.cipher))
if session.remote_user_agent is not None:
send_notice('Remote SIP User Agent is "%s"' % session.remote_user_agent)
def _NH_SIPSessionDidFail(self, notification):
notification_center = NotificationCenter()
ui = UI()
session = notification.sender
notification_center.remove_observer(self, sender=session)
ui.status = None
if self.question is not None:
notification_center.remove_observer(self, sender=self.question)
ui.remove_question(self.question)
self.question = None
IncomingCallInitializer.sessions -= 1
if self.wave_ringtone:
self.wave_ringtone.stop()
self.wave_ringtone = None
if IncomingCallInitializer.sessions == 0 and IncomingCallInitializer.tone_ringtone is not None:
IncomingCallInitializer.tone_ringtone.stop()
IncomingCallInitializer.tone_ringtone = None
if notification.data.failure_reason == 'user request' and notification.data.code == 487:
send_notice('SIP session cancelled by user')
if notification.data.failure_reason == 'Call completed elsewhere' and notification.data.code == 487:
send_notice('SIP session cancelled, call was answered elsewhere')
elif notification.data.failure_reason == 'user request':
send_notice('SIP session rejected (%d %s)' % (notification.data.code, notification.data.reason))
else:
send_notice('SIP session failed: %s' % notification.data.failure_reason)
class OutgoingProposalHandler(object):
implements(IObserver)
def __init__(self, session, audio=False, chat=False):
self.session = session
self.stream = None
if audio:
self.stream = MediaStreamRegistry.AudioStream()
if chat:
self.stream = MediaStreamRegistry.ChatStream()
if not self.stream:
raise ValueError("Need to specify exactly one stream")
def start(self):
notification_center = NotificationCenter()
notification_center.add_observer(self, sender=self.session)
try:
self.session.add_stream(self.stream)
except IllegalStateError:
notification_center.remove_observer(self, sender=self.session)
raise
remote_identity = str(self.session.remote_identity.uri)
if self.session.remote_identity.display_name:
remote_identity = '"%s" <%s>' % (self.session.remote_identity.display_name, remote_identity)
send_notice("Proposing %s to '%s'..." % (self.stream.type, remote_identity))
def handle_notification(self, notification):
handler = getattr(self, '_NH_%s' % notification.name, Null)
handler(notification)
def _NH_SIPSessionProposalAccepted(self, notification):
notification_center = NotificationCenter()
notification_center.remove_observer(self, sender=self.session)
application = SIPSessionApplication()
application.sessions_with_proposals.remove(notification.sender)
send_notice('Proposal accepted')
def _NH_SIPSessionProposalRejected(self, notification):
notification_center = NotificationCenter()
notification_center.remove_observer(self, sender=self.session)
application = SIPSessionApplication()
application.sessions_with_proposals.remove(notification.sender)
ui = UI()
ui.status = None
if notification.data.code == 487:
send_notice('Proposal cancelled (%d %s)' % (notification.data.code, notification.data.reason))
else:
send_notice('Proposal rejected (%d %s)' % (notification.data.code, notification.data.reason))
def _NH_SIPSessionDidEnd(self, notification):
notification_center = NotificationCenter()
notification_center.remove_observer(self, sender=self.session)
class IncomingProposalHandler(object):
implements(IObserver)
sessions = 0
tone_ringtone = None
def __init__(self, session):
self.session = session
self.question = None
def start(self):
IncomingProposalHandler.sessions += 1
notification_center = NotificationCenter()
notification_center.add_observer(self, sender=self.session)
# start ringing
if IncomingProposalHandler.tone_ringtone is None:
IncomingProposalHandler.tone_ringtone = WavePlayer(SIPApplication.voice_audio_mixer, ResourcePath('sounds/ring_tone.wav').normalized, loop_count=0, pause_time=6)
SIPApplication.voice_audio_bridge.add(IncomingProposalHandler.tone_ringtone)
IncomingProposalHandler.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("'%s' wants to add %s, do you want to accept? (a)ccept/(r)eject" % (identity, streams), 'ar', 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()
notification_center.remove_observer(self, sender=notification.sender)
answer = notification.data.answer
self.question = None
if answer == 'a':
self.session.accept_proposal(self.session.proposed_streams)
ui.status = 'Accepting proposal...'
elif answer == 'r':
self.session.reject_proposal()
ui.status = 'Rejecting proposal...'
if IncomingProposalHandler.sessions == 1 and IncomingProposalHandler.tone_ringtone:
IncomingProposalHandler.tone_ringtone.stop()
IncomingProposalHandler.tone_ringtone = None
def _NH_SIPSessionProposalAccepted(self, notification):
notification_center = NotificationCenter()
session = notification.sender
notification_center.remove_observer(self, sender=session)
application = SIPSessionApplication()
application.sessions_with_proposals.remove(notification.sender)
IncomingProposalHandler.sessions -= 1
ui = UI()
ui.status = None
send_notice('Proposal accepted')
def _NH_SIPSessionProposalRejected(self, notification):
notification_center = NotificationCenter()
session = notification.sender
notification_center.remove_observer(self, sender=session)
application = SIPSessionApplication()
application.sessions_with_proposals.remove(notification.sender)
IncomingProposalHandler.sessions -= 1
ui = UI()
ui.status = None
if notification.data.code == 487:
send_notice('Proposal cancelled (%d %s)' % (notification.data.code, notification.data.reason))
else:
send_notice('Proposal rejected (%d %s)' % (notification.data.code, notification.data.reason))
if IncomingProposalHandler.tone_ringtone:
IncomingProposalHandler.tone_ringtone.stop()
IncomingProposalHandler.tone_ringtone = None
if self.question is not None:
notification_center.remove_observer(self, sender=self.question)
ui.remove_question(self.question)
self.question = None
def _NH_SIPSessionHadProposalFailure(self, notification):
notification_center = NotificationCenter()
session = notification.sender
notification_center.remove_observer(self, sender=session)
IncomingProposalHandler.sessions -= 1
ui = UI()
ui.status = None
send_notice('Proposal failed (%s)' % notification.data.failure_reason)
def _NH_SIPSessionDidEnd(self, notification):
notification_center = NotificationCenter()
ui = UI()
session = notification.sender
notification_center.remove_observer(self, sender=session)
ui.status = None
if self.question is not None:
notification_center.remove_observer(self, sender=self.question)
ui.remove_question(self.question)
self.question = None
IncomingProposalHandler.sessions -= 1
if IncomingProposalHandler.sessions == 0 and IncomingProposalHandler.tone_ringtone is not None:
IncomingProposalHandler.tone_ringtone.stop()
IncomingProposalHandler.tone_ringtone = None
class OutgoingTransferHandler(object):
implements(IObserver)
def __init__(self, account, target, filepath):
self.account = account
self.target = target
self.filepath = filepath.decode(sys.getfilesystemencoding())
self.file_selector = None
self.hash_compute_proc = None
self.session = None
self.stream = None
self.handler = None
self.wave_ringtone = None
@run_in_green_thread
def start(self):
if isinstance(self.account, BonjourAccount) and '@' not in self.target:
send_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:
send_notice('Illegal SIP URI: %s' % self.target)
return
send_notice('Preparing transfer...')
self.file_selector = FileSelector.for_file(self.filepath)
if '.' not in self.target.host 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})
elif isinstance(self.account, Account) and self.account.sip.always_use_my_proxy:
uri = SIPURI(host=self.account.id.domain)
else:
uri = self.target
lookup.lookup_sip_proxy(uri, settings.sip.transport_list)
def _terminate(self, failure_reason=None):
notification_center = NotificationCenter()
notification_center.remove_observer(self, sender=self.session)
notification_center.remove_observer(self, sender=self.stream)
notification_center.remove_observer(self, sender=self.handler)
ui = UI()
ui.status = None
if self.wave_ringtone:
self.wave_ringtone.stop()
self.wave_ringtone = None
if failure_reason is None:
send_notice('File transfer of %s finished' % os.path.basename(self.filepath))
else:
send_notice('File transfer of %s failed: %s' % (os.path.basename(self.filepath), failure_reason))
self.session = None
self.stream = None
self.handler = None
def handle_notification(self, notification):
handler = getattr(self, '_NH_%s' % notification.name, Null)
handler(notification)
def _NH_DNSLookupDidSucceed(self, notification):
notification.center.remove_observer(self, sender=notification.sender)
self.session = Session(self.account)
self.stream = MediaStreamRegistry.FileTransferStream(self.file_selector, 'sendonly')
self.handler = self.stream.handler
notification.center.add_observer(self, sender=self.session)
notification.center.add_observer(self, sender=self.stream)
notification.center.add_observer(self, sender=self.handler)
self.session.connect(ToHeader(self.target), routes=notification.data.result, streams=[self.stream])
def _NH_DNSLookupDidFail(self, notification):
notification.center.remove_observer(self, sender=notification.sender)
send_notice('File transfer to %s failed: DNS lookup error: %s' % (self.target, notification.data.error))
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)
if session.remote_identity.display_name:
remote_identity = '"%s" <%s>' % (session.remote_identity.display_name, remote_identity)
send_notice("Initiating file transfer from '%s' to '%s' via %s..." % (local_identity, remote_identity, session.route))
def _NH_SIPSessionGotRingIndication(self, notification):
settings = SIPSimpleSettings()
ui = UI()
ringtone = settings.sounds.audio_outbound
if ringtone and self.wave_ringtone is None:
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()
ui.status = 'Connecting...'
def _NH_SIPSessionDidStart(self, notification):
session = notification.sender
ui = UI()
ui.status = 'File transfer connected'
identity = str(session.remote_identity.uri)
if session.remote_identity.display_name:
identity = '"%s" <%s>' % (session.remote_identity.display_name, identity)
send_notice("File transfer for %s to '%s' started" % (os.path.basename(self.filepath), identity))
def _NH_MediaStreamDidNotInitialize(self, notification):
self._terminate(failure_reason=notification.data.reason)
def _NH_FileTransferHandlerDidEnd(self, notification):
self.session.end()
self._terminate(failure_reason=notification.data.reason)
class IncomingTransferHandler(object):
implements(IObserver)
sessions = 0
tone_ringtone = None
def __init__(self, session, auto_answer_interval=None):
self.session = session
self.stream = None
self.handler = None
self.auto_answer_interval = auto_answer_interval
self.file = None
self.filename = None
self.finished = False
self.hash = None
self.question = None
self.wave_ringtone = None
def start(self):
self.stream = self.session.proposed_streams[0]
self.handler = self.stream.handler
self.file_selector = self.stream.file_selector
self.filename = self.file_selector.name
IncomingTransferHandler.sessions += 1
notification_center = NotificationCenter()
notification_center.add_observer(self, sender=self.session)
notification_center.add_observer(self, sender=self.stream)
notification_center.add_observer(self, sender=self.handler)
# 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 > 0:
self.answer_timer = reactor.callFromThread(reactor.callLater, self.auto_answer_interval, self.session.accept, self.session.proposed_streams)
# start ringing
application = SIPSessionApplication()
if application.active_session is None:
if IncomingTransferHandler.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 IncomingTransferHandler.tone_ringtone is None:
IncomingTransferHandler.tone_ringtone = WavePlayer(SIPApplication.voice_audio_mixer, ResourcePath('sounds/ring_tone.wav').normalized, loop_count=0, pause_time=6)
SIPApplication.voice_audio_bridge.add(IncomingTransferHandler.tone_ringtone)
IncomingTransferHandler.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)
self.question = Question("Incoming file transfer for %s from '%s', do you want to accept? (a)ccept/(r)eject" % (os.path.basename(self.filename), identity), 'ari', bold=True)
notification_center.add_observer(self, sender=self.question)
ui = UI()
ui.add_question(self.question)
def _terminate(self, failure_reason=None):
notification_center = NotificationCenter()
notification_center.remove_observer(self, sender=self.session)
notification_center.remove_observer(self, sender=self.stream)
notification_center.remove_observer(self, sender=self.handler)
ui = UI()
ui.status = None
if self.question is not None:
notification_center.remove_observer(self, sender=self.question)
ui.remove_question(self.question)
self.question = None
if self.wave_ringtone:
self.wave_ringtone.stop()
if failure_reason is None:
send_notice('File transfer of %s finished' % os.path.basename(self.filename))
else:
send_notice('File transfer of %s failed: %s' % (os.path.basename(self.filename), failure_reason))
self.session = None
self.stream = None
self.handler = None
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()
notification_center.remove_observer(self, sender=notification.sender)
answer = notification.data.answer
self.question = None
if answer == 'a':
self.session.accept(self.session.proposed_streams)
ui.status = 'Accepting...'
elif answer == 'r':
self.session.reject()
ui.status = 'Rejecting...'
if IncomingTransferHandler.sessions == 1:
if self.wave_ringtone:
self.wave_ringtone.stop()
self.wave_ringtone = None
if IncomingTransferHandler.tone_ringtone:
IncomingTransferHandler.tone_ringtone.stop()
IncomingTransferHandler.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...'
notification_center = NotificationCenter()
notification_center.add_observer(self, sender=notification.sender.proposed_streams[0])
def _NH_SIPSessionDidStart(self, notification):
session = notification.sender
IncomingCallInitializer.sessions -= 1
ui = UI()
ui.status = 'File transfer connected'
identity = str(session.remote_identity.uri)
if session.remote_identity.display_name:
identity = '"%s" <%s>' % (session.remote_identity.display_name, identity)
send_notice("File transfer for %s with '%s' started" % (os.path.basename(self.filename), identity))
if IncomingTransferHandler.sessions == 1:
if self.wave_ringtone:
self.wave_ringtone.stop()
self.wave_ringtone = None
if IncomingTransferHandler.tone_ringtone:
IncomingTransferHandler.tone_ringtone.stop()
IncomingTransferHandler.tone_ringtone = None
def _NH_SIPSessionDidFail(self, notification):
IncomingTransferHandler.sessions -= 1
if self.wave_ringtone:
self.wave_ringtone.stop()
self.wave_ringtone = None
if IncomingTransferHandler.sessions == 0 and IncomingTransferHandler.tone_ringtone is not None:
IncomingTransferHandler.tone_ringtone.stop()
IncomingTransferHandler.tone_ringtone = None
def _NH_MediaStreamDidNotInitialize(self, notification):
self._terminate(failure_reason=notification.data.reason)
def _NH_FileTransferHandlerDidInitialize(self, notification):
self.filename = self.stream.file_selector.name
def _NH_FileTransferHandlerProgress(self, notification):
ui = UI()
ui.status = '%s: %s%%' % (os.path.basename(self.filename), notification.data.transferred_bytes*100//notification.data.total_bytes)
def _NH_FileTransferHandlerDidEnd(self, notification):
reactor.callFromThread(reactor.callLater, 0, self.session.end)
self._terminate(failure_reason=notification.data.reason)
class SIPSessionApplication(SIPApplication):
# public methods
#
def __init__(self):
self.account = None
self.options = None
self.target = None
self.active_session = None
self.outgoing_session = None
self.connected_sessions = []
self.sessions_with_proposals = set()
self.hangup_timers = {}
self.neighbours = {}
self.registration_succeeded = False
self.stopped_event = Event()
self.ip_address_monitor = IPAddressMonitor()
self.logger = None
self.rtp_statistics = None
self.hold_tone = None
self.ignore_local_hold = False
self.ignore_local_unhold = False
def start(self, target, options):
notification_center = NotificationCenter()
ui = UI()
self.options = options
self.target = target
self.logger = Logger(sip_to_stdout=options.trace_sip,
msrp_to_stdout=options.trace_msrp,
pjsip_to_stdout=options.trace_pjsip,
notifications_to_stdout=options.trace_notifications)
notification_center.add_observer(self, sender=self)
notification_center.add_observer(self, sender=ui)
notification_center.add_observer(self, name='SIPSessionNewIncoming')
notification_center.add_observer(self, name='SIPSessionNewOutgoing')
notification_center.add_observer(self, name='RTPStreamDidChangeRTPParameters')
notification_center.add_observer(self, name='RTPStreamICENegotiationDidSucceed')
notification_center.add_observer(self, name='RTPStreamICENegotiationDidFail')
log.level.current = log.level.WARNING # get rid of twisted messages
control_bindings={'s': 'trace sip',
'm': 'trace msrp',
'j': 'trace pjsip',
'n': 'trace notifications',
'h': 'hangup',
'r': 'record',
'i': 'input',
'o': 'output',
'a': 'alert',
'u': 'mute',
' ': 'hold',
'q': 'quit',
'/': 'help',
'?': 'help',
'0': 'dtmf 0',
'1': 'dtmf 1',
'2': 'dtmf 2',
'3': 'dtmf 3',
'4': 'dtmf 4',
'5': 'dtmf 5',
'6': 'dtmf 6',
'7': 'dtmf 7',
'8': 'dtmf 8',
'9': 'dtmf 9',
'*': 'dtmf *',
'#': 'dtmf #',
'A': 'dtmf A',
'B': 'dtmf B',
'C': 'dtmf C',
'D': 'dtmf D'}
ui.start(control_bindings=control_bindings, display_text=False)
Account.register_extension(AccountExtension)
BonjourAccount.register_extension(AccountExtension)
SIPSimpleSettings.register_extension(SIPSimpleSettingsExtension)
try:
SIPApplication.start(self, FileStorage(options.config_directory or config_directory))
except ConfigurationError, e:
send_notice("Failed to load sipclient's configuration: %s\n" % str(e), bold=False)
send_notice("If an old configuration file is in place, delete it or move it and recreate the configuration using the sip_settings script.", bold=False)
ui.stop()
self.stopped_event.set()
# notification handlers
#
def _NH_SIPApplicationWillStart(self, notification):
account_manager = AccountManager()
notification_center = NotificationCenter()
settings = SIPSimpleSettings()
ui = UI()
settings.logs.trace_sip = self.options.trace_sip
settings.logs.trace_msrp = self.options.trace_msrp
settings.logs.trace_pjsip = self.options.trace_pjsip
settings.logs.trace_notifications = self.options.trace_notifications
settings.save()
for account in account_manager.iter_accounts():
if isinstance(account, Account):
account.sip.register = False
if self.options.account is None:
self.account = account_manager.default_account
else:
possible_accounts = [account for account in account_manager.iter_accounts() if self.options.account in account.id and account.enabled]
if len(possible_accounts) > 1:
send_notice('More than one account exists which matches %s: %s' % (self.options.account, ', '.join(sorted(account.id for account in possible_accounts))), bold=False)
self.stop()
return
elif len(possible_accounts) == 0:
send_notice('No enabled account which matches %s was found. Available and enabled accounts: %s' % (self.options.account, ', '.join(sorted(account.id for account in account_manager.get_accounts() if account.enabled))), bold=False)
self.stop()
return
else:
self.account = possible_accounts[0]
notification_center.add_observer(self, sender=self.account)
if isinstance(self.account, Account):
self.account.sip.register = True
send_notice('Using account %s' % self.account.id, bold=False)
ui.prompt = Prompt(self.account.id, foreground='default')
self.logger.start()
if settings.logs.trace_sip and self.logger._siptrace_filename is not None:
send_notice('Logging SIP trace to file "%s"' % self.logger._siptrace_filename, bold=False)
if settings.logs.trace_msrp and self.logger._msrptrace_filename is not None:
send_notice('Logging MSRP trace to file "%s"' % self.logger._msrptrace_filename, bold=False)
if settings.logs.trace_pjsip and self.logger._pjsiptrace_filename is not None:
send_notice('Logging PJSIP trace to file "%s"' % self.logger._pjsiptrace_filename, bold=False)
if settings.logs.trace_notifications and self.logger._notifications_filename is not None:
send_notice('Logging notifications trace to file "%s"' % self.logger._notifications_filename, bold=False)
if self.options.disable_sound:
settings.audio.input_device = None
settings.audio.output_device = None
settings.audio.alert_device = None
def _NH_SIPApplicationDidStart(self, notification):
settings = SIPSimpleSettings()