-
Notifications
You must be signed in to change notification settings - Fork 7
/
ContactWindowController.py
6386 lines (5433 loc) · 302 KB
/
ContactWindowController.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 (NSAccessibilityUnignoredDescendant,
NSAccessibilityDescriptionAttribute,
NSAccessibilityChildrenAttribute,
NSAccessibilityRoleDescriptionAttribute,
NSAlertAlternateReturn,
NSAlertDefaultReturn,
NSApp,
NSCompositeSourceOver,
NSDragOperationMove,
NSDragOperationCopy,
NSDragOperationNone,
NSDragOperationAll,
NSFilenamesPboardType,
NSFloatingWindowLevel,
NSFontAttributeName,
NSForegroundColorAttributeName,
NSGetInformationalAlertPanel,
NSKeyDown,
NSLeftMouseUp,
NSLineBreakByTruncatingTail,
NSModalPanelRunLoopMode,
NSNormalWindowLevel,
NSOnState,
NSOffState,
NSRightMouseUp,
NSOutlineViewSelectionDidChangeNotification,
NSParagraphStyleAttributeName,
NSPNGFileType,
NSReleaseAlertPanel,
NSRunAlertPanel,
NSRunContinuesResponse,
NSStringPboardType,
NSSplitViewDidResizeSubviewsNotification,
NSTableViewSelectionDidChangeNotification,
NSTableViewDropAbove,
NSVariableStatusItemLength,
NSStatusBar)
from Foundation import (NSArray,
NSAttributedString,
NSBezierPath,
NSBitmapImageRep,
NSColor,
NSDate,
NSDefaultRunLoopMode,
NSDictionary,
NSEvent,
NSFont,
NSGraphicsContext,
NSHeight,
NSImage,
NSImageView,
NSIndexSet,
NSMakeSize,
NSMenu,
NSMenuItem,
NSMinY,
NSMutableAttributedString,
NSMakeRange,
NSMakeRect,
NSNotFound,
NSNotificationCenter,
NSParagraphStyle,
NSPasteboard,
NSRunLoop,
NSSpeechSynthesizer,
NSString,
NSLocalizedString,
NSTimer,
NSURL,
NSUserDefaults,
NSWindowController,
NSWorkspace,
NSZeroRect)
import objc
import pickle
import datetime
import hashlib
import os
import re
import random
import ldap
import shutil
import string
import sys
import uuid
import time
from collections import deque
from dateutil.tz import tzlocal
from itertools import chain
from application.notification import NotificationCenter, IObserver, NotificationData
from application.python import Null
from application.system import unlink, makedirs, host
from sipsimple.account import AccountManager, Account, BonjourAccount
from sipsimple.addressbook import AddressbookManager, ContactURI, Policy, unique_id
from sipsimple.application import SIPApplication
from sipsimple.audio import AudioConference, WavePlayer
from sipsimple.configuration.settings import SIPSimpleSettings
from sipsimple.core import SIPURI, SIPCoreError
from sipsimple.util import ISOTimestamp
from sipsimple.threading import run_in_thread
from sipsimple.threading.green import run_in_green_thread
from operator import attrgetter
from twisted.internet import reactor, task
from zope.interface import implementer
from LaunchServices import LSFindApplicationForInfo, kLSUnknownCreator
import ContactOutlineView # this is used from the UI
import ListView # this is used from the UI
import SMSWindowManager
from AccountSettings import AccountSettings
from AlertPanel import AlertPanel
from AudioSession import AudioSession
from BlockedContact import BlockedContact
from BlinkLogger import BlinkLogger
from HistoryManager import SessionHistory
from HistoryViewer import HistoryViewer
from ContactCell import ContactCell # this is used from the UI
from ContactListModel import presence_status_for_contact, BlinkContact, BlinkBlockedPresenceContact, BonjourBlinkContact, BlinkConferenceContact, BlinkPresenceContact, BlinkGroup, AllContactsBlinkGroupBlinkPresenceContact
from ContactListModel import BlinkPendingWatcher, LdapSearchResultContact, HistoryBlinkContact, VoicemailBlinkContact, SearchResultContact, SystemAddressBookBlinkContact, Avatar
from ContactListModel import DefaultUserAvatar, DefaultMultiUserAvatar, ICON_SIZE, HistoryBlinkGroup, MissedCallsBlinkGroup, IncomingCallsBlinkGroup, OutgoingCallsBlinkGroup, OnlineGroup
from MediaStream import STREAM_CONNECTED, STREAM_RINGING, STREAM_PROPOSING
from EnrollmentController import EnrollmentController
from FileTransferWindowController import openFileTransferSelectionDialog, FileTransferWindowController
from ConferenceController import random_room, default_conference_server, JoinConferenceWindowController, AddParticipantsWindowController
from PresenceInfoController import PresenceInfoController
from SessionController import SessionControllersManager
from SIPManager import MWIData
from PhotoPicker import PhotoPicker
from PresencePublisher import PresencePublisher, PresenceActivityList, on_the_phone_activity
from OfflineNoteController import OfflineNoteController
from MyVideoWindowController import MyVideoWindowController
from configuration.datatypes import UserIcon
from resources import ApplicationData, Resources
from util import allocate_autorelease_pool, format_date, format_identity_to_string, format_uri_type, is_anonymous, is_sip_aor_format, normalize_sip_uri_for_outgoing_session
from util import run_in_gui_thread, sip_prefix_pattern, sipuri_components_from_string, translate_alpha2digit, AccountInfo, utc_to_local
PARTICIPANTS_MENU_ADD_CONFERENCE_CONTACT = 314
PARTICIPANTS_MENU_ADD_CONTACT = 301
PARTICIPANTS_MENU_REMOVE_FROM_CONFERENCE = 310
PARTICIPANTS_MENU_MUTE = 315
PARTICIPANTS_MENU_INVITE_TO_CONFERENCE = 312
PARTICIPANTS_MENU_GOTO_CONFERENCE_WEBSITE = 313
PARTICIPANTS_MENU_START_AUDIO_SESSION = 320
PARTICIPANTS_MENU_START_CHAT_SESSION = 321
PARTICIPANTS_MENU_START_VIDEO_SESSION = 322
PARTICIPANTS_MENU_SEND_FILES = 323
normal_font_color = NSDictionary.dictionaryWithObjectsAndKeys_(NSFont.systemFontOfSize_(NSFont.systemFontSize()), NSFontAttributeName)
gray_font_color = NSDictionary.dictionaryWithObjectsAndKeys_(NSFont.systemFontOfSize_(10), NSFontAttributeName, NSColor.grayColor(), NSForegroundColorAttributeName)
red_font_color = NSDictionary.dictionaryWithObjectsAndKeys_(NSFont.systemFontOfSize_(10), NSFontAttributeName, NSColor.redColor(), NSForegroundColorAttributeName)
mini_blue = NSDictionary.dictionaryWithObjectsAndKeys_(NSFont.systemFontOfSize_(10), NSFontAttributeName, NSColor.alternateSelectedControlColor(), NSForegroundColorAttributeName)
session_status_localized = {
'missed': NSLocalizedString("missed", "Label"),
'completed': NSLocalizedString("completed", "Label"),
'failed': NSLocalizedString("failed", "Label"),
'cancelled': NSLocalizedString("cancelled", "Label")
}
class PhotoView(NSImageView):
entered = False
callback = None
def mouseDown_(self, event):
self.callback(self)
def mouseEntered_(self, event):
self.entered = True
self.setNeedsDisplay_(True)
def mouseExited_(self, event):
self.entered = False
self.setNeedsDisplay_(True)
def updateTrackingAreas(self):
rect = NSZeroRect
rect.size = self.frame().size
self.addTrackingRect_owner_userData_assumeInside_(rect, self, None, False)
def drawRect_(self, rect):
NSColor.whiteColor().set()
path = NSBezierPath.bezierPathWithRoundedRect_xRadius_yRadius_(rect, 5.0, 5.0)
path.fill()
if self.image():
NSGraphicsContext.saveGraphicsState()
path.addClip()
frect = NSZeroRect
frect.size = self.image().size()
self.image().drawInRect_fromRect_operation_fraction_(rect, frect, NSCompositeSourceOver, 1.0)
NSGraphicsContext.restoreGraphicsState()
NSColor.blackColor().colorWithAlphaComponent_(0.5).set()
if self.entered:
path.fill()
@implementer(IObserver)
class ContactWindowController(NSWindowController):
accounts = []
model = objc.IBOutlet()
backend = None
loggerModel = None
participants = []
searchResultsModel = objc.IBOutlet()
fileTransfersWindow = None
loaded = False
collapsedState = False
originalSize = None
originalWindowPosition = None
accountSettingsPanels = {}
authFailPopupShown = False
alertPanel = None
presenceActivityBeforeOnThePhone = None
disbandingConference = False
toolTipView = objc.IBOutlet()
contactsScrollView = objc.IBOutlet()
drawer = objc.IBOutlet()
mainTabView = objc.IBOutlet()
drawerSplitView = objc.IBOutlet()
dialPadView = objc.IBOutlet()
participantsView = objc.IBOutlet()
participantsTableView = objc.IBOutlet()
participantMenu = objc.IBOutlet()
sessionsView = objc.IBOutlet()
audioSessionsListView = objc.IBOutlet()
drawerSplitterPosition = None
searchBox = objc.IBOutlet()
accountPopUp = objc.IBOutlet()
contactOutline = objc.IBOutlet()
groupMenu = objc.IBOutlet()
actionButtons = objc.IBOutlet()
actionButtonsNoVideo = objc.IBOutlet()
addContactButton = objc.IBOutlet()
groupButton = objc.IBOutlet()
addContactButtonSearch = objc.IBOutlet()
addContactButtonDialPad = objc.IBOutlet()
conferenceButton = objc.IBOutlet()
contactContextMenu = objc.IBOutlet()
photoImage = objc.IBOutlet()
presenceActivityPopUp = objc.IBOutlet()
presenceNoteText = objc.IBOutlet()
nameText = objc.IBOutlet()
muteButton = objc.IBOutlet()
silentButton = objc.IBOutlet()
searchOutline = objc.IBOutlet()
notFoundText = objc.IBOutlet()
notFoundTextOffset = None
searchOutlineTopOffset = None
addContactToConferenceDialPad = objc.IBOutlet()
blinkMenu = objc.IBOutlet()
historyMenu = objc.IBOutlet()
recordingsSubMenu = objc.IBOutlet()
recordingsMenu = objc.IBOutlet()
contactsMenu = objc.IBOutlet()
devicesMenu = objc.IBOutlet()
callMenu = objc.IBOutlet()
presenceMenu = objc.IBOutlet()
presenceWatchersMenu = objc.IBOutlet()
presencePopUpMenu = objc.IBOutlet()
windowMenu = objc.IBOutlet()
restoreContactsMenu = objc.IBOutlet()
alwaysOnTopMenuItem = objc.IBOutlet()
useSpeechRecognitionMenuItem = objc.IBOutlet()
useSpeechSynthesisMenuItem = objc.IBOutlet()
myvideoMenuItem = objc.IBOutlet()
videoView = objc.IBOutlet()
chatMenu = objc.IBOutlet()
screenShareMenu = objc.IBOutlet()
historyViewer = None
searchInfoAttrs = NSDictionary.dictionaryWithObjectsAndKeys_(
NSFont.systemFontOfSize_(NSFont.labelFontSize()), NSFontAttributeName,
NSColor.grayColor(), NSForegroundColorAttributeName)
conference = None
joinConferenceWindow = None
addParticipantsWindow = None
silence_player = None
ldap_directory = None
ldap_search = None
ldap_found_contacts = []
local_found_contacts = []
sessionControllersManager = None
presence_notes_history = deque(maxlen=6)
first_run = False
presencePublisher = None
white = None
presenceInfoPanel = None
tellMeWhenContactBecomesAvailableList = set()
#statusbar = NSStatusBar.systemStatusBar()
statusbar = Null
statusBarMenu = objc.IBOutlet()
speech_synthesizer = None
speech_synthesizer_active = False
scheduled_conferences = set()
my_device_is_active = True
sync_presence_at_start = False
new_audio_sample_rate = None
last_status_per_device = {}
created_accounts = set()
purge_presence_timer = None
full_screen_in_progress = False
myvideo = None
refresh_drawer_counter = 1
last_failure_reason = None
ready = False
@property
def has_audio(self):
has_audio = False
for v in self.audioSessionsListView.subviews():
if v.delegate is not None and v.delegate.sessionController is not None and v.delegate.sessionController.session is not None and v.delegate.sessionController.session.state in ('terminating', 'terminated'):
continue
else:
has_audio = True
break
return has_audio
def __del__(self):
NSNotificationCenter.defaultCenter().removeObserver_(self)
def awakeFromNib(self):
BlinkLogger().log_debug('Starting Contact Manager')
# check how much space there is left for the search Outline, so we can restore it after
# minimizing
self.searchOutlineTopOffset = NSHeight(self.searchOutline.enclosingScrollView().superview().frame()) - NSHeight(self.searchOutline.enclosingScrollView().frame())
self.contactOutline.setRowHeight_(40)
self.contactOutline.setTarget_(self)
self.contactOutline.setDoubleAction_("actionButtonClicked:")
self.contactOutline.setDraggingSourceOperationMask_forLocal_(NSDragOperationMove, True)
self.contactOutline.registerForDraggedTypes_(NSArray.arrayWithObjects_("dragged-contact", "x-blink-audio-session", NSFilenamesPboardType))
self.searchOutline.setTarget_(self)
self.searchOutline.setDoubleAction_("actionButtonClicked:")
self.contactOutline.setDraggingSourceOperationMask_forLocal_(NSDragOperationCopy, True)
self.searchOutline.registerForDraggedTypes_(NSArray.arrayWithObjects_("dragged-contact", "x-blink-audio-session", NSFilenamesPboardType))
# work around for Lion that resizes the contact cell width bigger than its parent view
self.contactOutline.setAutoresizesOutlineColumn_(False)
self.searchOutline.setAutoresizesOutlineColumn_(False)
self.chatMenu.setAutoenablesItems_(False)
# save the position of this view, because when the window is collapsed
# the position gets messed
f = self.notFoundText.frame()
self.notFoundTextOffset = NSHeight(self.notFoundText.superview().frame()) - NSMinY(f)
self.audioSessionsListView.setSpacing_(0)
self.participantsTableView.registerForDraggedTypes_(NSArray.arrayWithObject_("x-blink-sip-uri"))
self.participantsTableView.setTarget_(self)
self.participantsTableView.setDoubleAction_("doubleClickReceived:")
nc = NotificationCenter()
nc.add_observer(self, name="AudioDevicesDidChange")
nc.add_observer(self, name="ActiveAudioSessionChanged")
nc.add_observer(self, name="BlinkChatWindowClosed")
nc.add_observer(self, name="BlinkVideoWindowClosed")
nc.add_observer(self, name="BlinkConferenceGotUpdate")
nc.add_observer(self, name="BlinkDidRenegotiateStreams")
nc.add_observer(self, name="BlinkContactsHaveChanged")
nc.add_observer(self, name="BlinkMuteChangedState")
nc.add_observer(self, name="BlinkShouldTerminate")
nc.add_observer(self, name="BlinkSessionChangedState")
nc.add_observer(self, name="BlinkContactBecameAvailable")
nc.add_observer(self, name="BlinkStreamHandlersChanged")
nc.add_observer(self, name="BlinkProposalDidFail")
nc.add_observer(self, name="SIPAccountGotSelfPresenceState")
nc.add_observer(self, name="BonjourAccountWillRegister")
nc.add_observer(self, name="BonjourAccountRegistrationDidSucceed")
nc.add_observer(self, name="BonjourAccountRegistrationDidFail")
nc.add_observer(self, name="BonjourAccountRegistrationDidEnd")
nc.add_observer(self, name="CFGSettingsObjectDidChange")
nc.add_observer(self, name="CFGSettingsObjectWasCreated")
nc.add_observer(self, name="ChatReplicationJournalEntryReceived")
nc.add_observer(self, name="DefaultAudioDeviceDidChange")
nc.add_observer(self, name="LDAPDirectorySearchFoundContact")
nc.add_observer(self, name="HistoryEntriesVisibilityChanged")
nc.add_observer(self, name="MediaStreamDidInitialize")
nc.add_observer(self, name="SIPApplicationWillStart")
nc.add_observer(self, name="SIPApplicationWillEnd")
nc.add_observer(self, name="SIPApplicationDidStart")
nc.add_observer(self, name="SIPAccountDidActivate")
nc.add_observer(self, name="SIPAccountDidDeactivate")
nc.add_observer(self, name="SIPAccountGotPresenceState")
nc.add_observer(self, name="SIPAccountWillRegister")
nc.add_observer(self, name="SystemWillSleep")
nc.add_observer(self, name="SystemDidWakeUpFromSleep")
nc.add_observer(self, name="SystemIPAddressDidChange")
nc.add_observer(self, name="SIPAccountRegistrationDidSucceed")
nc.add_observer(self, name="SIPAccountRegistrationDidFail")
nc.add_observer(self, name="SIPAccountRegistrationGotAnswer")
nc.add_observer(self, name="SIPAccountRegistrationDidEnd")
nc.add_observer(self, name="AddressbookGroupWasActivated")
nc.add_observer(self, name="AddressbookGroupWasDeleted")
nc.add_observer(self, name="AddressbookGroupDidChange")
nc.add_observer(self, name="BonjourGroupWasActivated")
nc.add_observer(self, name="BonjourGroupWasDeactivated")
nc.add_observer(self, name="VirtualGroupWasActivated")
nc.add_observer(self, name="VirtualGroupWasDeleted")
nc.add_observer(self, name="VirtualGroupDidChange")
nc.add_observer(self, name="SIPSessionLoggedToHistory")
nc.add_observer(self, name="SIPSessionLoggedToHistory")
nc.add_observer(self, name="PresenceSubscriptionDidFail")
nc.add_observer(self, name="PresenceSubscriptionDidEnd")
nc.add_observer(self, sender=AccountManager())
ns_nc = NSNotificationCenter.defaultCenter()
ns_nc.addObserver_selector_name_object_(self, "contactSelectionChanged:", NSOutlineViewSelectionDidChangeNotification, self.contactOutline)
ns_nc.addObserver_selector_name_object_(self, "participantSelectionChanged:", NSTableViewSelectionDidChangeNotification, self.participantsTableView)
ns_nc.addObserver_selector_name_object_(self, "drawerSplitViewDidResize:", NSSplitViewDidResizeSubviewsNotification, self.drawerSplitView)
ns_nc.addObserver_selector_name_object_(self, "userDefaultsDidChange:", "NSUserDefaultsDidChangeNotification", NSUserDefaults.standardUserDefaults())
self.sessionControllersManager = SessionControllersManager()
# never show debug window when application launches
NSUserDefaults.standardUserDefaults().setInteger_forKey_(0, "ShowDebugWindow")
self.photoImage.callback = self.photoClicked
self.window().makeFirstResponder_(self.contactOutline)
self.contactsMenu.itemWithTag_(42).setEnabled_(True) # Dialpad
if not NSApp.delegate().answering_machine_enabled:
# Answering machine
item = self.statusBarMenu.itemWithTag_(50)
item.setEnabled_(False)
item.setHidden_(True)
if not NSApp.delegate().history_enabled:
# History menu
item = self.windowMenu.itemWithTag_(3)
item.setHidden_(True)
item = self.historyMenu.itemWithTag_(1)
item.setHidden_(True)
self.window().setTitle_(NSApp.delegate().applicationNamePrint)
segmentChildren = NSAccessibilityUnignoredDescendant(self.actionButtons).accessibilityAttributeValue_(NSAccessibilityChildrenAttribute)
segmentChildren.objectAtIndex_(0).accessibilitySetOverrideValue_forAttribute_(NSString.stringWithString_('Start Audio Call'), NSAccessibilityDescriptionAttribute)
segmentChildren.objectAtIndex_(1).accessibilitySetOverrideValue_forAttribute_(NSString.stringWithString_('Start Video Call'), NSAccessibilityDescriptionAttribute)
segmentChildren.objectAtIndex_(2).accessibilitySetOverrideValue_forAttribute_(NSString.stringWithString_('Start Text Chat'), NSAccessibilityDescriptionAttribute)
segmentChildren.objectAtIndex_(3).accessibilitySetOverrideValue_forAttribute_(NSString.stringWithString_('Screen Sharing'), NSAccessibilityDescriptionAttribute)
segmentChildren.objectAtIndex_(0).accessibilitySetOverrideValue_forAttribute_(NSString.stringWithString_('Push button'), NSAccessibilityRoleDescriptionAttribute)
segmentChildren.objectAtIndex_(1).accessibilitySetOverrideValue_forAttribute_(NSString.stringWithString_('Push button'), NSAccessibilityRoleDescriptionAttribute)
segmentChildren.objectAtIndex_(2).accessibilitySetOverrideValue_forAttribute_(NSString.stringWithString_('Push button'), NSAccessibilityRoleDescriptionAttribute)
segmentChildren.objectAtIndex_(3).accessibilitySetOverrideValue_forAttribute_(NSString.stringWithString_('Push button'), NSAccessibilityRoleDescriptionAttribute)
segmentChildren2 = NSAccessibilityUnignoredDescendant(self.actionButtons).accessibilityAttributeValue_(NSAccessibilityChildrenAttribute)
segmentChildren2.objectAtIndex_(0).accessibilitySetOverrideValue_forAttribute_(NSString.stringWithString_('Start Audio Call'), NSAccessibilityDescriptionAttribute)
segmentChildren2.objectAtIndex_(1).accessibilitySetOverrideValue_forAttribute_(NSString.stringWithString_('Start Text Chat'), NSAccessibilityDescriptionAttribute)
segmentChildren2.objectAtIndex_(2).accessibilitySetOverrideValue_forAttribute_(NSString.stringWithString_('Screen Sharing'), NSAccessibilityDescriptionAttribute)
segmentChildren2.objectAtIndex_(0).accessibilitySetOverrideValue_forAttribute_(NSString.stringWithString_('Push button'), NSAccessibilityRoleDescriptionAttribute)
segmentChildren2.objectAtIndex_(1).accessibilitySetOverrideValue_forAttribute_(NSString.stringWithString_('Push button'), NSAccessibilityRoleDescriptionAttribute)
segmentChildren2.objectAtIndex_(2).accessibilitySetOverrideValue_forAttribute_(NSString.stringWithString_('Push button'), NSAccessibilityRoleDescriptionAttribute)
self.setAlwaysOnTop()
path = ApplicationData.get('presence')
makedirs(path)
try:
with open(ApplicationData.get('presence_notes_history.pickle'), 'rb'):
pass
except IOError:
pass
else:
src = ApplicationData.get('presence_notes_history.pickle')
dst = ApplicationData.get('presence/presence_notes_history.pickle')
try:
shutil.move(src, dst)
except shutil.Error:
pass
try:
with open(ApplicationData.get('presence_offline_note.pickle'), 'rb'):
pass
except IOError:
pass
else:
unlink(ApplicationData.get('presence_offline_note.pickle'))
# TODO3
try:
with open(ApplicationData.get('presence/presence_notes_history.pickle'), 'rb') as f:
self.presence_notes_history.extend(pickle.load(f))
except (TypeError, EOFError):
# data is corrupted, reset it
self.deletePresenceHistory_(None)
except (IOError, pickle.UnpicklingError):
pass
self.presencePublisher = PresencePublisher(self)
self.statusBarItem = self.statusbar.statusItemWithLength_(NSVariableStatusItemLength)
self.setStatusBarIcon()
self.statusBarItem.setHighlightMode_(1)
self.statusBarItem.setToolTip_(NSApp.delegate().applicationName)
self.statusBarItem.setMenu_(self.statusBarMenu)
self.last_calls_submenu = NSMenu.alloc().init()
self.last_calls_submenu.setAutoenablesItems_(False)
dotPath = NSBezierPath.bezierPathWithRoundedRect_xRadius_yRadius_(NSMakeRect(0, 1, 5, 12), 2.0, 2.0)
self.presence_dots = {}
for i, color in [("available", NSColor.greenColor()),
("away", NSColor.yellowColor()),
("busy", NSColor.redColor()),
("invisible", NSColor.grayColor()),
("offline", NSColor.whiteColor())]:
dot = NSImage.alloc().initWithSize_(NSMakeSize(14, 14))
dot.lockFocus()
color.set()
dotPath.fill()
dot.unlockFocus()
self.presence_dots[i] = dot
self.speech_synthesizer = NSSpeechSynthesizer.alloc().init() or Null
self.speech_synthesizer.setDelegate_(self)
self.rotateCameraTimer = NSTimer.timerWithTimeInterval_target_selector_userInfo_repeats_(30, self, "rotateCamera:", None, True)
NSRunLoop.currentRunLoop().addTimer_forMode_(self.rotateCameraTimer, NSModalPanelRunLoopMode)
NSRunLoop.currentRunLoop().addTimer_forMode_(self.rotateCameraTimer, NSDefaultRunLoopMode)
self.conference_timer = NSTimer.timerWithTimeInterval_target_selector_userInfo_repeats_(30, self, "startConferenceTimer:", None, True)
NSRunLoop.currentRunLoop().addTimer_forMode_(self.conference_timer, NSModalPanelRunLoopMode)
NSRunLoop.currentRunLoop().addTimer_forMode_(self.conference_timer, NSDefaultRunLoopMode)
self.purge_presence_timer = NSTimer.timerWithTimeInterval_target_selector_userInfo_repeats_(10, self, "purgePresenceTimer:", None, True)
NSRunLoop.currentRunLoop().addTimer_forMode_(self.purge_presence_timer, NSModalPanelRunLoopMode)
NSRunLoop.currentRunLoop().addTimer_forMode_(self.purge_presence_timer, NSDefaultRunLoopMode)
if host.default_ip:
t = NSTimer.timerWithTimeInterval_target_selector_userInfo_repeats_(10, self, "showUnsentMessages:", None, False)
NSRunLoop.currentRunLoop().addTimer_forMode_(t, NSModalPanelRunLoopMode)
NSRunLoop.currentRunLoop().addTimer_forMode_(t, NSDefaultRunLoopMode)
self.loaded = True
@objc.python_method
def initFileTransfersWindow(self):
if not self.fileTransfersWindow:
self.fileTransfersWindow = FileTransferWindowController()
@objc.python_method
def setCollapsed(self, flag):
if self.loaded:
self.collapsedState = flag
self.updateParticipantsView()
if flag:
self.contactOutline.deselectAll_(None)
@objc.python_method
def init_aspect_ratio(self, width, height):
self.refresh_drawer_counter += 1
@objc.IBAction
def refreshDevices_(self, sender):
#BlinkLogger().log_info('Refresh audio devices')
SIPApplication().engine._ua.refresh_sound_devices()
settings = SIPSimpleSettings()
in_out_devices = list(set(self.backend._app.engine.input_devices) & set(self.backend._app.engine.output_devices))
in_out_devices.append('system_default')
#BlinkLogger().log_info('Selected input device %s' % settings.audio.input_device)
#BlinkLogger().log_info('Selected output device %s' % settings.audio.input_device)
#BlinkLogger().log_info('Available devices %s' % in_out_devices)
if settings.audio.input_device not in in_out_devices:
BlinkLogger().log_info('Changing input to system_default')
settings.audio.input_device = 'system_default'
if settings.audio.output_device not in in_out_devices:
BlinkLogger().log_info('Changing output to system_default')
settings.audio.output_device = 'system_default'
settings.save()
@objc.python_method
@run_in_gui_thread
def refreshAccountList(self):
if not self.sessionControllersManager.isMediaTypeSupported('video'):
self.actionButtonsNoVideo.setHidden_(False)
self.actionButtons.setHidden_(True)
else:
self.actionButtonsNoVideo.setHidden_(True)
self.actionButtons.setHidden_(False)
style = NSParagraphStyle.defaultParagraphStyle().mutableCopy()
style.setLineBreakMode_(NSLineBreakByTruncatingTail)
grayAttrs = NSDictionary.dictionaryWithObjectsAndKeys_(NSColor.disabledControlTextColor(), NSForegroundColorAttributeName, style, NSParagraphStyleAttributeName)
redAttrs = NSDictionary.dictionaryWithObjectsAndKeys_(NSColor.redColor(), NSForegroundColorAttributeName, style, NSParagraphStyleAttributeName)
self.accountPopUp.removeAllItems()
self.accounts.sort(key=attrgetter('order'))
account_manager = AccountManager()
for account_info in (account_info for account_info in self.accounts if account_info.account.enabled):
label = account_info.account.gui.account_label or account_info.name
self.accountPopUp.addItemWithTitle_(label)
item = self.accountPopUp.lastItem()
item.setRepresentedObject_(account_info.account)
if isinstance(account_info.account, BonjourAccount):
image = NSImage.imageNamed_("NSBonjour")
image.setScalesWhenResized_(True)
image.setSize_(NSMakeSize(12, 12))
item.setImage_(image)
if account_info.account.enabled and not account_info.register_state == 'succeeded':
if account_info.register_failure_reason:
name = '%s (%s)' % (label, account_info.register_failure_reason)
else:
name = label
title = NSAttributedString.alloc().initWithString_attributes_(name, grayAttrs)
item.setAttributedTitle_(title)
else:
if not account_info.register_state == 'succeeded':
if account_info.account.sip.register:
if account_info.register_failure_reason:
name = '%s (%s)' % (label, account_info.register_failure_reason)
else:
name = label
else:
name = label
title = NSAttributedString.alloc().initWithString_attributes_(name, grayAttrs)
item.setAttributedTitle_(title)
item.setImage_(None)
else:
if account_info.account.audio.do_not_disturb:
title = NSAttributedString.alloc().initWithString_attributes_(label, redAttrs)
item.setAttributedTitle_(title)
image = NSImage.imageNamed_("blocked")
image.setScalesWhenResized_(True)
image.setSize_(NSMakeSize(12, 12))
item.setImage_(image)
else:
if account_info.registrar is not None:
if account_info.registrar.startswith("tls"):
image = NSImage.imageNamed_("locked-green")
else:
image = NSImage.imageNamed_("unlocked-darkgray")
image.setScalesWhenResized_(True)
image.setSize_(NSMakeSize(16, 16))
item.setImage_(image)
else:
item.setImage_(None)
if account_info.account is account_manager.default_account:
self.accountPopUp.selectItem_(item)
if self.accountPopUp.numberOfItems() == 0:
self.accountPopUp.addItemWithTitle_(NSLocalizedString("No Accounts", "Account popup menu item"))
self.accountPopUp.lastItem().setEnabled_(False)
if self.backend.validateAddAccountAction():
self.accountPopUp.menu().addItem_(NSMenuItem.separatorItem())
self.accountPopUp.addItemWithTitle_(NSLocalizedString("Add Account...", "Account popup menu item"))
if account_manager.default_account is not None:
self.updateNameLabel(account_manager.default_account.display_name or account_manager.default_account.id)
else:
self.updateNameLabel('')
@objc.python_method
def activeAccount(self):
return self.accountPopUp.selectedItem().representedObject()
@objc.python_method
def updateNameLabel(self, name):
self.nameText.setStringValue_(name)
@objc.python_method
def refreshContactsList(self, sender=None):
if sender is None:
sender = self.model
if sender is self.model:
self.contactOutline.reloadData()
for group in self.model.groupsList:
if group.group is not None and group.group.expanded:
self.contactOutline.expandItem_expandChildren_(group, False)
else:
self.contactOutline.reloadItem_reloadChildren_(sender, True)
@objc.python_method
def getSelectedContacts(self, includeGroups=False):
contacts = []
if self.mainTabView.selectedTabViewItem().identifier() == "contacts":
outline = self.contactOutline
elif self.mainTabView.selectedTabViewItem().identifier() == "search":
outline = self.searchOutline
if outline.selectedRowIndexes().count() == 0:
text = self.searchBox.stringValue()
if not text:
return []
contact = BlinkContact(text, name=text)
return [contact]
else:
return []
selection = outline.selectedRowIndexes()
item = selection.firstIndex()
while item != NSNotFound:
object = outline.itemAtRow_(item)
if isinstance(object, BlinkContact):
contacts.append(object)
elif includeGroups and isinstance(object, BlinkGroup):
contacts.append(object)
item = selection.indexGreaterThanIndex_(item)
return contacts
@objc.python_method
@run_in_gui_thread
def renderLastCallsEntriesForContact(self, results, contact):
while self.last_calls_submenu.numberOfItems() > 0:
self.last_calls_submenu.removeItemAtIndex_(0)
if results:
for result in reversed(list(results)):
if 'video' in result.media_types.lower():
label = 'Video'
elif 'screen' in result.media_types.lower():
label = 'Screen Sharing'
elif 'audio' in result.media_types.lower():
label = 'Audio'
else:
label = result.media_types.title()
label += NSLocalizedString(" from ", "Menu item") if result.direction == 'incoming' else NSLocalizedString(" to ", "Menu item")
label += contact.name
duration = result.end_time - result.start_time
if result.duration == 0:
status = session_status_localized[result.status]
else:
status = ''
if duration.days > 0 or duration.seconds > 60 * 60:
status = NSLocalizedString("%i hours, ", "Menu item") % (duration.days * 60 * 60 * 24 + int(duration.seconds/(60 * 60)))
s = duration.seconds % (60 * 60)
status += "%02i:%02i" % divmod(s, 60)
title = '%s %s (%s)' % (label, format_date(utc_to_local(result.start_time)), status)
r_item = self.last_calls_submenu.insertItemWithTitle_action_keyEquivalent_atIndex_(title, "", "", 0)
image = None
if 'screen' in result.media_types:
image = 'display_16'
elif 'audio' in result.media_types:
image = 'hangup_16' if result.status == 'missed' else 'audio_16'
elif result.media_types == 'chat':
image = 'pencil'
elif result.media_types == 'file-transfer':
image = 'outgoing_file' if result.direction == 'outgoing' else 'incoming_file'
if image:
icon = NSImage.imageNamed_(image)
icon.setScalesWhenResized_(True)
icon.setSize_(NSMakeSize(14, 14))
r_item.setImage_(icon)
@objc.python_method
@run_in_gui_thread
def renderHistoryEntriesInStatusBarMenu(self, entries):
menu = self.statusBarMenu
for i in range(10):
missed_call_item = menu.itemWithTag_(1001+i)
if missed_call_item:
self.statusBarMenu.removeItem_(missed_call_item)
else:
break
index = menu.indexOfItem_(menu.itemWithTag_(1000))
tag = 1001
for item in entries['missed']:
lastItem = menu.insertItemWithTitle_action_keyEquivalent_atIndex_("%(remote_party)s %(start_time)s" % item, "historyClicked:", "", index+1)
lastItem.setAttributedTitle_(self.format_history_menu_item(item))
lastItem.setIndentationLevel_(1)
lastItem.setTarget_(self)
lastItem.setTag_(tag)
lastItem.setRepresentedObject_(item)
tag += 1
index += 1
@objc.python_method
@run_in_gui_thread
def renderHistoryEntriesInHistoryMenu(self, entries):
def get_icon_history_result(media_types, direction, status):
image = None
if 'screen' in media_types:
image = 'display_16'
elif 'audio' in media_types:
image = 'audio_16' if status == 'completed' else 'hangup_16'
elif 'chat' in media_types:
image = 'pencil'
elif 'file-transfer' in media_types:
image = 'outgoing_file' if direction == 'outgoing' else 'incoming_file'
return image
menu = self.historyMenu
i = 3 if not NSApp.delegate().history_enabled else 4
while menu.numberOfItems() > i:
menu.removeItemAtIndex_(i)
lastItem = menu.addItemWithTitle_action_keyEquivalent_(NSLocalizedString("Missed Calls", "Menu item"), "", "")
lastItem.setEnabled_(False)
for item in entries['missed']:
lastItem = menu.addItemWithTitle_action_keyEquivalent_("%(remote_party)s %(start_time)s" % item, "historyClicked:", "")
lastItem.setAttributedTitle_(self.format_history_menu_item(item))
lastItem.setIndentationLevel_(1)
lastItem.setTarget_(self)
lastItem.setRepresentedObject_(item)
image = get_icon_history_result(item['streams'], 'incoming', item['status'])
if image:
icon = NSImage.imageNamed_(image)
icon.setScalesWhenResized_(True)
icon.setSize_(NSMakeSize(14, 14))
lastItem.setImage_(icon)
menu.addItem_(NSMenuItem.separatorItem())
lastItem = menu.addItemWithTitle_action_keyEquivalent_(NSLocalizedString("Incoming Calls", "Menu item"), "", "")
lastItem.setEnabled_(False)
for item in entries['incoming']:
lastItem = menu.addItemWithTitle_action_keyEquivalent_("%(remote_party)s %(start_time)s" % item, "historyClicked:", "")
lastItem.setAttributedTitle_(self.format_history_menu_item(item))
lastItem.setIndentationLevel_(1)
lastItem.setTarget_(self)
lastItem.setRepresentedObject_(item)
image = get_icon_history_result(item['streams'], 'incoming', item['status'])
if image:
icon = NSImage.imageNamed_(image)
icon.setScalesWhenResized_(True)
icon.setSize_(NSMakeSize(14, 14))
lastItem.setImage_(icon)
menu.addItem_(NSMenuItem.separatorItem())
lastItem = menu.addItemWithTitle_action_keyEquivalent_(NSLocalizedString("Outgoing Calls", "Menu item"), "", "")
lastItem.setEnabled_(False)
for item in entries['outgoing']:
lastItem = menu.addItemWithTitle_action_keyEquivalent_("%(remote_party)s %(start_time)s" % item, "historyClicked:", "")
lastItem.setAttributedTitle_(self.format_history_menu_item(item))
lastItem.setIndentationLevel_(1)
lastItem.setTarget_(self)
lastItem.setRepresentedObject_(item)
image = get_icon_history_result(item['streams'], 'outgoing', item['status'])
if image:
icon = NSImage.imageNamed_(image)
icon.setScalesWhenResized_(True)
icon.setSize_(NSMakeSize(14, 14))
lastItem.setImage_(icon)
menu.addItem_(NSMenuItem.separatorItem())
lastItem = menu.addItemWithTitle_action_keyEquivalent_(NSLocalizedString("Clear History", "Menu item"), "historyClicked:", "")
lastItem.setEnabled_(True if entries['incoming'] or entries['outgoing'] or entries['missed'] else False)
lastItem.setTag_(444)
lastItem.setTarget_(self)
@objc.python_method
def showHelp(self, append_url=''):
NSWorkspace.sharedWorkspace().openURL_(NSURL.URLWithString_(NSApp.delegate().help_url+append_url))
@objc.python_method
def updateBlinkMenu(self):
settings = SIPSimpleSettings()
self.blinkMenu.itemWithTag_(1).setTitle_(NSLocalizedString("About %s", "Menu item") % NSApp.delegate().applicationNamePrint)
self.blinkMenu.itemWithTag_(10).setTitle_(NSLocalizedString("Hide", "Menu item"))
find_sylkserver = LSFindApplicationForInfo(kLSUnknownCreator, 'com.agprojects.SylkServer', None, None, None)
# sylkserver_exists = find_sylkserver[2] is not None
sylkserver_exists = True
self.blinkMenu.itemWithTag_(2).setHidden_(bool(NSApp.delegate().updater is None))
if NSApp.delegate().applicationName in ('Blink Pro', 'Blink Lite'):
self.blinkMenu.itemWithTag_(3).setHidden_(True)
self.blinkMenu.itemWithTag_(7).setHidden_(True)
self.blinkMenu.itemWithTag_(8).setHidden_(True)
self.blinkMenu.itemWithTag_(9).setHidden_(True)
elif NSApp.delegate().applicationName == 'SIP2SIP':
self.blinkMenu.itemWithTag_(3).setHidden_(True)
self.blinkMenu.itemWithTag_(7).setHidden_(False)
self.blinkMenu.itemWithTag_(8).setHidden_(sylkserver_exists)
self.blinkMenu.itemWithTag_(9).setHidden_(sylkserver_exists)
else:
self.blinkMenu.itemWithTag_(3).setHidden_(True)
self.blinkMenu.itemWithTag_(7).setHidden_(False)
self.blinkMenu.itemWithTag_(8).setHidden_(False)
self.blinkMenu.itemWithTag_(9).setHidden_(True)
if settings.service_provider.name:
if settings.service_provider.about_url or settings.service_provider.help_url:
self.blinkMenu.itemWithTag_(4).setHidden_(False)
if settings.service_provider.about_url:
title = NSLocalizedString("About %s...", "Menu item") % settings.service_provider.name
self.blinkMenu.itemWithTag_(5).setTitle_(title)
self.blinkMenu.itemWithTag_(5).setHidden_(False)
if settings.service_provider.help_url:
title = NSLocalizedString("%s Support Page...", "Menu item") % settings.service_provider.name
self.blinkMenu.itemWithTag_(6).setTitle_(title)
self.blinkMenu.itemWithTag_(6).setHidden_(False)
else:
self.blinkMenu.itemWithTag_(4).setHidden_(True)
self.blinkMenu.itemWithTag_(5).setHidden_(True)
self.blinkMenu.itemWithTag_(6).setHidden_(True)
@objc.python_method
def updateCallMenu(self):
menu = self.callMenu
item = menu.itemWithTag_(300) # mute
item.setState_(NSOnState if self.backend.is_muted() else NSOffState)
item = menu.itemWithTag_(301) # silent
settings = SIPSimpleSettings()
item.setState_(NSOnState if settings.audio.silent else NSOffState)
item = menu.itemWithTag_(302) # dnd
account = AccountManager().default_account
item.setState_(NSOnState if account is not None and account.audio.do_not_disturb else NSOffState)
item.setEnabled_(True)
settings = SIPSimpleSettings()
self.useSpeechRecognitionMenuItem.setState_(NSOnState if settings.sounds.use_speech_recognition else NSOffState)
while menu.numberOfItems() > 9:
menu.removeItemAtIndex_(9)
account = self.activeAccount()
if account is None:
return
item = menu.itemWithTag_(44) # Join Conference
item.setEnabled_(self.sessionControllersManager.isMediaTypeSupported('chat'))
# outbound proxy
if not isinstance(account, BonjourAccount) and (account.sip.primary_proxy or account.sip.alternative_proxy):
menu.addItem_(NSMenuItem.separatorItem())
lastItem = menu.addItemWithTitle_action_keyEquivalent_(NSLocalizedString("Outbound Proxy", "Menu item"), "", "")
lastItem.setEnabled_(False)
lastItem = menu.addItemWithTitle_action_keyEquivalent_(NSLocalizedString("None", "Menu Item"), "selectOutboundProxyClicked:", "")
lastItem.setIndentationLevel_(2)
lastItem.setState_(NSOffState if account.sip.always_use_my_proxy else NSOnState)
lastItem.setTag_(700)
lastItem.setTarget_(self)
lastItem.setRepresentedObject_(account)
if account.sip.primary_proxy is None:
title = NSLocalizedString("Discovered using DNS Lookup", "Menu item")
else:
title = str(account.sip.primary_proxy)
lastItem = menu.addItemWithTitle_action_keyEquivalent_(title, "selectOutboundProxyClicked:", "")
lastItem.setIndentationLevel_(2)
lastItem.setState_(NSOnState if not account.sip.selected_proxy and account.sip.always_use_my_proxy else NSOffState)
lastItem.setTag_(701)
lastItem.setTarget_(self)
lastItem.setRepresentedObject_(account)
if account.sip.alternative_proxy:
lastItem = menu.addItemWithTitle_action_keyEquivalent_(str(account.sip.alternative_proxy), "selectOutboundProxyClicked:", "")
lastItem.setIndentationLevel_(2)
lastItem.setState_(NSOnState if account.sip.selected_proxy and account.sip.always_use_my_proxy else NSOffState)
lastItem.setTag_(702)
lastItem.setTarget_(self)
lastItem.setRepresentedObject_(account)
# voicemail
def format_account_item(account, mwi_data, mwi_format_new, mwi_format_no_new):
a = NSMutableAttributedString.alloc().init()