-
Notifications
You must be signed in to change notification settings - Fork 7
/
SMSViewController.py
1555 lines (1254 loc) · 70.8 KB
/
SMSViewController.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,
NSEventTrackingRunLoopMode,
NSFontAttributeName,
NSForegroundColorAttributeName,
NSWorkspace)
from Foundation import (NSAttributedString,
NSBundle,
NSColor,
NSDate,
NSDictionary,
NSFont,
NSImage,
NSLocalizedString,
NSMakePoint,
NSMakeSize,
NSMaxX,
NSMenuItem,
NSObject,
NSRunLoopCommonModes,
NSRunLoop,
NSSplitView,
NSString,
NSTimer,
NSWorkspace,
NSURL)
import objc
import os
import pgpy
import uuid
import datetime
import hashlib
import ast
import re
import json
from binascii import unhexlify, hexlify
from application.notification import IObserver, NotificationCenter, NotificationData
from application.python import Null
from application.python.queue import EventQueue
from application.system import host
from dateutil.parser._parser import ParserError as DateParserError
from zope.interface import implementer
from resources import ApplicationData
from otr import OTRTransport, OTRState, SMPStatus
from otr.exceptions import IgnoreMessage, UnencryptedMessage, EncryptedMessageError, OTRError, OTRFinishedError
from sipsimple.account import Account, BonjourAccount
from sipsimple.core import Message, FromHeader, ToHeader, RouteHeader, Header, SIPURI, Route
from sipsimple.configuration.settings import SIPSimpleSettings
from sipsimple.lookup import DNSLookup, DNSLookupError
from sipsimple.payloads import ParserError
from sipsimple.payloads.iscomposing import IsComposingDocument, IsComposingMessage, State, LastActive, Refresh, ContentType
from sipsimple.payloads.imdn import IMDNDocument, DisplayNotification, DeliveryNotification
from sipsimple.streams.msrp.chat import CPIMPayload, SimplePayload, CPIMParserError, CPIMHeader, ChatIdentity, OTREncryption, CPIMNamespace
from sipsimple.threading.green import run_in_green_thread
from sipsimple.util import ISOTimestamp
from pgpy.constants import PubKeyAlgorithm, KeyFlags, HashAlgorithm, SymmetricKeyAlgorithm, CompressionAlgorithm
from BlinkLogger import BlinkLogger
from ChatViewController import MSG_STATE_SENDING, MSG_STATE_SENT, MSG_STATE_DELIVERED, MSG_STATE_FAILED, MSG_STATE_DISPLAYED, MSG_STATE_FAILED_LOCAL, MSG_STATE_DEFERRED
from HistoryManager import ChatHistory
from SmileyManager import SmileyManager
from util import format_identity_to_string, html2txt, sipuri_components_from_string, run_in_gui_thread
from ChatOTR import ChatOtrSmp
import SMSWindowManager
# OpenPGP settings compatible with Sylk client
pgpOptions = {'cipher': 'aes256',
'compression': 'zlib',
'hash': 'sha512',
'RSABits': 4096,
'compressionLevel': 5
}
MAX_MESSAGE_LENGTH = 16000
class MessageInfo(object):
def __init__(self, id, content=None, content_type='text/plain', call_id=None, direction='outgoing', sender=None, recipient=None, timestamp=None, status=None, encryption=None, require_delivered_notification=False, require_displayed_notification=False):
self.id = id
self.call_id = call_id
self.pjsip_id = None
self.direction = direction
self.sender = sender # an identity object with uri and display_name
self.recipient = recipient # an identity object with uri and display_name
self.timestamp = timestamp
self.content = content if isinstance(content, bytes) else content.encode()
self.content_type = content_type
self.status = status
self.encryption = encryption
self.require_delivered_notification = require_delivered_notification
self.require_displayed_notification = require_displayed_notification
class OTRInternalMessage(MessageInfo):
def __init__(self, content):
super(OTRInternalMessage, self).__init__('OTR', content=content, content_type='text/plain')
class SMSSplitView(NSSplitView):
text = None
attributes = NSDictionary.dictionaryWithObjectsAndKeys_(
NSFont.systemFontOfSize_(NSFont.labelFontSize()-1), NSFontAttributeName,
NSColor.darkGrayColor(), NSForegroundColorAttributeName)
def setText_(self, text):
self.text = NSString.stringWithString_(text)
self.setNeedsDisplay_(True)
def dividerThickness(self):
return NSFont.labelFontSize()+1
def drawDividerInRect_(self, rect):
NSSplitView.drawDividerInRect_(self, rect)
if self.text:
point = NSMakePoint(NSMaxX(rect) - self.text.sizeWithAttributes_(self.attributes).width - 10, rect.origin.y)
self.text.drawAtPoint_withAttributes_(point, self.attributes)
@implementer(IObserver)
class SMSViewController(NSObject):
chatViewController = objc.IBOutlet()
splitView = objc.IBOutlet()
smileyButton = objc.IBOutlet()
outputContainer = objc.IBOutlet()
addContactView = objc.IBOutlet()
addContactLabel = objc.IBOutlet()
zoom_period_label = ''
showHistoryEntries = 50
remoteTypingTimer = None
handle_scrolling = True
scrollingTimer = None
scrolling_back = False
message_count_from_history = 0
contact = None
not_read_queue_started = False
not_read_queue_paused = False
incoming_queue_started = False
started = False
paused = False
account = None
target_uri = None
routes = None
private_key = None
public_key = None
my_public_key = None
public_key_sent = False
windowController = None
last_route = None
chatOtrSmpWindow = None
dns_lookup_in_progress = False
last_failure_reason = None
otr_negotiation_timer = None
pgp_encrypted = False
bonjour_lookup_enabled = True
def initWithAccount_target_name_instance_(self, account, target, display_name, instance_id, selected_contact=None, is_replication_message=False):
self = objc.super(SMSViewController, self).init()
if self:
self.keys_path = ApplicationData.get('keys')
self.messages = {}
self.sent_readable_messages = set()
self.session_id = str(uuid.uuid1())
self.instance_id = instance_id
self.notification_center = NotificationCenter()
self.account = account
self.target_uri = target
self.encryption = OTREncryption(self)
self.outgoing_queue = EventQueue(self._send_message) # outgoing messages
self.incoming_queue = EventQueue(self._receive_message) # displayed messages
self.not_read_queue = EventQueue(self._send_read_notification) # not_read incoming messsages
self.history = ChatHistory()
self.msg_id_list = set() # prevent display of duplicate messages
self.local_uri = '%s@%s' % (account.id.username, account.id.domain)
self.remote_uri = '%s@%s' % (self.target_uri.user.decode(), self.target_uri.host.decode())
self.contact = selected_contact or SMSWindowManager.SMSWindowManager().getContact(self.remote_uri, addGroup=True)
self.display_name = self.contact.name if self.contact else display_name
self.is_replication_message = is_replication_message
self.load_remote_public_keys()
self.load_private_key()
NSBundle.loadNibNamed_owner_("SMSView", self)
self.chatViewController.setContentFile_(NSBundle.mainBundle().pathForResource_ofType_("ChatView", "html"))
self.chatViewController.setAccount_(self.account)
self.chatViewController.resetRenderedMessages()
self.chatViewController.inputText.unregisterDraggedTypes()
self.chatViewController.inputText.setMaxLength_(MAX_MESSAGE_LENGTH)
self.splitView.setText_(NSLocalizedString("%i chars left", "Label") % MAX_MESSAGE_LENGTH)
self.log_info('Using account %s with target %s' % (self.local_uri, self.target_uri))
if self.account.sms.private_key and self.public_key:
self.pgp_encrypted = True
self.notification_center.post_notification('PGPEncryptionStateChanged', sender=self)
self.notification_center.add_observer(self, name='ChatStreamOTREncryptionStateChanged')
self.notification_center.add_observer(self, name='BlinkContactsHaveChanged')
self.notification_center.add_observer(self, name='PGPPublicKeyReceived', sender=self.account)
if not self.is_replication_message:
self.lookup_destination(self.target_uri)
return self
@objc.python_method
def load_remote_public_keys(self):
public_key_path = "%s/%s.pubkey" % (self.keys_path, self.remote_uri)
if not os.path.exists(public_key_path):
self.requestPublicKey()
return
try:
self.public_key, _ = pgpy.PGPKey.from_file(public_key_path)
except Exception as e:
self.log_info('Cannot import PGP public key: %s' % str(e))
else:
self.log_info('PGP public key of %s imported from %s' % (self.remote_uri, public_key_path))
@objc.python_method
def load_private_key(self):
if self.account.enabled and not self.account.sms.private_key or not os.path.exists(self.account.sms.private_key):
self.generateKeys()
try:
self.private_key, _ = pgpy.PGPKey.from_file(self.account.sms.private_key)
except Exception as e:
self.log_info('Cannot import PGP private key: %s' % str(e))
else:
self.log_info('My PGP private key imported from %s' % self.account.sms.private_key)
public_key_path = "%s/%s.pubkey" % (self.keys_path, self.account.id)
try:
self.my_public_key, _ = pgpy.PGPKey.from_file(public_key_path)
except Exception as e:
self.log_info('Cannot import my own PGP public key: %s' % str(e))
else:
self.log_info('My PGP public key imported from %s' % public_key_path)
@objc.python_method
def generateKeys(self):
private_key = pgpy.PGPKey.new(PubKeyAlgorithm.RSAEncryptOrSign, 4096)
uid = pgpy.PGPUID.new(self.account.display_name, comment='Blink client', email=self.account.id)
private_key.add_uid(uid, usage={KeyFlags.Sign, KeyFlags.EncryptCommunications, KeyFlags.EncryptStorage},
hashes=[HashAlgorithm.SHA512],
ciphers=[SymmetricKeyAlgorithm.AES256],
compression=[CompressionAlgorithm.Uncompressed])
private_key_path = "%s/%s.privkey" % (self.keys_path, self.account.id)
fd = open(private_key_path, "wb+")
fd.write(str(private_key).encode())
fd.close()
BlinkLogger().log_info("My PGP private key saved to %s" % private_key_path)
public_key_path = "%s/%s.pubkey" % (self.keys_path, self.account.id)
fd = open(public_key_path, "wb+")
fd.write(str(private_key.pubkey).encode())
fd.close()
BlinkLogger().log_info("My PGP public key saved to %s" % public_key_path)
public_key_checksum = hashlib.sha1(str(private_key.pubkey).encode()).hexdigest()
self.account.sms.private_key = private_key_path
self.account.sms.public_key = public_key_path
self.account.sms.public_key_checksum = public_key_checksum
self.account.save()
@property
def enableIsComposing(self):
return self.account.sms.enable_composing
def dealloc(self):
if self.remoteTypingTimer:
self.remoteTypingTimer.invalidate()
if self.encryption.active:
self.stopEncryption()
self.chatViewController.close()
objc.super(SMSViewController, self).dealloc()
@objc.python_method
def heartbeat(self):
#self.log_info('--- We have a stack of %d messages' % len(self.messages.keys()))
for message in list(self.messages.values()):
if message.content_type in (IsComposingDocument.content_type, "text/pgp-public-key", "text/pgp-private-key"):
if ISOTimestamp.now() - message.timestamp > datetime.timedelta(seconds=30):
try:
self.messages.pop(message.id)
except KeyError:
pass
continue
if message.status != MSG_STATE_SENDING:
self.log_debug('Message id %s %s: %s' % (message.id, message.content_type, message.status))
else:
self.log_debug('Message id %s is sent by PJSIP: %s' % (message.id, message.pjsip_id))
if message.status == MSG_STATE_FAILED_LOCAL and not message.pjsip_id and ISOTimestamp.now() - message.timestamp > datetime.timedelta(seconds=20):
if host.default_ip is not None:
if self.account is BonjourAccount():
if self.bonjour_lookup_enabled:
self.log_info('Resending message %s' % message.id)
self.outgoing_queue.put(message)
else:
self.log_info('Resending message %s' % message.id)
self.outgoing_queue.put(message)
else:
self.log_debug('Waiting for connectivity to resend message %s' % message.id)
continue
if message.status in (MSG_STATE_DELIVERED, MSG_STATE_FAILED, MSG_STATE_DISPLAYED, MSG_STATE_SENT):
try:
self.messages.pop(message.id)
except KeyError:
pass
if host.default_ip and (not self.last_route or self.paused):
self.lookup_destination(self.target_uri)
elif not host.default_ip and self.last_route:
self.last_route = None
self.stop_queue()
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:
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)
@objc.python_method
def revalidateToolbar(self):
pass
@objc.python_method
def isOutputFrameVisible(self):
return True
@objc.python_method
def log_info(self, text):
BlinkLogger().log_info("[SMS with %s] %s" % (self.instance_id or self.remote_uri, text))
@objc.python_method
def log_debug(self, text):
BlinkLogger().log_debug("[SMS with %s] %s" % (self.instance_id or self.remote_uri, text))
@objc.python_method
def log_error(self, text):
BlinkLogger().log_error("[SMS with %s] %s" % (self.instance_id or self.remote_uri, text))
@objc.IBAction
def addContactPanelClicked_(self, sender):
if sender.tag() == 1:
NSApp.delegate().contactsWindowController.addContact(uris=[(self.target_uri, 'sip')])
self.addContactView.removeFromSuperview()
frame = self.chatViewController.outputView.frame()
frame.origin.y = 0
frame.size = self.outputContainer.frame().size
self.chatViewController.outputView.setFrame_(frame)
@objc.python_method
def delete_message(self, id, local=False):
self.log_info('Delete message %s ' % id)
self.history.delete_message(id);
self.chatViewController.markMessage(id, 'deleted')
if not local:
self.sendMessage(id, 'application/sylk-api-message-remove')
@objc.python_method
def insertSmiley_(self, sender):
smiley = sender.representedObject()
self.chatViewController.appendAttributedString_(smiley)
@objc.python_method
def matchesTargetOrInstanceAndAccount(self, target, instance_id, account):
that_contact = NSApp.delegate().contactsWindowController.getFirstContactMatchingURI(target)
this_contact = NSApp.delegate().contactsWindowController.getFirstContactMatchingURI(self.target_uri)
if instance_id is not None and instance_id == self.instance_id:
return True
m = (self.target_uri==target or (this_contact and that_contact and this_contact==that_contact)) and self.account==account
#self.log_info('Viewer match with target %s and account %s: %s' % (target, account, m))
return m
@objc.python_method
def gotMessage(self, sender_identity, id, call_id, direction, content, content_type, is_replication_message=False, window=None, cpim_imdn_events=None, imdn_timestamp=None, account=None, imdn_message_id=None, from_journal=False, status=None):
self.is_replication_message = is_replication_message
if id in self.msg_id_list:
self.log_info('Discard duplicate message %s' % id)
return
if id in self.sent_readable_messages:
self.log_info('Discard message %s that looped back to myself' % id)
return
message_tuple = (sender_identity, id, call_id, direction, content, content_type, is_replication_message, window, cpim_imdn_events, imdn_timestamp, account, imdn_message_id, status)
self.incoming_queue.put(message_tuple)
@objc.python_method
def _receive_message(self, message_tuple):
(sender_identity, id, call_id, direction, content, content_type, is_replication_message, window, cpim_imdn_events, imdn_timestamp, account, imdn_message_id, status) = message_tuple
if content_type in ('text/pgp-public-key', 'text/pgp-private-key'):
return
icon = NSApp.delegate().contactsWindowController.iconPathForURI(format_identity_to_string(sender_identity))
sender_name = format_identity_to_string(sender_identity, format='compact')
if direction == 'incoming':
sender_name = self.normalizeSender(sender_name)
try:
timestamp=ISOTimestamp(imdn_timestamp)
except (DateParserError, TypeError) as e:
self.log_error('Failed to parse timestamp %s for message id %s: %s' % (imdn_timestamp, id, str(e)))
timestamp = ISOTimestamp.now()
try:
require_delivered_notification = imdn_timestamp and cpim_imdn_events and 'positive-delivery' in cpim_imdn_events and direction == 'incoming' and content_type != IMDNDocument.content_type
require_displayed_notification = imdn_timestamp and cpim_imdn_events and 'display' in cpim_imdn_events and direction == 'incoming' and content_type != IMDNDocument.content_type
is_html = content_type == 'text/html'
encrypted = False
text_content = content.decode().strip()
if text_content.startswith('-----BEGIN PGP MESSAGE-----') and text_content.endswith('-----END PGP MESSAGE-----'):
if not self.private_key:
self.chatViewController.showSystemMessage("No PGP private key available", ISOTimestamp.now(), is_error=True)
return
else:
try:
pgpMessage = pgpy.PGPMessage.from_blob(text_content)
decrypted_message = self.private_key.decrypt(pgpMessage)
except (pgpy.errors.PGPDecryptionError, pgpy.errors.PGPError) as e:
if self.pgp_encrypted:
self.pgp_encrypted = False
self.notification_center.post_notification('PGPEncryptionStateChanged', sender=self)
#self.chatViewController.showSystemMessage("PGP decryption error: %s" % str(e), ISOTimestamp.now(), is_error=True)
self.chatViewController.showMessage(call_id, id, direction, sender_name, icon, "PGP decryption error: %s" % str(e), timestamp, state=MSG_STATE_FAILED, media_type='sms')
self.log_error('PGP decrypt error: %s' % str(e))
if require_delivered_notification:
self.sendIMDNNotification(id, 'failed')
return
else:
self.log_info('PGP message %s decrypted' % id)
if not self.pgp_encrypted:
self.pgp_encrypted = True
self.notification_center.post_notification('PGPEncryptionStateChanged', sender=self)
try:
content = bytes(decrypted_message.message, 'latin1')
except TypeError as e:
self.log_error('Data decode error: %s' % str(e))
self.log_error('Decrypted data type: %s' % type(decrypted_message.message))
self.log_error('Decrypted data: %s' % decrypted_message)
return
else:
self.pgp_encrypted = False
if content_type not in (IsComposingDocument.content_type, IMDNDocument.content_type) and not is_replication_message:
try:
content = self.encryption.otr_session.handle_input(content, content_type)
except IgnoreMessage:
self.log_info('OTR message %s received' % call_id)
return None
except UnencryptedMessage:
self.log_info('OTR in use but unencrypted message received')
encrypted = False
encryption_active = True
except EncryptedMessageError as e:
self.log_info('OTP encrypted message error: %s' % str(e))
return None
except OTRFinishedError:
self.chatViewController.showSystemMessage("Recipient ended OTR encryption", ISOTimestamp.now(), is_error=True)
self.log_info('OTR has finished')
encrypted = False
encryption_active = False
except OTRError as e:
self.log_info('OTP error: %s' % str(e))
return None
else:
#self.log_info('OTR message %s handled without error' % call_id)
encrypted = encryption_active = self.encryption.active
try:
content = content.decode() if isinstance(content, bytes) else content
except UnicodeDecodeError:
return
if content.startswith('?OTR:'):
if not is_replication_message:
self.log_info('Dropped %s OTR message that could not be decoded' % content_type)
self.chatViewController.showSystemMessage("Recipient ended OTR encryption", ISOTimestamp.now(), is_error=True)
if self.encryption.active:
self.stopEncryption()
else:
self.chatViewController.showSystemMessage("OTR encrypted message from another device of my own", ISOTimestamp.now())
return None
msg_id = imdn_message_id if imdn_message_id and is_replication_message else id
if msg_id in self.msg_id_list:
return
self.msg_id_list.add(msg_id)
status = status or MSG_STATE_DELIVERED
if require_delivered_notification:
self.sendIMDNNotification(id, 'delivered')
if not is_replication_message and not window.isKeyWindow() and status != 'displayed':
nc_body = html2txt(content) if is_html else content
nc_title = NSLocalizedString("Message Received", "Label")
nc_subtitle = format_identity_to_string(sender_identity, format='full')
NSApp.delegate().gui_notify(nc_title, nc_body, nc_subtitle)
if encrypted:
encryption = 'verified' if self.encryption.verified or self.pgp_encrypted else 'unverified'
elif self.pgp_encrypted:
encryption = 'verified'
else:
encryption = ''
self.chatViewController.showMessage(call_id, msg_id, direction, sender_name, icon, content, timestamp, is_html=is_html, state=status, media_type='sms', encryption=encryption)
self.notification_center.post_notification('ChatViewControllerDidDisplayMessage', sender=self, data=NotificationData(id=msg_id, direction=direction, history_entry=False, status=status, is_replication_message=is_replication_message, remote_party=format_identity_to_string(sender_identity), local_party=format_identity_to_string(self.account) if self.account is not BonjourAccount() else 'bonjour@local', check_contact=True))
# save to history
recipient = ChatIdentity(self.target_uri, self.display_name) if direction == 'outgoing' else ChatIdentity(self.account.uri, self.account.display_name)
if direction == 'outgoing' and not sender_identity.display_name:
try:
sender_identity.display_name = self.account.display_name
except AttributeError:
# this happens for replicated messages where we have FrozenIdentityHeader received from network
pass
mInfo = MessageInfo(msg_id, call_id=call_id, direction=direction, sender=sender_identity, recipient=recipient, timestamp=timestamp, content=content, content_type=content_type, status=status, encryption=encryption, require_displayed_notification=require_displayed_notification, require_delivered_notification=require_delivered_notification)
self.add_to_history(mInfo)
if require_displayed_notification:
self.not_read_queue.put(msg_id)
except Exception as e:
self.log_info('Error in render_message: %s' % str(e))
self.log_info(message_tuple)
import traceback
self.log_info(traceback.format_exc())
@objc.python_method
def _send_read_notification(self, id):
if id is None:
return
self.log_info('Send read notification for message %s' % id)
self.sendIMDNNotification(id, 'displayed')
def remoteBecameIdle_(self, timer):
window = timer.userInfo()
if window:
window.noteView_isComposing_(self, False)
if self.remoteTypingTimer:
self.remoteTypingTimer.invalidate()
self.remoteTypingTimer = None
@objc.python_method
def gotIsComposing(self, window, state, refresh, last_active):
flag = state == "active"
if flag:
if refresh is None:
refresh = 120
if last_active is not None and (last_active - ISOTimestamp.now() > datetime.timedelta(seconds=refresh)):
# message is old, discard it
return
if self.remoteTypingTimer:
# if we don't get any indications in the request refresh, then we assume remote to be idle
self.remoteTypingTimer.setFireDate_(NSDate.dateWithTimeIntervalSinceNow_(refresh))
else:
self.remoteTypingTimer = NSTimer.scheduledTimerWithTimeInterval_target_selector_userInfo_repeats_(refresh, self, "remoteBecameIdle:", window, False)
else:
if self.remoteTypingTimer:
self.remoteTypingTimer.invalidate()
self.remoteTypingTimer = None
window.noteView_isComposing_(self, flag)
@objc.python_method
@run_in_gui_thread
def handle_notification(self, notification):
handler = getattr(self, '_NH_%s' % notification.name, Null)
handler(notification.sender, notification.data)
@objc.python_method
def inject_otr_message(self, data):
messageObject = OTRInternalMessage(data)
self.sendMessage(messageObject)
@objc.python_method
def _NH_PGPPublicKeyReceived(self, stream, data):
if data.uri != self.remote_uri:
return
self.log_info("Public PGP key for %s was updated" % self.remote_uri)
self.load_remote_public_keys()
@objc.python_method
def _NH_BlinkContactsHaveChanged(self, sender, data):
self.bonjour_lookup_enabled = True
@objc.python_method
def _NH_ChatStreamOTREncryptionStateChanged(self, stream, data):
try:
if data.new_state is OTRState.Encrypted:
local_fingerprint = stream.encryption.key_fingerprint
remote_fingerprint = stream.encryption.peer_fingerprint
self.log_info("Chat encryption activated using OTR protocol")
self.log_info("OTR local fingerprint %s" % local_fingerprint)
self.log_info("OTR remote fingerprint %s" % remote_fingerprint)
self.chatViewController.showSystemMessage("OTR encryption enabled", ISOTimestamp.now())
elif data.new_state is OTRState.Finished:
self.log_info("OTR encryption has finished")
self.chatViewController.showSystemMessage("OTR encryption has finished", ISOTimestamp.now(), is_error=True)
elif data.new_state is OTRState.Plaintext:
self.log_info("OTR encryption has been deactivated")
self.chatViewController.showSystemMessage("OTR encryption has been deactivated", ISOTimestamp.now(), is_error=True)
except:
import traceback
traceback.print_exc()
@objc.python_method
def update_message_status(self, id, status, direction='outgoing'):
self.log_info("Message %s is %s" % (id, status))
self.history.update_message_status(id, status)
if direction == 'outgoing':
self.chatViewController.markMessage(id, status)
@objc.python_method
def add_to_history(self, message):
self.log_info('%s %s message with id %s saved with status %s' % (message.direction.title(), message.content_type, message.id, message.status))
# writes the record to the sql database
cpim_to = format_identity_to_string(message.recipient, format='full') if message.recipient else ''
cpim_from = format_identity_to_string(message.sender, format='full') if message.sender else ''
cpim_timestamp = str(message.timestamp)
remote_uri = self.instance_id if (self.account is BonjourAccount() and self.instance_id) else self.remote_uri
self.msg_id_list.add(message.id)
self.history.add_message(message.id, 'sms', self.local_uri, remote_uri, message.direction, cpim_from, cpim_to, cpim_timestamp, message.content.decode(), message.content_type, "0", message.status, call_id=message.call_id, encryption=message.encryption)
@objc.python_method
def sendIMDNNotification(self, message_id, event):
if not self.account.sms.enable_imdn:
return
notification = DisplayNotification('displayed') if event == 'displayed' else DeliveryNotification(event)
content = IMDNDocument.create(message_id=message_id, datetime=ISOTimestamp.now(), recipient_uri=self.target_uri, notification=notification)
#self.log_info('Composing IMDN %s for message %s' % (event, message_id))
self.sendMessage(content, IMDNDocument.content_type)
@objc.python_method
def sendMyPublicKey(self, force=False):
if self.public_key_sent and not force:
return
if not self.account.sms.enable_pgp:
return
if not self.account.sms.private_key or not self.private_key:
return
public_key_path = "%s/%s.pubkey" % (self.keys_path, self.account.id)
try:
public_key = open(public_key_path, 'rb').read()
except Exception as e:
BlinkLogger().log_info('Cannot import my own PGP public key: %s' % str(e))
else:
self.log_info('Send my public key')
self.sendMessage(public_key.decode(), 'text/pgp-public-key')
@objc.python_method
@run_in_gui_thread
def sendMessage(self, content, content_type="text/plain"):
# entry point for sending messages, they will be added to self.outgoing_queue
status = MSG_STATE_FAILED_LOCAL if self.paused else 'queued'
if host.default_ip:
if isinstance(content, OTRInternalMessage):
self.outgoing_queue.put(content)
return
else:
status = MSG_STATE_FAILED_LOCAL
timestamp = ISOTimestamp.now()
content = content.decode() if isinstance(content, bytes) else content
id = str(uuid.uuid4()) # use IMDN compatible id
if self.encryption.active:
encryption = 'verified' if self.encryption.verified else 'unverified'
elif self.pgp_encrypted:
encryption = 'verified'
else:
encryption = ''
recipient = ChatIdentity(self.target_uri, self.display_name)
mInfo = MessageInfo(id, sender=self.account, recipient=recipient, timestamp=timestamp, content_type=content_type, content=content, status=status, encryption=encryption)
if self.is_renderable(mInfo):
icon = NSApp.delegate().contactsWindowController.iconPathForSelf()
self.chatViewController.showMessage('', id, 'outgoing', None, icon, content, timestamp, state=status, media_type='sms', encryption=encryption)
self.add_to_history(mInfo)
self.messages[mInfo.id] = mInfo
if content_type in ('application/sylk-message-remove', 'application/sylk-conversation-read', 'application/sylk-conversation-remove'):
self.add_to_history(mInfo)
self.messages[mInfo.id] = mInfo
if mInfo.status != MSG_STATE_FAILED_LOCAL:
self.log_info('Adding outgoing %s %s message %s to the sending queue' % (id, status, content_type))
self.outgoing_queue.put(mInfo)
if host.default_ip and (not self.last_route or self.paused):
self.lookup_destination(self.target_uri)
@objc.python_method
def lookup_destination(self, uri):
if host is None or host.default_ip is None:
self.setRoutesFailed(NSLocalizedString("No Internet connection", "Label"))
return
if self.account is BonjourAccount():
if not self.bonjour_lookup_enabled:
return
blink_contact = NSApp.delegate().contactsWindowController.getBonjourContact(self.instance_id, str(uri))
if blink_contact:
uri = SIPURI.parse(str(blink_contact.uri))
route = Route(address=uri.host, port=uri.port, transport=uri.transport, tls_name=self.account.sip.tls_name or uri.host)
self.target_uri = uri
self.log_info('Found Bonjour neighbour %s with uri %s' % (self.instance_id, str(self.target_uri)))
self.setRoutesResolved([route])
else:
self.setRoutesFailed('Bonjour neighbour %s not found' % self.instance_id)
self.bonjour_lookup_enabled = False
return
else:
self.log_info("Lookup destination for %s" % uri)
self.lookup_dns(uri)
@objc.python_method
@run_in_green_thread
def lookup_dns(self, target_uri):
if self.dns_lookup_in_progress:
return
self.log_info("Lookup DNS for %s" % target_uri)
self.dns_lookup_in_progress = True
settings = SIPSimpleSettings()
lookup = DNSLookup()
self.notification_center.add_observer(self, sender=lookup)
tls_name = target_uri.host.decode()
if self.account is not BonjourAccount():
if self.account.id.domain == target_uri.host.decode():
tls_name = self.account.sip.tls_name or self.account.id.domain
elif "isfocus" in str(target_uri) and target_uri.host.decode().endswith(self.account.id.domain):
tls_name = self.account.conference.tls_name or self.account.sip.tls_name or self.account.id.domain
else:
if "isfocus" in str(target_uri) and self.account.conference.tls_name:
tls_name = self.account.conference.tls_name
if self.account.sip.outbound_proxy is not None:
proxy = self.account.sip.outbound_proxy
uri = SIPURI(host=proxy.host, port=proxy.port, parameters={'transport': proxy.transport})
tls_name = self.account.sip.tls_name or proxy.host
self.log_info("Starting DNS lookup for %s via proxy %s" % (target_uri.host.decode(), uri))
elif self.account.sip.always_use_my_proxy:
uri = SIPURI(host=self.account.id.domain)
tls_name = self.account.sip.tls_name or self.account.id.domain
self.log_info("Starting DNS lookup for %s via proxy of account %s" % (target_uri.host.decode(), self.account.id))
else:
uri = target_uri
self.log_info("Starting DNS lookup for %s" % target_uri.host.decode())
lookup.lookup_sip_proxy(uri, settings.sip.transport_list, tls_name=tls_name)
@objc.python_method
def _NH_DNSLookupDidFail(self, lookup, data):
self.dns_lookup_in_progress = False
self.notification_center.remove_observer(self, sender=lookup)
message = "DNS lookup for %s failed" % self.target_uri.host.decode()
self.log_info(message)
self.setRoutesFailed(message)
@objc.python_method
def _NH_DNSLookupDidSucceed(self, lookup, data):
self.dns_lookup_in_progress = False
self.notification_center.remove_observer(self, sender=lookup)
result_text = ', '.join(('%s:%s (%s)' % (result.address, result.port, result.transport.upper()) for result in data.result))
self.log_info("DNS lookup for %s succeeded: %s" % (self.target_uri.host.decode(), result_text))
self.setRoutesResolved(data.result)
@objc.python_method
@run_in_gui_thread
def setRoutesResolved(self, routes):
self.routes = routes
if self.routes[0] and self.routes[0] != self.last_route:
self.last_route = self.routes[0]
self.log_info('Using route %s' % self.last_route)
if not self.last_route:
return
self.start_queue()
if not self.is_replication_message:
self.sendMyPublicKey()
if not self.encryption.active and self.account.sms.enable_otr:
self.startEncryption()
@objc.python_method
def setRoutesFailed(self, reason):
self.log_info('Routing failed: %s' % reason)
self.last_route = None
self.stop_queue()
if self.last_failure_reason != reason:
#self.chatViewController.showSystemMessage(reason, ISOTimestamp.now(), True)
self.last_failure_reason = reason
for message in self.messages.values():
if message.content_type not in (IsComposingDocument.content_type, IMDNDocument.content_type):
self.update_message_status(message.id, MSG_STATE_FAILED_LOCAL)
@objc.python_method
def start_queue(self):
if self.started:
if self.paused:
self.outgoing_queue.unpause()
if len(self.outgoing_queue.queue.queue) > 0:
self.log_debug('Sendind queue resumed with %d messages' % len(self.outgoing_queue.queue.queue))
self.paused = False
else:
self.started = True
try:
self.outgoing_queue.start()
self.log_debug('Sending queue started')
except RuntimeError:
pass
@objc.python_method
def stop_queue(self):
if self.paused:
return
self.log_debug('Sending queue paused with %d messages' % len(self.outgoing_queue.queue.queue))
self.paused = True
self.outgoing_queue.pause()
# work around for the queue that still runs on next tick
self.outgoing_queue.put(None)
@objc.python_method
def not_read_queue_start(self):
if self.not_read_queue_started:
if self.not_read_queue_paused:
if len(self.not_read_queue.queue.queue):
self.log_debug('Display notifications queue resumed with %d pending messages' % len(self.not_read_queue.queue.queue))
else:
self.log_debug('Display notifications queue resumed')
self.not_read_queue.unpause()
self.not_read_queue_paused = False
else:
try:
self.not_read_queue.start()
self.not_read_queue_started = True
except RuntimeError as e:
pass
@objc.python_method
def not_read_queue_stop(self):
if len(self.not_read_queue.queue.queue):
self.log_debug('Display notifications queue paused with %d messages' % len(self.not_read_queue.queue.queue))
else:
self.log_debug('Display notifications queue paused')
self.not_read_queue_paused = True
self.not_read_queue.pause()
# work around for the queue that still runs on next tick
self.not_read_queue.put(None)
@objc.python_method
def is_renderable(self, message):
if isinstance(message, OTRInternalMessage):
return False
if message.content_type in (IsComposingDocument.content_type, IMDNDocument.content_type, 'text/pgp-public-key', 'text/pgp-private-key', 'application/sylk-api-pgp-key-lookup', 'application/sylk-api-message-remove', 'application/sylk-api-conversation-read', 'application/sylk-api-conversation-remove'):
return False
return True
@objc.python_method
def _send_message(self, message):
# called by event queue
if message is None:
return
if message.content_type == IsComposingDocument.content_type:
if ISOTimestamp.now() - message.timestamp > datetime.timedelta(seconds=30):
return
pgp_encrypted = False
if (not self.last_route):
reason = 'No routes found'
self.log_info("%s message %s for %s sent failed: %s" % (message.content_type, message.id, message.recipient, reason))
if self.is_renderable(message):
self.update_message_status(message.id, MSG_STATE_FAILED_LOCAL)
message.status = MSG_STATE_FAILED_LOCAL
message.pjsip_id = None
self.messages[message.id] = message
if self.last_failure_reason != reason:
if host.default_ip:
self.chatViewController.showSystemMessage(reason, ISOTimestamp.now(), True)
return
if self.is_renderable(message):
self.sent_readable_messages.add(message.id)
try:
content = self.encryption.otr_session.handle_output(message.content, message.content_type)
except OTRError as e:
if 'has ended the private conversation' in str(e):