-
Notifications
You must be signed in to change notification settings - Fork 7
/
ContactListModel.py
4310 lines (3663 loc) · 189 KB
/
ContactListModel.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.
#
__all__ = ['BlinkContact',
'BlinkConferenceContact',
'BlinkPendingWatcher',
'BlinkPresenceContact',
'BlinkBlockedPresenceContact',
'HistoryBlinkContact',
'BonjourBlinkContact',
'SearchResultContact',
'LdapSearchResultContact',
'SystemAddressBookBlinkContact',
'BlinkGroup',
'BonjourBlinkGroup',
'NoBlinkGroup',
'AllContactsBlinkGroup',
'HistoryBlinkGroup',
'MissedCallsBlinkGroup',
'OutgoingCallsBlinkGroup',
'IncomingCallsBlinkGroup',
'AddressBookBlinkGroup',
'Avatar',
'DefaultUserAvatar',
'DefaultMultiUserAvatar',
'PresenceContactAvatar',
'ContactListModel',
'SearchContactListModel',
'presence_status_for_contact',
'presence_status_icons']
from AppKit import (NSAlertDefaultReturn,
NSApp,
NSDragOperationCopy,
NSDragOperationGeneric,
NSDragOperationMove,
NSDragOperationNone,
NSEventTrackingRunLoopMode,
NSFilenamesPboardType,
NSLeftMouseUp,
NSOutlineViewDropOnItemIndex,
NSOutlineViewItemDidCollapseNotification,
NSOutlineViewItemDidExpandNotification,
NSPNGFileType,
NSRunAlertPanel,
NSTIFFCompressionLZW,
NSSound)
from Foundation import (NSArray,
NSBitmapImageRep,
NSBundle,
NSData,
NSDate,
NSEvent,
NSImage,
NSIndexSet,
NSMakeSize,
NSMenu,
NSNotificationCenter,
NSObject,
NSRunLoop,
NSRunLoopCommonModes,
NSString,
NSLocalizedString,
NSTimer,
NSURL,
NSWorkspace)
import AddressBook
import objc
import base64
import bisect
import datetime
import glob
import os
import re
import pickle
import unicodedata
import urllib.request, urllib.parse, urllib.error
import uuid
import sys
import time
from application.notification import NotificationCenter, IObserver, NotificationData
from application.python import Null
from application.python.descriptor import classproperty
from application.python.types import Singleton
from application.system import makedirs, unlink
from eventlib.green import urllib2
from itertools import chain
from sipsimple.configuration import DuplicateIDError
from sipsimple.configuration.settings import SIPSimpleSettings
from sipsimple.core import FrozenSIPURI, SIPURI, SIPCoreError
from sipsimple.addressbook import AddressbookManager, Contact, ContactURI, Group, unique_id, Policy
from sipsimple.account import Account, AccountManager, BonjourAccount
from sipsimple.payloads import prescontent
from sipsimple.threading.green import run_in_green_thread
from sipsimple.threading import run_in_thread
from sipsimple.util import ISOTimestamp
from twisted.internet.error import ConnectionLost
from zope.interface import implementer
from ContactController import AddContactController, EditContactController
from GroupController import AddGroupController
from AudioSession import AudioSession
from BlinkLogger import BlinkLogger
from HistoryManager import SessionHistory
from SIPManager import MWIData
from MergeContactController import MergeContactController
from VirtualGroups import VirtualGroupsManager, VirtualGroup
from PresencePublisher import on_the_phone_activity
from resources import ApplicationData, Resources
from util import allocate_autorelease_pool, format_date, format_uri_type, is_anonymous, sipuri_components_from_string, sip_prefix_pattern, strip_addressbook_special_characters, run_in_gui_thread, utc_to_local
status_localized = {
'busy': NSLocalizedString("busy", "Label"),
'available': NSLocalizedString("available", "Label"),
'away': NSLocalizedString("away", "Label"),
'offline': NSLocalizedString("offline", "Label")
}
ICON_SIZE = 128
presence_status_icons = {'away': NSImage.imageNamed_("away"),
'busy': NSImage.imageNamed_("busy"),
'available': NSImage.imageNamed_("available"),
'offline': NSImage.imageNamed_("offline"),
'blocked': NSImage.imageNamed_("blocked")
}
def presence_status_for_contact(contact, uri=None):
status = None
if contact is None:
return status
if uri is None:
if isinstance(contact, BonjourBlinkContact):
status = contact.presence_state
elif isinstance(contact, BlinkPresenceContact) and contact.contact is not None:
if contact.presence_state['status']['busy']:
status = 'busy'
elif contact.presence_state['status']['available']:
status = 'available'
elif contact.presence_state['status']['away']:
status = 'away'
elif contact.contact.presence.policy == 'block':
return 'blocked'
elif contact.contact.presence.subscribe:
status = 'offline'
elif isinstance(contact, BlinkConferenceContact) and contact.presence_contact is not None:
if contact.presence_state['status']['busy']:
status = 'busy'
elif contact.presence_state['status']['available']:
status = 'available'
elif contact.presence_state['status']['away']:
status = 'away'
elif contact.presence_contact.contact.presence.policy == 'block':
status = 'blocked'
elif contact.presence_contact.contact.presence.subscribe:
status = 'offline'
return status
else:
try:
uri = 'sip:%s' % uri
pidfs = set()
for value in list(contact.pidfs_map[uri].values()):
for p in value:
pidfs.add(p)
except KeyError:
pass
else:
basic_status = 'closed'
available = False
away = False
busy = False
for pidf in pidfs:
if basic_status == 'closed':
basic_status = 'open' if any(service for service in pidf.services if service.status.basic == 'open') else 'closed'
if available is False:
available = any(service for service in pidf.services if service.status.extended == 'available' or (service.status.extended == None and basic_status == 'open'))
if busy is False:
busy = any(service for service in pidf.services if service.status.extended == 'busy')
if away is False:
away = any(service for service in pidf.services if service.status.extended == 'away')
if busy:
status = 'busy'
elif available:
status = 'available'
elif away:
status = 'away'
else:
status = 'offline'
return status
def encode_icon(icon):
if not icon:
return None
try:
tiff_data = icon.TIFFRepresentation()
bitmap_data = NSBitmapImageRep.alloc().initWithData_(tiff_data)
png_data = bitmap_data.representationUsingType_properties_(NSPNGFileType, None)
return base64.b64encode(png_data.bytes().tobytes()).decode()
except Exception as e:
BlinkLogger().log_error('Failed to encode icon: %s' % str(e))
return None
def decode_icon(data):
if not data:
return None
try:
data = base64.b64decode(data if isinstance(data, bytes) else data.encode())
return NSImage.alloc().initWithData_(NSData.alloc().initWithBytes_length_(data, len(data)))
except Exception as e:
BlinkLogger().log_error('Failed to decode icon: %s' % str(e))
return None
class Avatar(object):
def __init__(self, icon, path=None):
self.icon = self.scale_icon(icon)
self.path = path
@classproperty
def base_path(cls):
return ApplicationData.get('photos')
@classmethod
def scale_icon(cls, icon):
size = icon.size()
if size.width > ICON_SIZE or size.height > ICON_SIZE:
icon.setScalesWhenResized_(True)
icon.setSize_(NSMakeSize(ICON_SIZE, ICON_SIZE * size.height/size.width))
return icon
def save(self):
pass
def delete(self):
pass
class DefaultUserAvatar(Avatar, metaclass=Singleton):
def __init__(self):
filename = 'default_user_icon.tiff'
path = os.path.join(self.base_path, filename)
makedirs(os.path.dirname(path))
if not os.path.isfile(path):
icon = NSImage.imageNamed_("NSUser")
icon.setSize_(NSMakeSize(32, 32))
data = icon.TIFFRepresentationUsingCompression_factor_(NSTIFFCompressionLZW, 1)
data.writeToFile_atomically_(path, False)
else:
icon = NSImage.alloc().initWithContentsOfFile_(path)
super(DefaultUserAvatar, self).__init__(icon, path)
class PendingWatcherAvatar(Avatar, metaclass=Singleton):
def __init__(self):
filename = 'pending_watcher.tiff'
path = os.path.join(self.base_path, filename)
makedirs(os.path.dirname(path))
if not os.path.isfile(path):
default_path = Resources.get(filename)
icon = NSImage.alloc().initWithContentsOfFile_(default_path)
data = icon.TIFFRepresentationUsingCompression_factor_(NSTIFFCompressionLZW, 1)
data.writeToFile_atomically_(path, False)
else:
icon = NSImage.alloc().initWithContentsOfFile_(path)
super(PendingWatcherAvatar, self).__init__(icon, path)
class BlockedPolicyAvatar(Avatar, metaclass=Singleton):
def __init__(self):
filename = 'blocked.png'
path = os.path.join(self.base_path, filename)
makedirs(os.path.dirname(path))
if not os.path.isfile(path):
default_path = Resources.get(filename)
icon = NSImage.alloc().initWithContentsOfFile_(default_path)
data = icon.TIFFRepresentationUsingCompression_factor_(NSTIFFCompressionLZW, 1)
data.writeToFile_atomically_(path, False)
else:
icon = NSImage.alloc().initWithContentsOfFile_(path)
super(BlockedPolicyAvatar, self).__init__(icon, path)
class DefaultMultiUserAvatar(Avatar, metaclass=Singleton):
def __init__(self):
filename = 'default_multi_user_icon.tiff'
path = os.path.join(self.base_path, filename)
makedirs(os.path.dirname(path))
if not os.path.isfile(path):
icon = NSImage.imageNamed_("NSEveryone")
icon.setSize_(NSMakeSize(32, 32))
data = icon.TIFFRepresentationUsingCompression_factor_(NSTIFFCompressionLZW, 1)
data.writeToFile_atomically_(path, False)
else:
icon = NSImage.alloc().initWithContentsOfFile_(path)
super(DefaultMultiUserAvatar, self).__init__(icon, path)
class PresenceContactAvatar(Avatar):
@classmethod
def from_contact(cls, contact):
path = cls.path_for_contact(contact)
if not os.path.isfile(path):
return DefaultUserAvatar()
icon = NSImage.alloc().initWithContentsOfFile_(path)
if not icon:
unlink(path)
return DefaultUserAvatar()
return cls(icon, path)
@classmethod
def path_for_contact(cls, contact):
return os.path.join(cls.base_path, '%s.tiff' % contact.id)
def save(self):
data = self.icon.TIFFRepresentationUsingCompression_factor_(NSTIFFCompressionLZW, 1)
data.writeToFile_atomically_(self.path, False)
def delete(self):
unlink(self.path)
class BlinkContact(NSObject):
"""Basic Contact representation in Blink UI"""
editable = True
deletable = True
auto_answer = False
default_preferred_media = 'audio'
dealloc_timer = None
destroyed = False
contact = None
def __new__(cls, *args, **kwargs):
return cls.alloc().init()
def __init__(self, uri, uri_type=None, name=None, icon=None):
self.id = None
self.uris = [ContactURI(uri=uri, type=format_uri_type(uri_type))]
self.name = name or self.uri
self.detail = self.uri
if icon is not None:
self.avatar = Avatar(icon)
else:
self.avatar = DefaultUserAvatar()
self._set_username_and_domain()
def _get_detail(self):
detail = self.__dict__.get('detail', None)
if detail is None:
detail = NSString.stringWithString_('')
return detail
def _set_detail(self, value):
if value.startswith("b'"):
# Workaround bug in bonjour note setting that sets the note wrong
value = value[2:-1]
self.__dict__['detail'] = NSString.stringWithString_(value)
detail = property(_get_detail, _set_detail)
del _get_detail, _set_detail
@property
def icon(self):
return self.avatar.icon
@property
def uri(self):
if self.uris:
return self.uris[0].uri
else:
return ''
@property
def preferred_media(self):
uri = str(self.uri)
if not uri.startswith(('sip:', 'sips:')):
uri = 'sip:'+uri
try:
uri = SIPURI.parse(uri)
except SIPCoreError:
return self.default_preferred_media
else:
return uri.parameters.get('session-type', self.default_preferred_media)
def dealloc(self):
self.avatar = None
self.contact = None
objc.super(BlinkContact, self).dealloc()
@objc.python_method
@run_in_gui_thread
def destroy(self):
if self.destroyed:
return
self.destroyed = True
# workaround to keep the object alive as cocoa still sends delegate outline view messages to deallocated contacts
self.dealloc_timer = NSTimer.timerWithTimeInterval_target_selector_userInfo_repeats_(2.0, self, "deallocTimer:", None, False)
NSRunLoop.currentRunLoop().addTimer_forMode_(self.dealloc_timer, NSRunLoopCommonModes)
NSRunLoop.currentRunLoop().addTimer_forMode_(self.dealloc_timer, NSEventTrackingRunLoopMode)
self.retain()
def deallocTimer_(self, timer):
if self.dealloc_timer:
self.dealloc_timer.invalidate()
self.dealloc_timer = None
self.release()
@objc.python_method
def _set_username_and_domain(self):
# save username and domain to speed up name lookups in the contacts list
uri_string = self.uri
if '@' in uri_string:
self.username = uri_string.partition("@")[0]
self.username = sip_prefix_pattern.sub("", self.username)
domain = uri_string.partition("@")[-1]
self.domain = domain if ':' not in domain else domain.partition(":")[0]
else:
self.username = uri_string.partition(":")[0] if ':' in uri_string else uri_string
default_account = AccountManager().default_account
self.domain = default_account.id.domain if default_account is not None and default_account is not BonjourAccount() else ''
def copyWithZone_(self, zone):
return self
@objc.python_method
def __str__(self):
return "<%s: %s>" % (self.__class__.__name__, self.uri)
__repr__ = __str__
@objc.python_method
def __contains__(self, text):
text = text.lower()
return any(text in item for item in chain((uri.uri.lower() for uri in self.uris), (self.name.lower(),)))
@objc.python_method
def split_uri(self, uri):
if isinstance(uri, (FrozenSIPURI, SIPURI)):
return (uri.user or '', uri.host or '')
elif '@' in uri:
uri = sip_prefix_pattern.sub("", uri)
user, _, host = uri.partition("@")
host = host.partition(":")[0]
return (user, host)
else:
user = uri.partition(":")[0] if uri else ''
return (user, '')
@objc.python_method
def matchesURI(self, uri, exact_match=False):
if isinstance(uri, SIPURI):
uri = '%s@%s' % (uri.user.decode(), uri.host.decode())
def match(me, candidate, exact_match=False):
# check exact match
if not len(candidate[1]):
if me[0].startswith(candidate[0]):
return True
else:
if (me[0], me[1]) == (candidate[0], candidate[1]):
return True
if exact_match:
return False
# check when a phone number, if the end matches
# remove special characters used by Address Book contacts
me_username=strip_addressbook_special_characters(me[0])
# remove leading plus if present
me_username = me_username.lstrip("+")
# first strip leading + from the candidate
candidate_username = candidate[0].lstrip("+")
# then strip leading 0s from the candidate
candidate_username = candidate_username.lstrip("0")
# now check if they're both numbers
if any(d not in "1234567890" for d in me_username + candidate_username) or not me_username or not candidate_username:
return False
# check if the trimmed candidate matches the end of the username if the number is long enough
return len(candidate_username) > 7 and me_username.endswith(candidate_username)
candidate = self.split_uri(uri)
if match((self.username, self.domain), candidate, exact_match):
return True
if hasattr(self, 'organization'):
if self.organization is not None and str(uri).lower() in self.organization.lower():
return True
if hasattr(self, 'job_title'):
if self.job_title is not None and str(uri).lower() in self.job_title.lower():
return True
if hasattr(self, 'note'):
if self.note is not None and str(uri).lower() in self.note.lower():
return True
try:
return any(match(self.split_uri(item.uri), candidate, exact_match) for item in self.uris if item.uri)
except TypeError:
return False
@implementer(IObserver)
class BlinkConferenceContact(BlinkContact):
"""Contact representation for conference drawer UI"""
def __init__(self, uri, name=None, icon=None, presence_contact=None):
objc.super(BlinkConferenceContact, self).__init__(uri, name=name, icon=icon)
self.active_media = []
self.screensharing_url = None
self.presence_contact = presence_contact
if presence_contact is not None:
NotificationCenter().add_observer(self, name="BlinkContactPresenceHasChanged", sender=self.presence_contact)
self.presence_note = None
self.updatePresenceState()
def setPresenceContact_(self, presence_contact):
if self.presence_contact is None and presence_contact is not None:
NotificationCenter().add_observer(self, name="BlinkContactPresenceHasChanged", sender=presence_contact)
elif self.presence_contact is not None and presence_contact is None:
NotificationCenter().remove_observer(self, name="BlinkContactPresenceHasChanged", sender=self.presence_contact)
self.presence_contact = presence_contact
self.updatePresenceState()
@objc.python_method
@run_in_gui_thread
def destroy(self):
if self.presence_contact is not None:
NotificationCenter().remove_observer(self, name="BlinkContactPresenceHasChanged", sender=self.presence_contact)
self.presence_contact = None
objc.super(BlinkConferenceContact, self).destroy()
@objc.python_method
@run_in_gui_thread
def handle_notification(self, notification):
handler = getattr(self, '_NH_%s' % notification.name, Null)
handler(notification)
@objc.python_method
def _NH_BlinkContactPresenceHasChanged(self, notification):
self.updatePresenceState()
@objc.python_method
def init_presence_state(self):
self.presence_state = { 'presence_notes': [],
'status': { 'available': False,
'away': False,
'busy': False
}
}
@objc.python_method
def setPresenceNote(self):
presence_notes = self.presence_state['presence_notes']
if presence_notes:
if self.presence_note is None:
self.presence_note = presence_notes[0]
else:
try:
index = presence_notes.index(self.presence_note)
except ValueError:
self.presence_note = presence_notes[0]
else:
try:
self.presence_note = presence_notes[index+1]
except IndexError:
self.presence_note = presence_notes[0]
detail = self.presence_note if self.presence_note else '%s' % self.uri
else:
detail = '%s' % self.uri
if detail != self.detail:
self.detail = detail
@objc.python_method
@run_in_gui_thread
def updatePresenceState(self):
self.init_presence_state()
if self.presence_contact is None:
return
pidfs = []
try:
pidfs = self.presence_contact.pidfs
except KeyError:
pass
presence_notes = []
basic_status = 'closed'
for pidf in pidfs:
if basic_status == 'closed':
basic_status = 'open' if any(service for service in pidf.services if service.status.basic == 'open') else 'closed'
if self.presence_state['status']['available'] is False:
self.presence_state['status']['available'] = any(service for service in pidf.services if service.status.extended == 'available' or (service.status.extended == None and basic_status == 'open'))
if self.presence_state['status']['busy'] is False:
self.presence_state['status']['busy'] = any(service for service in pidf.services if service.status.extended == 'busy')
if self.presence_state['status']['away'] is False:
self.presence_state['status']['away'] = any(service for service in pidf.services if service.status.extended == 'away')
presence_notes = (note for service in pidf.services for note in service.notes if note)
pidfs = None
notes = list(str(note) for note in presence_notes)
self.presence_state['presence_notes'] = notes
self.setPresenceNote()
NotificationCenter().post_notification("BlinkConferenceContactPresenceHasChanged", sender=self)
class BlinkHistoryViewerContact(BlinkConferenceContact):
pass
class BlinkMyselfConferenceContact(BlinkContact):
"""Contact representation for conference drawer UI for myself"""
def __init__(self, account, name=None):
if account is BonjourAccount():
uri = '%s@%s' % (account.uri.user.decode(), account.uri.host.decode())
else:
uri = '%s@%s' % (account.id.username, account.id.domain)
self.account = account
own_icon = None
path = NSApp.delegate().contactsWindowController.iconPathForSelf()
if path:
own_icon = NSImage.alloc().initWithContentsOfFile_(path)
name = name or account.display_name or uri
objc.super(BlinkMyselfConferenceContact, self).__init__(uri, name=name, icon=own_icon)
self.active_media = []
self.screensharing_url = None
self.presence_note = None
class BlinkPendingWatcher(BlinkContact):
"""Contact representation for a pending watcher"""
editable = False
deletable = False
def __init__(self, watcher):
uri = sip_prefix_pattern.sub('', watcher.sipuri)
objc.super(BlinkPendingWatcher, self).__init__(uri, name=watcher.display_name)
self.avatar = PendingWatcherAvatar()
class BlinkBlockedPresenceContact(BlinkContact):
"""Contact representation for a blocked policy contact"""
editable = False
deletable = True
def __init__(self, policy):
self.policy = policy
uri = policy.uri
name = policy.name
objc.super(BlinkBlockedPresenceContact, self).__init__(uri, name=name)
self.avatar = BlockedPolicyAvatar()
@objc.python_method
@run_in_gui_thread
def destroy(self):
self.policy = None
objc.super(BlinkBlockedPresenceContact, self).destroy()
class BlinkPresenceContactAttribute(object):
def __init__(self, name):
self.name = name
def __get__(self, obj, objtype):
if obj is None:
return self
try:
return getattr(obj.contact, self.name, None)
except AttributeError:
return None
def __set__(self, obj, value):
if obj.contact is not None:
setattr(obj.contact, self.name, value)
obj.contact.save()
@implementer(IObserver)
class BlinkPresenceContact(BlinkContact):
"""Contact representation with Presence Enabled"""
auto_answer = BlinkPresenceContactAttribute('auto_answer')
name = BlinkPresenceContactAttribute('name')
uris = BlinkPresenceContactAttribute('uris')
organization = BlinkPresenceContactAttribute('organization')
def __init__(self, contact, log_presence_transitions=False):
self.log_presence_transitions = log_presence_transitions
self.contact = contact
self.old_devices = []
self.avatar = PresenceContactAvatar.from_contact(contact)
# TODO: how to handle xmmp: uris?
#uri = self.uri.replace(';xmpp', '') if self.uri_type is not None and self.uri_type.lower() == 'xmpp' and ';xmpp' in self.uri else self.uri
self.detail = '%s (%s)' % (self.uri, self.uri_type)
self._set_username_and_domain()
self.presence_note = None
self.old_presence_status = None
self.old_presence_note = None
self.old_resource_state = None
self.pidfs_map = {}
self.init_presence_state()
self.timer = None
self.application_will_end = False
NotificationCenter().add_observer(self, name="SIPAccountDidDeactivate")
NotificationCenter().add_observer(self, name="CFGSettingsObjectDidChange")
NotificationCenter().add_observer(self, name="SIPApplicationWillEnd")
NotificationCenter().add_observer(self, name="SystemDidWakeUpFromSleep")
NotificationCenter().add_observer(self, name="BlinkPresenceFailed")
@property
def id(self):
return self.contact.id
@property
def uri(self):
if self.default_uri is not None:
return self.default_uri.uri
try:
uri = next(iter(self.contact.uris))
except (StopIteration, AttributeError):
return ''
else:
return uri.uri
@property
def uri_type(self):
if self.default_uri is not None:
return self.default_uri.type or 'SIP'
try:
uri = next(iter(self.contact.uris))
except (StopIteration, AttributeError):
return 'SIP'
else:
return uri.type or 'SIP'
@property
def pidfs(self):
pidfs = set()
for key in list(self.pidfs_map.keys()):
for account in list(self.pidfs_map[key].keys()):
pidfs_for_account = self.pidfs_map[key][account]
found = False
for pidf in pidfs_for_account:
for old_pidf in pidfs:
if old_pidf == pidf:
found = True
if not found:
pidfs.add(pidf)
return pidfs
def _get_favorite(self):
addressbook_manager = AddressbookManager()
try:
group = addressbook_manager.get_group('favorites')
except KeyError:
return False
else:
return self.contact.id in group.contacts
def _set_favorite(self, value):
addressbook_manager = AddressbookManager()
try:
group = addressbook_manager.get_group('favorites')
except KeyError:
group = Group(id='favorites')
group.name = 'Favorites'
group.expanded = True
group.position = None
group.save()
operation = group.contacts.add if value else group.contacts.remove
try:
operation(self.contact)
except ValueError:
pass
else:
group.save()
favorite = property(_get_favorite, _set_favorite)
del _get_favorite, _set_favorite
def _get_preferred_media(self):
uri = str(self.uri)
if not uri.startswith(('sip:', 'sips:')):
uri = 'sip:'+uri
try:
uri = SIPURI.parse(uri)
except SIPCoreError:
return self.contact.preferred_media
else:
return uri.parameters.get('session-type', self.contact.preferred_media)
def _set_preferred_media(self, value):
self.contact.preferred_media = value
self.contact.save()
preferred_media = property(_get_preferred_media, _set_preferred_media)
del _get_preferred_media, _set_preferred_media
def _get_default_uri(self):
try:
return self.contact.uris.default if self.contact is not None else None
except AttributeError:
return None
def _set_default_uri(self, value):
self.contact.uris.default = value
self.contact.save()
default_uri = property(_get_default_uri, _set_default_uri)
del _get_default_uri, _set_default_uri
@objc.python_method
def account_has_pidfs_for_uris(self, account, uris):
for key in (key for key in self.pidfs_map.keys() if key in uris):
if account in self.pidfs_map[key]:
return True
return False
@objc.python_method
def init_presence_state(self):
self.presence_state = { 'pending_authorizations': {},
'status': { 'available': False,
'away': False,
'busy': False,
'offline': False
},
'devices': {},
'urls': [],
'time_offset': None
}
def presenceNoteTimer_(self, timer):
self.setPresenceNote()
@objc.python_method
def clone_presence_state(self, other=None):
if not NSApp.delegate().contactsWindowController.ready:
return
model = NSApp.delegate().contactsWindowController.model
if other is None:
try:
other = next(item for item in model.all_contacts_group.contacts if item.contact == self.contact)
except StopIteration:
return
self.pidfs_map = other.pidfs_map.copy()
self.presence_state = other.presence_state.copy()
self.presence_note = other.presence_note
self.setPresenceNote()
if other.timer is not None and other.timer.isValid():
self.timer = NSTimer.timerWithTimeInterval_target_selector_userInfo_repeats_(10.0, self, "presenceNoteTimer:", None, True)
NSRunLoop.currentRunLoop().addTimer_forMode_(self.timer, NSRunLoopCommonModes)
NSRunLoop.currentRunLoop().addTimer_forMode_(self.timer, NSEventTrackingRunLoopMode)
@objc.python_method
@run_in_gui_thread
def destroy(self):
NotificationCenter().discard_observer(self, name="SIPAccountDidDeactivate")
NotificationCenter().discard_observer(self, name="CFGSettingsObjectDidChange")
NotificationCenter().discard_observer(self, name="SIPApplicationWillEnd")
NotificationCenter().discard_observer(self, name="BlinkPresenceFailed")
NotificationCenter().discard_observer(self, name="SystemDidWakeUpFromSleep")
#NotificationCenter().discard_observer(self, name="SIPAccountGotPresenceState")
if self.timer:
self.timer.invalidate()
self.timer = None
self.pidfs_map = {}
objc.super(BlinkPresenceContact, self).destroy()
@objc.python_method
@run_in_gui_thread
def reloadModelItem(self, item):
NSApp.delegate().contactsWindowController.model.contactOutline.reloadItem_reloadChildren_(item, True)
@objc.python_method
def purge_pidfs_for_account(self, account):
changes = False
for key, value in self.pidfs_map.copy().items():
for acc in list(value.keys()):
if acc == account:
try:
del self.pidfs_map[key][account]
except KeyError:
pass
else:
changes = True
for key, value in self.pidfs_map.copy().items():
if not value:
try:
del self.pidfs_map[key]
except KeyError:
pass
else:
changes = True
self.handle_pidfs()
if changes:
if type(self) is BlinkOnlineContact:
if not self.pidfs_map:
NotificationCenter().post_notification("BlinkOnlineContactMustBeRemoved", sender=self)
else:
NotificationCenter().post_notification("BlinkContactsHaveChanged", sender=self)
else:
NotificationCenter().post_notification("BlinkContactsHaveChanged", sender=self)
@objc.python_method
def handle_presence_resources(self, resources, account, full_state=False):
if self.application_will_end:
return
changes = False
if not self.contact:
return changes
old_pidfs = self.pidfs
resources_uris = set()
for uri, resource in resources.items():
if not resource.pidf_list:
#BlinkLogger().log_info('PIDF list for %s is empty' % uri)
pass
uri_text = sip_prefix_pattern.sub('', uri)
try:
SIPURI.parse(str('sip:%s' % uri_text))
except SIPCoreError:
continue
resources_uris.add(uri_text)
if self.log_presence_transitions:
model = NSApp.delegate().contactsWindowController.model
if resource.state == 'pending':
self.presence_state['pending_authorizations'][str(resource.uri)] = account
if self.old_resource_state != resource.state:
contacts_for_subscription = model.getBlinkContactsForURI(str(resource.uri))
if not contacts_for_subscription:
BlinkLogger().log_error("We have no contact for subscription of %s to %s" % (account, uri_text))
else:
BlinkLogger().log_debug("Subscription from %s for account %s is pending" % (account, uri_text))
elif resource.state == 'terminated':
contacts_for_subscription = model.getBlinkContactsForURI(str(resource.uri))
if self.old_resource_state != resource.state:
if not contacts_for_subscription:
BlinkLogger().log_error("We have no contact for subscription of %s to %s" % (account, uri_text))
else:
BlinkLogger().log_debug("Availability subscription from %s to %s is terminated" % (account, uri_text))
self.old_resource_state = resource.state
old_pidf_list_for_uri = []
if uri not in list(self.pidfs_map.keys()):
self.pidfs_map[uri] = {}
try:
old_pidf_list_for_uri = self.pidfs_map[uri][account]
except KeyError:
if resource.pidf_list:
#BlinkLogger().log_info('Presence changed, added pidfs for %s: %s' % (uri, resource.pidf_list))
self.pidfs_map[uri][account] = resource.pidf_list
changes = True
else:
if old_pidf_list_for_uri != resource.pidf_list:
#BlinkLogger().log_info('Presence changed, updated pidfs for %s: %s' % (uri, resource.pidf_list))
self.pidfs_map[uri][account] = resource.pidf_list
changes = True