-
Notifications
You must be signed in to change notification settings - Fork 231
Expand file tree
/
Copy pathAccountController.m
More file actions
911 lines (737 loc) · 37.9 KB
/
AccountController.m
File metadata and controls
911 lines (737 loc) · 37.9 KB
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
//
// AccountController.m
// Telephone
//
// Copyright © 2008-2016 Alexey Kuznetsov
// Copyright © 2016-2022 64 Characters
//
// Telephone is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// Telephone is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
#import "AccountController.h"
@import AddressBook;
@import UseCases;
#import "AKABAddressBook+Localizing.h"
#import "AKKeychain.h"
#import "AKNetworkReachability.h"
#import "AKNSString+Scanning.h"
#import "AKSIPURIFormatter.h"
#import "AKTelephoneNumberFormatter.h"
#import "AccountControllerToAccountAdapter.h"
#import "AccountViewController.h"
#import "AccountWindowController.h"
#import "ActiveAccountViewController.h"
#import "AuthenticationFailureController.h"
#import "CallTransferController.h"
#import "SIPResponseLocalization.h"
#import "Telephone-Swift.h"
NSString * const kEmailSIPLabel = @"sip";
static NSString * const kRussian = @"ru";
@interface AccountController () <AccountWindowControllerDelegate>
@property(nonatomic) AKNetworkReachability *registrarReachability;
@property(nonatomic, readonly) AKSIPUserAgent *userAgent;
@property(nonatomic, readonly) WorkspaceSleepStatus *sleepStatus;
@property(nonatomic, readonly) AuthenticationFailureController *authenticationFailureController;
@property(nonatomic, readonly) AccountViewController *accountViewController;
@property(nonatomic, readonly) AccountWindowController *windowController;
@property(nonatomic, readonly, getter=isAccountAdded) BOOL accountAdded;
@property(nonatomic, strong) NSTimer *reRegistrationTimer;
@property(nonatomic, copy) NSString *destinationToCall;
@end
@implementation AccountController
@synthesize authenticationFailureController = _authenticationFailureController;
- (void)setEnabled:(BOOL)flag {
_enabled = flag;
NSNotificationCenter *notificationCenter = [NSNotificationCenter defaultCenter];
if (flag) {
AKNetworkReachability *reachability
= [AKNetworkReachability networkReachabilityWithHost:self.account.registrar.host];
[self setRegistrarReachability:reachability];
if (reachability != nil) {
[notificationCenter addObserver:self
selector:@selector(networkReachabilityDidBecomeReachable:)
name:AKNetworkReachabilityDidBecomeReachableNotification
object:reachability];
}
} else {
if ([self registrarReachability] != nil) {
[notificationCenter removeObserver:self
name:AKNetworkReachabilityDidBecomeReachableNotification
object:[self registrarReachability]];
[self setRegistrarReachability:nil];
}
}
}
- (BOOL)isAccountRegistered {
return [[self account] isRegistered];
}
- (void)setAccountRegistered:(BOOL)flag {
[self invalidateReRegistrationTimer];
if ([self isAccountAdded]) {
[self showConnectingState];
[[self account] setRegistered:flag];
} else {
NSString *serviceName = [NSString stringWithFormat:@"SIP: %@", [[self account] registrar]];
NSString *password = [AKKeychain passwordForService:serviceName account:[[self account] username]];
[self showConnectingState];
BOOL accountAdded = [[self userAgent] addAccount:[self account] withPassword:password];
// Error connecting to registrar.
if (accountAdded &&
![self isAccountRegistered] &&
[[self account] registrationExpireTime] == kAKSIPAccountRegistrationExpireTimeNotSpecified &&
[[self userAgent] isStarted]) {
[self showUnavailableState];
// Schedule account automatic re-registration timer.
if ([self reRegistrationTimer] == nil) {
NSTimeInterval reregistrationTimeInterval = (NSTimeInterval)[[self account] reregistrationTime];
[self setReRegistrationTimer:
[NSTimer scheduledTimerWithTimeInterval:reregistrationTimeInterval
target:self
selector:@selector(reRegistrationTimerTick:)
userInfo:nil
repeats:YES]];
}
if ([self shouldPresentRegistrationError]) {
NSString *statusText;
NSString *preferredLocalization = [[NSBundle mainBundle] preferredLocalizations][0];
if ([preferredLocalization isEqualToString:kRussian]) {
statusText = LocalizedStringForSIPResponseCode([[self account] registrationStatus]);
} else {
statusText = [[self account] registrationStatusText];
}
NSString *error;
if (statusText == nil) {
error = [NSString stringWithFormat:
NSLocalizedString(@"Error %ld", @"Error #."),
[[self account] registrationStatus]];
error = [error stringByAppendingString:@"."];
} else {
error = [NSString stringWithFormat:
NSLocalizedString(@"The error was: “%ld %@”.", @"Error description."),
[[self account] registrationStatus], statusText];
}
[self showRegistrarConnectionErrorSheetWithError:error];
}
[self setShouldPresentRegistrationError:NO];
}
}
}
- (BOOL)isAccountAdded {
return self.account.identifier != kAKSIPUserAgentInvalidIdentifier;
}
- (AuthenticationFailureController *)authenticationFailureController {
if (_authenticationFailureController == nil) {
_authenticationFailureController
= [[AuthenticationFailureController alloc] initWithAccountController:self userAgent:self.userAgent];
}
return _authenticationFailureController;
}
- (BOOL)canMakeCalls {
return self.windowController.allowsCallDestinationInput;
}
- (instancetype)initWithSIPAccount:(AKSIPAccount *)account
accountDescription:(NSString *)accountDescription
userAgent:(AKSIPUserAgent *)userAgent
ringtonePlayback:(id<RingtonePlaybackUseCase>)ringtonePlayback
sleepStatus:(WorkspaceSleepStatus *)sleepStatus
callHistoryViewEventTargetFactory:(AsyncCallHistoryViewEventTargetFactory *)callHistoryViewEventTargetFactory
purchaseCheckUseCaseFactory:(AsyncCallHistoryPurchaseCheckUseCaseFactory *)purchaseCheckUseCaseFactory
storeWindowPresenter:(StoreWindowPresenter *)storeWindowPresenter{
self = [super init];
if (self == nil) {
return nil;
}
_account = account;
_account.delegate = self;
_userAgent = userAgent;
_ringtonePlayback = ringtonePlayback;
_sleepStatus = sleepStatus;
_callControllers = [[NSMutableArray alloc] init];
_accountDescription = [accountDescription copy];
_destinationToCall = @"";
_accountViewController
= [[AccountViewController alloc] initWithActiveAccountViewController:[[ActiveAccountViewController alloc] initWithAccountController:self]
callHistoryViewController:[[CallHistoryViewController alloc] init]
callHistoryViewEventTargetFactory:callHistoryViewEventTargetFactory
purchaseCheckUseCaseFactory:purchaseCheckUseCaseFactory
account:[[AccountControllerToAccountAdapter alloc] initWithController:self]
storeWindowPresenter:storeWindowPresenter];
_windowController = [[AccountWindowController alloc] initWithAccountDescription:_accountDescription
SIPAddress:_account.SIPAddress
accountViewController:_accountViewController
delegate:self];
[[NSNotificationCenter defaultCenter] addObserver:self
selector:@selector(SIPUserAgentDidFinishStarting:)
name:AKSIPUserAgentDidFinishStartingNotification
object:nil];
return self;
}
- (void)dealloc {
for (CallController *aCallController in [self callControllers]) {
[aCallController close];
}
if ([[[self account] delegate] isEqual:self]) {
[[self account] setDelegate:nil];
}
[[NSNotificationCenter defaultCenter] removeObserver:self];
// Close authentication failure sheet if it's raised.
[[_authenticationFailureController cancelButton] performClick:nil];
}
- (NSString *)description {
return [NSString stringWithFormat:@"%@ controller", [self account]];
}
- (void)registerAccount {
if (![[self userAgent] isStarted]) {
[self setAttemptingToRegisterAccount:YES];
}
[self setAccountRegistered:YES];
}
- (void)unregisterAccount {
if (![self isAccountAdded]) {
[self setAttemptingToUnregisterAccount:YES];
}
[self setAccountRegistered:NO];
}
- (void)removeAccountFromUserAgent {
NSAssert([self isEnabled], @"Account conroller must be enabled to remove account from the user agent.");
[self invalidateReRegistrationTimer];
[self showOfflineState];
[[self userAgent] removeAccount:[self account]];
}
- (void)makeCallToURI:(AKSIPURI *)destinationURI
phoneLabel:(NSString *)phoneLabel
callTransferController:(CallTransferController *)callTransferController {
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
AKTelephoneNumberFormatter *telephoneNumberFormatter = [[AKTelephoneNumberFormatter alloc] init];
[telephoneNumberFormatter setSplitsLastFourDigits:
[defaults boolForKey:UserDefaultsKeys.telephoneNumberFormatterSplitsLastFourDigits]];
NSString *enteredCallDestinationString = [[destinationURI user] copy];
// Make user part a string of contiguous digits if needed.
if (![[destinationURI user] ak_hasLetters]) {
[destinationURI setUser:[telephoneNumberFormatter telephoneNumberFromString:[destinationURI user]]];
}
// Replace plus character if needed.
if ([self substitutesPlusCharacter] &&
[[destinationURI user] hasPrefix:@"+"]) {
[destinationURI setUser:[[destinationURI user]
stringByReplacingCharactersInRange:NSMakeRange(0, 1)
withString:[self plusCharacterSubstitution]]];
enteredCallDestinationString = [enteredCallDestinationString
stringByReplacingCharactersInRange:NSMakeRange(0, 1)
withString:[self plusCharacterSubstitution]];
}
// If it's a regular call, not a transfer, create the new CallController.
CallController *aCallController;
if (callTransferController == nil) {
aCallController = [[CallController alloc] initWithWindowNibName:@"Call"
accountController:self
userAgent:self.userAgent
delegate:self];
} else {
aCallController = callTransferController;
}
[aCallController setNameFromAddressBook:[destinationURI displayName]];
[aCallController setPhoneLabelFromAddressBook:phoneLabel];
[aCallController setEnteredCallDestination:enteredCallDestinationString];
[[self callControllers] addObject:aCallController];
// Set title.
if ([[destinationURI host] length] > 0) {
[aCallController setTitle:[destinationURI SIPAddress]];
} else if (![enteredCallDestinationString ak_hasLetters]) {
if ([enteredCallDestinationString ak_isTelephoneNumber] && [defaults boolForKey:UserDefaultsKeys.formatTelephoneNumbers]) {
[aCallController setTitle:[telephoneNumberFormatter stringForObjectValue:enteredCallDestinationString]];
} else {
[aCallController setTitle:enteredCallDestinationString];
}
} else {
[aCallController setTitle:[[SIPAddress alloc] initWithUser:destinationURI.user host:self.account.uri.host].stringValue];
}
// Set displayed name.
if ([[destinationURI displayName] length] > 0) {
[aCallController setDisplayedName:[destinationURI displayName]];
} else {
if ([[destinationURI host] length] > 0) {
[aCallController setDisplayedName:[destinationURI SIPAddress]];
} else if ([enteredCallDestinationString ak_isTelephoneNumber] &&
[defaults boolForKey:UserDefaultsKeys.formatTelephoneNumbers]) {
[aCallController setDisplayedName:
[telephoneNumberFormatter stringForObjectValue:enteredCallDestinationString]];
} else {
[aCallController setDisplayedName:enteredCallDestinationString];
}
}
// Clean display-name part of the destination URI to prevent another call
// party from seeing local Address Book records.
[destinationURI setDisplayName:@""];
if ([[destinationURI host] length] == 0) {
[destinationURI setHost:[[[self account] uri] host]];
}
// Set URI for redial.
[aCallController setRedialURI:destinationURI];
[aCallController prepareForCall];
if ([phoneLabel length] > 0) {
[aCallController setStatus:
[NSString stringWithFormat:NSLocalizedString(@"calling %@...",
@"Outgoing call in progress. Calling specific phone "
"type (mobile, home, etc)."), phoneLabel]];
} else {
[aCallController setStatus:NSLocalizedString(@"calling...", @"Outgoing call in progress.")];
}
if (callTransferController == nil) {
[aCallController showWindow:self];
}
// Finally, make a call.
[self.account makeCallTo:destinationURI completion:^(AKSIPCall *call) {
if (call != nil) {
[aCallController setCall:call];
[aCallController setCallActive:YES];
} else {
[aCallController showEndedCallView];
[aCallController setStatus:NSLocalizedString(@"Call Failed", @"Call failed.")];
}
}];
}
- (void)makeCallToURI:(AKSIPURI *)destinationURI phoneLabel:(NSString *)phoneLabel {
if (self.isAccountAdded) {
[self makeCallToURI:destinationURI phoneLabel:phoneLabel callTransferController:nil];
}
}
- (void)makeCallToDestinationRegisteringAccountIfNeeded:(SanitizedCallDestination *)destination {
if (![self isAccountAdded]) {
[self setDestinationToCall:destination.value];
[self registerAccount];
} else {
[self makeCallToDestination:destination.value];
}
}
- (void)makeCallToDestination:(NSString *)destination {
[self.windowController makeCallToDestination:destination];
}
- (void)makeCallToSavedDestination {
[self makeCallToDestination:[self destinationToCall]];
[self setDestinationToCall:@""];
}
- (void)showWindow {
[self.windowController showWindow:self];
}
- (void)showWindowWithoutMakingKey {
[self.windowController showWindowWithoutMakingKey];
}
- (void)hideWindow {
[self.windowController hideWindow];
}
- (BOOL)isWindowKey {
return self.windowController.isWindowKey;
}
- (void)orderWindow:(NSWindowOrderingMode)place relativeTo:(NSInteger)otherWindow {
[self.windowController orderWindow:place relativeTo:otherWindow];
}
- (NSInteger)windowNumber {
return self.windowController.windowNumber;
}
- (void)changeAccountState:(AccountWindowControllerAccountState)state {
[self invalidateReRegistrationTimer];
switch (state) {
case AccountWindowControllerAccountStateOffline:
self.accountUnavailable = NO;
[self removeAccountFromUserAgent];
break;
case AccountWindowControllerAccountStateAvailable:
self.accountUnavailable = NO;
self.shouldPresentRegistrationError = YES;
[self registerAccount];
break;
case AccountWindowControllerAccountStateUnavailable:
if (self.isAccountRegistered || !self.isAccountAdded) {
self.accountUnavailable = YES;
self.shouldPresentRegistrationError = YES;
[self unregisterAccount];
}
break;
}
}
- (void)showRegistrarConnectionErrorSheetWithError:(NSString *)error {
NSAlert *alert = [[NSAlert alloc] init];
[alert setMessageText:[NSString stringWithFormat:
NSLocalizedString(@"Could not register with %@.", @"Registrar connection error."),
[[self account] registrar]]];
if (error == nil) {
[alert setInformativeText:
[NSString stringWithFormat:
NSLocalizedString(@"Please check network connection and Registry Server settings.",
@"Registrar connection error informative text."),
[[self account] registrar]]];
} else {
[alert setInformativeText:error];
}
[self.windowController showAlert:alert];
}
- (void)showAvailableState {
[self.windowController showAvailableState];
}
- (void)showUnavailableState {
[self.windowController showUnavailableState];
}
- (void)showOfflineState {
[self.windowController showOfflineState];
}
- (void)showConnectingState {
[self.windowController showConnectingState];
}
- (void)reRegistrationTimerTick:(NSTimer *)theTimer {
[[self account] setRegistered:YES];
}
- (void)invalidateReRegistrationTimer {
[self.reRegistrationTimer invalidate];
self.reRegistrationTimer = nil;
}
#pragma mark - AccountWindowControllerDelegate
- (void)accountWindowController:(AccountWindowController *)controller didChangeAccountState:(AccountWindowControllerAccountState)state {
[self changeAccountState:state];
}
#pragma mark - AKSIPAccountDelegate
// When account registration changes, make appropriate modifications to the UI. A call can also be made from here if
// the user called from the Address Book or from the application URL handler.
- (void)SIPAccountRegistrationDidChange:(AKSIPAccount *)account {
// The account can be not added if notification on the main thread was delivered after
// user agent had removed the account. Don't bother in that case.
if (![self isAccountAdded]) {
return;
}
if ([[self account] isRegistered]) {
[self invalidateReRegistrationTimer];
// If the account was offline and the user chose Unavailable state, -unregisterAccount will add the account
// to the user agent. User agent will register the account. Set the account to Unavailable (unregister it) here.
if ([self attemptingToUnregisterAccount]) {
[self unregisterAccount];
} else {
[self setAccountUnavailable:NO];
[self showAvailableState];
if ([[self destinationToCall] length] > 0) {
[self makeCallToSavedDestination];
}
}
} else {
[self showUnavailableState];
// Handle authentication failure
if ([[self account] registrationStatus] == PJSIP_SC_UNAUTHORIZED &&
[[self account] registrationErrorCode] == PJSIP_EFAILEDCREDENTIAL) {
[[[self authenticationFailureController] informativeText] setStringValue:
[NSString stringWithFormat:
NSLocalizedString(@"Telephone was unable to login to %@. "
"Change user name or password and try again.",
@"Registrar authentication failed."),
[[self account] registrar]]];
NSString *service = [NSString stringWithFormat:@"SIP: %@", [[self account] registrar]];
NSString *password = [AKKeychain passwordForService:service account:[[self account] username]];
[[[self authenticationFailureController] usernameField] setStringValue:[[self account] username]];
[[[self authenticationFailureController] passwordField] setStringValue:password];
[[self windowController] beginSheet:[[self authenticationFailureController] window]];
} else if (([[self account] registrationStatus] / 100 != 2) &&
([[self account] registrationExpireTime] == kAKSIPAccountRegistrationExpireTimeNotSpecified)) {
// Raise a sheet if connection to the registrar failed. If last registration status is 2xx and expiration
// interval is not specified, it is unregistration, not failure. Condition of failure is: last registration
// status != 2xx AND expiration interval is not specified.
if ([[self userAgent] isStarted]) {
if ([self shouldPresentRegistrationError]) {
NSString *statusText;
NSString *preferredLocalization = [[NSBundle mainBundle] preferredLocalizations][0];
if ([preferredLocalization isEqualToString:kRussian]) {
statusText = LocalizedStringForSIPResponseCode([[self account] registrationStatus]);
} else {
statusText = [[self account] registrationStatusText];
}
NSString *error;
if (statusText == nil) {
error = [NSString stringWithFormat:NSLocalizedString(@"Error %ld", @"Error #."),
[[self account] registrationStatus]];
error = [error stringByAppendingString:@"."];
} else {
error = [NSString stringWithFormat:
NSLocalizedString(@"The error was: “%ld %@”.", @"Error description."),
[[self account] registrationStatus], statusText];
}
[self showRegistrarConnectionErrorSheetWithError:error];
} else {
// Schedule account automatic re-registration timer.
if ([self reRegistrationTimer] == nil) {
NSTimeInterval reregistrationTimeInterval = (NSTimeInterval)[[self account] reregistrationTime];
[self setReRegistrationTimer:
[NSTimer scheduledTimerWithTimeInterval:reregistrationTimeInterval
target:self
selector:@selector(reRegistrationTimerTick:)
userInfo:nil
repeats:YES]];
}
}
}
}
}
[self setAttemptingToRegisterAccount:NO];
[self setAttemptingToUnregisterAccount:NO];
[self setShouldPresentRegistrationError:NO];
}
- (void)SIPAccountWillRemove:(AKSIPAccount *)account {
[self invalidateReRegistrationTimer];
}
- (void)SIPAccount:(AKSIPAccount *)account didReceiveCall:(AKSIPCall *)aCall {
if ([self isAccountUnavailable]) {
// Reply with 480 Temporarily Unavailable if the user selected Unavailable account state.
[aCall replyWithTemporarilyUnavailable];
return;
} else if (![[NSUserDefaults standardUserDefaults] boolForKey:UserDefaultsKeys.callWaiting]) {
// Reply with 486 Busy Here if needed.
for (CallController *callController in [self callControllers]) {
if ([callController isCallActive]) {
[aCall replyWithBusyHere];
return;
}
}
}
CallController *aCallController = [[CallController alloc] initWithWindowNibName:@"Call"
accountController:self
userAgent:self.userAgent
delegate:self];
[aCallController setCall:aCall];
[aCallController setCallActive:YES];
[[self callControllers] addObject:aCallController];
AKSIPURIFormatter *SIPURIFormatter = [[AKSIPURIFormatter alloc] init];
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
[SIPURIFormatter setFormatsTelephoneNumbers:[defaults boolForKey:UserDefaultsKeys.formatTelephoneNumbers]];
[SIPURIFormatter setTelephoneNumberFormatterSplitsLastFourDigits:
[defaults boolForKey:UserDefaultsKeys.telephoneNumberFormatterSplitsLastFourDigits]];
// These variables will be changed during the Address Book search if the record is found.
NSString *finalDisplayedName = [SIPURIFormatter stringForObjectValue:[aCall remoteURI]];
NSString *finalStatus = NSLocalizedString(@"calling",
@"John Smith calling. Somebody is calling us right "
"now. Call status string. Deliberately in lower case, "
"translators should do the same, if possible.");
// Search Address Book for caller's name.
ABAddressBook *AB = [ABAddressBook sharedAddressBook];
NSArray *records = nil;
ABSearchElement *SIPAddressMatch
= [ABPerson searchElementForProperty:kABEmailProperty
label:nil
key:nil
value:[[aCall remoteURI] SIPAddress]
comparison:kABEqualCaseInsensitive];
records = [AB recordsMatchingSearchElement:SIPAddressMatch];
if ([records count] > 0) {
id theRecord = records[0];
finalDisplayedName = [theRecord ak_fullName];
[aCallController setNameFromAddressBook:[theRecord ak_fullName]];
NSString *localizedLabel = [AB ak_localizedLabel:kEmailSIPLabel];
finalStatus = localizedLabel;
[aCallController setPhoneLabelFromAddressBook:localizedLabel];
} else if ([[[aCall remoteURI] displayName] ak_isTelephoneNumber] ||
([[[aCall remoteURI] displayName] length] == 0 &&
[[[aCall remoteURI] user] ak_isTelephoneNumber]))
{ // No SIP Address found, search for the phone number.
NSString *phoneNumberToSearch;
if ([[[aCall remoteURI] displayName] length] > 0) {
phoneNumberToSearch = [[aCall remoteURI] displayName];
} else {
phoneNumberToSearch = [[aCall remoteURI] user];
}
BOOL recordFound = NO;
// Look for the whole phone number match first.
ABSearchElement *phoneNumberMatch
= [ABPerson searchElementForProperty:kABPhoneProperty
label:nil
key:nil
value:phoneNumberToSearch
comparison:kABEqual];
records = [AB recordsMatchingSearchElement:phoneNumberMatch];
if ([records count] > 0) {
recordFound = YES;
id theRecord = records[0];
finalDisplayedName = [theRecord ak_fullName];
[aCallController setNameFromAddressBook:[theRecord ak_fullName]];
// Find the exact phone number match.
ABMultiValue *phones = [theRecord valueForProperty:kABPhoneProperty];
for (NSUInteger i = 0; i < [phones count]; ++i) {
if ([[phones valueAtIndex:i] isEqualToString:phoneNumberToSearch]) {
NSString *localizedLabel = [AB ak_localizedLabel:[phones labelAtIndex:i]];
finalStatus = localizedLabel;
[aCallController setPhoneLabelFromAddressBook:localizedLabel];
break;
}
}
}
NSUInteger significantPhoneNumberLength = [defaults integerForKey:UserDefaultsKeys.significantPhoneNumberLength];
// Get the significant phone suffix if the phone number length is greater
// than we defined.
NSString *significantPhoneSuffix;
if ([phoneNumberToSearch length] >= significantPhoneNumberLength) {
significantPhoneSuffix = [phoneNumberToSearch substringFromIndex:
([phoneNumberToSearch length] - significantPhoneNumberLength)];
// If the the record hasn't been found with the whole number, look for
// significant suffix match.
if (!recordFound) {
ABSearchElement *phoneNumberSuffixMatch
= [ABPerson searchElementForProperty:kABPhoneProperty
label:nil
key:nil
value:significantPhoneSuffix
comparison:kABSuffixMatch];
records = [AB recordsMatchingSearchElement:phoneNumberSuffixMatch];
if ([records count] > 0) {
recordFound = YES;
id theRecord = records[0];
finalDisplayedName = [theRecord ak_fullName];
[aCallController setNameFromAddressBook:[theRecord ak_fullName]];
// Find the exact phone number match.
ABMultiValue *phones = [theRecord valueForProperty:kABPhoneProperty];
for (NSUInteger i = 0; i < [phones count]; ++i) {
if ([[phones valueAtIndex:i] hasSuffix:significantPhoneSuffix]) {
NSString *localizedLabel = [AB ak_localizedLabel:[phones labelAtIndex:i]];
finalStatus = localizedLabel;
[aCallController setPhoneLabelFromAddressBook:localizedLabel];
break;
}
}
}
}
}
// If still not found, search phone numbers that contain spaces, dashes, etc.
if (!recordFound) {
NSArray *allPeople = [AB people];
AKTelephoneNumberFormatter *telephoneNumberFormatter = [[AKTelephoneNumberFormatter alloc] init];
for (id theRecord in allPeople) {
ABMultiValue *phones = [theRecord valueForProperty:kABPhoneProperty];
for (NSUInteger i = 0; i < [phones count]; ++i) {
NSString *phoneNumber = [phones valueAtIndex:i];
// Don't bother if the phone number contains only contiguous
// digits, we should have covered such numbers in previous search.
if ([phoneNumber ak_isTelephoneNumber]) {
continue;
}
// Don't bother if the phone number has letters.
if ([phoneNumber ak_hasLetters]) {
continue;
}
// Here phone number probably includes spaces or other dividers.
// Scan valid phone characters to compare with a given string.
NSString *scannedPhoneNumber = [telephoneNumberFormatter telephoneNumberFromString:phoneNumber];
if ([scannedPhoneNumber isEqualToString:phoneNumberToSearch]) {
recordFound = YES;
} else if (([phoneNumberToSearch length] >= significantPhoneNumberLength) &&
[scannedPhoneNumber hasSuffix:significantPhoneSuffix]) {
recordFound = YES;
}
if (recordFound) {
NSString *localizedLabel = [AB ak_localizedLabel:[phones labelAtIndex:i]];
finalStatus = localizedLabel;
[aCallController setPhoneLabelFromAddressBook:localizedLabel];
break;
}
}
if (recordFound) {
finalDisplayedName = [theRecord ak_fullName];
[aCallController setNameFromAddressBook:[theRecord ak_fullName]];
break;
}
}
}
}
// Address Book search ends here.
[aCallController setTitle:([[aCall remoteURI] SIPAddress] ?: @"")];
[aCallController setDisplayedName:finalDisplayedName];
[aCallController setStatus:finalStatus];
[aCallController setRedialURI:[aCall remoteURI]];
[aCallController showIncomingCallView];
[aCallController showWindow:nil];
// Show user notification.
NSString *callSource;
AKTelephoneNumberFormatter *telephoneNumberFormatter = [[AKTelephoneNumberFormatter alloc] init];
[telephoneNumberFormatter setSplitsLastFourDigits:
[defaults boolForKey:UserDefaultsKeys.telephoneNumberFormatterSplitsLastFourDigits]];
if ([[aCallController phoneLabelFromAddressBook] length] > 0) {
callSource = [aCallController phoneLabelFromAddressBook];
} else if ([[[aCall remoteURI] user] length] > 0) {
if ([[[aCall remoteURI] user] ak_isTelephoneNumber]) {
if ([defaults boolForKey:UserDefaultsKeys.formatTelephoneNumbers]) {
callSource = [telephoneNumberFormatter stringForObjectValue:[[aCall remoteURI] user]];
} else {
callSource = [[aCall remoteURI] user];
}
} else {
callSource = [[aCall remoteURI] SIPAddress];
}
} else {
callSource = [[aCall remoteURI] host];
}
NSString *notificationTitle, *notificationDescription;
if ([[aCallController nameFromAddressBook] length] > 0) {
notificationTitle = [aCallController nameFromAddressBook];
notificationDescription = callSource;
} else if ([[[aCall remoteURI] displayName] length] > 0) {
notificationTitle = [[aCall remoteURI] displayName];
notificationDescription
= [NSString stringWithFormat:
NSLocalizedString(@"calling from %@",
@"John Smith calling from 1234567. "
"Somebody is calling us right now from some source. "
"User notification description. Deliberately in "
"lower case, translators should do the same, if "
"possible."),
callSource];
} else {
notificationTitle = callSource;
notificationDescription
= NSLocalizedString(@"calling",
@"John Smith calling. Somebody is calling us right "
"now. User notification description. "
"Deliberately in lower case, translators should do "
"the same, if possible.");
}
NSUserNotification *userNotification = [[NSUserNotification alloc] init];
userNotification.identifier = aCallController.identifier;
userNotification.title = notificationTitle;
userNotification.informativeText = notificationDescription;
userNotification.actionButtonTitle = NSLocalizedString(@"Answer", @"Call answer button.");
NSString *decline = NSLocalizedString(@"Decline", @"Call decline button.");
userNotification.additionalActions = @[[NSUserNotificationAction actionWithIdentifier:@"decline" title:decline]];
[[NSUserNotificationCenter defaultUserNotificationCenter] deliverNotification:userNotification];
[self startPlayingRingtoneOrLogError];
[aCall sendRingingNotification];
}
- (void)startPlayingRingtoneOrLogError {
NSError *error;
BOOL success = [self.ringtonePlayback startAndReturnError:&error];
if (!success) {
NSLog(@"Could not start playing ringtone: %@", error);
}
}
#pragma mark - CallControllerDelegate
- (void)callControllerWillClose:(CallController *)callController {
[self.callControllers removeObject:callController];
[(AppController *)[NSApp delegate] updateDockTileBadgeLabel];
}
#pragma mark - AKSIPUserAgent notifications
- (void)SIPUserAgentDidFinishStarting:(NSNotification *)notification {
if (![[notification object] isStarted]) {
[self showOfflineState];
return;
}
if ([self attemptingToRegisterAccount]) {
[self registerAccount];
} else if ([self attemptingToUnregisterAccount]) {
[self unregisterAccount];
}
}
#pragma mark - AKNetworkReachability notifications
// This is the moment when the application starts doing its main job.
- (void)networkReachabilityDidBecomeReachable:(NSNotification *)notification {
if (!self.sleepStatus.isSleeping && !self.isAccountUnavailable && !self.isAccountRegistered) {
[self registerAccount];
}
}
@end