-
Notifications
You must be signed in to change notification settings - Fork 7
/
SessionController.py
2645 lines (2246 loc) · 128 KB
/
SessionController.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
# Copyright (C) 2009-2011 AG Projects. See LICENSE for details.
#
from AppKit import (NSAlertDefaultReturn,
NSApp,
NSEventTrackingRunLoopMode,
NSRunAlertPanel)
from Foundation import (NSBundle,
NSLocalizedString,
NSObject,
NSRunLoop,
NSRunLoopCommonModes,
NSTimer,
NSURL,
NSWorkspace)
import objc
import json
import hashlib
import os
import re
import socket
import time
import urllib.request, urllib.parse, urllib.error
import uuid
import zipfile
import zlib
import traceback
import platform
from itertools import chain
from datetime import datetime
from application.notification import IObserver, NotificationCenter, NotificationData
from application.python import Null
from application.python.types import Singleton
from application.system import host
from zope.interface import implementer
from resources import ApplicationData
from resources import Resources
from sipsimple.account import Account, AccountManager, BonjourAccount
from sipsimple.application import SIPApplication
from sipsimple.audio import WavePlayer
from sipsimple.configuration.settings import SIPSimpleSettings
from sipsimple.core import SIPURI, ToHeader, SIPCoreError, Route, Header
from sipsimple.lookup import DNSLookup
from sipsimple.session import Session, SessionManager, IllegalStateError, IllegalDirectionError
from sipsimple.streams.rtp.audio import AudioStream
from sipsimple.streams.rtp.video import VideoStream
from sipsimple.threading.green import run_in_green_thread
from sipsimple.util import ISOTimestamp
from AlertPanel import AlertPanel
from AudioController import AudioController
from AccountSettings import AccountSettings
from BlinkLogger import BlinkLogger
from ContactListModel import BlinkPresenceContact, BonjourBlinkContact
from ChatController import ChatController, BlinkChatStream
from ScreenSharingController import ScreenSharingController, ScreenSharingServerController, ScreenSharingViewerController
from FileTransferController import FileTransferController
from FileTransferSession import OutgoingPushFileTransferHandler
from HistoryManager import ChatHistory, SessionHistory
from HistoryManager import SessionHistoryReplicator, ChatHistoryReplicator
from MediaStream import STATE_IDLE, STATE_CONNECTED, STATE_CONNECTING, STATE_DNS_LOOKUP, STATE_DNS_FAILED, STATE_FINISHED, STATE_FAILED
from MediaStream import STREAM_IDLE, STREAM_FAILED, STREAM_CONNECTED, STREAM_CANCELLING
from SessionRinger import Ringer
from SessionInfoController import SessionInfoController
from SIPManager import SIPManager
from VideoController import VideoController
from interfaces.itunes import MusicApplications
from util import format_identity_to_string, normalize_sip_uri_for_outgoing_session, sip_prefix_pattern, sipuri_components_from_string, run_in_gui_thread, checkValidPhoneNumber, local_to_utc, osx_version
SessionIdentifierSerial = 0
OUTBOUND_AUDIO_CALLS = 0
StreamHandlerForType = {
"chat" : ChatController,
"audio" : AudioController,
"file-transfer" : FileTransferController,
"screen-sharing" : ScreenSharingController,
"screen-sharing-server" : ScreenSharingServerController,
"screen-sharing-client" : ScreenSharingViewerController,
"video": VideoController
}
@implementer(IObserver)
class SessionControllersManager(object, metaclass=Singleton):
def __init__(self):
BlinkLogger().log_debug('Starting Sessions Manager')
self.notification_center = NotificationCenter()
self.notification_center.add_observer(self, name='AudioStreamGotDTMF')
self.notification_center.add_observer(self, name='BlinkSessionDidEnd')
self.notification_center.add_observer(self, name='BlinkSessionDidFail')
self.notification_center.add_observer(self, name='BlinkShouldTerminate')
self.notification_center.add_observer(self, name='SIPApplicationDidStart')
self.notification_center.add_observer(self, name='SIPApplicationWillEnd')
self.notification_center.add_observer(self, name='SIPSessionNewIncoming')
self.notification_center.add_observer(self, name='SIPSessionNewOutgoing')
self.notification_center.add_observer(self, name='SIPSessionDidStart')
self.notification_center.add_observer(self, name='SIPSessionDidFail')
self.notification_center.add_observer(self, name='SIPSessionDidEnd')
self.notification_center.add_observer(self, name='SIPSessionNewProposal')
self.notification_center.add_observer(self, name='SIPSessionProposalRejected')
self.notification_center.add_observer(self, name='SystemWillSleep')
self.notification_center.add_observer(self, name='SystemDidWakeUpFromSleep')
self.notification_center.add_observer(self, name='MediaStreamDidInitialize')
self.notification_center.add_observer(self, name='MediaStreamDidEnd')
self.notification_center.add_observer(self, name='MediaStreamDidFail')
self.sessionControllers = []
self.ringer = None
self.incomingSessions = set()
self.activeAudioStreams = set()
self.redial_uri = None
SessionHistoryReplicator()
@property
def pause_music(self):
return SIPSimpleSettings().audio.pause_music and NSApp.delegate().pause_music_enabled
@property
def alertPanel(self):
return NSApp.delegate().contactsWindowController.alertPanel
@property
def audioSessions(self):
return (sess.session for sess in self.sessionControllers if sess.hasStreamOfType("audio"))
@property
def videoSessions(self):
return (sess.session for sess in self.sessionControllers if sess.hasStreamOfType("video"))
@property
def connectedVideoSessions(self):
return list(sess.session for sess in self.sessionControllers if sess.hasStreamOfType("video") and sess.state == STATE_CONNECTED)
@property
def dndSessions(self):
return any(sess.session for sess in self.sessionControllers if sess.do_not_disturb_until_end)
@property
def chatSessions(self):
return (sess.session for sess in self.sessionControllers if sess.hasStreamOfType("chat"))
def addControllerWithSession_(self, session):
sessionController = SessionController.alloc().initWithSession_(session)
self.sessionControllers.append(sessionController)
return sessionController
def addControllerWithAccount_target_displayName_contact_(self, account, target_uri, display_name, contact):
sessionController = SessionController.alloc().initWithAccount_target_displayName_contact_(account, target_uri, display_name, contact)
self.sessionControllers.append(sessionController)
return sessionController
def addControllerWithSessionTransfer_(self, session):
sessionController = SessionController.alloc().initWithSessionTransfer_(session)
self.sessionControllers.append(sessionController)
return sessionController
def removeController(self, controller):
try:
self.sessionControllers.remove(controller)
except ValueError:
pass
NSApp.delegate().contactsWindowController.toggleOnThePhonePresenceActivity()
def sessionControllerForSession(self, session):
try:
controller = next((controller for controller in self.sessionControllers if controller.session == session))
except StopIteration:
return None
else:
return controller
def startIncomingSession(self, session, streams, answeringMachine=False, add_to_conference=False):
session_controller = self.sessionControllerForSession(session)
if session.state in ('terminating', 'terminated'):
if session_controller is not None:
session_controller.log_info('Session was already terminated')
else:
BlinkLogger().log_info('Session was already terminated')
return
if session_controller is None:
session_controller = self.addControllerWithSession_(session)
session_controller.setAnsweringMachineMode_(answeringMachine)
session_controller.handleIncomingStreams(streams, is_update=False, add_to_conference=add_to_conference)
def closeAllSessions(self):
if self.sessionControllers:
BlinkLogger().log_info('Ending all sessions')
for session in self.sessionControllers[:]:
session.end()
def isScreenSharingEnabled(self):
try:
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect(('127.0.0.1', 5900))
return True
except socket.error:
return False
finally:
s.close()
def isProposedMediaTypeSupported(self, streams):
settings = SIPSimpleSettings()
stream_type_list = list(set(stream.type for stream in streams))
if 'screen-sharing' in stream_type_list:
ds = [s for s in streams if s.type == "screen-sharing"]
if ds and ds[0].handler.type != "active":
if settings.screen_sharing_server.disabled:
BlinkLogger().log_info("Screen Sharing is disabled in Blink Preferences")
return False
if not self.isScreenSharingEnabled():
BlinkLogger().log_info("Screen Sharing is disabled in System Preferences")
return False
if settings.file_transfer.disabled and 'file-transfer' in stream_type_list:
BlinkLogger().log_info("File Transfers are disabled")
return False
if settings.chat.disabled and 'chat' in stream_type_list:
BlinkLogger().log_info("Chat sessions are disabled")
return False
if 'video' in stream_type_list:
return self.isMediaTypeSupported('video')
return True
def isMediaTypeSupported(self, type):
settings = SIPSimpleSettings()
if type == 'screen-sharing-server':
if settings.screen_sharing_server.disabled:
return False
if not self.isScreenSharingEnabled():
return False
if settings.file_transfer.disabled and type == 'file-transfer':
BlinkLogger().log_info("File Transfers are disabled")
return False
if settings.chat.disabled and type == 'chat':
BlinkLogger().log_info("Chat sessions are disabled")
return False
if type == 'sms':
return settings.chat.enable_sms
if type == 'video':
return True
return True
def log_incoming_session_missed(self, controller, data):
account = controller.account
media_type = ",".join(data.streams)
participants = ",".join(data.participants)
local_uri = 'bonjour@local' if account is BonjourAccount() else format_identity_to_string(account)
remote_uri = format_identity_to_string(controller.target_uri).lower() if account is not BonjourAccount() else controller.device_id
focus = "1" if data.focus else "0"
failure_reason = ''
duration = 0
call_id = data.call_id if data.call_id is not None else str(uuid.uuid1())
from_tag = data.from_tag if data.from_tag is not None else ''
to_tag = data.to_tag if data.to_tag is not None else ''
self.add_to_session_history(controller.history_id, media_type, 'incoming', 'missed', failure_reason, local_to_utc(data.timestamp), local_to_utc(data.timestamp), duration, local_uri, remote_uri, focus, participants, call_id, from_tag, to_tag, controller.answering_machine_filename, json.dumps(controller.encryption), controller.display_name or '', controller.device_id or '', str(controller.target_uri))
if 'audio' in data.streams:
message = '<h3>Missed Incoming Call</h3>'
#message += '<h4>Technicall Information</h4><table class=table_session_info><tr><td class=td_session_info>Call Id</td><td class=td_session_info>%s</td></tr><tr><td class=td_session_info>From Tag</td><td class=td_session_info>%s</td></tr><tr><td class=td_session_info>To Tag</td><td class=td_session_info>%s</td></tr></table>' % (call_id, from_tag, to_tag)
media_type = 'missed-call'
direction = 'incoming'
status = 'delivered'
cpim_from = data.target_uri
cpim_to = local_uri
timestamp = str(ISOTimestamp.now())
self.add_to_chat_history(controller.history_id, media_type, local_uri, remote_uri, direction, cpim_from, cpim_to, timestamp, message, status, skip_replication=True)
NotificationCenter().post_notification('AudioCallLoggedToHistory', sender=self, data=NotificationData(direction='incoming', missed=True, history_entry=False, remote_party=format_identity_to_string(controller.target_uri), local_party=local_uri if account is not BonjourAccount() else 'bonjour@local', check_contact=True))
NotificationCenter().post_notification('SIPSessionLoggedToHistory', sender=self)
def log_incoming_session_voicemail(self, controller, data):
account = controller.account
media_type = ",".join(data.streams)
participants = ",".join(data.participants)
local_uri = 'bonjour@local' if account is BonjourAccount() else format_identity_to_string(account)
remote_uri = format_identity_to_string(controller.target_uri).lower() if account is not BonjourAccount() else controller.device_id
focus = "1" if data.focus else "0"
failure_reason = ''
duration = 0
call_id = data.call_id if data.call_id is not None else str(uuid.uuid1())
from_tag = data.from_tag if data.from_tag is not None else ''
to_tag = data.to_tag if data.to_tag is not None else ''
self.add_to_session_history(controller.history_id, media_type, 'incoming', 'missed', failure_reason, local_to_utc(data.timestamp), local_to_utc(data.timestamp), duration, local_uri, remote_uri, focus, participants, call_id, from_tag, to_tag, controller.answering_machine_filename, json.dumps(controller.encryption), controller.display_name or '', controller.device_id or '', str(controller.target_uri))
if 'audio' in data.streams:
message = '<h3>Missed Incoming Call</h3>'
media_type = 'missed-call'
direction = 'incoming'
status = 'delivered'
cpim_from = data.target_uri
cpim_to = local_uri
timestamp = str(ISOTimestamp.now())
self.add_to_chat_history(controller.history_id, media_type, local_uri, remote_uri, direction, cpim_from, cpim_to, timestamp, message, status, skip_replication=True)
NotificationCenter().post_notification('AudioCallLoggedToHistory', sender=self, data=NotificationData(direction='incoming', missed=True, history_entry=False, remote_party=format_identity_to_string(controller.target_uri), local_party=local_uri if account is not BonjourAccount() else 'bonjour@local', check_contact=True))
NotificationCenter().post_notification('SIPSessionLoggedToHistory', sender=self)
def log_incoming_session_ended(self, controller, data):
account = controller.account
session = controller.session
media_type = ",".join(data.streams)
participants = ",".join(data.participants)
local_uri = 'bonjour@local' if account is BonjourAccount() else format_identity_to_string(account)
remote_uri = format_identity_to_string(controller.target_uri).lower() if account is not BonjourAccount() else controller.device_id
focus = "1" if data.focus else "0"
failure_reason = ''
if session.start_time is None and session.end_time is not None:
# Session could have ended before it was completely started
session.start_time = session.end_time
try:
duration = session.end_time - session.start_time
except TypeError:
duration = 0
call_id = data.call_id if data.call_id is not None else str(uuid.uuid1())
from_tag = data.from_tag if data.from_tag is not None else ''
to_tag = data.to_tag if data.to_tag is not None else ''
self.add_to_session_history(controller.history_id, media_type, 'incoming', 'completed', failure_reason, local_to_utc(session.start_time), local_to_utc(session.end_time), duration.seconds, local_uri, remote_uri, focus, participants, call_id, from_tag, to_tag, controller.answering_machine_filename, json.dumps(controller.encryption), controller.display_name or '', controller.device_id or '', str(controller.target_uri))
if 'audio' in data.streams:
duration = self.get_printed_duration(session.start_time, session.end_time)
message = '<h3>Incoming Call</h3>'
message += '<p>Call duration: %s' % duration
message += '<p>Media: %s' % ', '.join(data.streams)
enc_keys = list(controller.encryption.keys())
if enc_keys:
message += '<h4>Encryption</h4>'
message += '<ul>'
for key in enc_keys:
try:
type = controller.encryption[key]['type']
message += '<li>%s: %s' % (key, type)
try:
verified = controller.encryption[key]['verified']
if verified == 'yes':
message += ', verified'
else:
message += ', not verified'
except KeyError:
pass
except KeyError:
continue
message += '</ul>'
media_type = 'audio'
direction = 'incoming'
status = 'delivered'
cpim_from = data.target_uri
cpim_to = format_identity_to_string(account)
timestamp = str(ISOTimestamp.now())
self.add_to_chat_history(controller.history_id, media_type, local_uri, remote_uri, direction, cpim_from, cpim_to, timestamp, message, status, skip_replication=True)
NotificationCenter().post_notification('AudioCallLoggedToHistory', sender=self, data=NotificationData(direction='incoming', missed=False, history_entry=False, remote_party=format_identity_to_string(controller.target_uri), local_party=local_uri if account is not BonjourAccount() else 'bonjour@local', check_contact=True))
NotificationCenter().post_notification('SIPSessionLoggedToHistory', sender=self)
def log_incoming_session_answered_elsewhere(self, controller, data):
account = controller.account
media_type = ",".join(data.streams)
participants = ",".join(data.participants)
local_uri = 'bonjour@local' if account is BonjourAccount() else format_identity_to_string(account)
remote_uri = format_identity_to_string(controller.target_uri).lower() if account is not BonjourAccount() else controller.device_id
focus = "1" if data.focus else "0"
failure_reason = 'Answered elsewhere'
call_id = data.call_id if data.call_id is not None else str(uuid.uuid1())
from_tag = data.from_tag if data.from_tag is not None else ''
to_tag = data.to_tag if data.to_tag is not None else ''
self.add_to_session_history(controller.history_id, media_type, 'incoming', 'completed', failure_reason, local_to_utc(data.timestamp), local_to_utc(data.timestamp), 0, local_uri, remote_uri, focus, participants, call_id, from_tag, to_tag, controller.answering_machine_filename, json.dumps(controller.encryption), controller.display_name or '', controller.device_id or '', str(controller.target_uri))
if 'audio' in data.streams:
message= '<h3>Incoming Audio Call</h3>'
message += '<p>The call has been answered elsewhere'
#message += '<h4>Technicall Information</h4><table class=table_session_info><tr><td class=td_session_info>Call Id</td><td class=td_session_info>%s</td></tr><tr><td class=td_session_info>From Tag</td><td class=td_session_info>%s</td></tr><tr><td class=td_session_info>To Tag</td><td class=td_session_info>%s</td></tr></table>' % (call_id, from_tag, to_tag)
media_type = 'audio'
local_uri = local_uri
remote_uri = remote_uri
direction = 'incoming'
status = 'delivered'
cpim_from = data.target_uri
cpim_to = local_uri
timestamp = str(ISOTimestamp.now())
self.add_to_chat_history(controller.history_id, media_type, local_uri, remote_uri, direction, cpim_from, cpim_to, timestamp, message, status, skip_replication=True)
NotificationCenter().post_notification('AudioCallLoggedToHistory', sender=self, data=NotificationData(direction='incoming', missed=False, history_entry=False, remote_party=format_identity_to_string(controller.target_uri), local_party=local_uri if account is not BonjourAccount() else 'bonjour@local', check_contact=True))
NotificationCenter().post_notification('SIPSessionLoggedToHistory', sender=self)
def log_outgoing_session_failed(self, controller, data):
account = controller.account
media_type = ",".join(data.streams)
participants = ",".join(data.participants)
focus = "1" if data.focus else "0"
local_uri = 'bonjour@local' if account is BonjourAccount() else format_identity_to_string(account)
remote_uri = format_identity_to_string(controller.target_uri).lower() if account is not BonjourAccount() else controller.device_id
self.redial_uri = format_identity_to_string(controller.target_uri, check_contact=True, format='full')
failure_reason = '%s (%s)' % (data.reason or data.failure_reason, data.code)
call_id = data.call_id if data.call_id is not None else str(uuid.uuid1())
from_tag = data.from_tag if data.from_tag is not None else ''
to_tag = data.to_tag if data.to_tag is not None else ''
self.add_to_session_history(controller.history_id, media_type, 'outgoing', 'failed', failure_reason, local_to_utc(data.timestamp), local_to_utc(data.timestamp), 0, local_uri, remote_uri, focus, participants, call_id, from_tag, to_tag, controller.answering_machine_filename, json.dumps(controller.encryption), controller.display_name or '', controller.device_id or '', str(controller.target_uri))
if 'audio' in data.streams:
message = '<h3>Failed Outgoing Call</h3>'
message += '<p>Reason: %s (%s)' % (data.reason or data.failure_reason, data.code)
#message += '<h4>Technicall Information</h4><table class=table_session_info><tr><td class=td_session_info>Call Id</td><td class=td_session_info>%s</td></tr><tr><td class=td_session_info>From Tag</td><td class=td_session_info>%s</td></tr><tr><td class=td_session_info>To Tag</td><td class=td_session_info>%s</td></tr></table>' % (call_id, from_tag, to_tag)
media_type = 'audio'
local_uri = local_uri
remote_uri = remote_uri
direction = 'incoming'
status = 'delivered'
cpim_from = data.target_uri
cpim_to = local_uri
timestamp = str(ISOTimestamp.now())
self.add_to_chat_history(controller.history_id, media_type, local_uri, remote_uri, direction, cpim_from, cpim_to, timestamp, message, status, skip_replication=True)
NotificationCenter().post_notification('AudioCallLoggedToHistory', sender=self, data=NotificationData(direction='outgoing', missed=False, history_entry=False, remote_party=format_identity_to_string(controller.target_uri), local_party=local_uri if account is not BonjourAccount() else 'bonjour@local', check_contact=True))
NotificationCenter().post_notification('SIPSessionLoggedToHistory', sender=self)
def log_outgoing_session_cancelled(self, controller, data):
account = controller.account
self.redial_uri = controller.target_uri
media_type = ",".join(data.streams)
participants = ",".join(data.participants)
focus = "1" if data.focus else "0"
local_uri = 'bonjour@local' if account is BonjourAccount() else format_identity_to_string(account)
remote_uri = format_identity_to_string(controller.target_uri).lower() if account is not BonjourAccount() else controller.device_id
self.redial_uri = format_identity_to_string(controller.target_uri, check_contact=True, format='full')
failure_reason = ''
call_id = data.call_id if data.call_id is not None else str(uuid.uuid1())
from_tag = data.from_tag if data.from_tag is not None else ''
to_tag = data.to_tag if data.to_tag is not None else ''
self.add_to_session_history(controller.history_id, media_type, 'outgoing', 'cancelled', failure_reason, local_to_utc(data.timestamp), local_to_utc(data.timestamp), 0, local_uri, remote_uri, focus, participants, call_id, from_tag, to_tag, controller.answering_machine_filename, json.dumps(controller.encryption), controller.display_name or '', controller.device_id or '', str(controller.target_uri))
if 'audio' in data.streams:
message= '<h3>Cancelled Outgoing Call</h3>'
#message += '<h4>Technicall Information</h4><table class=table_session_info><tr><td class=td_session_info>Call Id</td><td class=td_session_info>%s</td></tr><tr><td class=td_session_info>From Tag</td><td class=td_session_info>%s</td></tr><tr><td class=td_session_info>To Tag</td><td class=td_session_info>%s</td></tr></table>' % (call_id, from_tag, to_tag)
media_type = 'audio'
direction = 'incoming'
status = 'delivered'
cpim_from = data.target_uri
cpim_to = local_uri
timestamp = str(ISOTimestamp.now())
self.add_to_chat_history(controller.history_id, media_type, local_uri, remote_uri, direction, cpim_from, cpim_to, timestamp, message, status, skip_replication=True)
NotificationCenter().post_notification('AudioCallLoggedToHistory', sender=self, data=NotificationData(direction='outgoing', missed=False, history_entry=False, remote_party=format_identity_to_string(controller.target_uri), local_party=local_uri if account is not BonjourAccount() else 'bonjour@local', check_contact=True))
NotificationCenter().post_notification('SIPSessionLoggedToHistory', sender=self)
def log_outgoing_session_ended(self, controller, data):
if not controller.session:
return
account = controller.account
session = controller.session
media_type = ",".join(data.streams)
participants = ",".join(data.participants)
focus = "1" if data.focus else "0"
local_uri = 'bonjour@local' if account is BonjourAccount() else format_identity_to_string(account)
remote_uri = format_identity_to_string(controller.target_uri).lower() if account is not BonjourAccount() else controller.device_id
self.redial_uri = format_identity_to_string(controller.target_uri, check_contact=True, format='full')
direction = 'incoming'
status = 'delivered'
failure_reason = ''
call_id = data.call_id if data.call_id is not None else str(uuid.uuid1())
from_tag = data.from_tag if data.from_tag is not None else ''
to_tag = data.to_tag if data.to_tag is not None else ''
if session.start_time is None and session.end_time is not None:
# Session could have ended before it was completely started
session.start_time = session.end_time
try:
duration = session.end_time - session.start_time
except TypeError:
seconds = 0
session.end_time = ISOTimestamp.now()
session.start_time = ISOTimestamp.now()
else:
seconds = duration.seconds
self.add_to_session_history(controller.history_id, media_type, 'outgoing', 'completed', failure_reason, local_to_utc(session.start_time), local_to_utc(session.end_time), seconds, local_uri, remote_uri, focus, participants, call_id, from_tag, to_tag, controller.answering_machine_filename, json.dumps(controller.encryption), controller.display_name or '', controller.device_id or '', str(controller.target_uri))
if 'audio' in data.streams:
duration = self.get_printed_duration(session.start_time, session.end_time)
message = '<h3>Outgoing Call</h3>'
message += '<p>Media: %s' % ', '.join(data.streams)
message += '<p>Call duration: %s' % duration
#message += '<h4>Technicall Information</h4><table class=table_session_info><tr><td class=td_session_info>Call Id</td><td class=td_session_info>%s</td></tr><tr><td class=td_session_info>From Tag</td><td class=td_session_info>%s</td></tr><tr><td class=td_session_info>To Tag</td><td class=td_session_info>%s</td></tr></table>' % (call_id, from_tag, to_tag)
enc_keys = list(controller.encryption.keys())
if enc_keys:
message += '<h4>Encryption</h4>'
message += '<ul>'
for key in enc_keys:
try:
type = controller.encryption[key]['type']
message += '<li>%s: %s' % (key, type)
try:
verified = controller.encryption[key]['verified']
if verified == 'yes':
message += ', verified'
else:
message += ', not verified'
except KeyError:
pass
except KeyError:
continue
message += '</ul>'
media_type = 'audio'
cpim_from = data.target_uri
cpim_to = local_uri
timestamp = str(ISOTimestamp.now())
self.add_to_chat_history(controller.history_id, media_type, local_uri, remote_uri, direction, cpim_from, cpim_to, timestamp, message, status, skip_replication=True)
NotificationCenter().post_notification('AudioCallLoggedToHistory', sender=self, data=NotificationData(direction='outgoing', missed=False, history_entry=False, remote_party=format_identity_to_string(controller.target_uri), local_party=local_uri if account is not BonjourAccount() else 'bonjour@local', check_contact=True))
NotificationCenter().post_notification('SIPSessionLoggedToHistory', sender=self)
def get_printed_duration(self, start_time, end_time):
duration = end_time - start_time
if (duration.days > 0 or duration.seconds > 0):
duration_print = ""
if duration.days > 0 or duration.seconds > 3600:
duration_print += "%i hours, " % (duration.days*24 + duration.seconds/3600)
seconds = duration.seconds % 3600
duration_print += "%02i:%02i" % (seconds/60, seconds%60)
else:
duration_print = "00:00"
return duration_print
def add_to_session_history(self, id, media_type, direction, status, failure_reason, start_time, end_time, duration, local_uri, remote_uri, remote_focus, participants, call_id, from_tag, to_tag, answering_machine_filename, encryption='', display_name='', device_id='', remote_full_uri=''):
return SessionHistory().add_entry(id, media_type, direction, status, failure_reason, start_time, end_time, duration, local_uri, remote_uri, remote_focus, participants, call_id, from_tag, to_tag, answering_machine_filename, encryption, display_name, device_id, remote_full_uri)
def add_to_chat_history(self, id, media_type, local_uri, remote_uri, direction, cpim_from, cpim_to, timestamp, message, status, skip_replication=False):
return ChatHistory().add_message(id, media_type, local_uri, remote_uri, direction, cpim_from, cpim_to, timestamp, message, "html", "0", status, skip_replication=skip_replication)
@run_in_green_thread
def get_redial_uri_from_history(self):
results = SessionHistory().get_entries(direction='outgoing', count=1)
try:
session_info = results[0]
except IndexError:
pass
else:
target_uri, display_name, full_uri, fancy_uri = sipuri_components_from_string(session_info.remote_uri)
self.redial_uri = fancy_uri
def send_files_to_contact(self, account, contact_uri, filenames):
if not self.isMediaTypeSupported('file-transfer'):
return
NSApp.delegate().contactsWindowController.showFileTransfers_(None)
target_uri = normalize_sip_uri_for_outgoing_session(contact_uri, AccountManager().default_account)
for file in filenames:
if os.path.isdir(file):
dir = file
base_name = os.path.basename(dir)
dir_name = os.path.dirname(dir)
zip_folder = ApplicationData.get('.tmp_file_transfers')
if not os.path.exists(zip_folder):
os.mkdir(zip_folder, 0o700)
zip_file = '%s/%s.zip' % (zip_folder, base_name)
if os.path.isfile(zip_file):
i = 1
while True:
zip_file = '%s/%s_%d.zip' % (zip_folder, base_name, i)
if not os.path.isfile(zip_file):
break
i += 1
zf = zipfile.ZipFile(zip_file, mode='w')
try:
BlinkLogger().log_error("Compressing folder %s to %s" % (dir, zip_file))
for root, dirs, files in os.walk(file):
for name in files:
_file = os.path.join(root, name)
arcname = _file[len(dir_name)+1:]
zf.write(_file, compress_type=zipfile.ZIP_DEFLATED, arcname=arcname)
except Exception as exc:
BlinkLogger().log_error("Error compressing %s to %s: %s" % (dir, zip_file, exc))
continue
finally:
zf.close()
file = zip_file
try:
xfer = OutgoingPushFileTransferHandler(account, target_uri, file)
xfer.start()
except Exception as exc:
BlinkLogger().log_error("Error while attempting to transfer file %s: %s" % (file, exc))
@run_in_gui_thread
def show_web_alert_page(self, session):
# open web page with caller information
if not NSApp.delegate().external_alert_enabled:
return
try:
session_controller = next((controller for controller in self.sessionControllers if controller.session == session))
except StopIteration:
return
if session.account is not BonjourAccount() and session.account.web_alert.alert_url:
url = str(session.account.web_alert.alert_url)
replace_caller = urllib.parse.urlencode({'x:': '%s@%s' % (session.remote_identity.uri.user, session.remote_identity.uri.host)})
caller_key = replace_caller[5:]
url = url.replace('$caller_party', caller_key)
replace_username = urllib.parse.urlencode({'x:': '%s' % session.remote_identity.uri.user})
url = url.replace('$caller_username', replace_username[5:])
replace_account = urllib.parse.urlencode({'x:': '%s' % session.account.id})
url = url.replace('$called_party', replace_account[5:])
settings = SIPSimpleSettings()
if settings.gui.use_default_web_browser_for_alerts or not url.startswith('http'):
session_controller.log_info("Opening Alert URL %s"% url)
NSWorkspace.sharedWorkspace().openURL_(NSURL.URLWithString_(url))
else:
session_controller.log_info("Opening Alert URL %s"% url)
if caller_key not in SIPManager()._delegate.accountSettingsPanels:
SIPManager()._delegate.accountSettingsPanels[caller_key] = AccountSettings.createWithOwner_(self)
SIPManager()._delegate.accountSettingsPanels[caller_key].showIncomingCall(session, url)
@run_in_gui_thread
def handle_notification(self, notification):
handler = getattr(self, '_NH_%s' % notification.name, Null)
try:
handler(notification.sender, notification.data)
except Exception:
self.log_error(traceback.format_exc())
def _NH_SIPApplicationDidStart(self, sender, data):
self.ringer = Ringer(self)
self.get_redial_uri_from_history()
ChatHistoryReplicator()
def _NH_BlinkShouldTerminate(self, sender, data):
self.closeAllSessions()
def _NH_SIPApplicationWillEnd(self, sender, data):
self.ringer.stop()
def _NH_SIPSessionDidFail(self, session, data):
self.incomingSessions.discard(session)
if self.pause_music:
if not self.activeAudioStreams and not self.incomingSessions:
MusicApplications().resume()
def _NH_SIPSessionDidStart(self, session, data):
self.incomingSessions.discard(session)
if self.pause_music:
if all(stream.type != 'audio' for stream in data.streams):
if not self.activeAudioStreams and not self.incomingSessions:
MusicApplications().resume()
if session.direction == 'incoming':
if session.account is not BonjourAccount() and session.account.web_alert.show_alert_page_after_connect:
self.show_web_alert_page(session)
def _NH_SIPSessionDidEnd(self, session, data):
if self.pause_music:
self.incomingSessions.discard(session)
if not self.activeAudioStreams and not self.incomingSessions:
MusicApplications().resume()
def _NH_SIPSessionNewProposal(self, session, data):
if self.pause_music:
if any(stream.type == 'audio' for stream in data.proposed_streams):
MusicApplications().resume()
def _NH_SIPSessionProposalRejected(self, session, data):
if self.pause_music:
if any(stream.type == 'audio' for stream in data.proposed_streams):
if not self.activeAudioStreams and not self.incomingSessions:
MusicApplications().resume()
def _NH_MediaStreamDidInitialize(self, stream, data):
if stream.type == 'audio':
self.activeAudioStreams.add(stream)
def _NH_SystemWillSleep(self, sender, data):
self.notification_center.remove_observer(self, name='SIPSessionNewIncoming')
def _NH_SystemDidWakeUpFromSleep(self, sender, data):
self.notification_center.add_observer(self, name='SIPSessionNewIncoming')
def _NH_MediaStreamDidEnd(self, stream, data):
if self.pause_music:
if stream.type == "audio":
self.activeAudioStreams.discard(stream)
# TODO: check if session has other streams and if yes, resume itunes
# in case of session ends, resume is handled by the Session Controller
if not self.activeAudioStreams and not self.incomingSessions:
MusicApplications().resume()
def _NH_MediaStreamDidFail(self, stream, data):
if self.pause_music:
if stream.type == "audio":
self.activeAudioStreams.discard(stream)
if not self.activeAudioStreams and not self.incomingSessions:
MusicApplications().resume()
def _NH_SIPSessionNewIncoming(self, session, data):
match_contact = NSApp.delegate().contactsWindowController.getFirstContactMatchingURI(session.remote_identity.uri, exact_match=True)
streams = [stream for stream in data.streams if self.isProposedMediaTypeSupported([stream])]
stream_type_list = list(set(stream.type for stream in streams))
caller_name = match_contact.name if match_contact else format_identity_to_string(session.remote_identity)
if data.streams and not streams:
BlinkLogger().log_info("Rejecting session for unsupported media type")
nc_title = 'Incompatible Media'
nc_body = 'Call from %s refused' % match_contact.name
NSApp.delegate().gui_notify(nc_title, nc_body, subtitle=caller_name)
try:
session.reject(488)
except IllegalStateError as e:
BlinkLogger().log_error(e)
return
elif not streams:
# Handle initial INVITE with no SDP, offer audio
streams = [AudioStream()]
if match_contact is not None and isinstance(match_contact, BlinkPresenceContact) and match_contact.contact.presence.policy == 'deny':
BlinkLogger().log_info("Blocked contact rejected")
try:
session.reject(603)
except IllegalStateError as e:
BlinkLogger().log_error(e)
nc_title = 'Blocked Contact Rejected'
nc_body = 'Call from %s refused' % caller_name
NSApp.delegate().gui_notify(nc_title, nc_body, subtitle=caller_name)
return
if self.dndSessions:
nc_title = 'Call Rejected'
nc_body = 'Do not disturb until done with other calls'
NSApp.delegate().gui_notify(nc_title, nc_body, subtitle=caller_name)
BlinkLogger().log_info("Rejecting call until we finish existing calls")
try:
session.reject(600)
except IllegalStateError as e:
BlinkLogger().log_error(e)
return
# if call waiting is disabled and we have audio calls reject with busy
hasAudio = any(sess.hasStreamOfType("audio") for sess in self.sessionControllers)
if 'audio' in stream_type_list and hasAudio and session.account is not BonjourAccount() and session.account.audio.call_waiting is False:
BlinkLogger().log_info("Refusing audio call from %s because we are busy and call waiting is disabled" % format_identity_to_string(session.remote_identity))
try:
session.reject(486)
except IllegalStateError as e:
BlinkLogger().log_error(e)
return
if 'audio' in stream_type_list and session.account is not BonjourAccount():
if session.account.audio.do_not_disturb:
nc_title = 'Do Not Disturb'
nc_body = 'Call refused with code %s' % session.account.sip.do_not_disturb_code
NSApp.delegate().gui_notify(nc_title, nc_body, subtitle=caller_name)
BlinkLogger().log_info("Refusing audio call from %s because do not disturb is enabled" % caller_name)
try:
session.reject(session.account.sip.do_not_disturb_code, 'Do Not Disturb')
except IllegalStateError as e:
BlinkLogger().log_error(e)
return
if session.account.audio.reject_anonymous:
if session.remote_identity.uri.user.lower() in ('anonymous', 'unknown', 'unavailable'):
nc_title = 'Anonymous Call Rejected'
nc_body = 'Call refused'
NSApp.delegate().gui_notify(nc_title, nc_body, subtitle=None)
BlinkLogger().log_info("Rejecting audio call from anonymous caller")
try:
session.reject(603) # todo: an alternative to this is 433 "Anonymity Disallowed" (see RFC 5079), but is not a global reject code and is not present in sipsimple -Dan
except IllegalStateError as e:
BlinkLogger().log_error(e)
return
if session.account.audio.reject_unauthorized_contacts:
if match_contact is not None and isinstance(match_contact, BlinkPresenceContact):
if match_contact.contact.presence.policy != 'allow':
nc_title = 'Unauthorized Caller Rejected'
nc_body = 'Call from %s refused' % caller_name
NSApp.delegate().gui_notify(nc_title, nc_body, subtitle=caller_name)
BlinkLogger().log_info("Rejecting audio call from unauthorized contact")
try:
session.reject(603)
except IllegalStateError as e:
BlinkLogger().log_error(e)
return
else:
BlinkLogger().log_info("Rejecting audio call from unauthorized contact")
nc_title = 'Unauthorized Caller Rejected'
nc_body = 'Call refused from blocked contact'
NSApp.delegate().gui_notify(nc_title, nc_body, subtitle=caller_name)
try:
session.reject(603)
except IllegalStateError as e:
BlinkLogger().log_error(e)
return
# save session subject
try:
session.subject = data.headers['Subject'].body
except KeyError:
session.subject = None
# at this stage call is allowed and will alert the user
self.incomingSessions.add(session)
if self.pause_music:
MusicApplications().pause()
self.ringer.add_incoming(session, streams)
session.blink_supported_streams = streams
settings = SIPSimpleSettings()
stream_type_list = list(set(stream.type for stream in streams))
if match_contact:
if settings.chat.auto_accept and stream_type_list == ['chat'] and NSApp.delegate().contactsWindowController.my_device_is_active:
BlinkLogger().log_info("Automatically accepting chat session from %s" % format_identity_to_string(session.remote_identity))
self.startIncomingSession(session, streams)
return
elif session.account is BonjourAccount() and stream_type_list == ['chat']:
BlinkLogger().log_info("Automatically accepting Bonjour chat session from %s" % format_identity_to_string(session.remote_identity))
self.startIncomingSession(session, streams)
return
if stream_type_list == ['file-transfer'] and 'screencapture' in streams[0].file_selector.name:
if NSApp.delegate().contactsWindowController.my_device_is_active:
BlinkLogger().log_info("Automatically accepting screenshot from %s" % format_identity_to_string(session.remote_identity))
self.startIncomingSession(session, streams)
return
try:
session.send_ring_indication()
except IllegalStateError as e:
BlinkLogger().log_info("IllegalStateError: %s" % e)
else:
if settings.answering_machine.enabled and settings.answering_machine.answer_delay == 0:
self.startIncomingSession(session, [s for s in streams if s.type=='audio'], answeringMachine=True)
else:
self.addControllerWithSession_(session)
self.alertPanel.addIncomingSession(session)
self.alertPanel.show()
if session.account is not BonjourAccount() and not session.account.web_alert.show_alert_page_after_connect:
self.show_web_alert_page(session)
def _NH_SIPSessionNewOutgoing(self, session, data):
self.ringer.add_outgoing(session, data.streams)
if session.transfer_info is not None:
# This Session was created as a result of a transfer
self.addControllerWithSessionTransfer_(session)
def _NH_AudioStreamGotDTMF(self, sender, data):
key = data.digit
filename = 'dtmf_%s_tone.wav' % {'*': 'star', '#': 'pound'}.get(key, key)
wave_player = WavePlayer(SIPApplication.voice_audio_mixer, Resources.get(filename))
self.notification_center.add_observer(self, sender=wave_player)
SIPApplication.voice_audio_bridge.add(wave_player)
wave_player.start()
def _NH_WavePlayerDidFail(self, sender, data):
self.notification_center.remove_observer(self, sender=sender)
def _NH_WavePlayerDidEnd(self, sender, data):
self.notification_center.remove_observer(self, sender=sender)
def _NH_BlinkSessionDidEnd(self, session_controller, data):
if session_controller.session is not None and session_controller.session.direction == "incoming":
if session_controller.accounting_for_answering_machine:
self.log_incoming_session_missed(session_controller, data)
else:
self.log_incoming_session_ended(session_controller, data)
else:
self.log_outgoing_session_ended(session_controller, data)
def _NH_BlinkSessionDidFail(self, session_controller, data):
if data.direction == "outgoing":
if data.code == 487:
self.log_outgoing_session_cancelled(session_controller, data)
else:
self.log_outgoing_session_failed(session_controller, data)
elif data.direction == "incoming":
session = session_controller.session
if data.code == 487 and data.failure_reason == 'Call completed elsewhere':
self.log_incoming_session_answered_elsewhere(session_controller, data)
else:
self.log_incoming_session_missed(session_controller, data)
if data.code == 487 and data.failure_reason == 'Call completed elsewhere':
pass
elif data.streams == ['file-transfer']:
pass
else:
session_controller.log_info("Missed incoming session from %s" % format_identity_to_string(session.remote_identity))
if 'audio' in data.streams:
NSApp.delegate().noteMissedCall()
nc_title = 'Missed Call (' + ", ".join(data.streams) + ')'
nc_subtitle = 'From %s' % format_identity_to_string(session.remote_identity, check_contact=True, format='full')
nc_body = 'Missed call at %s' % data.timestamp.strftime("%Y-%m-%d %H:%M")
NSApp.delegate().gui_notify(nc_title, nc_body, nc_subtitle)
@implementer(IObserver)
class SessionController(NSObject):
session = None
state = STATE_IDLE
sub_state = None
routes = None
target_uri = None
endingBy = None
answeringMachineMode = False
failureReason = None
inProposal = False
proposalOriginator = None
waitingForITunes = False
waitingForLocalVideo = False
streamHandlers = None
chatPrintView = None
collaboration_form_id = None
remote_conference_has_audio = False
transfer_window = None
outbound_audio_calls = 0
pending_chat_messages = {}
info_panel = None
call_id = None
from_tag = None
to_tag = None
dealloc_timer = None
answering_machine_filename = ''
do_not_disturb_until_end = False
previous_conference_users = None
notify_when_participants_changed = False
transport = None
screensharing_urls = {}
cancelled_during_dns_lookup = False
retries = 0
display_name = None
encryption = {}
device_id = None
finished = False
@property
def sessionControllersManager(self):
return NSApp.delegate().contactsWindowController.sessionControllersManager
def initWithAccount_target_displayName_contact_(self, account, target_uri, display_name, contact):
global SessionIdentifierSerial
self = objc.super(SessionController, self).init()
SessionIdentifierSerial += 1
BlinkLogger().log_debug("Creating %s" % self)
self.display_name = sip_prefix_pattern.sub("", display_name)
self.remoteIdentity = target_uri
self.contact = contact
self.account = account
self.target_uri = target_uri
self.postdial_string = None
self.identifier = SessionIdentifierSerial
self.streamHandlers = []
self.cancelledStream = None