-
Notifications
You must be signed in to change notification settings - Fork 7
/
ChatController.py
2483 lines (2105 loc) · 118 KB
/
ChatController.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 (NSApp,
NSCompositeSourceOver,
NSDocumentTypeDocumentAttribute,
NSExcludedElementsDocumentAttribute,
NSEventTrackingRunLoopMode,
NSFontAttributeName,
NSHTMLTextDocumentType,
NSImageCompressionFactor,
NSInformationalRequest,
NSJPEGFileType,
NSPNGFileType,
NSOffState,
NSUTF8StringEncoding,
NSString,
NSSplitViewDidResizeSubviewsNotification,
NSSplitViewDividerStyleThick,
NSSplitViewDividerStyleThin,
NSToolbarPrintItemIdentifier,
NSWindowBelow)
from Foundation import (NSAttributedString,
NSBitmapImageRep,
NSBundle,
NSColor,
NSData,
NSDate,
NSDictionary,
NSFont,
NSImage,
NSMakeRect,
NSMakeSize,
NSMakeRange,
NSMenuItem,
NSNotificationCenter,
NSObject,
NSRunLoop,
NSRunLoopCommonModes,
NSScreen,
NSLocalizedString,
NSTask,
NSTaskDidTerminateNotification,
NSTimer,
NSUserDefaults,
NSZeroSize,
NSURL,
NSWorkspace,
NSDownloadsDirectory,
NSSearchPathForDirectoriesInDomains,
NSUserDomainMask
)
from Quartz import (CGDisplayBounds,
CGImageGetWidth,
CGMainDisplayID,
CGWindowListCopyWindowInfo,
CGWindowListCreateImage,
kCGWindowImageBoundsIgnoreFraming,
kCGWindowListExcludeDesktopElements,
kCGWindowListOptionIncludingWindow,
kCGWindowNumber)
import base64
import datetime
import hashlib
import os
import objc
import re
import random
import string
import time
import unicodedata
import uuid
import traceback
from otr import OTRState
from util import call_later
from dateutil.tz import tzlocal
from gnutls.errors import GNUTLSError
from application.notification import IObserver, NotificationCenter, NotificationData
from application.python import Null
from application.system import host
from itertools import chain
from zope.interface import implementer
from sipsimple.account import BonjourAccount
from sipsimple.core import SDPAttribute, SIPURI
from sipsimple.configuration.settings import SIPSimpleSettings
from sipsimple.streams.msrp.chat import ChatStream, ChatStreamError, ChatIdentity, SMPStatus
from sipsimple.threading.green import run_in_green_thread
from sipsimple.application import SIPApplication
from sipsimple.util import ISOTimestamp
import ChatWindowController
from BlinkLogger import BlinkLogger
from ChatViewController import ChatViewController, MSG_STATE_FAILED, MSG_STATE_SENDING, MSG_STATE_DELIVERED
from ChatOTR import ChatOtrSmp
from ContactListModel import BlinkPresenceContact
from ContactListModel import encode_icon, decode_icon
from FileTransferWindowController import openFileTransferSelectionDialog
from HistoryManager import ChatHistory
from MediaStream import MediaStream, STATE_IDLE, STREAM_IDLE, STREAM_FAILED, STREAM_CONNECTED, STREAM_PROPOSING, STREAM_WAITING_DNS_LOOKUP, STREAM_INCOMING, STREAM_CONNECTING, STREAM_RINGING, STREAM_DISCONNECTING, STREAM_CANCELLING
from MediaStream import STATE_IDLE
from PhotoPicker import PhotoPicker
from SIPManager import SIPManager
from SmileyManager import SmileyManager
from ScreensharingPreviewPanel import ScreensharingPreviewPanel
from resources import ApplicationData
from util import allocate_autorelease_pool, format_identity_to_string, format_size, html2txt, image_file_extension_pattern, sipuri_components_from_string, run_in_gui_thread
# Copied from Carbon.h
kUIModeNormal = 0
kUIModeContentSuppressed = 1
kUIModeContentHidden = 2
kUIModeAllSuppressed = 4
kUIModeAllHidden = 3
kUIOptionAutoShowMenuBar = 1 << 0
kUIOptionDisableAppleMenu = 1 << 2
kUIOptionDisableProcessSwitch = 1 << 3
kUIOptionDisableForceQuit = 1 << 4
kUIOptionDisableSessionTerminate = 1 << 5
kUIOptionDisableHide = 1 << 6
MAX_MESSAGE_LENGTH = 16*1024
TOOLBAR_SCREENSHARING_MENU_REQUEST_REMOTE = 201
TOOLBAR_SCREENSHARING_MENU_OFFER_LOCAL = 202
TOOLBAR_SCREENSHARING_MENU_CANCEL = 203
TOOLBAR_SCREENSHOT_MENU_WINDOW = 301
TOOLBAR_SCREENSHOT_MENU_AREA = 302
TOOLBAR_SCREENSHOT_MENU_QUALITY_MENU_HIGH = 401
TOOLBAR_SCREENSHOT_MENU_QUALITY_MENU_LOW = 402
TOOLBAR_SCREENSHOT_MENU_QUALITY_MENU_MEDIUM = 403
bundle = NSBundle.bundleWithPath_('/System/Library/Frameworks/Carbon.framework')
objc.loadBundleFunctions(bundle, globals(), (('SetSystemUIMode', b'III', " Sets the presentation mode for system-provided user interface elements."),))
kCGWindowListOptionOnScreenOnly = 1 << 0
kCGNullWindowID = 0
kCGWindowImageDefault = 0
class BlinkChatStream(ChatStream):
priority = ChatStream.priority + 1
accept_wrapped_types = ['text/*', 'image/*', 'application/im-iscomposing+xml', 'application/blink-icon', 'application/blink-zrtp-sas', 'application/blink-logging-status']
def _create_local_media(self, uri_path):
local_media = super(BlinkChatStream, self)._create_local_media(uri_path)
local_media.attributes.append(SDPAttribute(b'blink-features', b'history-control icon'))
return local_media
@implementer(IObserver)
class ChatController(MediaStream):
type = "chat"
chatViewController = objc.IBOutlet()
smileyButton = objc.IBOutlet()
splitView = objc.IBOutlet()
splitViewFrame = None
inputContainer = objc.IBOutlet()
outputContainer = objc.IBOutlet()
databaseLoggingButton = objc.IBOutlet()
privateLabel = objc.IBOutlet()
document = None
fail_reason = None
sessionController = None
stream = None
finishedLoading = False
showHistoryEntries = 50
mustShowUnreadMessages = False
silence_notifications = False # don't send GUI notifications if active chat is not active
history = None
handler = None
screensharing_handler = None
session_was_active = False
lastDeliveredTime = None
undeliveredMessages = {} # id -> message
# timer is reset whenever remote end sends is-composing active, when it times out, go to idle
remoteTypingTimer = None
drawerSplitterPosition = None
mainViewSplitterPosition = None
screenshot_task = None
dealloc_timer = None
zoom_period_label = ''
message_count_from_history = 0
nickname_request_map = {} # message id -> nickname
chatOtrSmpWindow = None
disable_chat_history = False
remote_party_history = True
video_attached = False
media_started = False
closed = False
smp_verifified_using_zrtp = False
smp_verification_delay = 0
smp_verification_tries = 5
smp_verification_question = b'What is the ZRTP authentication string?'
@property
def local_fingerprint(self):
if self.stream.encryption.active:
return self.stream.encryption.key_fingerprint.upper()
else:
return None
@property
def remote_fingerprint(self):
if self.stream.encryption.active:
return self.stream.encryption.peer_fingerprint.upper()
else:
return None
@objc.python_method
@classmethod
def createStream(self):
return BlinkChatStream()
@objc.python_method
def resetStream(self):
self.sessionController.log_debug("Reset stream %s" % self)
self.notification_center.discard_observer(self, sender=self.stream)
self.media_started = False
self.stream = BlinkChatStream()
self.databaseLoggingButton.setHidden_(True)
self.databaseLoggingButton.setState_(NSOffState)
def initWithOwner_stream_(self, sessionController, stream):
self = objc.super(ChatController, self).initWithOwner_stream_(sessionController, stream)
sessionController.log_debug("Creating %s" % self)
self.mediastream_ended = False
self.session_succeeded = False
self.last_failure_reason = None
self.remoteIcon = None
self.share_screen_in_conference = False
self.previous_is_encrypted = False
self.history_msgid_list=set()
self.remote_uri = self.sessionController.remoteAOR if self.sessionController.account is not BonjourAccount() else self.sessionController.device_id
self.local_uri = '%s@%s' % (self.sessionController.account.id.username, self.sessionController.account.id.domain) if self.sessionController.account is not BonjourAccount() else 'bonjour@local'
BlinkLogger().log_info('Init chat controller %s -> %s' % (self.local_uri, self.remote_uri))
self.silence_notifications = self.sessionController.contact.contact.silence_notifications if self.sessionController.contact is not None and isinstance(self.sessionController.contact, BlinkPresenceContact) else False
self.notification_center = NotificationCenter()
self.notification_center.add_observer(self, name='BlinkFileTransferDidEnd')
self.notification_center.add_observer(self, name='ChatReplicationJournalEntryReceived')
self.notification_center.add_observer(self, name='CFGSettingsObjectDidChange')
self.notification_center.add_observer(self, name='BonjourAccountDidAddNeighbour')
self.notification_center.add_observer(self, name='BonjourAccountDidUpdateNeighbour')
self.notification_center.add_observer(self, name='BonjourAccountDidRemoveNeighbour')
NSBundle.loadNibNamed_owner_("ChatView", self)
self.chatViewController.setContentFile_(NSBundle.mainBundle().pathForResource_ofType_("ChatView", "html"))
if self.sessionController.account is BonjourAccount():
self.chatViewController.setHandleScrolling_(False)
self.chatViewController.lastMessagesLabel.setHidden_(True)
settings = SIPSimpleSettings()
if settings.chat.font_size < 0:
i = settings.chat.font_size
while i < 0:
self.chatViewController.outputView.makeTextSmaller_(None)
i += 1
elif settings.chat.font_size > 0:
i = settings.chat.font_size
while i > 0:
self.chatViewController.outputView.makeTextLarger_(None)
i -= 1
if self.sessionController.contact is not None and isinstance(self.sessionController.contact, BlinkPresenceContact) and self.sessionController.contact.contact.disable_smileys:
self.chatViewController.expandSmileys = False
self.chatViewController.toggleSmileys(self.chatViewController.expandSmileys)
self.chatViewController.setAccount_(self.sessionController.account)
self.chatViewController.resetRenderedMessages()
self.outgoing_message_handler = OutgoingMessageHandler.alloc().initWithView_(self.chatViewController)
self.screensharing_handler = ConferenceScreenSharingHandler()
self.screensharing_handler.setDelegate(self)
self.history = ChatHistory()
self.backend = SIPManager()
self.chatOtrSmpWindow = None
if self.sessionController.contact is not None and isinstance(self.sessionController.contact, BlinkPresenceContact) and self.sessionController.contact.contact.disable_chat_history is not None:
self.disable_chat_history = self.sessionController.contact.contact.disable_chat_history
else:
self.disable_chat_history = settings.chat.disable_history
self.updateDatabaseRecordingButton()
return self
@property
@objc.python_method
def local_identity(self):
if self.sessionController.account.display_name and self.sessionController.account.display_name != self.local_uri:
return ChatIdentity.parse('%s <sip:%s>' % (self.sessionController.account.display_name, self.local_uri))
else:
return ChatIdentity.parse('<sip:%s>' % self.local_uri)
@property
@objc.python_method
def remote_identity(self):
if self.sessionController.display_name and self.sessionController.display_name != self.sessionController.remoteAOR:
return ChatIdentity.parse('%s <sip:%s>' % (self.sessionController.display_name, self.sessionController.remoteAOR))
else:
return ChatIdentity.parse('<sip:%s>' % self.sessionController.remoteAOR)
@objc.python_method
def toggle_silence_notifications(self):
if self.sessionController.contact:
self.sessionController.contact.contact.silence_notifications = not self.sessionController.contact.contact.silence_notifications
self.silence_notifications = not self.silence_notifications
@objc.python_method
def updateDatabaseRecordingButton(self):
settings = SIPSimpleSettings()
remote = self.sessionController.remoteAOR
if self.remote_party_history and not self.disable_chat_history:
self.privateLabel.setHidden_(True)
self.databaseLoggingButton.setImage_(NSImage.imageNamed_("database-on"))
self.databaseLoggingButton.setToolTip_(NSLocalizedString("Text conversation is saved to history database", "Tooltip"))
elif not self.remote_party_history and not self.disable_chat_history:
self.databaseLoggingButton.setImage_(NSImage.imageNamed_("database-remote-off"))
self.privateLabel.setHidden_(False)
self.databaseLoggingButton.setToolTip_(NSLocalizedString("%s wishes that text conversation is not saved in history database", "Tooltip text") % remote)
else:
self.privateLabel.setHidden_(False)
self.databaseLoggingButton.setImage_(NSImage.imageNamed_("database-local-off"))
self.databaseLoggingButton.setToolTip_(NSLocalizedString("Text conversation is not saved to history database", "Tooltip"))
@property
def otr_status(self):
finished = self.stream.encryption.state is OTRState.Finished
encrypted = self.stream.encryption.active
trusted = self.stream.encryption.verified
return (encrypted, trusted, finished)
@property
def is_encrypted(self):
return self.stream.encryption.active
@property
def screensharing_allowed(self):
try:
return 'com.ag-projects.screen-sharing' in self.stream.chatroom_capabilities
except AttributeError:
return False
@property
def zrtp_sas_allowed(self):
try:
return 'com.ag-projects.zrtp-sas' in self.stream.chatroom_capabilities
except AttributeError:
return False
@property
def send_icon_allowed(self):
if not self.stream:
return false
blink_features = self.stream.remote_media.attributes.getfirst(b'blink-features')
blink_caps = blink_features.decode().split() if blink_features else []
return 'icon' in blink_caps
@property
def history_control_allowed(self):
if not self.stream:
return false
blink_features = self.stream.remote_media.attributes.getfirst(b'blink-features')
blink_caps = blink_features.decode().split() if blink_features else []
return 'history-control' in blink_caps
@objc.python_method
def delete_message(self, id, local=False):
self.sessionController.log_info('Delete message %s ' % id)
self.history.delete_message(id);
self.chatViewController.markMessage(id, 'deleted')
@property
def control_allowed(self):
if not self.stream:
return false
try:
return 'com.ag-projects.sylkserver-control' in self.stream.chatroom_capabilities
except AttributeError:
return False
@property
def chatWindowController(self):
return NSApp.delegate().chatWindowController
def awakeFromNib(self):
# setup smiley popup
smileys = SmileyManager().get_smiley_list()
menu = self.smileyButton.menu()
while menu.numberOfItems() > 0:
menu.removeItemAtIndex_(0)
bigText = NSAttributedString.alloc().initWithString_attributes_(" ", NSDictionary.dictionaryWithObject_forKey_(NSFont.systemFontOfSize_(16), NSFontAttributeName))
for text, file in smileys:
image = NSImage.alloc().initWithContentsOfFile_(file)
if not image:
BlinkLogger().log_info("cant load smiley file %s" % file)
continue
image.setScalesWhenResized_(True)
image.setSize_(NSMakeSize(16, 16))
atext = bigText.mutableCopy()
atext.appendAttributedString_(NSAttributedString.alloc().initWithString_(text))
item = NSMenuItem.alloc().initWithTitle_action_keyEquivalent_(text, "insertSmiley:", "")
menu.addItem_(item)
item.setTarget_(self)
item.setAttributedTitle_(atext)
item.setRepresentedObject_(NSAttributedString.alloc().initWithString_(text))
item.setImage_(image)
NSNotificationCenter.defaultCenter().addObserver_selector_name_object_(self, "drawerSplitViewDidResize:", NSSplitViewDidResizeSubviewsNotification, self.splitView)
def drawerSplitViewDidResize_(self, notification):
self.chatViewController.scrollToBottom()
@objc.python_method
def saveSplitterPosition(self):
self.mainViewSplitterPosition={'output_frame': self.outputContainer.frame(), 'input_frame': self.inputContainer.frame()}
@objc.python_method
def restoreSplitterPosition(self):
if self.mainViewSplitterPosition:
self.outputContainer.setFrame_(self.mainViewSplitterPosition['output_frame'])
self.inputContainer.setFrame_(self.mainViewSplitterPosition['input_frame'])
@objc.python_method
def getContentView(self):
return self.chatViewController.view
@objc.python_method
def showSystemMessage(self, message, timestamp, is_error=False):
if self.chatViewController:
self.chatViewController.showSystemMessage(message, timestamp, is_error, call_id=self.sessionController.call_id)
def insertSmiley_(self, sender):
smiley = sender.representedObject()
self.chatViewController.appendAttributedString_(smiley)
@objc.python_method
@run_in_gui_thread
def changeStatus(self, newstate, fail_reason=None):
MediaStream.changeStatus(self, self.status, newstate, fail_reason)
self.status = newstate
@objc.python_method
def openChatWindow(self):
old_session = self.chatWindowController.replaceInactiveWithCompatibleSession_(self.sessionController)
if not old_session:
view = self.getContentView()
self.chatWindowController.addSession_withView_(self.sessionController, view)
else:
self.chatWindowController.selectSession_(self.sessionController)
self.chatWindowController.window().makeKeyAndOrderFront_(None)
self.chatWindowController.closing = False
self.chatWindowController.addTimer()
self.changeStatus(STREAM_IDLE)
self.sessionController.setVideoConsumer("chat")
@objc.python_method
def closeWindow(self):
self.chatWindowController.removeSession_(self.sessionController)
if not self.chatWindowController.sessions:
self.chatWindowController.window().orderOut_(None)
@objc.python_method
def startOutgoing(self, is_update):
self.sessionController.log_debug("Start outgoing...")
self.sessionController.video_consumer = "chat"
self.session_succeeded = False
self.last_failure_reason = None
self.notification_center.add_observer(self, sender=self.stream)
self.notification_center.add_observer(self, sender=self.sessionController)
self.session_was_active = True
self.mustShowUnreadMessages = True
self.openChatWindow()
if is_update and self.sessionController.canProposeMediaStreamChanges():
self.changeStatus(STREAM_PROPOSING)
else:
self.changeStatus(STREAM_WAITING_DNS_LOOKUP)
@objc.python_method
def startIncoming(self, is_update):
self.sessionController.log_debug("Start incoming...")
self.sessionController.video_consumer = "chat"
self.session_succeeded = False
self.last_failure_reason = None
self.notification_center.add_observer(self, sender=self.stream)
self.notification_center.add_observer(self, sender=self.sessionController)
self.session_was_active = True
self.mustShowUnreadMessages = True
self.openChatWindow()
self.changeStatus(STREAM_PROPOSING if is_update else STREAM_INCOMING)
@objc.python_method
def sendFiles(self, fnames):
filenames = [unicodedata.normalize('NFC', file) for file in fnames if os.path.isfile(file) or os.path.isdir(file)]
if filenames:
self.sessionControllersManager.send_files_to_contact(self.sessionController.account, self.sessionController.target_uri, filenames)
return True
return False
@objc.python_method
def sendOwnIcon(self):
if not self.send_icon_allowed:
return
if self.sessionController.account is not BonjourAccount():
return
if self.stream:
base64icon = encode_icon(self.chatWindowController.own_icon)
if base64icon:
self.stream.send_message(base64icon, content_type='application/blink-icon', timestamp=ISOTimestamp.now())
@objc.python_method
def sendLoggingState(self):
if not self.history_control_allowed:
return
if self.status == STREAM_CONNECTED:
content = 'enabled' if not self.disable_chat_history else 'disabled'
self.stream.send_message(content, content_type='application/blink-logging-status', timestamp=ISOTimestamp.now())
@objc.python_method
def sendZRTPSas(self):
if not self.zrtp_sas_allowed:
return
session = self.sessionController.session
try:
audio_stream = next(stream for stream in session.streams if stream.type=='audio' and stream.encryption.type=='ZRTP' and stream.encryption.active)
except (StopIteration, TypeError):
return
full_local_path = self.stream.msrp.full_local_path
full_remote_path = self.stream.msrp.full_remote_path
sas = audio_stream.encryption.zrtp.sas
if sas and self.stream and all(len(path)==1 for path in (full_local_path, full_remote_path)):
self.stream.send_message(sas, 'application/blink-zrtp-sas')
@objc.python_method
def setNickname(self, nickname):
if self.stream and self.stream.nickname_allowed:
try:
message_id = self.stream.set_local_nickname(nickname)
except ChatStreamError:
pass
else:
self.nickname_request_map[message_id] = nickname
def validateToolbarItem_(self, item):
return True
@objc.IBAction
def userClickedDatabaseLoggingButton_(self, sender):
self.disable_chat_history = not self.disable_chat_history
if self.sessionController.contact is not None and isinstance(self.sessionController.contact, BlinkPresenceContact):
self.sessionController.contact.contact.disable_chat_history = self.disable_chat_history
self.sessionController.contact.contact.save()
self.updateDatabaseRecordingButton()
self.sendLoggingState()
def userClickedEncryptionMenu_(self, sender):
tag = sender.tag()
if tag == 4: # active
if self.status == STREAM_CONNECTED:
if self.is_encrypted:
self.sessionController.log_info("Chat encryption will stop")
self.stream.encryption.stop()
else:
self.sessionController.log_info("Chat encryption requested")
self.stream.encryption.start()
elif tag == 5: # verified
self.stream.encryption.verified = not self.stream.encryption.verified
elif tag == 9: # SMP window
if self.stream.encryption.active:
self.chatOtrSmpWindow.show()
elif tag == 10:
NSWorkspace.sharedWorkspace().openURL_(NSURL.URLWithString_("https://otr.cypherpunks.ca/Protocol-v3-4.0.0.html"))
self.revalidateToolbar()
@objc.python_method
def revalidateToolbar(self):
self.chatWindowController.revalidateToolbar()
@objc.python_method
@run_in_gui_thread
def resetStyle(self):
str_attributes = NSDictionary.dictionaryWithObjectsAndKeys_(NSFont.fontWithName_size_("Lucida Grande", 11), NSFontAttributeName)
self.chatViewController.inputText.textStorage().setAttributedString_(NSAttributedString.alloc().initWithString_attributes_(" ", str_attributes))
def textView_doCommandBySelector_(self, textView, selector):
if selector == "insertNewline:" and self.chatViewController.inputText == textView:
# attempt convert rich text to html
try:
# http://stackoverflow.com/questions/5298188/how-do-i-convert-nsattributedstring-into-html-string
text_storage = textView.textStorage()
exclude = ["doctype", "html", "head", "body", "xml"]
documentAttributes = NSDictionary.dictionaryWithObjectsAndKeys_(NSHTMLTextDocumentType, NSDocumentTypeDocumentAttribute, exclude, NSExcludedElementsDocumentAttribute)
data = text_storage.dataFromRange_documentAttributes_error_(NSMakeRange(0, text_storage.length()), documentAttributes, None)
htmlData = NSData.alloc().initWithBytes_length_(data[0], len(data[0]))
content = str(NSString.alloc().initWithData_encoding_(htmlData, NSUTF8StringEncoding))
content_type = 'html'
except Exception as e:
content = str(textView.string())
content_type = 'text'
if content.endswith('\r\n'):
content = content[:-2]
elif content.endswith('\n'):
content = content[:-1]
if self.chatViewController.textWasPasted:
# set style to default
self.chatViewController.textWasPasted = False
self.resetStyle()
if content:
self.chatViewController.inputText.setString_("")
if self.outgoing_message_handler.send(content, recipient=self.remote_identity, content_type=content_type):
NotificationCenter().post_notification('ChatViewControllerDidDisplayMessage', sender=self, data=NotificationData(direction='outgoing', history_entry=False, remote_party=self.sessionController.remoteAOR, local_party=format_identity_to_string(self.sessionController.account) if self.sessionController.account is not BonjourAccount() else 'bonjour@local', check_contact=True))
if not self.stream or self.status in [STREAM_FAILED, STREAM_IDLE]:
self.sessionController.log_info("Session not established, starting it")
if self.outgoing_message_handler.messages:
# save unsend messages and pass them to the newly spawned handler
self.sessionController.pending_chat_messages = self.outgoing_message_handler.messages
self.sessionController.startChatSession()
self.chatViewController.resetTyping()
return True
return False
def chatView_becameIdle_(self, chatView, time):
if self.closed:
return
if self.stream:
self.stream.send_composing_indication("idle", 60, last_active=time)
def chatView_becameActive_(self, chatView, time):
if self.closed:
return
if self.stream:
self.stream.send_composing_indication("active", 60, last_active=time)
if self.outgoing_message_handler.must_propose_otr:
self.outgoing_message_handler.propose_otr()
def chatViewDidLoad_(self, chatView):
if self.closed:
return
self.replay_history()
def isOutputFrameVisible(self):
return True if self.outputContainer.frame().size.height > 10 else False
@objc.python_method
def scroll_back_in_time(self):
try:
msgid = self.history_msgid_list[0]
except IndexError:
msgid = None
self.chatViewController.clear()
self.chatViewController.resetRenderedMessages()
self.replay_history(msgid)
@objc.python_method
@run_in_green_thread
@allocate_autorelease_pool
def replay_history(self, scrollToMessageId=None):
if self.closed:
return
if self.sessionController is None:
return
blink_contact = self.sessionController.contact
if not blink_contact or self.sessionController.account is BonjourAccount():
remote_uris = self.remote_uri
else:
remote_uris = list(str(uri.uri) for uri in blink_contact.uris if '@' in uri.uri)
zoom_factor = self.chatViewController.scrolling_zoom_factor
if zoom_factor:
period_array = {
1: datetime.datetime.now()-datetime.timedelta(days=2),
2: datetime.datetime.now()-datetime.timedelta(days=7),
3: datetime.datetime.now()-datetime.timedelta(days=31),
4: datetime.datetime.now()-datetime.timedelta(days=90),
5: datetime.datetime.now()-datetime.timedelta(days=180),
6: datetime.datetime.now()-datetime.timedelta(days=365),
7: datetime.datetime.now()-datetime.timedelta(days=3650)
}
after_date = period_array[zoom_factor].strftime("%Y-%m-%d")
if zoom_factor == 1:
self.zoom_period_label = NSLocalizedString("Displaying messages from last day", "Label")
elif zoom_factor == 2:
self.zoom_period_label = NSLocalizedString("Displaying messages from last week", "Label")
elif zoom_factor == 3:
self.zoom_period_label = NSLocalizedString("Displaying messages from last month", "Label")
elif zoom_factor == 4:
self.zoom_period_label = NSLocalizedString("Displaying messages from last three months", "Label")
elif zoom_factor == 5:
self.zoom_period_label = NSLocalizedString("Displaying messages from last six months", "Label")
elif zoom_factor == 6:
self.zoom_period_label = NSLocalizedString("Displaying messages from last year", "Label")
elif zoom_factor == 7:
self.zoom_period_label = NSLocalizedString("Displaying all messages", "Label")
self.chatViewController.setHandleScrolling_(False)
results = self.history.get_messages(remote_uri=remote_uris, media_type=('chat', 'sms'), after_date=after_date, count=10000, search_text=self.chatViewController.search_text)
else:
results = self.history.get_messages(remote_uri=remote_uris, media_type=('chat', 'sms'), count=self.showHistoryEntries, search_text=self.chatViewController.search_text)
# build a list of previously failed messages
last_failed_messages=[]
for row in results:
if row.status == 'delivered':
break
last_failed_messages.append(row)
last_failed_messages.reverse()
self.history_msgid_list = [row.msgid for row in reversed(list(results))]
# render last delievered messages except those due to be resent
# messages_to_render = [row for row in reversed(list(results)) if row not in last_failed_messages]
messages_to_render = [row for row in reversed(list(results))]
#self.resend_last_failed_message(last_failed_messages)
self.render_history_messages(messages_to_render, scrollToMessageId)
self.send_pending_message()
@objc.python_method
@run_in_gui_thread
def render_history_messages(self, messages, scrollToMessageId=None):
if self.chatViewController.scrolling_zoom_factor:
if not self.message_count_from_history:
self.message_count_from_history = len(messages)
self.chatViewController.lastMessagesLabel.setStringValue_(self.zoom_period_label)
else:
if self.message_count_from_history >= len(messages):
self.chatViewController.setHandleScrolling_(False)
self.zoom_period_label = NSLocalizedString("%s. There are no previous messages.", "Label") % self.zoom_period_label
self.chatViewController.lastMessagesLabel.setStringValue_(self.zoom_period_label)
self.chatViewController.setHandleScrolling_(False)
else:
self.chatViewController.lastMessagesLabel.setStringValue_(self.zoom_period_label)
else:
self.message_count_from_history = len(messages)
if len(messages):
self.chatViewController.lastMessagesLabel.setStringValue_(NSLocalizedString("Scroll up for going back in time", "Label"))
else:
self.chatViewController.setHandleScrolling_(False)
self.chatViewController.lastMessagesLabel.setStringValue_(NSLocalizedString("There are no previous messages", "Label"))
if len(messages):
message = messages[0]
delta = datetime.date.today() - message.date
if not self.chatViewController.scrolling_zoom_factor:
if delta.days <= 2:
self.chatViewController.scrolling_zoom_factor = 1
elif delta.days <= 7:
self.chatViewController.scrolling_zoom_factor = 2
elif delta.days <= 31:
self.chatViewController.scrolling_zoom_factor = 3
elif delta.days <= 90:
self.chatViewController.scrolling_zoom_factor = 4
elif delta.days <= 180:
self.chatViewController.scrolling_zoom_factor = 5
elif delta.days <= 365:
self.chatViewController.scrolling_zoom_factor = 6
else:
self.chatViewController.scrolling_zoom_factor = 7
call_id = None
seen_sms = {}
last_media_type = None
cpim_re = re.compile(r'^(?:"?(?P<display_name>[^<]*[^"\s])"?)?\s*<(?P<uri>.+)>$')
for message in messages:
if message.status == 'sent':
message.status = 'failed'
if message.status == 'failed':
continue
if message.sip_callid != '' and message.media_type == 'sms':
try:
seen_sms[message.sip_callid]
except KeyError:
seen_sms[message.sip_callid] = True
else:
continue
if message.direction == 'outgoing':
icon = NSApp.delegate().contactsWindowController.iconPathForSelf()
else:
sender_uri = sipuri_components_from_string(message.cpim_from)[0]
icon = NSApp.delegate().contactsWindowController.iconPathForURI(sender_uri)
timestamp=ISOTimestamp(message.cpim_timestamp)
is_html = message.content_type != 'text'
private = bool(int(message.private))
if self.chatViewController:
#if call_id is not None and call_id != message.sip_callid and message.media_type == 'chat':
#self.chatViewController.showSystemMessage('Connection established', timestamp, False, call_id=message.sip_callid,)
#if message.media_type == 'sms' and last_media_type == 'chat':
#self.chatViewController.showSystemMessage('Short messages', timestamp, False, call_id=message.sip_callid,)
sender = message.cpim_from
recipient = message.cpim_to
match = cpim_re.match(sender)
if match:
sender = match.group('display_name') or match.group('uri')
match = cpim_re.match(recipient)
if match:
recipient = match.group('display_name') or match.group('uri')
self.chatViewController.showMessage(message.sip_callid, message.msgid, message.direction, sender, icon, message.body, timestamp, is_private=private, recipient=recipient, state=message.status, is_html=is_html, history_entry=True, media_type = message.media_type, encryption=message.encryption)
call_id = message.sip_callid
last_media_type = 'chat' if message.media_type == 'chat' else 'sms'
if scrollToMessageId is not None:
self.chatViewController.scrollToId(scrollToMessageId)
self.chatViewController.loadingProgressIndicator.stopAnimation_(None)
self.chatViewController.loadingTextIndicator.setStringValue_("")
@objc.python_method
@run_in_gui_thread
def resend_last_failed_message(self, messages):
if self.sessionController.account is BonjourAccount():
return
for message in messages:
private = True if message.private == "1" else False
self.outgoing_message_handler.resend(message.msgid, message.body, self.remote_identity, private, message.content_type)
@objc.python_method
@run_in_gui_thread
def send_pending_message(self):
if self.sessionController.pending_chat_messages:
for message in reversed(list(self.sessionController.pending_chat_messages.values())):
self.outgoing_message_handler.resend(message.msgid, message.content, message.recipient, message.private)
self.sessionController.pending_chat_messages = {}
def chatViewDidGetNewMessage_(self, chatView):
NSApp.delegate().noteNewMessage(self.chatViewController.outputView.window())
if self.mustShowUnreadMessages:
self.chatWindowController.noteNewMessageForSession_(self.sessionController)
@objc.python_method
def updateEncryptionWidgets(self):
if self.status == STREAM_CONNECTED:
if self.is_encrypted:
if self.stream.encryption.verified:
self.chatWindowController.encryptionIconMenuItem.setImage_(NSImage.imageNamed_("locked-green"))
else:
self.chatWindowController.encryptionIconMenuItem.setImage_(NSImage.imageNamed_("locked-red"))
else:
self.chatWindowController.encryptionIconMenuItem.setImage_(NSImage.imageNamed_("unlocked-darkgray"))
# TODO: use orange if first time
# self.chatWindowController.encryptionIconMenuItem.setImage_(NSImage.imageNamed_("locked-orange"))
else:
self.chatWindowController.encryptionIconMenuItem.setImage_(NSImage.imageNamed_("unlocked-darkgray"))
@objc.python_method
def connectButtonEnabled(self):
if '@127.0.0.1' in str(self.remote_identity.uri):
return False
if self.status in (STREAM_IDLE, STREAM_WAITING_DNS_LOOKUP, STREAM_CONNECTING, STREAM_CONNECTED):
return True
elif self.status == STREAM_PROPOSING:
return self.sessionController.proposalOriginator == 'local'
elif self.status == STREAM_DISCONNECTING:
return False
else:
return self.sessionController.canProposeMediaStreamChanges() or self.sessionController.canStartSession()
@objc.python_method
def audioButtonEnabled(self):
if '@127.0.0.1' in str(self.remote_identity.uri):
return False
if self.status in (STREAM_WAITING_DNS_LOOKUP, STREAM_CONNECTING, STREAM_PROPOSING, STREAM_DISCONNECTING, STREAM_CANCELLING):
return False
if self.sessionController.hasStreamOfType("audio"):
audio_stream = self.sessionController.streamHandlerOfType("audio")
if audio_stream.status == STREAM_FAILED:
return False
if audio_stream.status == STREAM_CONNECTED:
return self.sessionController.canProposeMediaStreamChanges() or self.sessionController.canStartSession()
elif audio_stream.status in (STREAM_PROPOSING, STREAM_RINGING):
return True if self.sessionController.canCancelProposal() else False
else:
return True if self.sessionController.canProposeMediaStreamChanges() and self.status in (STATE_IDLE, STREAM_CONNECTED) else False
else:
return self.sessionController.canProposeMediaStreamChanges() or self.sessionController.canStartSession()
@objc.python_method
def fileTransferButtonEnabled(self):
if '@127.0.0.1' in str(self.remote_identity.uri):
return False
return True
@objc.python_method
def videoButtonEnabled(self):
if '@127.0.0.1' in str(self.remote_identity.uri):
return False
if self.status in (STREAM_WAITING_DNS_LOOKUP, STREAM_CONNECTING, STREAM_PROPOSING, STREAM_DISCONNECTING, STREAM_CANCELLING):
return False
if self.sessionController.hasStreamOfType("video"):
video_stream = self.sessionController.streamHandlerOfType("video")
if video_stream.status == STREAM_FAILED:
return False
if video_stream.status == STREAM_CONNECTED:
return self.sessionController.canProposeMediaStreamChanges() or self.sessionController.canStartSession()
elif video_stream.status in (STREAM_PROPOSING, STREAM_RINGING):
return True if self.sessionController.canCancelProposal() else False
else:
return True if self.sessionController.canProposeMediaStreamChanges() and self.status in (STATE_IDLE, STREAM_CONNECTED) else False
else:
return self.sessionController.canProposeMediaStreamChanges() or self.sessionController.canStartSession()
@objc.python_method
def updateToolbarButtons(self, toolbar, got_proposal=False):
"""Called by ChatWindowController when receiving various middleware notifications"""
settings = SIPSimpleSettings()
audio_stream = self.sessionController.streamHandlerOfType("audio")
for item in toolbar.visibleItems():
identifier = item.itemIdentifier()
if identifier == 'encryption':
self.updateEncryptionWidgets()
item.setEnabled_(True)
elif identifier == 'connect_button':
if self.status in (STREAM_CONNECTING, STREAM_WAITING_DNS_LOOKUP):
item.setToolTip_(NSLocalizedString("Cancel Chat", "Tooltip"))
item.setLabel_(NSLocalizedString("Cancel", "Button title"))
item.setImage_(NSImage.imageNamed_("stop_chat"))
elif self.status == STREAM_PROPOSING:
if self.sessionController.proposalOriginator != 'remote':
item.setToolTip_(NSLocalizedString("Cancel Chat", "Tooltip"))
item.setLabel_(NSLocalizedString("Cancel", "Button title"))
item.setImage_(NSImage.imageNamed_("stop_chat"))
elif self.status == STREAM_CONNECTED:
item.setToolTip_(NSLocalizedString("End chat", "Tooltip"))