-
Notifications
You must be signed in to change notification settings - Fork 7
/
Copy pathSMSWindowManager.py
1562 lines (1286 loc) · 65 KB
/
SMSWindowManager.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, NSPortraitOrientation, NSFitPagination, NSOffState, NSOnState, NSControlTextDidChangeNotification, NSEventTrackingRunLoopMode
from Foundation import (NSBundle,
NSImage,
NSLocalizedString,
NSNotFound,
NSRunLoop,
NSRunLoopCommonModes,
NSTimer,
NSObject,
NSColor,
NSPrintInfo,
NSTabViewItem,
NSNotificationCenter,
NSWindowController)
import datetime
import objc
import re
import hashlib
import uuid
import pgpy
import json
import socket
import string
import random
import urllib
from http.client import RemoteDisconnected
from Crypto.Protocol.KDF import PBKDF2
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 makedirs
from zope.interface import implementer
from resources import ApplicationData
from sipsimple.configuration import DuplicateIDError
from sipsimple.addressbook import AddressbookManager, Group
from sipsimple.account import AccountManager, BonjourAccount, Account
from sipsimple.core import SIPURI, Message, FromHeader, ToHeader, RouteHeader, Route
from sipsimple.lookup import DNSLookup, DNSLookupError
from sipsimple.configuration.settings import SIPSimpleSettings
from sipsimple.payloads.iscomposing import IsComposingMessage, IsComposingDocument
from sipsimple.payloads.imdn import IMDNDocument, DeliveryNotification, DisplayNotification
from sipsimple.streams.msrp.chat import CPIMPayload, CPIMParserError, ChatIdentity
from sipsimple.threading import run_in_thread
from sipsimple.threading.green import run_in_green_thread
from sipsimple.util import ISOTimestamp
from ChatViewController import MSG_STATE_SENT, MSG_STATE_DELIVERED, MSG_STATE_DISPLAYED, MSG_STATE_FAILED
from BlinkLogger import BlinkLogger
from HistoryManager import ChatHistory
from SMSViewController import SMSViewController
from util import format_identity_to_string, run_in_gui_thread
unpad = lambda s: s[:-ord(s[len(s) - 1:])]
@implementer(IObserver)
class SMSWindowController(NSWindowController):
tabView = objc.IBOutlet()
tabSwitcher = objc.IBOutlet()
toolbar = objc.IBOutlet()
encryptionMenu = objc.IBOutlet()
encryptionIconMenuItem = objc.IBOutlet()
heartbeat_timer = None
def initWithOwner_(self, owner):
self = objc.super(SMSWindowController, self).init()
if self:
self._owner = owner
NSBundle.loadNibNamed_owner_("SMSSession", self)
self.notification_center = NotificationCenter()
self.notification_center.add_observer(self, name="BlinkShouldTerminate")
self.notification_center.add_observer(self, name="ChatStreamOTREncryptionStateChanged")
self.notification_center.add_observer(self, name="OTREncryptionDidStop")
self.notification_center.add_observer(self, name="PGPEncryptionStateChanged")
self.notification_center.add_observer(self, name="PGPPublicKeyReceived")
self.unreadMessageCounts = {}
self.heartbeat_timer = NSTimer.timerWithTimeInterval_target_selector_userInfo_repeats_(10.0, self, "heartbeatTimer:", None, True)
NSRunLoop.currentRunLoop().addTimer_forMode_(self.heartbeat_timer, NSRunLoopCommonModes)
NSRunLoop.currentRunLoop().addTimer_forMode_(self.heartbeat_timer, NSEventTrackingRunLoopMode)
return self
def heartbeatTimer_(self, timer):
for viewer in self.viewers:
viewer.heartbeat()
@objc.python_method
def selectedSessionController(self):
activeTab = self.tabView.selectedTabViewItem()
if activeTab:
return activeTab.identifier()
return None
@property
def titleLong(self):
session = self.selectedSessionController()
if session:
display_name = session.display_name
sip_address = '%s@%s' % (session.target_uri.user.decode(), session.target_uri.host.decode())
if session.account is BonjourAccount():
title = NSLocalizedString("Short Messages with %s", "Window Title") % display_name
title = title + ' (Bonjour)'
else:
if display_name and display_name != sip_address:
title = NSLocalizedString("Short Messages with %s", "Window Title") % display_name + " <%s>" % format_identity_to_string(session.target_uri)
else:
title = NSLocalizedString("Short Messages with %s", "Window Title") % format_identity_to_string(session.target_uri)
else:
title = NSLocalizedString("Short Messages", "Window Title")
return title
@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 _NH_BlinkShouldTerminate(self, sender, data):
if self.window():
self.window().orderOut_(self)
@objc.python_method
def _NH_ChatStreamOTREncryptionStateChanged(self, sender, data):
self.updateEncryptionWidgets()
@objc.python_method
def _NH_PGPEncryptionStateChanged(self, sender, data):
self.updateEncryptionWidgets()
@objc.python_method
def _NH_PGPPublicKeyReceived(self, sender, data):
self.updateEncryptionWidgets()
@objc.python_method
def _NH_OTREncryptionDidStop(self, sender, data):
self.updateEncryptionWidgets()
def menuWillOpen_(self, menu):
pass
def noteNewMessageForSession_(self, session):
index = self.tabView.indexOfTabViewItemWithIdentifier_(session)
if index == NSNotFound:
return
tabItem = self.tabView.tabViewItemAtIndex_(index)
item = self.tabSwitcher.itemForTabViewItem_(tabItem)
if not item:
return
count = self.unreadMessageCounts.get(session, 0)
count = self.unreadMessageCounts[session] = count + 1
if self.tabView.selectedTabViewItem() == tabItem:
session = self.selectedSessionController()
if self.window().isKeyWindow():
item.setBadgeLabel_("")
del self.unreadMessageCounts[session]
session.not_read_queue_start()
else:
item.setBadgeLabel_(str(count))
else:
item.setBadgeLabel_(str(count))
session.not_read_queue_stop()
def noteNoMessageForSession_(self, session):
print('noteNoMessageForSession_')
index = self.tabView.indexOfTabViewItemWithIdentifier_(session)
if index == NSNotFound:
return
tabItem = self.tabView.tabViewItemAtIndex_(index)
item = self.tabSwitcher.itemForTabViewItem_(tabItem)
if not item:
return
item.setBadgeLabel_("")
try:
del self.unreadMessageCounts[session]
except KeyError:
pass
def noteView_isComposing_(self, smsview, flag):
index = self.tabView.indexOfTabViewItemWithIdentifier_(smsview)
if index == NSNotFound:
return
tabItem = self.tabView.tabViewItemAtIndex_(index)
item = self.tabSwitcher.itemForTabViewItem_(tabItem)
if item:
item.setComposing_(flag)
@objc.python_method
def addViewer(self, viewer, focusTab=False):
tabItem = NSTabViewItem.alloc().initWithIdentifier_(viewer)
tabItem.setView_(viewer.getContentView())
sip_address = '%s@%s' % (viewer.target_uri.user.decode(), viewer.target_uri.host.decode())
if viewer.display_name and viewer.display_name != sip_address:
tabItem.setLabel_("%s" % viewer.display_name)
else:
tabItem.setLabel_(format_identity_to_string(viewer.target_uri))
self.tabSwitcher.addTabViewItem_(tabItem)
if len(list(self.viewers)) == 1 or focusTab:
self.tabSwitcher.selectLastTabViewItem_(None)
self.window().makeFirstResponder_(viewer.chatViewController.inputText)
def removeViewer_(self, viewer):
i = self.tabView.indexOfTabViewItemWithIdentifier_(viewer)
if i != NSNotFound:
item = self.tabView.tabViewItemAtIndex_(i)
self.tabSwitcher.removeTabViewItem_(item)
@property
def viewers(self):
return (item.identifier() for item in self.tabView.tabViewItems())
def close_(self, sender):
selected = self.selectedSessionController()
if selected in self.unreadMessageCounts:
del self.unreadMessageCounts[selected]
self.heartbeat_timer.invalidate()
self.heartbeat_timer = None
self.tabSwitcher.removeTabViewItem_(self.tabView.selectedTabViewItem())
if self.tabView.numberOfTabViewItems() == 0:
self.window().performClose_(None)
def tabView_shouldCloseTabViewItem_(self, sender, item):
if item.identifier() in self.unreadMessageCounts:
del self.unreadMessageCounts[item.identifier()]
return True
def tabView_didSelectTabViewItem_(self, sender, item):
self.window().setTitle_(self.titleLong)
session = self.selectedSessionController()
self.updateEncryptionWidgets(session)
for viewer in self.viewers:
if viewer != session:
viewer.not_read_queue_stop()
else:
if self.window().isKeyWindow():
_item = self.tabSwitcher.itemForTabViewItem_(item)
_item.setBadgeLabel_("")
viewer.send_read_messages_notifications()
viewer.not_read_queue_start()
try:
del self.unreadMessageCounts[item.identifier()]
except KeyError:
pass
else:
self.noteNewMessageForSession_(item.identifier())
def tabViewDidChangeNumberOfTabViewItems_(self, tabView):
if tabView.numberOfTabViewItems() == 0:
self.window().performClose_(None)
def tabView_didDettachTabViewItem_atPosition_(self, tabView, item, pos):
if tabView.numberOfTabViewItems() > 1:
session = item.identifier()
window = SMSWindowManager().dettachSMSViewer(session)
if window:
window.window().setFrameOrigin_(pos)
def windowShouldClose_(self, sender):
for item in self.tabView.tabViewItems().copy():
self.tabSwitcher.removeTabViewItem_(item)
if self in SMSWindowManager().windows:
SMSWindowManager().windows.remove(self)
self.notification_center.remove_observer(self, name="BlinkShouldTerminate")
return True
def windowDidResignKey_(self, notification):
session = self.selectedSessionController()
if session:
session.not_read_queue_stop()
def windowDidBecomeKey_(self, notification):
session = self.selectedSessionController()
if session:
session.not_read_queue_start()
tabItem = self.tabView.selectedTabViewItem()
if tabItem.identifier() in self.unreadMessageCounts:
del self.unreadMessageCounts[tabItem.identifier()]
item = self.tabSwitcher.itemForTabViewItem_(tabItem)
item.setBadgeLabel_("")
@objc.IBAction
def requestPublicKey_(self, sender):
session = self.selectedSessionController()
if session:
session.requestPublicKey()
@objc.IBAction
def sendMyPublicKey_(self, sender):
session = self.selectedSessionController()
if session:
session.sendMyPublicKey(force=True)
@objc.IBAction
def toolbarButtonClicked_(self, sender):
session = self.selectedSessionController()
contactWindow = self._owner._owner
if sender.itemIdentifier() == 'audio':
contactWindow.startSessionWithTarget(format_identity_to_string(session.target_uri))
elif sender.itemIdentifier() == 'video':
contactWindow.startSessionWithTarget(format_identity_to_string(session.target_uri), media_type="video")
elif sender.itemIdentifier() == 'smileys':
chatViewController = self.selectedSessionController().chatViewController
chatViewController.expandSmileys = not chatViewController.expandSmileys
sender.setImage_(NSImage.imageNamed_("smiley_on" if chatViewController.expandSmileys else "smiley_off"))
chatViewController.toggleSmileys(chatViewController.expandSmileys)
elif sender.itemIdentifier() == 'history' and NSApp.delegate().history_enabled:
contactWindow.showHistoryViewer_(None)
contactWindow.historyViewer.filterByURIs((format_identity_to_string(session.target_uri),))
@objc.IBAction
def userClickedEncryptionMenu_(self, sender):
# dispatch the click to the active session
session = self.selectedSessionController()
if session:
session.userClickedEncryptionMenu_(sender)
def menuWillOpen_(self, menu):
if menu == self.encryptionMenu:
settings = SIPSimpleSettings()
item = menu.itemWithTag_(1)
item.setHidden_(not settings.chat.enable_encryption)
item = menu.itemWithTag_(2)
item.setEnabled_(False)
item.setState_(NSOffState)
item = menu.itemWithTag_(4)
item.setHidden_(True)
item = menu.itemWithTag_(5)
item.setHidden_(True)
item = menu.itemWithTag_(6)
item.setHidden_(True)
item = menu.itemWithTag_(8)
item.setHidden_(True)
item = menu.itemWithTag_(9)
item.setEnabled_(False)
item.setHidden_(True)
item = menu.itemWithTag_(10)
item.setHidden_(True)
selectedSession = self.selectedSessionController()
if selectedSession:
chat_stream = selectedSession.encryption
display_name = selectedSession.display_name
item = menu.itemWithTag_(1)
if settings.chat.enable_encryption:
item.setHidden_(False)
item.setEnabled_(True)
item.setTitle_(NSLocalizedString("Activate OTR encryption for this session", "Menu item") if not chat_stream.active else NSLocalizedString("Deactivate OTR encryption for this session", "Menu item"))
item = menu.itemWithTag_(11)
item.setHidden_('@' not in selectedSession.remote_uri or selectedSession.account is BonjourAccount())
# item.setRepresentedObject_({'account': selectedSession.account, 'recipient': selectedSession.remote_uri})
item = menu.itemWithTag_(2)
item.setHidden_(False)
if chat_stream.active:
item.setTitle_(NSLocalizedString("My fingerprint is %s", "Menu item") % str(chat_stream.key_fingerprint))
else:
item.setEnabled_(False)
item.setTitle_(NSLocalizedString("OTR encryption is disabled in Chat preferences", "Menu item"))
if settings.chat.enable_encryption:
if chat_stream.peer_fingerprint:
item = menu.itemWithTag_(4)
item.setHidden_(False)
item.setEnabled_(False)
_t = NSLocalizedString("%s's fingerprint is ", "Menu item") % display_name
item.setTitle_( "%s %s" % (_t, chat_stream.peer_fingerprint))
item = menu.itemWithTag_(5)
item.setHidden_(False)
item.setState_(NSOnState if chat_stream.verified else NSOffState)
item = menu.itemWithTag_(6)
item.setEnabled_(True)
item.setHidden_(False)
item.setTitle_(NSLocalizedString("Validate the identity of %s" % display_name, "Menu item"))
if selectedSession.pgp_encrypted:
item = menu.itemWithTag_(8)
item.setHidden_(False)
item = menu.itemWithTag_(9)
item.setEnabled_(True)
item.setHidden_(False)
item = menu.itemWithTag_(10)
item.setHidden_(False)
@objc.python_method
def updateEncryptionWidgets(self, selectedSession=None):
if selectedSession is None:
selectedSession = self.selectedSessionController()
if selectedSession and selectedSession.started:
if selectedSession.encryption.active:
if selectedSession.encryption.verified:
self.encryptionIconMenuItem.setImage_(NSImage.imageNamed_("locked-green"))
else:
self.encryptionIconMenuItem.setImage_(NSImage.imageNamed_("locked-red"))
elif selectedSession.pgp_encrypted:
self.encryptionIconMenuItem.setImage_(NSImage.imageNamed_("locked-green"))
else:
self.encryptionIconMenuItem.setImage_(NSImage.imageNamed_("unlocked-darkgray"))
elif selectedSession and selectedSession.pgp_encrypted:
self.encryptionIconMenuItem.setImage_(NSImage.imageNamed_("locked-green"))
else:
self.encryptionIconMenuItem.setImage_(NSImage.imageNamed_("unlocked-darkgray"))
@objc.IBAction
def printDocument_(self, sender):
printInfo = NSPrintInfo.sharedPrintInfo()
printInfo.setTopMargin_(30)
printInfo.setBottomMargin_(30)
printInfo.setLeftMargin_(10)
printInfo.setRightMargin_(10)
printInfo.setOrientation_(NSPortraitOrientation)
printInfo.setHorizontallyCentered_(True)
printInfo.setVerticallyCentered_(False)
printInfo.setHorizontalPagination_(NSFitPagination)
printInfo.setVerticalPagination_(NSFitPagination)
NSPrintInfo.setSharedPrintInfo_(printInfo)
# print the content of the web view
print_view = self.selectedSessionController().chatViewController.outputView
print_view.mainFrame().frameView().documentView().print_(self)
SMSWindowManagerInstance = None
def SMSWindowManager():
global SMSWindowManagerInstance
if SMSWindowManagerInstance is None:
SMSWindowManagerInstance = SMSWindowManagerClass.alloc().init()
return SMSWindowManagerInstance
@implementer(IObserver)
class SMSWindowManagerClass(NSObject):
#__metaclass__ = Singleton
windows = []
received_call_ids = set()
import_key_window = None
export_key_window = None
syncConversationsInProgress = {}
pendingSaveMessage = {}
new_contacts = set()
private_keys = {}
def init(self):
self = objc.super(SMSWindowManagerClass, self).init()
if self:
self.notification_center = NotificationCenter()
self.notification_center.add_observer(self, name="SIPEngineGotMessage")
self.notification_center.add_observer(self, name="SIPAccountDidActivate")
self.notification_center.add_observer(self, name="CFGSettingsObjectDidChange")
self.notification_center.add_observer(self, name="SIPAccountRegistrationDidSucceed")
self.notification_center.add_observer(self, name="MessageSaved")
self.keys_path = ApplicationData.get('keys')
makedirs(self.keys_path)
self.history = ChatHistory()
self.contacts_queue = EventQueue(self.handle_contacts_queue)
self.contacts_queue.start()
return self
@objc.python_method
def _NH_CFGSettingsObjectDidChange(self, account, data):
if isinstance(account, Account):
if 'sms.history_token' in data.modified:
if account.sms.history_token:
BlinkLogger().log_info("Sync token for account %s has been updated" % account.id)
self.syncConversations(account)
else:
BlinkLogger().log_info("Sync token for account %s has been removed" % account.id)
account.sms.history_last_id = None
account.sms.enable_replication = False
account.save()
if 'sms.history_url' in data.modified:
if account.sms.history_url:
BlinkLogger().log_info("Sync url for account %s has been updated: %s" % (account.id, account.sms.history_url))
else:
account.sms.history_last_id = None
account.sms.history_token = None
account.sms.enable_replication = False
account.save()
if 'sms.enable_replication' in data.modified:
if account.sms.enable_replication:
self.requestSyncToken(account)
@objc.python_method
def _NH_SIPAccountDidActivate(self, account, data):
pass
#BlinkLogger().log_info("Account %s activated" % account.id)
@objc.python_method
def _NH_MessageSaved(self, sender, data):
try:
del self.pendingSaveMessage[data.msgid]
except KeyError:
pass
remaining_messages = len(self.pendingSaveMessage.keys())
if remaining_messages > 1000:
remaining = 1000
elif remaining_messages > 100:
remaining = 100
else:
remaining = 10
if remaining_messages % remaining == 0:
if remaining_messages == 0:
pass
#BlinkLogger().log_info('Sync conversations completed')
else:
BlinkLogger().log_info('%d pending history messages' % remaining_messages)
@objc.python_method
def _NH_SIPAccountRegistrationDidSucceed(self, account, data):
if account is not BonjourAccount():
self.syncConversations(account)
@objc.python_method
def requestSyncToken(self, account):
if not account.sms.enable_replication:
BlinkLogger().log_info('Sync conversations is disabled for account %s' % account.id)
return
self.sendMessage(account, 'I need a token', 'application/sylk-api-token')
@objc.python_method
@run_in_green_thread
def sendMessage(self, account, content, content_type, recipient=None):
if account.sip.outbound_proxy is not None:
proxy = account.sip.outbound_proxy
uri = SIPURI(host=proxy.host, port=proxy.port, parameters={'transport': proxy.transport})
tls_name = account.sip.tls_name or proxy.host
BlinkLogger().log_info("Starting DNS lookup via proxy %s" % uri)
elif account.sip.always_use_my_proxy:
uri = SIPURI(host=account.id.domain)
tls_name = account.sip.tls_name or account.id.domain
BlinkLogger().log_info("Starting DNS lookup via proxy of account %s" % account.id)
else:
uri = SIPURI.parse('sip:%s' % account.id)
settings = SIPSimpleSettings()
lookup = DNSLookup()
try:
routes = lookup.lookup_sip_proxy(uri, settings.sip.transport_list).wait()
except DNSLookupError as e:
BlinkLogger().log_info('DNS Lookup error for token request: %s' % str(e))
else:
if not routes:
BlinkLogger().log_info('DNS Lookup failed for token request, no routes found')
return
route = routes[0]
BlinkLogger().log_info('Sending %s message to %s' % (content_type, route.uri))
from_uri = SIPURI.parse('sip:%s' % account.id)
if recipient:
to_uri = SIPURI.parse('sip:%s' % recipient)
else:
to_uri = SIPURI.parse('sip:%s' % account.id)
message_request = Message(FromHeader(from_uri), ToHeader(to_uri), RouteHeader(route.uri), content_type, content.encode(), credentials=account.credentials)
message_request.send()
@objc.python_method
@run_in_thread('contact_sync')
def handle_contacts_queue(self, payload):
content = payload['data']
account = payload['account']
if content.startswith('-----BEGIN PGP MESSAGE-----') and content.endswith('-----END PGP MESSAGE-----'):
try:
private_key = self.private_keys[account]
except KeyError:
private_key_path = "%s/%s.privkey" % (self.keys_path, account)
try:
private_key, _ = pgpy.PGPKey.from_file(private_key_path)
except Exception as e:
BlinkLogger().log_error('Cannot import PGP private key from %s: %s' % (private_key_path, str(e)))
return
else:
BlinkLogger().log_info('PGP private key imported from %s' % private_key_path)
self.private_keys[account] = private_key
if private_key:
try:
pgpMessage = pgpy.PGPMessage.from_blob(content.strip())
decrypted_message = private_key.decrypt(pgpMessage)
except (pgpy.errors.PGPDecryptionError, pgpy.errors.PGPError) as e:
BlinkLogger().log_info('PGP decryption failed for contact update')
return
else:
content = bytes(decrypted_message.message, 'latin1').decode()
try:
contact_data = json.loads(content)
uri = contact_data['uri']
try:
display_name = contact_data['name']
except KeyError:
display_name = uri
organization = contact_data['organization']
self.saveContact(uri, {'name': display_name or uri, 'organization': organization})
except (TypeError, KeyError, json.decoder.JSONDecodeError):
BlinkLogger().log_error('Failed to update contact %s: %s' % (content, str(e)))
@objc.python_method
@run_in_thread('sms_sync')
def syncConversations(self, account):
if not account.sms.enable_replication:
BlinkLogger().log_info('Sync conversations is disabled for account %s' % account.id)
return
if not account.sms.history_token:
BlinkLogger().log_info('Sync conversations token is missing for account %s' % account.id)
self.requestSyncToken(account)
return
if not account.sms.history_url:
BlinkLogger().log_info('Sync conversations url is missing for account %s' % account.id)
return
try:
self.syncConversationsInProgress[account.id]
except KeyError:
self.syncConversationsInProgress[account.id] = True
else:
return
sync_contacts = set()
url = account.sms.history_url.replace("@", "%40")
last_id = account.sms.history_last_id
if last_id:
url = "%s/%s" % (url, account.sms.history_last_id)
BlinkLogger().log_info('Sync conversations from %s' % url)
req = urllib.request.Request(url, method="GET")
req.add_header('Authorization', 'Apikey %s' % account.sms.history_token)
try:
raw_response = urllib.request.urlopen(req, timeout=20)
except (urllib.error.URLError) as e:
BlinkLogger().log_info('SylkServer connection error for %s: %s' % (url, e.code))
try:
del self.syncConversationsInProgress[account.id]
except KeyError:
pass
if e.code == 401:
# request new token on 401
self.requestSyncToken(account)
return
except (TimeoutError, socket.timeout, RemoteDisconnected, urllib.error.HTTPError) as e:
BlinkLogger().log_info('SylkServer connection error for %s: %s' % (url, str(e)))
try:
del self.syncConversationsInProgress[account.id]
except KeyError:
pass
return
else:
try:
raw_data = raw_response.read().decode().replace('\\/', '/')
except Exception as e:
BlinkLogger().log_debug('SylkServer API read error for %s: %s' % (url, str(e)))
try:
del self.syncConversationsInProgress[account.id]
except KeyError:
pass
return
try:
json_data = json.loads(raw_data)
except (TypeError, json.decoder.JSONDecodeError):
BlinkLogger().log_debug('Error parsing SylkServer response: %s' % str(e))
return
else:
last_message_id = None
BlinkLogger().log_debug('Sync %d message journal entries for %s (%d bytes)' % (len(json_data['messages']), account.id, len(raw_data)))
i = 0
self.contacts_queue.pause()
for msg in json_data['messages']:
#BlinkLogger().log_info('Process journal %d: %s' % (i, msg['timestamp']))
i = i + 1
try:
content_type = msg['content_type']
last_message_id = msg['message_id']
if content_type == 'application/sylk-conversation-remove':
BlinkLogger().log_info('Remove conversation with %s' % msg['content'])
self.history.delete_messages(local_uri=str(account.id), remote_uri=msg['content'])
self.history.delete_messages(local_uri=msg['content'], remote_uri=str(account.id))
elif content_type == 'application/sylk-message-remove':
BlinkLogger().log_info('Remove message %s with %s' % (msg['message_id'], msg['contact']))
self.history.delete_message(msg['message_id']);
elif content_type == 'message/imdn':
payload = eval(msg['content'])
imdn_status = payload['state']
imdn_message_id = payload['message_id']
status = None
if imdn_status == 'delivered':
status = MSG_STATE_DELIVERED
elif imdn_status == 'displayed':
status = MSG_STATE_DISPLAYED
elif imdn_status == 'failed':
status = MSG_STATE_FAILED
if status:
#BlinkLogger().log_info('Sync IMDN state %s for message %s' % (status, imdn_message_id))
self.pendingSaveMessage[imdn_message_id] = True
self.history.update_message_status(imdn_message_id, status)
elif content_type == 'application/sylk-contact-update':
self.contacts_queue.put({'account': str(account.id), 'data': msg['content']})
elif content_type == 'text/pgp-public-key':
uri = msg['contact']
BlinkLogger().log_info(u"Public key from %s received" % (uri))
content = msg['content'].encode()
if AccountManager().has_account(uri):
BlinkLogger().log_debug(u"Public key save skipped for own accounts")
continue
public_key = ''
start_public = False
for l in content.decode().split("\n"):
if l == "-----BEGIN PGP PUBLIC KEY BLOCK-----":
start_public = True
if l == "-----END PGP PUBLIC KEY BLOCK-----":
public_key = public_key + l + '\n'
start_public = False
break
if start_public:
public_key = public_key + l + '\n'
if public_key:
public_key_checksum = hashlib.sha1(public_key.encode()).hexdigest()
key_file = "%s/%s.pubkey" % (self.keys_path, uri)
fd = open(key_file, "wb+")
fd.write(public_key.encode())
fd.close()
#BlinkLogger().log_info(u"Public key for %s was saved to %s" % (uri, key_file))
nc_title = NSLocalizedString("Public key", "System notification title")
nc_subtitle = format_identity_to_string(sender_identity, check_contact=True, format='full')
nc_body = NSLocalizedString("Public key received", "System notification title")
#NSApp.delegate().gui_notify(nc_title, nc_body, nc_subtitle)
self.notification_center.post_notification('PGPPublicKeyReceived', sender=account, data=NotificationData(uri=uri, key=public_key))
self.saveContact(uri, {'public_key': key_file, 'public_key_checksum': public_key_checksum})
else:
BlinkLogger().log_info(u"No public key detected in the payload")
elif content_type.startswith('text/'):
if msg['direction'] == 'incoming':
sync_contacts.add(msg['contact'])
self.syncIncomingMessage(account, msg, account.sms.history_last_id)
elif msg['direction'] == 'outgoing':
sync_contacts.add(msg['contact'])
self.syncOutgoingMessage(account, msg, account.sms.history_last_id)
else:
pass
#BlinkLogger().log_error("Unknown sync message type %s" % content_type)
except Exception as e:
BlinkLogger().log_error('Failed to sync message %s' % msg)
import traceback
traceback.print_exc()
try:
del self.syncConversationsInProgress[account.id]
except KeyError:
pass
if last_message_id:
account.sms.history_last_id = last_message_id
BlinkLogger().log_info('Sync done till %s' % last_message_id)
account.save()
for uri in sync_contacts:
self.saveContact(uri)
for window in self.windows:
for viewer in window.viewers:
if viewer.remote_uri == uri and account == viewer.account:
BlinkLogger().log_info('Refresh viewer for %s' % uri)
viewer.scroll_back_in_time()
self.addContactsToMessagesGroup()
self.contacts_queue.unpause()
@objc.python_method
def saveContact(self, uri, data={}):
if self.illegal_uri(uri):
return
contact = self.getContact(uri)
if contact is not None:
attrs = ('public_key', 'public_key_checksum', 'name', 'organization')
for a in attrs:
try:
value = data[a]
except KeyError:
pass
else:
setattr(contact, a, value)
contact.save()
else:
BlinkLogger().log_info("No contact found to save the public key for %s" % uri)
@objc.python_method
def illegal_uri(self, uri):
if '@videoconference.' in uri:
return True
if '@guest.' in uri:
return True
try:
SIPURI.parse('sip:%s' % uri)
except:
return True
return False
@objc.python_method
def getContact(self, uri, addGroup=False):
if self.illegal_uri(uri):
return None
blink_contact = NSApp.delegate().contactsWindowController.getFirstContactMatchingURI(uri)
if not blink_contact:
BlinkLogger().log_info('Adding contact for %s' % uri)
contact = NSApp.delegate().contactsWindowController.model.addContactForUri(uri)
self.new_contacts.add(contact)
else:
contact = blink_contact.contact
if addGroup:
self.addContactsToMessagesGroup()
return contact
@objc.python_method
def addContactsToMessagesGroup(self):
if len(self.new_contacts) == 0:
return
group_id = '_messages'
try:
group = next((group for group in AddressbookManager().get_groups() if group.id == group_id))
except StopIteration:
try:
group = Group(id=group_id)
except DuplicateIDError as e:
return
else:
group.name = 'Messages'
group.position = 0
group.expanded = True
for contact in self.new_contacts:
group.contacts.add(contact)
group.save()
self.new_contacts = set()
@objc.python_method
@run_in_gui_thread
def syncIncomingMessage(self, account, msg, last_id=None):
direction = 'incoming'
self.pendingSaveMessage[msg['message_id']] = True
if 'display' not in msg['disposition']:
status = MSG_STATE_DISPLAYED
else:
status = MSG_STATE_DELIVERED
if msg['content'].startswith('-----BEGIN PGP MESSAGE-----') and msg['content'].endswith('-----END PGP MESSAGE-----'):
encryption = 'pgp_encrypted'
else:
encryption = ''
if not last_id:
self.history.add_message(msg['message_id'],
'sms',
str(account.id),
msg['contact'],
direction,
msg['contact'],
str(account.id),
msg['timestamp'],
msg['content'],
msg['content_type'],
"0",
status,
call_id=msg['message_id'],
encryption=encryption)
return
BlinkLogger().log_info('Sync %s %s message %s with %s' % (msg['direction'], status, msg['message_id'], msg['contact']))
# only open windows for messages newer than one week
create_if_needed = ISOTimestamp.now() - ISOTimestamp(msg['timestamp']) < datetime.timedelta(days=7)
sender_uri = SIPURI.parse(str('sip:%s' % msg['contact']))
viewer = self.getWindow(sender_uri, msg['contact'], account, create_if_needed=create_if_needed, note_new_message=bool(last_id), is_replication_message=False)
sender_identity = ChatIdentity(sender_uri, viewer.display_name)
if status != MSG_STATE_DISPLAYED and create_if_needed:
self.windowForViewer(viewer).noteNewMessageForSession_(viewer)
window = self.windowForViewer(viewer).window()
viewer.gotMessage(sender_identity, msg['message_id'], msg['message_id'], direction, msg['content'].encode(), msg['content_type'], is_replication_message=False, window=window, cpim_imdn_events=msg['disposition'], imdn_timestamp=msg['timestamp'], account=account, from_journal=True, status=status)
if create_if_needed:
self.windowForViewer(viewer).noteView_isComposing_(viewer, False)
@objc.python_method
@run_in_gui_thread
def syncOutgoingMessage(self, account, msg, last_id=None):
direction = 'outgoing'
self.pendingSaveMessage[msg['message_id']] = True
if not last_id:
state = MSG_STATE_SENT
if msg['state'] == 'delivered':
state = MSG_STATE_DELIVERED
elif msg['state'] == 'displayed':
state = MSG_STATE_DISPLAYED
elif msg['state'] == 'failed':
state = MSG_STATE_FAILED
if msg['content'].startswith('-----BEGIN PGP MESSAGE-----') and msg['content'].endswith('-----END PGP MESSAGE-----'):
encryption = 'pgp_encrypted'
else:
encryption = ''
self.history.add_message(msg['message_id'],
'sms',
str(account.id),
msg['contact'],
direction,
str(account.id),
msg['contact'],
msg['timestamp'],
msg['content'],
msg['content_type'],