Recursively added dot syntax, translating more terms when they were encountered in the dif

FREEBIE
This commit is contained in:
Craig Gidney 2014-09-07 16:31:05 -07:00 committed by Frederic Jacobs
parent f582dd7a24
commit f1de95ab06
98 changed files with 415 additions and 418 deletions

View File

@ -5,6 +5,6 @@
int main(int argc, char *argv[]) int main(int argc, char *argv[])
{ {
@autoreleasepool { @autoreleasepool {
return UIApplicationMain(argc, argv, nil, NSStringFromClass([AppDelegate class])); return UIApplicationMain(argc, argv, nil, NSStringFromClass(AppDelegate.class));
} }
} }

View File

@ -40,8 +40,8 @@
- (void)performUpdateCheck{ - (void)performUpdateCheck{
// We check if NSUserDefaults key for version exists. // We check if NSUserDefaults key for version exists.
NSString *previousVersion = [[Environment preferences] lastRanVersion]; NSString *previousVersion = Environment.preferences.lastRanVersion;
NSString *currentVersion = [[Environment preferences] setAndGetCurrentVersion]; NSString *currentVersion = [Environment.preferences setAndGetCurrentVersion];
if (!previousVersion) { if (!previousVersion) {
DDLogError(@"No previous version found. Possibly first launch since install."); DDLogError(@"No previous version found. Possibly first launch since install.");
@ -69,7 +69,7 @@
NSDictionary *attrs = @{NSFileProtectionKey: NSFileProtectionCompleteUntilFirstUserAuthentication}; NSDictionary *attrs = @{NSFileProtectionKey: NSFileProtectionCompleteUntilFirstUserAuthentication};
[[NSFileManager defaultManager] setAttributes:attrs ofItemAtPath:preferencesPath error:&error]; [[NSFileManager defaultManager] setAttributes:attrs ofItemAtPath:preferencesPath error:&error];
[pathsToExclude addObject:[[preferencesPath stringByAppendingString:[[NSBundle mainBundle] bundleIdentifier]] stringByAppendingString:@".plist"]]; [pathsToExclude addObject:[[preferencesPath stringByAppendingString:NSBundle.mainBundle.bundleIdentifier] stringByAppendingString:@".plist"]];
NSString *logPath = [NSHomeDirectory() stringByAppendingString:@"/Library/Caches/Logs/"]; NSString *logPath = [NSHomeDirectory() stringByAppendingString:@"/Library/Caches/Logs/"];
NSArray *logsFiles = [[NSFileManager defaultManager] contentsOfDirectoryAtPath:logPath error:&error]; NSArray *logsFiles = [[NSFileManager defaultManager] contentsOfDirectoryAtPath:logPath error:&error];
@ -111,7 +111,7 @@
[DebugLogger.sharedInstance enableTTYLogging]; [DebugLogger.sharedInstance enableTTYLogging];
#elif RELEASE #elif RELEASE
loggingIsEnabled = [[Environment preferences] loggingIsEnabled]; loggingIsEnabled = Environment.preferences.loggingIsEnabled;
#endif #endif
if (loggingIsEnabled) { if (loggingIsEnabled) {
@ -121,7 +121,7 @@
[self performUpdateCheck]; [self performUpdateCheck];
[self protectPreferenceFiles]; [self protectPreferenceFiles];
self.window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]]; self.window = [[UIWindow alloc] initWithFrame:UIScreen.mainScreen.bounds];
[self prepareScreenshotProtection]; [self prepareScreenshotProtection];
@ -130,8 +130,8 @@
CategorizingLogger* logger = [CategorizingLogger categorizingLogger]; CategorizingLogger* logger = [CategorizingLogger categorizingLogger];
[logger addLoggingCallback:^(NSString *category, id details, NSUInteger index) {}]; [logger addLoggingCallback:^(NSString *category, id details, NSUInteger index) {}];
[Environment setCurrent:[Release releaseEnvironmentWithLogging:logger]]; [Environment setCurrent:[Release releaseEnvironmentWithLogging:logger]];
[[Environment getCurrent].phoneDirectoryManager startUntilCancelled:nil]; [Environment.getCurrent.phoneDirectoryManager startUntilCancelled:nil];
[[Environment getCurrent].contactsManager doAfterEnvironmentInitSetup]; [Environment.getCurrent.contactsManager doAfterEnvironmentInitSetup];
[UIApplication.sharedApplication setStatusBarStyle:UIStatusBarStyleDefault]; [UIApplication.sharedApplication setStatusBarStyle:UIStatusBarStyleDefault];
LeftSideMenuViewController *leftSideMenuViewController = [LeftSideMenuViewController new]; LeftSideMenuViewController *leftSideMenuViewController = [LeftSideMenuViewController new];
@ -147,15 +147,15 @@
[self application:application didReceiveRemoteNotification:remoteNotif]; [self application:application didReceiveRemoteNotification:remoteNotif];
} }
[[[Environment phoneManager] currentCallObservable] watchLatestValue:^(CallState* latestCall) { [Environment.phoneManager.currentCallObservable watchLatestValue:^(CallState* latestCall) {
if (latestCall == nil){ if (latestCall == nil){
return; return;
} }
InCallViewController *callViewController = [InCallViewController inCallViewControllerWithCallState:latestCall InCallViewController *callViewController = [InCallViewController inCallViewControllerWithCallState:latestCall
andOptionallyKnownContact:[latestCall potentiallySpecifiedContact]]; andOptionallyKnownContact:latestCall.potentiallySpecifiedContact];
[_drawerController.centerViewController presentViewController:callViewController animated:YES completion:nil]; [_drawerController.centerViewController presentViewController:callViewController animated:YES completion:nil];
} onThread:[NSThread mainThread] untilCancelled:nil]; } onThread:NSThread.mainThread untilCancelled:nil];
return YES; return YES;
@ -185,7 +185,7 @@
return; return;
} }
[[Environment phoneManager] incomingCallWithSession:call]; [Environment.phoneManager incomingCallWithSession:call];
} }
-(void) application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo fetchCompletionHandler:(void (^)(UIBackgroundFetchResult))completionHandler { -(void) application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo fetchCompletionHandler:(void (^)(UIBackgroundFetchResult))completionHandler {
@ -228,8 +228,8 @@
} }
- (void)protectScreen{ - (void)protectScreen{
if ([[Environment preferences] screenSecurityIsEnabled]) { if (Environment.preferences.screenSecurityIsEnabled) {
self.blankWindow.rootViewController = [[UIViewController alloc] init]; self.blankWindow.rootViewController = [UIViewController new];
UIImageView *imageView = [[UIImageView alloc] initWithFrame:self.blankWindow.bounds]; UIImageView *imageView = [[UIImageView alloc] initWithFrame:self.blankWindow.bounds];
if (self.blankWindow.bounds.size.height == 568) { if (self.blankWindow.bounds.size.height == 568) {
imageView.image = [UIImage imageNamed:@"Default-568h"]; imageView.image = [UIImage imageNamed:@"Default-568h"];
@ -243,7 +243,7 @@
} }
- (void)removeScreenProtection{ - (void)removeScreenProtection{
if ([[Environment preferences] screenSecurityIsEnabled]) { if (Environment.preferences.screenSecurityIsEnabled) {
self.blankWindow.rootViewController = nil; self.blankWindow.rootViewController = nil;
self.blankWindow.hidden = YES; self.blankWindow.hidden = YES;
} }

View File

@ -26,7 +26,7 @@ AppAudioManager* sharedAppAudioManager;
+(AppAudioManager*) sharedInstance { +(AppAudioManager*) sharedInstance {
@synchronized(self){ @synchronized(self){
if( nil == sharedAppAudioManager){ if( nil == sharedAppAudioManager){
sharedAppAudioManager = [[AppAudioManager alloc] init]; sharedAppAudioManager = [AppAudioManager new];
sharedAppAudioManager.soundPlayer = [SoundPlayer new]; sharedAppAudioManager.soundPlayer = [SoundPlayer new];
[sharedAppAudioManager setAudioEnabled:YES]; [sharedAppAudioManager setAudioEnabled:YES];
} }

View File

@ -24,7 +24,7 @@
+(BOOL) isOutputRoutedToSpeaker{ +(BOOL) isOutputRoutedToSpeaker{
AVAudioSession* session = AVAudioSession.sharedInstance; AVAudioSession* session = AVAudioSession.sharedInstance;
AVAudioSessionRouteDescription* routeDesc = [session currentRoute]; AVAudioSessionRouteDescription* routeDesc = session.currentRoute;
for( AVAudioSessionPortDescription* portDesc in routeDesc.outputs){ for( AVAudioSessionPortDescription* portDesc in routeDesc.outputs){
if (AVAudioSessionPortBuiltInSpeaker == [portDesc portType]){ if (AVAudioSessionPortBuiltInSpeaker == [portDesc portType]){
@ -36,7 +36,7 @@
+(BOOL) isOutputRoutedToReciever{ +(BOOL) isOutputRoutedToReciever{
AVAudioSession* session = AVAudioSession.sharedInstance; AVAudioSession* session = AVAudioSession.sharedInstance;
AVAudioSessionRouteDescription* routeDesc = [session currentRoute]; AVAudioSessionRouteDescription* routeDesc = session.currentRoute;
for( AVAudioSessionPortDescription* portDesc in routeDesc.outputs){ for( AVAudioSessionPortDescription* portDesc in routeDesc.outputs){
if (AVAudioSessionPortBuiltInReceiver == [portDesc portType]){ if (AVAudioSessionPortBuiltInReceiver == [portDesc portType]){

View File

@ -38,7 +38,7 @@
+(NSURL*) urlToFile:(NSString*) file { +(NSURL*) urlToFile:(NSString*) file {
return [NSURL fileURLWithPath: return [NSURL fileURLWithPath:
[NSString stringWithFormat:@"%@/%@", [[NSBundle mainBundle] resourcePath],file]]; [NSString stringWithFormat:@"%@/%@", NSBundle.mainBundle.resourcePath,file]];
} }
+(AVAudioPlayer*) createAudioPlayerForFile:(NSString*) audioFile { +(AVAudioPlayer*) createAudioPlayerForFile:(NSString*) audioFile {

View File

@ -23,11 +23,11 @@ NSMutableDictionary* currentActiveAudioPlayers;
[sound setCompeletionBlock:^(SoundInstance* soundInst) { [sound setCompeletionBlock:^(SoundInstance* soundInst) {
[self removeSoundFromManifest:soundInst]; [self removeSoundFromManifest:soundInst];
}]; }];
[currentActiveAudioPlayers setValue:sound forKey:[sound getId]]; [currentActiveAudioPlayers setValue:sound forKey:sound.getId];
} }
} }
-(void) removeSoundFromManifest:(SoundInstance*) sound { -(void) removeSoundFromManifest:(SoundInstance*) sound {
[self removeSoundFromMainifestById:[sound getId]]; [self removeSoundFromMainifestById:sound.getId];
} }
-(void) removeSoundFromMainifestById:(NSString*) soundId { -(void) removeSoundFromMainifestById:(NSString*) soundId {
@ -44,7 +44,7 @@ NSMutableDictionary* currentActiveAudioPlayers;
} }
-(void) stopSound:(SoundInstance*) sound { -(void) stopSound:(SoundInstance*) sound {
SoundInstance* playingSoundInstance = currentActiveAudioPlayers[[sound getId]]; SoundInstance* playingSoundInstance = currentActiveAudioPlayers[sound.getId];
[self removeSoundFromManifest:sound]; [self removeSoundFromManifest:sound];
[playingSoundInstance stop]; [playingSoundInstance stop];
} }
@ -56,7 +56,7 @@ NSMutableDictionary* currentActiveAudioPlayers;
} }
-(BOOL) isSoundPlaying:(SoundInstance*) sound { -(BOOL) isSoundPlaying:(SoundInstance*) sound {
return nil != currentActiveAudioPlayers[[sound getId]]; return nil != currentActiveAudioPlayers[sound.getId];
} }
-(void) awake { -(void) awake {

View File

@ -23,7 +23,7 @@
-(void)packFrame:(EncodedAudioFrame*)frame{ -(void)packFrame:(EncodedAudioFrame*)frame{
require(frame != nil); require(frame != nil);
require(!frame.isMissingAudioData); require(!frame.isMissingAudioData);
[framesToSend addObject:[frame tryGetAudioData]]; [framesToSend addObject:frame.tryGetAudioData];
} }
-(EncodedAudioPacket*) tryGetFinishedAudioPacket{ -(EncodedAudioPacket*) tryGetFinishedAudioPacket{

View File

@ -18,7 +18,7 @@
PacketHandlerBlock valueHandler = ^(RtpPacket* rtpPacket) { PacketHandlerBlock valueHandler = ^(RtpPacket* rtpPacket) {
require(rtpPacket != nil); require(rtpPacket != nil);
require([rtpPacket isKindOfClass:[RtpPacket class]]); require([rtpPacket isKindOfClass:RtpPacket.class]);
[handler handlePacket:[EncodedAudioPacket encodedAudioPacketWithAudioData:rtpPacket.payload [handler handlePacket:[EncodedAudioPacket encodedAudioPacketWithAudioData:rtpPacket.payload
andTimeStamp:rtpPacket.timeStamp andTimeStamp:rtpPacket.timeStamp
andSequenceNumber:rtpPacket.sequenceNumber]]; andSequenceNumber:rtpPacket.sequenceNumber]];

View File

@ -27,14 +27,14 @@ static bool doesActiveInstanceExist;
doesActiveInstanceExist = true; doesActiveInstanceExist = true;
RemoteIOAudio* newRemoteIoInterface = [RemoteIOAudio new]; RemoteIOAudio* newRemoteIoInterface = [RemoteIOAudio new];
newRemoteIoInterface->starveLogger = [[Environment logging] getOccurrenceLoggerForSender:newRemoteIoInterface withKey:@"starve"]; newRemoteIoInterface->starveLogger = [Environment.logging getOccurrenceLoggerForSender:newRemoteIoInterface withKey:@"starve"];
newRemoteIoInterface->conditionLogger = [[Environment logging] getConditionLoggerForSender:newRemoteIoInterface]; newRemoteIoInterface->conditionLogger = [Environment.logging getConditionLoggerForSender:newRemoteIoInterface];
newRemoteIoInterface->recordingQueue = [CyclicalBuffer new]; newRemoteIoInterface->recordingQueue = [CyclicalBuffer new];
newRemoteIoInterface->playbackQueue = [CyclicalBuffer new]; newRemoteIoInterface->playbackQueue = [CyclicalBuffer new];
newRemoteIoInterface->unusedBuffers = [NSMutableSet set]; newRemoteIoInterface->unusedBuffers = [NSMutableSet set];
newRemoteIoInterface->state = NOT_STARTED; newRemoteIoInterface->state = NOT_STARTED;
newRemoteIoInterface->playbackBufferSizeLogger = [[Environment logging] getValueLoggerForValue:@"|playback queue|" from:newRemoteIoInterface]; newRemoteIoInterface->playbackBufferSizeLogger = [Environment.logging getValueLoggerForValue:@"|playback queue|" from:newRemoteIoInterface];
newRemoteIoInterface->recordingQueueSizeLogger = [[Environment logging] getValueLoggerForValue:@"|recording queue|" from:newRemoteIoInterface]; newRemoteIoInterface->recordingQueueSizeLogger = [Environment.logging getValueLoggerForValue:@"|recording queue|" from:newRemoteIoInterface];
while (newRemoteIoInterface->unusedBuffers.count < INITIAL_NUMBER_OF_BUFFERS) { while (newRemoteIoInterface->unusedBuffers.count < INITIAL_NUMBER_OF_BUFFERS) {
[newRemoteIoInterface addUnusedBuffer]; [newRemoteIoInterface addUnusedBuffer];

View File

@ -15,7 +15,7 @@
+(SpeexCodec*) speexCodec { +(SpeexCodec*) speexCodec {
SpeexCodec* c = [SpeexCodec new]; SpeexCodec* c = [SpeexCodec new];
c->logging = [[Environment logging] getConditionLoggerForSender:self]; c->logging = [Environment.logging getConditionLoggerForSender:self];
[c openSpeex]; [c openSpeex];
return c; return c;
} }

View File

@ -57,7 +57,7 @@
haveReceivedDataYet |= !frame.isMissingAudioData; haveReceivedDataYet |= !frame.isMissingAudioData;
if (!haveReceivedDataYet) return nil; if (!haveReceivedDataYet) return nil;
NSData* raw = [codec decode:[frame tryGetAudioData]]; NSData* raw = [codec decode:frame.tryGetAudioData];
double stretch = [stretchFactorController getAndUpdateDesiredStretchFactor]; double stretch = [stretchFactorController getAndUpdateDesiredStretchFactor];
return [audioStretcher stretchAudioData:raw stretchFactor:stretch]; return [audioStretcher stretchAudioData:raw stretchFactor:stretch];
} }

View File

@ -17,7 +17,7 @@
NSTimeInterval audioDurationPerPacket = (NSTimeInterval)(AUDIO_FRAMES_PER_PACKET*[SpeexCodec frameSizeInSamples]) NSTimeInterval audioDurationPerPacket = (NSTimeInterval)(AUDIO_FRAMES_PER_PACKET*[SpeexCodec frameSizeInSamples])
/ SAMPLE_RATE; / SAMPLE_RATE;
double initialDesiredBufferDepth = [[Environment preferences] getCachedOrDefaultDesiredBufferDepth]; double initialDesiredBufferDepth = Environment.preferences.getCachedOrDefaultDesiredBufferDepth;
DropoutTracker* dropoutTracker = [DropoutTracker dropoutTrackerWithAudioDurationPerPacket:audioDurationPerPacket]; DropoutTracker* dropoutTracker = [DropoutTracker dropoutTrackerWithAudioDurationPerPacket:audioDurationPerPacket];
@ -28,16 +28,16 @@
DesiredBufferDepthController* result = [DesiredBufferDepthController new]; DesiredBufferDepthController* result = [DesiredBufferDepthController new];
result->dropoutTracker = dropoutTracker; result->dropoutTracker = dropoutTracker;
result->decayingDesiredBufferDepth = decayingDesiredBufferDepth; result->decayingDesiredBufferDepth = decayingDesiredBufferDepth;
result->desiredDelayLogger = [[Environment logging] getValueLoggerForValue:@"desired buffer depth" from:self]; result->desiredDelayLogger = [Environment.logging getValueLoggerForValue:@"desired buffer depth" from:self];
[jitterQueue registerWatcher:result]; [jitterQueue registerWatcher:result];
return result; return result;
} }
-(double) getAndUpdateDesiredBufferDepth { -(double) getAndUpdateDesiredBufferDepth {
double r = [decayingDesiredBufferDepth currentEstimate]; double r = decayingDesiredBufferDepth.currentEstimate;
[decayingDesiredBufferDepth updateWithNextSample:[dropoutTracker getDepthForThreshold:DROPOUT_THRESHOLD]]; [decayingDesiredBufferDepth updateWithNextSample:[dropoutTracker getDepthForThreshold:DROPOUT_THRESHOLD]];
[decayingDesiredBufferDepth forceEstimateTo:[NumberUtil clamp:[decayingDesiredBufferDepth currentEstimate] [decayingDesiredBufferDepth forceEstimateTo:[NumberUtil clamp:decayingDesiredBufferDepth.currentEstimate
toMin:MIN_DESIRED_FRAME_DELAY toMin:MIN_DESIRED_FRAME_DELAY
andMax:MAX_DESIRED_FRAME_DELAY]]; andMax:MAX_DESIRED_FRAME_DELAY]];
[desiredDelayLogger logValue:r]; [desiredDelayLogger logValue:r];
@ -59,7 +59,7 @@
} }
-(void) terminate { -(void) terminate {
[[Environment preferences] setCachedDesiredBufferDepth:[decayingDesiredBufferDepth currentEstimate]]; [Environment.preferences setCachedDesiredBufferDepth:decayingDesiredBufferDepth.currentEstimate];
} }
@end @end

View File

@ -13,7 +13,7 @@
JitterQueue* q = [JitterQueue new]; JitterQueue* q = [JitterQueue new];
q->readHeadSpan = READ_HEAD_BAD_SPAN_THRESHOLD+1; q->readHeadSpan = READ_HEAD_BAD_SPAN_THRESHOLD+1;
q->watchers = [NSMutableArray array]; q->watchers = [NSMutableArray array];
[q registerWatcher:[[Environment logging] jitterQueueNotificationReceiver]]; [q registerWatcher:Environment.logging.jitterQueueNotificationReceiver];
return q; return q;
} }

View File

@ -27,17 +27,17 @@ static double STRETCH_MODE_FACTORS[] = {1/0.95, 1, 1/1.05, 0.5};
p->currentStretchMode = STRETCH_MODE_NORMAL; p->currentStretchMode = STRETCH_MODE_NORMAL;
p->bufferDepthMeasure = jitterQueue; p->bufferDepthMeasure = jitterQueue;
p->decayingBufferDepthMeasure = [DecayingSampleEstimator decayingSampleEstimatorWithInitialEstimate:0 andDecayPerUnitSample:BUFFER_DEPTH_DECAYING_FACTOR]; p->decayingBufferDepthMeasure = [DecayingSampleEstimator decayingSampleEstimatorWithInitialEstimate:0 andDecayPerUnitSample:BUFFER_DEPTH_DECAYING_FACTOR];
p->stretchModeChangeLogger = [[Environment logging] getValueLoggerForValue:@"stretch factor" from:self]; p->stretchModeChangeLogger = [Environment.logging getValueLoggerForValue:@"stretch factor" from:self];
return p; return p;
} }
-(int) reconsiderStretchMode { -(int) reconsiderStretchMode {
int16_t currentBufferDepth = [bufferDepthMeasure currentBufferDepth]; int16_t currentBufferDepth = bufferDepthMeasure.currentBufferDepth;
[decayingBufferDepthMeasure updateWithNextSample:currentBufferDepth]; [decayingBufferDepthMeasure updateWithNextSample:currentBufferDepth];
double desiredBufferDepth = [desiredBufferDepthController getAndUpdateDesiredBufferDepth]; double desiredBufferDepth = desiredBufferDepthController.getAndUpdateDesiredBufferDepth;
double currentBufferDepthDelta = currentBufferDepth - desiredBufferDepth; double currentBufferDepthDelta = currentBufferDepth - desiredBufferDepth;
double decayingBufferDepthDelta = [decayingBufferDepthMeasure currentEstimate] - desiredBufferDepth; double decayingBufferDepthDelta = decayingBufferDepthMeasure.currentEstimate - desiredBufferDepth;
bool shouldStartSuperShrink = currentBufferDepthDelta > SUPER_SHRINK_THRESHOLD; bool shouldStartSuperShrink = currentBufferDepthDelta > SUPER_SHRINK_THRESHOLD;
bool shouldMaintainSuperShrink = currentBufferDepthDelta > 0 && currentStretchMode == STRETCH_MODE_SUPER_SHRINK; bool shouldMaintainSuperShrink = currentBufferDepthDelta > 0 && currentStretchMode == STRETCH_MODE_SUPER_SHRINK;

View File

@ -34,7 +34,7 @@ typedef BOOL (^SearchTermConditionalBlock)(RecentCall*, NSUInteger, BOOL*);
} }
-(void) watchForContactUpdatesFrom:(ContactsManager*) contactManager untillCancelled:(TOCCancelToken*) cancelToken{ -(void) watchForContactUpdatesFrom:(ContactsManager*) contactManager untillCancelled:(TOCCancelToken*) cancelToken{
[[contactManager getObservableWhisperUsers] watchLatestValue:^(NSArray* latestUsers) { [contactManager.getObservableWhisperUsers watchLatestValue:^(NSArray* latestUsers) {
for (RecentCall* recentCall in _allRecents) { for (RecentCall* recentCall in _allRecents) {
if (![contactManager latestContactWithRecordId:recentCall.contactRecordID]) { if (![contactManager latestContactWithRecordId:recentCall.contactRecordID]) {
Contact* contact = [contactManager latestContactForPhoneNumber:recentCall.phoneNumber]; Contact* contact = [contactManager latestContactForPhoneNumber:recentCall.phoneNumber];
@ -43,18 +43,18 @@ typedef BOOL (^SearchTermConditionalBlock)(RecentCall*, NSUInteger, BOOL*);
} }
} }
} }
} onThread:[NSThread mainThread] untilCancelled:cancelToken]; } onThread:NSThread.mainThread untilCancelled:cancelToken];
} }
-(void) watchForCallsThrough:(PhoneManager*)phoneManager -(void) watchForCallsThrough:(PhoneManager*)phoneManager
untilCancelled:(TOCCancelToken*)untilCancelledToken { untilCancelled:(TOCCancelToken*)untilCancelledToken {
require(phoneManager != nil); require(phoneManager != nil);
[[phoneManager currentCallObservable] watchLatestValue:^(CallState* latestCall) { [phoneManager.currentCallObservable watchLatestValue:^(CallState* latestCall) {
if (latestCall != nil && [[Environment preferences] getHistoryLogEnabled]) { if (latestCall != nil && Environment.preferences.getHistoryLogEnabled) {
[self addCall:latestCall]; [self addCall:latestCall];
} }
} onThread:[NSThread mainThread] untilCancelled:untilCancelledToken]; } onThread:NSThread.mainThread untilCancelled:untilCancelledToken];
} }
-(void) addCall:(CallState*)call { -(void) addCall:(CallState*)call {
@ -81,7 +81,7 @@ typedef BOOL (^SearchTermConditionalBlock)(RecentCall*, NSUInteger, BOOL*);
} }
-(Contact*) tryGetContactForNumber:(PhoneNumber*)number { -(Contact*) tryGetContactForNumber:(PhoneNumber*)number {
return [[[Environment getCurrent] contactsManager] latestContactForPhoneNumber:number]; return [Environment.getCurrent.contactsManager latestContactForPhoneNumber:number];
} }
- (void)addMissedCallDueToBusy:(ResponderSessionDescriptor*)incomingCallDescriptor { - (void)addMissedCallDueToBusy:(ResponderSessionDescriptor*)incomingCallDescriptor {
@ -101,7 +101,7 @@ typedef BOOL (^SearchTermConditionalBlock)(RecentCall*, NSUInteger, BOOL*);
- (void)addRecentCall:(RecentCall *)recentCall { - (void)addRecentCall:(RecentCall *)recentCall {
[_allRecents insertObject:recentCall atIndex:0]; [_allRecents insertObject:recentCall atIndex:0];
[[Environment preferences] setFreshInstallTutorialsEnabled:NO]; [Environment.preferences setFreshInstallTutorialsEnabled:NO];
[observableRecentsController updateValue:_allRecents.copy]; [observableRecentsController updateValue:_allRecents.copy];
[self saveContactsToDefaults]; [self saveContactsToDefaults];
} }
@ -127,7 +127,7 @@ typedef BOOL (^SearchTermConditionalBlock)(RecentCall*, NSUInteger, BOOL*);
} }
- (void)saveContactsToDefaults { - (void)saveContactsToDefaults {
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults]; NSUserDefaults *defaults = NSUserDefaults.standardUserDefaults;
NSData *saveData = [NSKeyedArchiver archivedDataWithRootObject:_allRecents.copy]; NSData *saveData = [NSKeyedArchiver archivedDataWithRootObject:_allRecents.copy];
[defaults setObject:saveData forKey:RECENT_CALLS_DEFAULT_KEY]; [defaults setObject:saveData forKey:RECENT_CALLS_DEFAULT_KEY];
@ -135,11 +135,11 @@ typedef BOOL (^SearchTermConditionalBlock)(RecentCall*, NSUInteger, BOOL*);
} }
- (NSMutableArray *)loadContactsFromDefaults { - (NSMutableArray *)loadContactsFromDefaults {
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults]; NSUserDefaults *defaults = NSUserDefaults.standardUserDefaults;
NSData *encodedData = [defaults objectForKey:RECENT_CALLS_DEFAULT_KEY]; NSData *encodedData = [defaults objectForKey:RECENT_CALLS_DEFAULT_KEY];
id data = [NSKeyedUnarchiver unarchiveObjectWithData:encodedData]; id data = [NSKeyedUnarchiver unarchiveObjectWithData:encodedData];
if(![data isKindOfClass:[NSArray class]]) { if(![data isKindOfClass:NSArray.class]) {
return [NSMutableArray array]; return [NSMutableArray array];
} else { } else {
return [NSMutableArray arrayWithArray:data]; return [NSMutableArray arrayWithArray:data];
@ -147,7 +147,7 @@ typedef BOOL (^SearchTermConditionalBlock)(RecentCall*, NSUInteger, BOOL*);
} }
- (NSArray *)recentsForSearchString:(NSString *)optionalSearchString andExcludeArchived:(BOOL)excludeArchived { - (NSArray *)recentsForSearchString:(NSString *)optionalSearchString andExcludeArchived:(BOOL)excludeArchived {
ContactsManager *contactsManager = [[Environment getCurrent] contactsManager]; ContactsManager *contactsManager = Environment.getCurrent.contactsManager;
SearchTermConditionalBlock searchBlock = ^BOOL(RecentCall *obj, NSUInteger idx, BOOL *stop) { SearchTermConditionalBlock searchBlock = ^BOOL(RecentCall *obj, NSUInteger idx, BOOL *stop) {
BOOL nameMatchesSearch = YES; BOOL nameMatchesSearch = YES;
BOOL numberMatchesSearch = YES; BOOL numberMatchesSearch = YES;

View File

@ -74,7 +74,7 @@ static NSString *const DEFAULTS_KEY_DATE = @"DefaultsKeyDate";
} }
- (UIImage *)image { - (UIImage *)image {
if ([[Environment preferences] getContactImagesEnabled]) { if (Environment.preferences.getContactImagesEnabled) {
return image; return image;
} else { } else {
return nil; return nil;

View File

@ -365,7 +365,7 @@ void onAddressBookChanged(ABAddressBookRef notifyAddressBook, CFDictionaryRef in
} }
+(BOOL)name:(NSString *)nameString matchesQuery:(NSString *)queryString { +(BOOL)name:(NSString *)nameString matchesQuery:(NSString *)queryString {
NSCharacterSet *whitespaceSet = [NSCharacterSet whitespaceCharacterSet]; NSCharacterSet *whitespaceSet = NSCharacterSet.whitespaceCharacterSet;
NSArray *queryStrings = [queryString componentsSeparatedByCharactersInSet:whitespaceSet]; NSArray *queryStrings = [queryString componentsSeparatedByCharactersInSet:whitespaceSet];
NSArray *nameStrings = [nameString componentsSeparatedByCharactersInSet:whitespaceSet]; NSArray *nameStrings = [nameString componentsSeparatedByCharactersInSet:whitespaceSet];
@ -402,14 +402,14 @@ void onAddressBookChanged(ABAddressBookRef notifyAddressBook, CFDictionaryRef in
#pragma mark - Favourites #pragma mark - Favourites
-(NSMutableArray *)loadFavouriteIds { -(NSMutableArray *)loadFavouriteIds {
NSArray *favourites = [[NSUserDefaults standardUserDefaults] objectForKey:FAVOURITES_DEFAULT_KEY]; NSArray *favourites = [NSUserDefaults.standardUserDefaults objectForKey:FAVOURITES_DEFAULT_KEY];
return favourites == nil ? [NSMutableArray array] : favourites.mutableCopy; return favourites == nil ? [NSMutableArray array] : favourites.mutableCopy;
} }
-(void)saveFavouriteIds { -(void)saveFavouriteIds {
[[NSUserDefaults standardUserDefaults] setObject:[_favouriteContactIds copy] [NSUserDefaults.standardUserDefaults setObject:[_favouriteContactIds copy]
forKey:FAVOURITES_DEFAULT_KEY]; forKey:FAVOURITES_DEFAULT_KEY];
[[NSUserDefaults standardUserDefaults] synchronize]; [NSUserDefaults.standardUserDefaults synchronize];
[observableFavouritesController updateValue:[self contactsForContactIds:_favouriteContactIds]]; [observableFavouritesController updateValue:[self contactsForContactIds:_favouriteContactIds]];
} }
@ -484,7 +484,7 @@ void onAddressBookChanged(ABAddressBookRef notifyAddressBook, CFDictionaryRef in
NSSet *oldSet = [NSSet setWithArray:oldArray]; NSSet *oldSet = [NSSet setWithArray:oldArray];
[newSet minusSet:oldSet]; [newSet minusSet:oldSet];
return [newSet allObjects]; return newSet.allObjects;
} }
- (BOOL)isContactRegisteredWithWhisper:(Contact*) contact { - (BOOL)isContactRegisteredWithWhisper:(Contact*) contact {
@ -497,7 +497,7 @@ void onAddressBookChanged(ABAddressBookRef notifyAddressBook, CFDictionaryRef in
} }
- (BOOL)isPhoneNumberRegisteredWithWhisper:(PhoneNumber *)phoneNumber { - (BOOL)isPhoneNumberRegisteredWithWhisper:(PhoneNumber *)phoneNumber {
PhoneNumberDirectoryFilter* directory = [[[Environment getCurrent] phoneDirectoryManager] getCurrentFilter]; PhoneNumberDirectoryFilter* directory = Environment.getCurrent.phoneDirectoryManager.getCurrentFilter;
return phoneNumber != nil && [directory containsPhoneNumber:phoneNumber]; return phoneNumber != nil && [directory containsPhoneNumber:phoneNumber];
} }
@ -508,29 +508,29 @@ void onAddressBookChanged(ABAddressBookRef notifyAddressBook, CFDictionaryRef in
NSMutableSet *users = [NSMutableSet setWithArray:latestWhisperUsersById.allValues]; NSMutableSet *users = [NSMutableSet setWithArray:latestWhisperUsersById.allValues];
[users addObjectsFromArray:contacts]; [users addObjectsFromArray:contacts];
[observableWhisperUsersController updateValue:[users allObjects]]; [observableWhisperUsersController updateValue:users.allObjects];
[self saveKnownWhisperUsers]; [self saveKnownWhisperUsers];
} }
-(BOOL) knownUserStoreInitialized{ -(BOOL) knownUserStoreInitialized{
NSUserDefaults *d = [[NSUserDefaults standardUserDefaults] objectForKey:KNOWN_USERS_DEFAULT_KEY]; NSUserDefaults *d = [NSUserDefaults.standardUserDefaults objectForKey:KNOWN_USERS_DEFAULT_KEY];
return (Nil != d); return (Nil != d);
} }
-(NSMutableArray*) loadKnownWhisperUsers{ -(NSMutableArray*) loadKnownWhisperUsers{
NSArray *knownUsers = [[NSUserDefaults standardUserDefaults] objectForKey:KNOWN_USERS_DEFAULT_KEY]; NSArray *knownUsers = [NSUserDefaults.standardUserDefaults objectForKey:KNOWN_USERS_DEFAULT_KEY];
return knownUsers == nil ? [NSMutableArray array] : knownUsers.mutableCopy; return knownUsers == nil ? [NSMutableArray array] : knownUsers.mutableCopy;
} }
-(void) saveKnownWhisperUsers{ -(void) saveKnownWhisperUsers{
_knownWhisperUserIds = [NSMutableArray arrayWithArray:[latestWhisperUsersById allKeys]]; _knownWhisperUserIds = [NSMutableArray arrayWithArray:[latestWhisperUsersById allKeys]];
[[NSUserDefaults standardUserDefaults] setObject:[_knownWhisperUserIds copy] forKey:KNOWN_USERS_DEFAULT_KEY]; [NSUserDefaults.standardUserDefaults setObject:[_knownWhisperUserIds copy] forKey:KNOWN_USERS_DEFAULT_KEY];
[[NSUserDefaults standardUserDefaults] synchronize]; [NSUserDefaults.standardUserDefaults synchronize];
} }
-(void) clearKnownWhisUsers{ -(void) clearKnownWhisUsers{
[[NSUserDefaults standardUserDefaults] setObject:@[] forKey:KNOWN_USERS_DEFAULT_KEY]; [NSUserDefaults.standardUserDefaults setObject:@[] forKey:KNOWN_USERS_DEFAULT_KEY];
[[NSUserDefaults standardUserDefaults] synchronize]; [NSUserDefaults.standardUserDefaults synchronize];
} }
@end @end

View File

@ -24,7 +24,7 @@
MacrosSingletonImplemention MacrosSingletonImplemention
- (void)enableFileLogging{ - (void)enableFileLogging{
self.fileLogger = [[DDFileLogger alloc] init]; //Logging to file, because it's in the Cache folder, they are not uploaded in iTunes/iCloud backups. self.fileLogger = [DDFileLogger new]; //Logging to file, because it's in the Cache folder, they are not uploaded in iTunes/iCloud backups.
self.fileLogger.rollingFrequency = 60 * 60 * 24; // 24 hour rolling. self.fileLogger.rollingFrequency = 60 * 60 * 24; // 24 hour rolling.
self.fileLogger.logFileManager.maximumNumberOfLogFiles = 3; // Keep three days of logs. self.fileLogger.logFileManager.maximumNumberOfLogFiles = 3; // Keep three days of logs.
[DDLog addLogger:self.fileLogger]; [DDLog addLogger:self.fileLogger];

View File

@ -35,7 +35,7 @@ contactsManager,
phoneDirectoryManager; phoneDirectoryManager;
+(NSString*) currentRegionCodeForPhoneNumbers { +(NSString*) currentRegionCodeForPhoneNumbers {
return [[self getCurrent] currentRegionCodeForPhoneNumbers]; return self.getCurrent.currentRegionCodeForPhoneNumbers;
} }
+(Environment*) getCurrent { +(Environment*) getCurrent {
@ -46,26 +46,26 @@ phoneDirectoryManager;
environment = curEnvironment; environment = curEnvironment;
} }
+(ErrorHandlerBlock) errorNoter { +(ErrorHandlerBlock) errorNoter {
return [[self getCurrent] errorNoter]; return self.getCurrent.errorNoter;
} }
+(bool) hasEnabledTestingOrLegacyOption:(NSString*)flag { +(bool) hasEnabledTestingOrLegacyOption:(NSString*)flag {
return [[self getCurrent].testingAndLegacyOptions containsObject:flag]; return [self.getCurrent.testingAndLegacyOptions containsObject:flag];
} }
+(NSString*) relayServerNameToHostName:(NSString*)name { +(NSString*) relayServerNameToHostName:(NSString*)name {
return [NSString stringWithFormat:@"%@.%@", return [NSString stringWithFormat:@"%@.%@",
name, name,
[[Environment getCurrent] relayServerHostNameSuffix]]; Environment.getCurrent.relayServerHostNameSuffix];
} }
+(SecureEndPoint*) getMasterServerSecureEndPoint { +(SecureEndPoint*) getMasterServerSecureEndPoint {
return [[Environment getCurrent] masterServerSecureEndPoint]; return Environment.getCurrent.masterServerSecureEndPoint;
} }
+(SecureEndPoint*) getSecureEndPointToDefaultRelayServer { +(SecureEndPoint*) getSecureEndPointToDefaultRelayServer {
return [Environment getSecureEndPointToSignalingServerNamed:[Environment getCurrent].defaultRelayName]; return [Environment getSecureEndPointToSignalingServerNamed:Environment.getCurrent.defaultRelayName];
} }
+(SecureEndPoint*) getSecureEndPointToSignalingServerNamed:(NSString*)name { +(SecureEndPoint*) getSecureEndPointToSignalingServerNamed:(NSString*)name {
require(name != nil); require(name != nil);
Environment* env = [Environment getCurrent]; Environment* env = Environment.getCurrent;
NSString* hostName = [self relayServerNameToHostName:name]; NSString* hostName = [self relayServerNameToHostName:name];
HostNameEndPoint* location = [HostNameEndPoint hostNameEndPointWithHostName:hostName andPort:env.serverPort]; HostNameEndPoint* location = [HostNameEndPoint hostNameEndPointWithHostName:hostName andPort:env.serverPort];
@ -101,7 +101,7 @@ phoneDirectoryManager;
// must support DH3k // must support DH3k
require([keyAgreementProtocolsInDescendingPriority any:^int(id p) { require([keyAgreementProtocolsInDescendingPriority any:^int(id p) {
return [p isKindOfClass:[DH3KKeyAgreementProtocol class]]; return [p isKindOfClass:DH3KKeyAgreementProtocol.class];
}]); }]);
Environment* e = [Environment new]; Environment* e = [Environment new];
@ -137,46 +137,42 @@ phoneDirectoryManager;
} }
+(PhoneManager*) phoneManager { +(PhoneManager*) phoneManager {
return [[Environment getCurrent] phoneManager]; return Environment.getCurrent.phoneManager;
} }
+(id<Logging>) logging { +(id<Logging>) logging {
// Many tests create objects that rely on Environment only for logging. // Many tests create objects that rely on Environment only for logging.
// So we bypass the nil check in getCurrent and silently don't log during unit testing, instead of failing hard. // So we bypass the nil check in getCurrent and silently don't log during unit testing, instead of failing hard.
if (environment == nil) return nil; if (environment == nil) return nil;
return [[Environment getCurrent] logging]; return Environment.getCurrent.logging;
} }
+(BOOL)isRegistered{ +(BOOL)isRegistered{
// Attributes that need to be set // Attributes that need to be set
NSData *signalingKey = [SGNKeychainUtil signalingCipherKey]; NSData *signalingKey = SGNKeychainUtil.signalingCipherKey;
NSData *macKey = [SGNKeychainUtil signalingMacKey]; NSData *macKey = SGNKeychainUtil.signalingMacKey;
NSData *extra = [SGNKeychainUtil signalingExtraKey]; NSData *extra = SGNKeychainUtil.signalingExtraKey;
NSString *serverAuth = [SGNKeychainUtil serverAuthPassword]; NSString *serverAuth = SGNKeychainUtil.serverAuthPassword;
BOOL registered = [[[NSUserDefaults standardUserDefaults] objectForKey:isRegisteredUserDefaultString] boolValue]; BOOL registered = [[NSUserDefaults.standardUserDefaults objectForKey:isRegisteredUserDefaultString] boolValue];
if (signalingKey && macKey && extra && serverAuth && registered) { return signalingKey && macKey && extra && serverAuth && registered;
return YES;
} else{
return NO;
}
} }
+(void)setRegistered:(BOOL)status{ +(void)setRegistered:(BOOL)status{
[[NSUserDefaults standardUserDefaults] setObject:status?@YES:@NO forKey:isRegisteredUserDefaultString]; [NSUserDefaults.standardUserDefaults setObject:status?@YES:@NO forKey:isRegisteredUserDefaultString];
} }
+(PropertyListPreferences*)preferences{ +(PropertyListPreferences*)preferences{
return [[PropertyListPreferences alloc]init]; return [PropertyListPreferences new];
} }
+(void)resetAppData{ +(void)resetAppData{
[SGNKeychainUtil wipeKeychain]; [SGNKeychainUtil wipeKeychain];
[[Environment preferences] clear]; [Environment.preferences clear];
if ([[self preferences] loggingIsEnabled]) { if (self.preferences.loggingIsEnabled) {
[DebugLogger.sharedInstance wipeLogs]; [DebugLogger.sharedInstance wipeLogs];
} }
[[self preferences] setAndGetCurrentVersion]; [self.preferences setAndGetCurrentVersion];
} }
@end @end

View File

@ -45,7 +45,7 @@
NSData* data = [[phoneNumberDirectoryFilter bloomFilter] data]; NSData* data = [[phoneNumberDirectoryFilter bloomFilter] data];
NSNumber* hashCount = @([[phoneNumberDirectoryFilter bloomFilter] hashCount]); NSNumber* hashCount = @([[phoneNumberDirectoryFilter bloomFilter] hashCount]);
NSDate* expiry = [phoneNumberDirectoryFilter getExpirationDate]; NSDate* expiry = phoneNumberDirectoryFilter.getExpirationDate;
[self setValueForKey:PHONE_DIRECTORY_BLOOM_FILTER_DATA_KEY toValue:data]; [self setValueForKey:PHONE_DIRECTORY_BLOOM_FILTER_DATA_KEY toValue:data];
[self setValueForKey:PHONE_DIRECTORY_BLOOM_FILTER_HASH_COUNT_KEY toValue:hashCount]; [self setValueForKey:PHONE_DIRECTORY_BLOOM_FILTER_HASH_COUNT_KEY toValue:hashCount];
[self setValueForKey:PHONE_DIRECTORY_EXPIRATION toValue:expiry]; [self setValueForKey:PHONE_DIRECTORY_EXPIRATION toValue:expiry];
@ -147,14 +147,15 @@
} }
-(NSString*)lastRanVersion{ -(NSString*)lastRanVersion{
return [[NSUserDefaults standardUserDefaults] objectForKey:kSignalVersionKey]; return [NSUserDefaults.standardUserDefaults objectForKey:kSignalVersionKey];
} }
-(NSString*)setAndGetCurrentVersion{ -(NSString*)setAndGetCurrentVersion{
NSString *lastVersion = self.lastRanVersion; NSString *lastVersion = self.lastRanVersion;
[[NSUserDefaults standardUserDefaults] setObject:[NSString stringWithFormat:@"%@", [[NSBundle mainBundle] infoDictionary][@"CFBundleVersion"]] forKey:kSignalVersionKey]; [NSUserDefaults.standardUserDefaults setObject:[NSString stringWithFormat:@"%@", NSBundle.mainBundle.infoDictionary[@"CFBundleVersion"]]
[[NSUserDefaults standardUserDefaults] synchronize]; forKey:kSignalVersionKey];
[NSUserDefaults.standardUserDefaults synchronize];
return lastVersion; return lastVersion;
} }

View File

@ -6,21 +6,21 @@
-(void) clear { -(void) clear {
@synchronized(self) { @synchronized(self) {
NSString *appDomain = [[NSBundle mainBundle] bundleIdentifier]; NSString *appDomain = NSBundle.mainBundle.bundleIdentifier;
[[NSUserDefaults standardUserDefaults] removePersistentDomainForName:appDomain]; [NSUserDefaults.standardUserDefaults removePersistentDomainForName:appDomain];
} }
} }
-(id) tryGetValueForKey:(NSString *)key { -(id) tryGetValueForKey:(NSString *)key {
require(key != nil); require(key != nil);
@synchronized(self) { @synchronized(self) {
return [[NSUserDefaults standardUserDefaults] objectForKey:key]; return [NSUserDefaults.standardUserDefaults objectForKey:key];
} }
} }
-(void) setValueForKey:(NSString *)key toValue:(id)value { -(void) setValueForKey:(NSString *)key toValue:(id)value {
require(key != nil); require(key != nil);
@synchronized(self) { @synchronized(self) {
NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults]; NSUserDefaults *userDefaults = NSUserDefaults.standardUserDefaults;
[userDefaults setObject:value forKey:key]; [userDefaults setObject:value forKey:key];
[userDefaults synchronize]; [userDefaults synchronize];
} }
@ -45,9 +45,9 @@
[UICKeyChainStore removeItemForKey:key]; [UICKeyChainStore removeItemForKey:key];
DDLogWarn(@"Removing object for key: %@", key); DDLogWarn(@"Removing object for key: %@", key);
} else { } else {
if ([value isKindOfClass:[NSData class]]) { if ([value isKindOfClass:NSData.class]) {
[UICKeyChainStore setData:value forKey:key]; [UICKeyChainStore setData:value forKey:key];
} else if ([value isKindOfClass:[NSString class]]){ } else if ([value isKindOfClass:NSString.class]){
[UICKeyChainStore setString:value forKey:key]; [UICKeyChainStore setString:value forKey:key];
} else{ } else{
DDLogError(@"Unexpected class stored in the Keychain."); DDLogError(@"Unexpected class stored in the Keychain.");

View File

@ -55,14 +55,14 @@ static unsigned char DH3K_PRIME[]={
andDefaultRelayName:@"relay" andDefaultRelayName:@"relay"
andRelayServerHostNameSuffix:@"whispersystems.org" andRelayServerHostNameSuffix:@"whispersystems.org"
andCertificate:[Certificate certificateFromResourcePath:@"whisperReal" ofType:@"cer"] andCertificate:[Certificate certificateFromResourcePath:@"whisperReal" ofType:@"cer"]
andCurrentRegionCodeForPhoneNumbers:[(NSLocale*)[NSLocale currentLocale] objectForKey:NSLocaleCountryCode] andCurrentRegionCodeForPhoneNumbers:[(NSLocale*)NSLocale.currentLocale objectForKey:NSLocaleCountryCode]
andSupportedKeyAgreementProtocols:[self supportedKeyAgreementProtocols] andSupportedKeyAgreementProtocols:[self supportedKeyAgreementProtocols]
andPhoneManager:[PhoneManager phoneManagerWithErrorHandler:errorNoter] andPhoneManager:[PhoneManager phoneManagerWithErrorHandler:errorNoter]
andRecentCallManager:[RecentCallManager new] andRecentCallManager:[RecentCallManager new]
andTestingAndLegacyOptions:@[ENVIRONMENT_LEGACY_OPTION_RTP_PADDING_BIT_IMPLIES_EXTENSION_BIT_AND_TWELVE_EXTRA_ZERO_BYTES_IN_HEADER] andTestingAndLegacyOptions:@[ENVIRONMENT_LEGACY_OPTION_RTP_PADDING_BIT_IMPLIES_EXTENSION_BIT_AND_TWELVE_EXTRA_ZERO_BYTES_IN_HEADER]
andZrtpClientId:RELEASE_ZRTP_CLIENT_ID andZrtpClientId:RELEASE_ZRTP_CLIENT_ID
andZrtpVersionId:RELEASE_ZRTP_VERSION_ID andZrtpVersionId:RELEASE_ZRTP_VERSION_ID
andContactsManager:[[ContactsManager alloc] init] andContactsManager:[ContactsManager new]
andPhoneDirectoryManager:[PhoneNumberDirectoryFilterManager new]]; andPhoneDirectoryManager:[PhoneNumberDirectoryFilterManager new]];
} }

View File

@ -26,7 +26,7 @@
NSDictionary *dict = [NSPropertyListSerialization propertyListWithData:plistData options:NSPropertyListImmutable format:&format error:&error]; NSDictionary *dict = [NSPropertyListSerialization propertyListWithData:plistData options:NSPropertyListImmutable format:&format error:&error];
NSArray *entries = [dict allKeys]; NSArray *entries = [dict allKeys];
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults]; NSUserDefaults *defaults = NSUserDefaults.standardUserDefaults;
for (NSUInteger i = 0; i < entries.count; i++) { for (NSUInteger i = 0; i < entries.count; i++) {
NSString *key = entries[i]; NSString *key = entries[i];

View File

@ -25,7 +25,7 @@
static PushManager *sharedManager = nil; static PushManager *sharedManager = nil;
static dispatch_once_t onceToken; static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{ dispatch_once(&onceToken, ^{
sharedManager = [[self alloc] init]; sharedManager = [self new];
}); });
return sharedManager; return sharedManager;
} }
@ -50,11 +50,11 @@
} }
if (needsPushSettingChangeAlert) { if (needsPushSettingChangeAlert) {
[[Environment preferences] setRevokedPushPermission:YES]; [Environment.preferences setRevokedPushPermission:YES];
UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:NSLocalizedString(@"ACTION_REQUIRED_TITLE", @"") message:NSLocalizedString(@"PUSH_SETTINGS_MESSAGE", @"") delegate:nil cancelButtonTitle:NSLocalizedString(@"OK", @"") otherButtonTitles:nil, nil]; UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:NSLocalizedString(@"ACTION_REQUIRED_TITLE", @"") message:NSLocalizedString(@"PUSH_SETTINGS_MESSAGE", @"") delegate:nil cancelButtonTitle:NSLocalizedString(@"OK", @"") otherButtonTitles:nil, nil];
[alertView show]; [alertView show];
} else if (!needsPushSettingChangeAlert){ } else if (!needsPushSettingChangeAlert){
if ([[Environment preferences] encounteredRevokedPushPermission]) { if (Environment.preferences.encounteredRevokedPushPermission) {
[self askForPushRegistration]; [self askForPushRegistration];
} }
} }
@ -73,21 +73,21 @@
[UIApplication.sharedApplication registerForRemoteNotificationTypes:(UIRemoteNotificationTypeAlert | UIRemoteNotificationTypeSound | UIRemoteNotificationTypeBadge)]; [UIApplication.sharedApplication registerForRemoteNotificationTypes:(UIRemoteNotificationTypeAlert | UIRemoteNotificationTypeSound | UIRemoteNotificationTypeBadge)];
} else{ } else{
#if __IPHONE_OS_VERSION_MAX_ALLOWED > __IPHONE_7_1 #if __IPHONE_OS_VERSION_MAX_ALLOWED > __IPHONE_7_1
UIMutableUserNotificationAction *action_accept = [[UIMutableUserNotificationAction alloc]init]; UIMutableUserNotificationAction *action_accept = [UIMutableUserNotificationAction new];
action_accept.identifier = @"Signal_Call_Accept"; action_accept.identifier = @"Signal_Call_Accept";
action_accept.title = @"Pick up"; action_accept.title = @"Pick up";
action_accept.activationMode = UIUserNotificationActivationModeForeground; action_accept.activationMode = UIUserNotificationActivationModeForeground;
action_accept.destructive = YES; action_accept.destructive = YES;
action_accept.authenticationRequired = NO; action_accept.authenticationRequired = NO;
UIMutableUserNotificationAction *action_decline = [[UIMutableUserNotificationAction alloc]init]; UIMutableUserNotificationAction *action_decline = [UIMutableUserNotificationAction new];
action_decline.identifier = @"Signal_Call_Decline"; action_decline.identifier = @"Signal_Call_Decline";
action_decline.title = @"Pick up"; action_decline.title = @"Pick up";
action_decline.activationMode = UIUserNotificationActivationModeForeground; action_decline.activationMode = UIUserNotificationActivationModeForeground;
action_decline.destructive = YES; action_decline.destructive = YES;
action_decline.authenticationRequired = NO; action_decline.authenticationRequired = NO;
UIMutableUserNotificationCategory *callCategory = [[UIMutableUserNotificationCategory alloc] init]; UIMutableUserNotificationCategory *callCategory = [UIMutableUserNotificationCategory new];
callCategory.identifier = @"Signal_IncomingCall"; callCategory.identifier = @"Signal_IncomingCall";
[callCategory setActions:@[action_accept, action_decline] forContext:UIUserNotificationActionContextDefault]; [callCategory setActions:@[action_accept, action_decline] forContext:UIUserNotificationActionContextDefault];
@ -105,11 +105,11 @@
- (void)registerForPushWithToken:(NSData*)token{ - (void)registerForPushWithToken:(NSData*)token{
[CallServerRequestsManager.sharedInstance registerPushToken:token success:^(NSURLSessionDataTask *task, id responseObject) { [CallServerRequestsManager.sharedInstance registerPushToken:token success:^(NSURLSessionDataTask *task, id responseObject) {
if ([task.response isKindOfClass: [NSHTTPURLResponse class]]){ if ([task.response isKindOfClass: NSHTTPURLResponse.class]){
NSInteger statusCode = [(NSHTTPURLResponse*) task.response statusCode]; NSInteger statusCode = [(NSHTTPURLResponse*) task.response statusCode];
if (statusCode == 200) { if (statusCode == 200) {
DDLogInfo(@"Device sent push ID to server"); DDLogInfo(@"Device sent push ID to server");
[[Environment preferences] setRevokedPushPermission:NO]; [Environment.preferences setRevokedPushPermission:NO];
if (self.PushRegisteringSuccessBlock) { if (self.PushRegisteringSuccessBlock) {
self.PushRegisteringSuccessBlock(); self.PushRegisteringSuccessBlock();
self.PushRegisteringSuccessBlock = nil; self.PushRegisteringSuccessBlock = nil;
@ -139,7 +139,7 @@
self.PushRegisteringFailureBlock(); self.PushRegisteringFailureBlock();
self.PushRegisteringFailureBlock = nil; self.PushRegisteringFailureBlock = nil;
} }
[[Environment preferences] setRevokedPushPermission:YES]; [Environment.preferences setRevokedPushPermission:YES];
} }
} }

View File

@ -30,7 +30,7 @@ void handleDnsCompleted(CFHostRef hostRef, CFHostInfoType typeInfo, const CFStre
checkOperationDescribe(addressDatas != nil, @"No addresses for host"); checkOperationDescribe(addressDatas != nil, @"No addresses for host");
NSArray* ips = [addressDatas map:^(id addressData) { NSArray* ips = [addressDatas map:^(id addressData) {
checkOperation([addressData isKindOfClass:[NSData class]]); checkOperation([addressData isKindOfClass:NSData.class]);
return [[IpEndPoint ipEndPointFromSockaddrData:addressData] address]; return [[IpEndPoint ipEndPointFromSockaddrData:addressData] address];
}]; }];

View File

@ -29,13 +29,13 @@ MacrosSingletonImplemention
self = [super init]; self = [super init];
if (self) { if (self) {
HostNameEndPoint *endpoint = [[[Environment getCurrent]masterServerSecureEndPoint] hostNameEndPoint]; HostNameEndPoint *endpoint = Environment.getCurrent.masterServerSecureEndPoint.hostNameEndPoint;
NSURL *endPointURL = [NSURL URLWithString:[NSString stringWithFormat:@"https://%@:%hu", endpoint.hostname, endpoint.port]]; NSURL *endPointURL = [NSURL URLWithString:[NSString stringWithFormat:@"https://%@:%hu", endpoint.hostname, endpoint.port]];
NSURLSessionConfiguration *sessionConf = [NSURLSessionConfiguration ephemeralSessionConfiguration]; NSURLSessionConfiguration *sessionConf = NSURLSessionConfiguration.ephemeralSessionConfiguration;
self.operationManager = [[AFHTTPSessionManager alloc] initWithBaseURL:endPointURL sessionConfiguration:sessionConf]; self.operationManager = [[AFHTTPSessionManager alloc] initWithBaseURL:endPointURL sessionConfiguration:sessionConf];
self.operationManager.responseSerializer = [AFJSONResponseSerializer serializer]; self.operationManager.responseSerializer = [AFJSONResponseSerializer serializer];
self.operationManager.securityPolicy.allowInvalidCertificates = YES; self.operationManager.securityPolicy.allowInvalidCertificates = YES;
NSString *certPath = [[NSBundle mainBundle] pathForResource:@"whisperReal" ofType:@"cer"]; NSString *certPath = [NSBundle.mainBundle pathForResource:@"whisperReal" ofType:@"cer"];
NSData *certData = [NSData dataWithContentsOfFile:certPath]; NSData *certData = [NSData dataWithContentsOfFile:certPath];
SecCertificateRef cert = SecCertificateCreateWithData(NULL, (__bridge CFDataRef)(certData)); SecCertificateRef cert = SecCertificateCreateWithData(NULL, (__bridge CFDataRef)(certData));
self.operationManager.securityPolicy.pinnedCertificates = @[(__bridge_transfer NSData *)SecCertificateCopyData(cert)]; self.operationManager.securityPolicy.pinnedCertificates = @[(__bridge_transfer NSData *)SecCertificateCopyData(cert)];

View File

@ -36,7 +36,7 @@
@try { @try {
TOCFutureSource* ev = [TOCFutureSource futureSourceUntil:unlessCancelledToken]; TOCFutureSource* ev = [TOCFutureSource futureSourceUntil:unlessCancelledToken];
@synchronized (self) { @synchronized (self) {
if ([lifetime.token isAlreadyCancelled]) { if (lifetime.token.isAlreadyCancelled) {
return [TOCFuture futureWithFailure:@"terminated"]; return [TOCFuture futureWithFailure:@"terminated"];
} }
[eventualResponseQueue enqueue:ev]; [eventualResponseQueue enqueue:ev];
@ -53,7 +53,7 @@
require(request != nil); require(request != nil);
require(errorHandler != nil); require(errorHandler != nil);
HttpManager* manager = [HttpManager startWithEndPoint:[Environment getMasterServerSecureEndPoint] HttpManager* manager = [HttpManager startWithEndPoint:Environment.getMasterServerSecureEndPoint
untilCancelled:unlessCancelledToken]; untilCancelled:unlessCancelledToken];
[manager startWithRejectingRequestHandlerAndErrorHandler:errorHandler [manager startWithRejectingRequestHandlerAndErrorHandler:errorHandler
@ -112,7 +112,7 @@
PacketHandlerBlock httpHandler = ^(HttpRequestOrResponse* requestOrResponse) { PacketHandlerBlock httpHandler = ^(HttpRequestOrResponse* requestOrResponse) {
require(requestOrResponse != nil); require(requestOrResponse != nil);
require([requestOrResponse isKindOfClass:[HttpRequestOrResponse class]]); require([requestOrResponse isKindOfClass:HttpRequestOrResponse.class]);
@synchronized (self) { @synchronized (self) {
if (requestOrResponse.isRequest) { if (requestOrResponse.isRequest) {
HttpResponse* response = requestHandler([requestOrResponse request]); HttpResponse* response = requestHandler([requestOrResponse request]);

View File

@ -13,10 +13,10 @@
return h; return h;
} }
-(bool) isRequest { -(bool) isRequest {
return [requestOrResponse isKindOfClass:[HttpRequest class]]; return [requestOrResponse isKindOfClass:HttpRequest.class];
} }
-(bool) isResponse { -(bool) isResponse {
return [requestOrResponse isKindOfClass:[HttpResponse class]]; return [requestOrResponse isKindOfClass:HttpResponse.class];
} }
-(HttpRequest*) request { -(HttpRequest*) request {
requireState(self.isRequest); requireState(self.isRequest);
@ -62,8 +62,8 @@
NSArray* headerLineParts = [headerLine componentsSeparatedByString:@":"]; NSArray* headerLineParts = [headerLine componentsSeparatedByString:@":"];
checkOperation(headerLineParts.count >= 2); checkOperation(headerLineParts.count >= 2);
NSString* headerKey = [headerLineParts[0] stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]]; NSString* headerKey = [headerLineParts[0] stringByTrimmingCharactersInSet:NSCharacterSet.whitespaceCharacterSet];
NSString* headerValue = [[headerLine substringFromIndex:[(NSString *)headerLineParts[0] length]+1] stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]]; NSString* headerValue = [[headerLine substringFromIndex:[(NSString *)headerLineParts[0] length]+1] stringByTrimmingCharactersInSet:NSCharacterSet.whitespaceCharacterSet];
headers[headerKey] = headerValue; headers[headerKey] = headerValue;
} }

View File

@ -19,7 +19,7 @@
andLocation:location andLocation:location
andOptionalBody:optionalBody andOptionalBody:optionalBody
andLocalNumber:SGNKeychainUtil.localNumber andLocalNumber:SGNKeychainUtil.localNumber
andPassword:[SGNKeychainUtil serverAuthPassword]]; andPassword:SGNKeychainUtil.serverAuthPassword];
} }
+(HttpRequest*)httpRequestWithOtpAuthenticationAndMethod:(NSString*)method +(HttpRequest*)httpRequestWithOtpAuthenticationAndMethod:(NSString*)method
andLocation:(NSString*)location { andLocation:(NSString*)location {
@ -34,7 +34,7 @@
andLocation:location andLocation:location
andOptionalBody:optionalBody andOptionalBody:optionalBody
andLocalNumber:SGNKeychainUtil.localNumber andLocalNumber:SGNKeychainUtil.localNumber
andPassword:[SGNKeychainUtil serverAuthPassword] andPassword:SGNKeychainUtil.serverAuthPassword
andCounter:[SGNKeychainUtil getAndIncrementOneTimeCounter]]; andCounter:[SGNKeychainUtil getAndIncrementOneTimeCounter]];
} }
+(HttpRequest*)httpRequestUnauthenticatedWithMethod:(NSString*)method +(HttpRequest*)httpRequestUnauthenticatedWithMethod:(NSString*)method

View File

@ -103,7 +103,7 @@
[r addObject:statusText]; [r addObject:statusText];
[r addObject:@"\r\n"]; [r addObject:@"\r\n"];
NSString* body = [self getOptionalBodyText]; NSString* body = self.getOptionalBodyText;
if (body != nil) { if (body != nil) {
[r addObject:@"Content-Length: "]; [r addObject:@"Content-Length: "];
[r addObject:[@(body.length) stringValue]]; [r addObject:[@(body.length) stringValue]];

View File

@ -11,8 +11,8 @@
HttpSocket* h = [HttpSocket new]; HttpSocket* h = [HttpSocket new];
h->rawDataChannelTcp = rawDataChannel; h->rawDataChannelTcp = rawDataChannel;
h->partialDataBuffer = [NSMutableData data]; h->partialDataBuffer = [NSMutableData data];
h->sentPacketsLogger = [[Environment logging] getOccurrenceLoggerForSender:self withKey:@"sent"]; h->sentPacketsLogger = [Environment.logging getOccurrenceLoggerForSender:self withKey:@"sent"];
h->receivedPacketsLogger = [[Environment logging] getOccurrenceLoggerForSender:self withKey:@"received"]; h->receivedPacketsLogger = [Environment.logging getOccurrenceLoggerForSender:self withKey:@"received"];
return h; return h;
} }
+(HttpSocket*) httpSocketOverUdp:(UdpSocket*)rawDataChannel { +(HttpSocket*) httpSocketOverUdp:(UdpSocket*)rawDataChannel {
@ -21,8 +21,8 @@
HttpSocket* h = [HttpSocket new]; HttpSocket* h = [HttpSocket new];
h->rawDataChannelUdp = rawDataChannel; h->rawDataChannelUdp = rawDataChannel;
h->partialDataBuffer = [NSMutableData data]; h->partialDataBuffer = [NSMutableData data];
h->sentPacketsLogger = [[Environment logging] getOccurrenceLoggerForSender:self withKey:@"sent"]; h->sentPacketsLogger = [Environment.logging getOccurrenceLoggerForSender:self withKey:@"sent"];
h->receivedPacketsLogger = [[Environment logging] getOccurrenceLoggerForSender:self withKey:@"received"]; h->receivedPacketsLogger = [Environment.logging getOccurrenceLoggerForSender:self withKey:@"received"];
return h; return h;
} }
@ -60,7 +60,7 @@
PacketHandler* packetHandler = [PacketHandler packetHandler:^(id packet) { PacketHandler* packetHandler = [PacketHandler packetHandler:^(id packet) {
require(packet != nil); require(packet != nil);
require([packet isKindOfClass:[NSData class]]); require([packet isKindOfClass:NSData.class]);
NSData* data = packet; NSData* data = packet;
[partialDataBuffer replaceBytesInRange:NSMakeRange(partialDataBuffer.length, data.length) withBytes:[data bytes]]; [partialDataBuffer replaceBytesInRange:NSMakeRange(partialDataBuffer.length, data.length) withBytes:[data bytes]];
@ -82,7 +82,7 @@
[receivedPacketsLogger markOccurrence:s]; [receivedPacketsLogger markOccurrence:s];
[handler handlePacket:s]; [handler handlePacket:s];
} }
} withErrorHandler:[handler errorHandler]]; } withErrorHandler:handler.errorHandler];
if (rawDataChannelTcp != nil) { if (rawDataChannelTcp != nil) {
[rawDataChannelTcp startWithHandler:packetHandler]; [rawDataChannelTcp startWithHandler:packetHandler];

View File

@ -24,7 +24,7 @@
PacketHandlerBlock valueHandler = ^(id packet) { PacketHandlerBlock valueHandler = ^(id packet) {
require(packet != nil); require(packet != nil);
require([packet isKindOfClass:[NSData class]]); require([packet isKindOfClass:NSData.class]);
NSData* data = packet; NSData* data = packet;
RtpPacket* rtpPacket = [RtpPacket rtpPacketParsedFromPacketData:data]; RtpPacket* rtpPacket = [RtpPacket rtpPacketParsedFromPacketData:data];
@ -51,7 +51,7 @@
} }
-(void) handleRtpPacket:(RtpPacket*)rtpPacket { -(void) handleRtpPacket:(RtpPacket*)rtpPacket {
@synchronized(self) { @synchronized(self) {
if ([ThreadManager lowLatencyThread] == [NSThread currentThread]) { if ([ThreadManager lowLatencyThread] == NSThread.currentThread) {
[currentHandler handlePacket:rtpPacket]; [currentHandler handlePacket:rtpPacket];
return; return;
} }

View File

@ -23,7 +23,7 @@
s->incomingContext = [SrtpStream srtpStreamWithCipherKey:incomingCipherKey andMacKey:incomingMacKey andCipherIvSalt:incomingSalt]; s->incomingContext = [SrtpStream srtpStreamWithCipherKey:incomingCipherKey andMacKey:incomingMacKey andCipherIvSalt:incomingSalt];
s->outgoingContext = [SrtpStream srtpStreamWithCipherKey:outgoingCipherKey andMacKey:outgoingMacKey andCipherIvSalt:outgoingSalt]; s->outgoingContext = [SrtpStream srtpStreamWithCipherKey:outgoingCipherKey andMacKey:outgoingMacKey andCipherIvSalt:outgoingSalt];
s->rtpSocket = rtpSocket; s->rtpSocket = rtpSocket;
s->badPacketLogger = [[Environment logging] getOccurrenceLoggerForSender:self withKey:@"Bad Packet"]; s->badPacketLogger = [Environment.logging getOccurrenceLoggerForSender:self withKey:@"Bad Packet"];
return s; return s;
} }
@ -43,7 +43,7 @@
PacketHandlerBlock packetHandler = ^(id packet) { PacketHandlerBlock packetHandler = ^(id packet) {
require(packet != nil); require(packet != nil);
require([packet isKindOfClass:[RtpPacket class]]); require([packet isKindOfClass:RtpPacket.class]);
RtpPacket* decryptedPacket; RtpPacket* decryptedPacket;
@try { @try {

View File

@ -79,8 +79,8 @@
counter, counter,
dhResult, dhResult,
@"ZRTP-HMAC-KDF".encodedAsUtf8, @"ZRTP-HMAC-KDF".encodedAsUtf8,
[initiatorZid getData], initiatorZid.getData,
[responderZid getData], responderZid.getData,
totalHash, totalHash,
s1Length, s1Length,
s2Length, s2Length,
@ -144,17 +144,17 @@
} }
-(NSData*) deriveKeyWithLabel:(NSString*)label andTruncatedLength:(uint16_t)truncatedLength { -(NSData*) deriveKeyWithLabel:(NSString*)label andTruncatedLength:(uint16_t)truncatedLength {
NSData* input = [@[ NSData* input = @[
counter, counter,
label.encodedAsUtf8, label.encodedAsUtf8,
[@[@0] toUint8Data], [@[@0] toUint8Data],
[initiatorZid getData], initiatorZid.getData,
[responderZid getData], responderZid.getData,
totalHash, totalHash,
[NSData dataWithBigEndianBytesOfUInt32:truncatedLength] [NSData dataWithBigEndianBytesOfUInt32:truncatedLength]
] concatDatas]; ].concatDatas;
NSData* digest = [input hmacWithSha256WithKey:sharedSecret]; NSData* digest = [input hmacWithSha256WithKey:sharedSecret];

View File

@ -7,8 +7,8 @@
ZrtpHandshakeSocket* z = [ZrtpHandshakeSocket new]; ZrtpHandshakeSocket* z = [ZrtpHandshakeSocket new];
z->rtpSocket = rtpSocket; z->rtpSocket = rtpSocket;
z->sentPacketsLogger = [[Environment logging] getOccurrenceLoggerForSender:self withKey:@"sent"]; z->sentPacketsLogger = [Environment.logging getOccurrenceLoggerForSender:self withKey:@"sent"];
z->receivedPacketsLogger = [[Environment logging] getOccurrenceLoggerForSender:self withKey:@"received"]; z->receivedPacketsLogger = [Environment.logging getOccurrenceLoggerForSender:self withKey:@"received"];
return z; return z;
} }
-(void) send:(HandshakePacket*)packet { -(void) send:(HandshakePacket*)packet {
@ -27,7 +27,7 @@
PacketHandlerBlock packetHandler = ^(id packet) { PacketHandlerBlock packetHandler = ^(id packet) {
require(packet != nil); require(packet != nil);
require([packet isKindOfClass:[RtpPacket class]]); require([packet isKindOfClass:RtpPacket.class]);
RtpPacket* rtpPacket = packet; RtpPacket* rtpPacket = packet;
HandshakePacket* handshakePacket = nil; HandshakePacket* handshakePacket = nil;
@ -43,7 +43,7 @@
}; };
[rtpSocket startWithHandler:[PacketHandler packetHandler:packetHandler [rtpSocket startWithHandler:[PacketHandler packetHandler:packetHandler
withErrorHandler:[handler errorHandler]] withErrorHandler:handler.errorHandler]
untilCancelled:untilCancelledToken]; untilCancelled:untilCancelledToken];
} }

View File

@ -22,12 +22,12 @@
ZrtpInitiator* s = [ZrtpInitiator new]; ZrtpInitiator* s = [ZrtpInitiator new];
s->allowedKeyAgreementProtocols = [[Environment getCurrent] keyAgreementProtocolsInDescendingPriority]; s->allowedKeyAgreementProtocols = Environment.getCurrent.keyAgreementProtocolsInDescendingPriority;
s->dhSharedSecretHashes = [DhPacketSharedSecretHashes dhPacketSharedSecretHashesRandomized]; s->dhSharedSecretHashes = [DhPacketSharedSecretHashes dhPacketSharedSecretHashesRandomized];
s->zid = [SGNKeychainUtil zid]; s->zid = [SGNKeychainUtil zid];
s->confirmIv = [CryptoTools generateSecureRandomData:IV_LENGTH]; s->confirmIv = [CryptoTools generateSecureRandomData:IV_LENGTH];
s->hashChain = [HashChain hashChainWithSecureGeneratedData]; s->hashChain = [HashChain hashChainWithSecureGeneratedData];
s->badPacketLogger = [[Environment logging] getOccurrenceLoggerForSender:self withKey:@"Bad Packet"]; s->badPacketLogger = [Environment.logging getOccurrenceLoggerForSender:self withKey:@"Bad Packet"];
s->packetExpectation = EXPECTING_HELLO; s->packetExpectation = EXPECTING_HELLO;
s->callController = callController; s->callController = callController;
@ -89,7 +89,7 @@
andSharedSecretHashes:dhSharedSecretHashes andSharedSecretHashes:dhSharedSecretHashes
andKeyAgreer:keyAgreementParticipant]; andKeyAgreer:keyAgreementParticipant];
commitPacket = [CommitPacket commitPacketWithDefaultSpecsAndKeyAgreementProtocol:[keyAgreementParticipant getProtocol] commitPacket = [CommitPacket commitPacketWithDefaultSpecsAndKeyAgreementProtocol:keyAgreementParticipant.getProtocol
andHashChain:hashChain andHashChain:hashChain
andZid:zid andZid:zid
andCommitmentToHello:foreignHello andCommitmentToHello:foreignHello
@ -141,7 +141,7 @@
-(bool) isAuthenticatedAudioDataImplyingConf2Ack:(id)packet { -(bool) isAuthenticatedAudioDataImplyingConf2Ack:(id)packet {
if (packetExpectation != EXPECTING_CONFIRM_ACK) return false; if (packetExpectation != EXPECTING_CONFIRM_ACK) return false;
if (![packet isKindOfClass:[RtpPacket class]]) return false; if (![packet isKindOfClass:RtpPacket.class]) return false;
@try { @try {
SrtpStream* incomingContext = [SrtpStream srtpStreamWithCipherKey:[masterSecret responderSrtpKey] SrtpStream* incomingContext = [SrtpStream srtpStreamWithCipherKey:[masterSecret responderSrtpKey]
@ -158,7 +158,7 @@
NSArray* idsOfProtocolsAllowedByPeer = [foreignHello agreeIdsIncludingImplied]; NSArray* idsOfProtocolsAllowedByPeer = [foreignHello agreeIdsIncludingImplied];
id<KeyAgreementProtocol> bestCommonKeyAgreementProtocol = [allowedKeyAgreementProtocols firstMatchingElseNil:^int(id<KeyAgreementProtocol> locallyAllowedProtocol) { id<KeyAgreementProtocol> bestCommonKeyAgreementProtocol = [allowedKeyAgreementProtocols firstMatchingElseNil:^int(id<KeyAgreementProtocol> locallyAllowedProtocol) {
return [idsOfProtocolsAllowedByPeer containsObject:[locallyAllowedProtocol getId]]; return [idsOfProtocolsAllowedByPeer containsObject:locallyAllowedProtocol.getId];
}]; }];
// Note: should never fail to find a common protocol because DH3k support is required and implied // Note: should never fail to find a common protocol because DH3k support is required and implied

View File

@ -67,7 +67,7 @@
-(TOCFuture*) asyncPerformHandshake { -(TOCFuture*) asyncPerformHandshake {
PacketHandlerBlock packetHandler = ^(id packet) { PacketHandlerBlock packetHandler = ^(id packet) {
require(packet != nil); require(packet != nil);
require([packet isKindOfClass:[HandshakePacket class]]); require([packet isKindOfClass:HandshakePacket.class]);
[self handleHandshakePacket:(HandshakePacket*)packet]; [self handleHandshakePacket:(HandshakePacket*)packet];
}; };
@ -178,7 +178,7 @@
handshakeCompletedSuccesfully = true; handshakeCompletedSuccesfully = true;
SrtpSocket* secureChannel = [zrtpRole useKeysToSecureRtpSocket:rtpSocketToSecure]; SrtpSocket* secureChannel = [zrtpRole useKeysToSecureRtpSocket:rtpSocketToSecure];
MasterSecret* masterSecret = [zrtpRole getMasterSecret]; MasterSecret* masterSecret = zrtpRole.getMasterSecret;
ZrtpHandshakeResult* result = [ZrtpHandshakeResult zrtpHandshakeResultWithSecureChannel:secureChannel andMasterSecret:masterSecret]; ZrtpHandshakeResult* result = [ZrtpHandshakeResult zrtpHandshakeResultWithSecureChannel:secureChannel andMasterSecret:masterSecret];

View File

@ -25,9 +25,9 @@
s->confirmIv = [CryptoTools generateSecureRandomData:IV_LENGTH]; s->confirmIv = [CryptoTools generateSecureRandomData:IV_LENGTH];
s->dhSharedSecretHashes = [DhPacketSharedSecretHashes dhPacketSharedSecretHashesRandomized]; s->dhSharedSecretHashes = [DhPacketSharedSecretHashes dhPacketSharedSecretHashesRandomized];
s->allowedKeyAgreementProtocols = [[Environment getCurrent] keyAgreementProtocolsInDescendingPriority]; s->allowedKeyAgreementProtocols = Environment.getCurrent.keyAgreementProtocolsInDescendingPriority;
s->hashChain = [HashChain hashChainWithSecureGeneratedData]; s->hashChain = [HashChain hashChainWithSecureGeneratedData];
s->badPacketLogger = [[Environment logging] getOccurrenceLoggerForSender:self withKey:@"Bad Packet"]; s->badPacketLogger = [Environment.logging getOccurrenceLoggerForSender:self withKey:@"Bad Packet"];
s->localHello = [HelloPacket helloPacketWithDefaultsAndHashChain:s->hashChain s->localHello = [HelloPacket helloPacketWithDefaultsAndHashChain:s->hashChain
andZid:[SGNKeychainUtil zid] andZid:[SGNKeychainUtil zid]
@ -140,7 +140,7 @@
-(id<KeyAgreementParticipant>) retrieveKeyAgreementParticipant{ -(id<KeyAgreementParticipant>) retrieveKeyAgreementParticipant{
id<KeyAgreementProtocol> matchingKeyAgreeProtocol = [allowedKeyAgreementProtocols firstMatchingElseNil:^int(id<KeyAgreementProtocol> a) { id<KeyAgreementProtocol> matchingKeyAgreeProtocol = [allowedKeyAgreementProtocols firstMatchingElseNil:^int(id<KeyAgreementProtocol> a) {
return [[foreignCommit agreementSpecId] isEqualToData:[a getId]]; return [[foreignCommit agreementSpecId] isEqualToData:a.getId];
}]; }];
checkOperation(matchingKeyAgreeProtocol != nil); checkOperation(matchingKeyAgreeProtocol != nil);

View File

@ -8,7 +8,7 @@
DH3KKeyAgreementParticipant* participant = [DH3KKeyAgreementParticipant new]; DH3KKeyAgreementParticipant* participant = [DH3KKeyAgreementParticipant new];
participant->protocol = protocol; participant->protocol = protocol;
participant->evpKeyAgreement = [EvpKeyAgreement evpDh3kKeyAgreementWithModulus:[protocol getModulus] andGenerator:[protocol getGenerator]]; participant->evpKeyAgreement = [EvpKeyAgreement evpDh3kKeyAgreementWithModulus:protocol.getModulus andGenerator:protocol.getGenerator];
return participant; return participant;
} }
@ -17,7 +17,7 @@
} }
-(NSData*) getPublicKeyData{ -(NSData*) getPublicKeyData{
return [self->evpKeyAgreement getPublicKey]; return self->evpKeyAgreement.getPublicKey;
} }
-(NSData*) calculateKeyAgreementAgainstRemotePublicKey:(NSData*)remotePublicKey{ -(NSData*) calculateKeyAgreementAgainstRemotePublicKey:(NSData*)remotePublicKey{

View File

@ -20,7 +20,7 @@
} }
-(NSData*) getPublicKeyData{ -(NSData*) getPublicKeyData{
return [evpKeyAgreement getPublicKey]; return evpKeyAgreement.getPublicKey;
} }
-(NSData*) calculateKeyAgreementAgainstRemotePublicKey:(NSData*)remotePublicKey{ -(NSData*) calculateKeyAgreementAgainstRemotePublicKey:(NSData*)remotePublicKey{

View File

@ -37,15 +37,15 @@
NSData* dhPart2Data = [[dhPart2 embeddedIntoHandshakePacket] dataUsedForAuthentication]; NSData* dhPart2Data = [[dhPart2 embeddedIntoHandshakePacket] dataUsedForAuthentication];
NSData* helloData = [[hello embeddedIntoHandshakePacket] dataUsedForAuthentication]; NSData* helloData = [[hello embeddedIntoHandshakePacket] dataUsedForAuthentication];
return [CommitPacket commitPacketWithHashChainH2:[hashChain h2] return [CommitPacket commitPacketWithHashChainH2:hashChain.h2
andZid:zid andZid:zid
andHashSpecId:COMMIT_DEFAULT_HASH_SPEC_ID andHashSpecId:COMMIT_DEFAULT_HASH_SPEC_ID
andCipherSpecId:COMMIT_DEFAULT_CIPHER_SPEC_ID andCipherSpecId:COMMIT_DEFAULT_CIPHER_SPEC_ID
andAuthSpecId:COMMIT_DEFAULT_AUTH_SPEC_ID andAuthSpecId:COMMIT_DEFAULT_AUTH_SPEC_ID
andAgreeSpecId:[keyAgreementProtocol getId] andAgreeSpecId:keyAgreementProtocol.getId
andSasSpecId:COMMIT_DEFAULT_SAS_SPEC_ID andSasSpecId:COMMIT_DEFAULT_SAS_SPEC_ID
andDhPart2HelloCommitment:[[@[dhPart2Data, helloData] concatDatas] hashWithSha256] andDhPart2HelloCommitment:@[dhPart2Data, helloData].concatDatas.hashWithSha256
andHmacKey:[hashChain h1]]; andHmacKey:hashChain.h1];
} }
+(CommitPacket*) commitPacketWithHashChainH2:(NSData*)h2 +(CommitPacket*) commitPacketWithHashChainH2:(NSData*)h2
@ -100,16 +100,16 @@
requireState(agreementSpecId.length == AGREE_SPEC_LENGTH); requireState(agreementSpecId.length == AGREE_SPEC_LENGTH);
requireState(sasSpecId.length == SAS_SPEC_LENGTH); requireState(sasSpecId.length == SAS_SPEC_LENGTH);
NSData* payload = [@[ NSData* payload = @[
h2, h2,
[zid getData], zid.getData,
hashSpecId, hashSpecId,
cipherSpecId, cipherSpecId,
authSpecId, authSpecId,
agreementSpecId, agreementSpecId,
sasSpecId, sasSpecId,
dhPart2HelloCommitment dhPart2HelloCommitment
] concatDatas]; ].concatDatas;
return [[HandshakePacket handshakePacketWithTypeId:HANDSHAKE_TYPE_COMMIT andPayload:payload] withHmacAppended:hmacKey]; return [[HandshakePacket handshakePacketWithTypeId:HANDSHAKE_TYPE_COMMIT andPayload:payload] withHmacAppended:hmacKey];
} }

View File

@ -25,7 +25,7 @@
return [self dhPacketWithHashChainH0:[hashChain h0] return [self dhPacketWithHashChainH0:[hashChain h0]
andSharedSecretHashes:sharedSecretHashes andSharedSecretHashes:sharedSecretHashes
andPublicKeyData:[agreer getPublicKeyData] andPublicKeyData:agreer.getPublicKeyData
andIsPart1:true]; andIsPart1:true];
} }
@ -39,7 +39,7 @@
return [self dhPacketWithHashChainH0:[hashChain h0] return [self dhPacketWithHashChainH0:[hashChain h0]
andSharedSecretHashes:sharedSecretHashes andSharedSecretHashes:sharedSecretHashes
andPublicKeyData:[agreer getPublicKeyData] andPublicKeyData:agreer.getPublicKeyData
andIsPart1:false]; andIsPart1:false];
} }

View File

@ -42,10 +42,10 @@
bool hasDH3k = false; bool hasDH3k = false;
for (id<KeyAgreementProtocol> e in keyAgreementProtocols) { for (id<KeyAgreementProtocol> e in keyAgreementProtocols) {
if ([[e getId] isEqualToData:COMMIT_DEFAULT_AGREE_SPEC_ID]) { if ([e.getId isEqualToData:COMMIT_DEFAULT_AGREE_SPEC_ID]) {
hasDH3k = true; hasDH3k = true;
} else { } else {
[agreeSpecIds addObject:[e getId]]; [agreeSpecIds addObject:e.getId];
} }
} }
@ -60,8 +60,8 @@
require(zid != nil); require(zid != nil);
require(keyAgreementProtocols != nil); require(keyAgreementProtocols != nil);
return [HelloPacket helloPacketWithVersion:[Environment getCurrent].zrtpVersionId return [HelloPacket helloPacketWithVersion:Environment.getCurrent.zrtpVersionId
andClientId:[Environment getCurrent].zrtpClientId andClientId:Environment.getCurrent.zrtpClientId
andHashChainH3:[hashChain h3] andHashChainH3:[hashChain h3]
andZid:zid andZid:zid
andFlags0SMP:0 andFlags0SMP:0
@ -155,7 +155,7 @@
versionId, versionId,
clientId, clientId,
hashChainH3, hashChainH3,
[zid getData], zid.getData,
[self generateFlags], [self generateFlags],
[[@[hashIds, cipherIds, authIds, agreeIds, sasIds] concatArrays] concatDatas] [[@[hashIds, cipherIds, authIds, agreeIds, sasIds] concatArrays] concatDatas]

View File

@ -26,7 +26,7 @@
require(resourcePath != nil); require(resourcePath != nil);
require(resourceType != nil); require(resourceType != nil);
NSString *certPath = [[NSBundle mainBundle] pathForResource:resourcePath ofType:resourceType]; NSString *certPath = [NSBundle.mainBundle pathForResource:resourcePath ofType:resourceType];
NSData *certData = [[NSData alloc] initWithContentsOfFile:certPath]; NSData *certData = [[NSData alloc] initWithContentsOfFile:certPath];
checkOperation(certData != nil); checkOperation(certData != nil);

View File

@ -16,7 +16,7 @@
require(remoteEndPoint != nil); require(remoteEndPoint != nil);
// all connections must be secure, unless testing // all connections must be secure, unless testing
bool isSecureEndPoint = [remoteEndPoint isKindOfClass:[SecureEndPoint class]]; bool isSecureEndPoint = [remoteEndPoint isKindOfClass:SecureEndPoint.class];
bool allowTestNonSecure = [Environment hasEnabledTestingOrLegacyOption:ENVIRONMENT_TESTING_OPTION_ALLOW_NETWORK_STREAM_TO_NON_SECURE_END_POINTS]; bool allowTestNonSecure = [Environment hasEnabledTestingOrLegacyOption:ENVIRONMENT_TESTING_OPTION_ALLOW_NETWORK_STREAM_TO_NON_SECURE_END_POINTS];
require(allowTestNonSecure || isSecureEndPoint); require(allowTestNonSecure || isSecureEndPoint);

View File

@ -181,7 +181,7 @@ void onReceivedData(CFSocketRef socket, CFSocketCallBackType type, CFDataRef add
[self setupRemoteEndPoint]; [self setupRemoteEndPoint];
NSRunLoop* runLoop = [ThreadManager lowLatencyThreadRunLoop]; NSRunLoop* runLoop = [ThreadManager lowLatencyThreadRunLoop];
CFRunLoopAddSource([runLoop getCFRunLoop], CFSocketCreateRunLoopSource(NULL, socket, 0), kCFRunLoopCommonModes); CFRunLoopAddSource(runLoop.getCFRunLoop, CFSocketCreateRunLoopSource(NULL, socket, 0), kCFRunLoopCommonModes);
[untilCancelledToken whenCancelledDo:^{ [untilCancelledToken whenCancelledDo:^{
@synchronized(self) { @synchronized(self) {

View File

@ -16,8 +16,8 @@
m->currentCallStateObservable = [ObservableValueController observableValueControllerWithInitialValue:nil]; m->currentCallStateObservable = [ObservableValueController observableValueControllerWithInitialValue:nil];
[m->currentCallControllerObservable watchLatestValue:^(CallController* latestValue) { [m->currentCallControllerObservable watchLatestValue:^(CallController* latestValue) {
[m->currentCallStateObservable updateValue:[latestValue callState]]; [m->currentCallStateObservable updateValue:latestValue.callState];
} onThread:[NSThread currentThread] untilCancelled:nil]; } onThread:NSThread.currentThread untilCancelled:nil];
return m; return m;
} }
@ -65,14 +65,14 @@
TOCFuture* futureCalling = [futureConnected thenTry:^id(CallConnectResult* connectResult) { TOCFuture* futureCalling = [futureConnected thenTry:^id(CallConnectResult* connectResult) {
[callController advanceCallProgressToConversingWithShortAuthenticationString:connectResult.shortAuthenticationString]; [callController advanceCallProgressToConversingWithShortAuthenticationString:connectResult.shortAuthenticationString];
CallAudioManager *cam = [CallAudioManager callAudioManagerStartedWithAudioSocket:connectResult.audioSocket CallAudioManager *cam = [CallAudioManager callAudioManagerStartedWithAudioSocket:connectResult.audioSocket
andErrorHandler:[callController errorHandler] andErrorHandler:callController.errorHandler
untilCancelled:lifetime]; untilCancelled:lifetime];
[callController setCallAudioManager:cam]; [callController setCallAudioManager:cam];
return nil; return nil;
}]; }];
[futureCalling catchDo:^(id error) { [futureCalling catchDo:^(id error) {
[callController errorHandler](error, nil, true); callController.errorHandler(error, nil, true);
}]; }];
} }
@ -82,21 +82,21 @@
int64_t prevSession = lastIncomingSessionId; int64_t prevSession = lastIncomingSessionId;
lastIncomingSessionId = session.sessionId; lastIncomingSessionId = session.sessionId;
if ([[[[currentCallControllerObservable currentValue] callState] futureTermination] isIncomplete]) { if (currentCallControllerObservable.currentValue.callState.futureTermination.isIncomplete) {
if (session.sessionId == prevSession) { if (session.sessionId == prevSession) {
[Environment errorNoter](@"Ignoring duplicate incoming call signal.", session, false); Environment.errorNoter(@"Ignoring duplicate incoming call signal.", session, false);
return; return;
} }
[[[Environment getCurrent] recentCallManager] addMissedCallDueToBusy:session]; [Environment.getCurrent.recentCallManager addMissedCallDueToBusy:session];
[[CallConnectUtil asyncSignalTooBusyToAnswerCallWithSessionDescriptor:session] catchDo:^(id error) { [[CallConnectUtil asyncSignalTooBusyToAnswerCallWithSessionDescriptor:session] catchDo:^(id error) {
[Environment errorNoter](error, @"Failed to signal busy.", false); Environment.errorNoter(error, @"Failed to signal busy.", false);
}]; }];
return; return;
} }
Contact* callingContact = [[[Environment getCurrent] contactsManager] latestContactForPhoneNumber:session.initiatorNumber]; Contact* callingContact = [Environment.getCurrent.contactsManager latestContactForPhoneNumber:session.initiatorNumber];
CallController* callController = [self cancelExistingCallAndInitNewCallWork:false CallController* callController = [self cancelExistingCallAndInitNewCallWork:false
remote:session.initiatorNumber remote:session.initiatorNumber
optionalContact:callingContact]; optionalContact:callingContact];
@ -109,18 +109,18 @@
TOCFuture* futureStarted = [futureConnected thenTry:^id(CallConnectResult* connectResult) { TOCFuture* futureStarted = [futureConnected thenTry:^id(CallConnectResult* connectResult) {
[callController advanceCallProgressToConversingWithShortAuthenticationString:connectResult.shortAuthenticationString]; [callController advanceCallProgressToConversingWithShortAuthenticationString:connectResult.shortAuthenticationString];
CallAudioManager* cam = [CallAudioManager callAudioManagerStartedWithAudioSocket:connectResult.audioSocket CallAudioManager* cam = [CallAudioManager callAudioManagerStartedWithAudioSocket:connectResult.audioSocket
andErrorHandler:[callController errorHandler] andErrorHandler:callController.errorHandler
untilCancelled:lifetime]; untilCancelled:lifetime];
[callController setCallAudioManager:cam]; [callController setCallAudioManager:cam];
return nil; return nil;
}]; }];
[futureStarted catchDo:^(id error) { [futureStarted catchDo:^(id error) {
[callController errorHandler](error, nil, true); callController.errorHandler(error, nil, true);
}]; }];
} }
-(CallController*) curCallController { -(CallController*) curCallController {
return [currentCallControllerObservable currentValue]; return currentCallControllerObservable.currentValue;
} }
-(void) answerCall { -(void) answerCall {
[[self curCallController] acceptCall]; [[self curCallController] acceptCall];

View File

@ -38,7 +38,7 @@ static NSString *const RPDefaultsKeyPhoneNumberCanonical = @"RPDefaultsKeyPhoneN
require(text != nil); require(text != nil);
return [PhoneNumber phoneNumberFromText:text return [PhoneNumber phoneNumberFromText:text
andRegion:[Environment currentRegionCodeForPhoneNumbers]]; andRegion:Environment.currentRegionCodeForPhoneNumbers];
} }
+(PhoneNumber*) phoneNumberFromE164:(NSString*)text { +(PhoneNumber*) phoneNumberFromE164:(NSString*)text {
@ -53,7 +53,7 @@ static NSString *const RPDefaultsKeyPhoneNumberCanonical = @"RPDefaultsKeyPhoneN
+(NSString*) bestEffortFormatPartialUserSpecifiedTextToLookLikeAPhoneNumber:(NSString*)input { +(NSString*) bestEffortFormatPartialUserSpecifiedTextToLookLikeAPhoneNumber:(NSString*)input {
return [PhoneNumber bestEffortFormatPartialUserSpecifiedTextToLookLikeAPhoneNumber:input return [PhoneNumber bestEffortFormatPartialUserSpecifiedTextToLookLikeAPhoneNumber:input
withSpecifiedRegionCode:[Environment currentRegionCodeForPhoneNumbers]]; withSpecifiedRegionCode:Environment.currentRegionCodeForPhoneNumbers];
} }
+(NSString*) bestEffortFormatPartialUserSpecifiedTextToLookLikeAPhoneNumber:(NSString*)input withSpecifiedCountryCodeString:(NSString *)countryCodeString{ +(NSString*) bestEffortFormatPartialUserSpecifiedTextToLookLikeAPhoneNumber:(NSString*)input withSpecifiedCountryCodeString:(NSString *)countryCodeString{

View File

@ -44,7 +44,7 @@
-(ErrorHandlerBlock) errorHandler { -(ErrorHandlerBlock) errorHandler {
return ^(id error, id relatedInfo, bool causedTermination) { return ^(id error, id relatedInfo, bool causedTermination) {
if (causedTermination) { if (causedTermination) {
if ([error isKindOfClass:[CallTermination class]]) { if ([error isKindOfClass:CallTermination.class]) {
CallTermination* t = error; CallTermination* t = error;
[self terminateWithReason:t.type [self terminateWithReason:t.type
withFailureInfo:t.failure withFailureInfo:t.failure
@ -56,7 +56,7 @@
} }
} }
[Environment errorNoter](error, relatedInfo, causedTermination); Environment.errorNoter(error, relatedInfo, causedTermination);
}; };
} }
-(TOCCancelToken*) untilCancelledToken { -(TOCCancelToken*) untilCancelledToken {
@ -111,7 +111,7 @@
} }
-(void)terminateWithRejectionOrRemoteHangupAndFailureInfo:(id)failureInfo andRelatedInfo:(id)relatedInfo { -(void)terminateWithRejectionOrRemoteHangupAndFailureInfo:(id)failureInfo andRelatedInfo:(id)relatedInfo {
enum CallProgressType progressType = ((CallProgress*)[progress currentValue]).type; enum CallProgressType progressType = ((CallProgress*)progress.currentValue).type;
bool hasAcceptedAlready = progressType > CallProgressType_Ringing; bool hasAcceptedAlready = progressType > CallProgressType_Ringing;
enum CallTerminationType terminationType = hasAcceptedAlready enum CallTerminationType terminationType = hasAcceptedAlready
? CallTerminationType_HangupRemote ? CallTerminationType_HangupRemote

View File

@ -12,7 +12,7 @@
} }
-(BOOL)isEqual:(id)object { -(BOOL)isEqual:(id)object {
return [object isKindOfClass:[CallProgress class]] && ((CallProgress*)object).type == type; return [object isKindOfClass:CallProgress.class] && ((CallProgress*)object).type == type;
} }
-(NSUInteger)hash { -(NSUInteger)hash {
return type; return type;

View File

@ -17,7 +17,7 @@
} }
-(BOOL)isEqual:(id)object { -(BOOL)isEqual:(id)object {
return [object isKindOfClass:[CallTermination class]] && ((CallTermination*)object).type == type; return [object isKindOfClass:CallTermination.class] && ((CallTermination*)object).type == type;
} }
-(NSUInteger)hash { -(NSUInteger)hash {
return type; return type;

View File

@ -32,7 +32,7 @@
TOCFuture* futureSignalConnection = [CallConnectUtil_Server asyncConnectToDefaultSignalingServerUntilCancelled:callController.untilCancelledToken]; TOCFuture* futureSignalConnection = [CallConnectUtil_Server asyncConnectToDefaultSignalingServerUntilCancelled:callController.untilCancelledToken];
return [futureSignalConnection thenTry:^(HttpManager* httpManager) { return [futureSignalConnection thenTry:^(HttpManager* httpManager) {
requireState([httpManager isKindOfClass:[HttpManager class]]); requireState([httpManager isKindOfClass:HttpManager.class]);
TOCFutureSource* predeclaredFutureSession = [TOCFutureSource new]; TOCFutureSource* predeclaredFutureSession = [TOCFutureSource new];
@ -43,14 +43,14 @@
}; };
[httpManager startWithRequestHandler:serverRequestHandler [httpManager startWithRequestHandler:serverRequestHandler
andErrorHandler:[callController errorHandler] andErrorHandler:callController.errorHandler
untilCancelled:[callController untilCancelledToken]]; untilCancelled:[callController untilCancelledToken]];
HttpRequest* initiateRequest = [HttpRequest httpRequestToInitiateToRemoteNumber:[callController callState].remoteNumber]; HttpRequest* initiateRequest = [HttpRequest httpRequestToInitiateToRemoteNumber:callController.callState.remoteNumber];
TOCFuture* futureResponseToInitiate = [httpManager asyncOkResponseForRequest:initiateRequest TOCFuture* futureResponseToInitiate = [httpManager asyncOkResponseForRequest:initiateRequest
unlessCancelled:[callController untilCancelledToken]]; unlessCancelled:[callController untilCancelledToken]];
TOCFuture* futureResponseToInitiateWithInterpretedFailures = [futureResponseToInitiate catchTry:^(id error) { TOCFuture* futureResponseToInitiateWithInterpretedFailures = [futureResponseToInitiate catchTry:^(id error) {
if ([error isKindOfClass:[HttpResponse class]]) { if ([error isKindOfClass:HttpResponse.class]) {
HttpResponse* badResponse = error; HttpResponse* badResponse = error;
return [TOCFuture futureWithFailure:[self callTerminationForBadResponse:badResponse return [TOCFuture futureWithFailure:[self callTerminationForBadResponse:badResponse
toInitiateRequest:initiateRequest]]; toInitiateRequest:initiateRequest]];
@ -60,7 +60,7 @@
}]; }];
TOCFuture* futureSession = [futureResponseToInitiateWithInterpretedFailures thenTry:^(HttpResponse* response) { TOCFuture* futureSession = [futureResponseToInitiateWithInterpretedFailures thenTry:^(HttpResponse* response) {
return [InitiatorSessionDescriptor initiatorSessionDescriptorFromJson:[response getOptionalBodyText]]; return [InitiatorSessionDescriptor initiatorSessionDescriptorFromJson:response.getOptionalBodyText];
}]; }];
[predeclaredFutureSession trySetResult:futureSession]; [predeclaredFutureSession trySetResult:futureSession];
@ -73,7 +73,7 @@
require(badResponse != nil); require(badResponse != nil);
require(initiateRequest != nil); require(initiateRequest != nil);
switch ([badResponse getStatusCode]) { switch (badResponse.getStatusCode) {
case SIGNAL_STATUS_CODE_NO_SUCH_USER: case SIGNAL_STATUS_CODE_NO_SUCH_USER:
return [CallTermination callTerminationOfType:CallTerminationType_NoSuchUser return [CallTermination callTerminationOfType:CallTerminationType_NoSuchUser
withFailure:badResponse withFailure:badResponse
@ -81,7 +81,7 @@
case SIGNAL_STATUS_CODE_SERVER_MESSAGE: case SIGNAL_STATUS_CODE_SERVER_MESSAGE:
return [CallTermination callTerminationOfType:CallTerminationType_ServerMessage return [CallTermination callTerminationOfType:CallTerminationType_ServerMessage
withFailure:badResponse withFailure:badResponse
andMessageInfo:[badResponse getOptionalBodyText]]; andMessageInfo:badResponse.getOptionalBodyText];
case SIGNAL_STATUS_CODE_LOGIN_FAILED: case SIGNAL_STATUS_CODE_LOGIN_FAILED:
return [CallTermination callTerminationOfType:CallTerminationType_LoginFailed return [CallTermination callTerminationOfType:CallTerminationType_LoginFailed
withFailure:badResponse withFailure:badResponse

View File

@ -40,7 +40,7 @@
untilCancelled:[callController untilCancelledToken]]; untilCancelled:[callController untilCancelledToken]];
return [futureSignalConnection thenTry:^id(HttpManager* httpManager) { return [futureSignalConnection thenTry:^id(HttpManager* httpManager) {
require([httpManager isKindOfClass:[httpManager class]]); require([httpManager isKindOfClass:httpManager.class]);
HttpResponse*(^serverRequestHandler)(HttpRequest*) = ^(HttpRequest* remoteRequest) { HttpResponse*(^serverRequestHandler)(HttpRequest*) = ^(HttpRequest* remoteRequest) {
return [self respondToServerRequest:remoteRequest return [self respondToServerRequest:remoteRequest
@ -49,14 +49,14 @@
}; };
[httpManager startWithRequestHandler:serverRequestHandler [httpManager startWithRequestHandler:serverRequestHandler
andErrorHandler:[Environment errorNoter] andErrorHandler:Environment.errorNoter
untilCancelled:[callController untilCancelledToken]]; untilCancelled:[callController untilCancelledToken]];
HttpRequest* ringRequest = [HttpRequest httpRequestToRingWithSessionId:sessionDescriptor.sessionId]; HttpRequest* ringRequest = [HttpRequest httpRequestToRingWithSessionId:sessionDescriptor.sessionId];
TOCFuture* futureResponseToRing = [httpManager asyncOkResponseForRequest:ringRequest TOCFuture* futureResponseToRing = [httpManager asyncOkResponseForRequest:ringRequest
unlessCancelled:[callController untilCancelledToken]]; unlessCancelled:[callController untilCancelledToken]];
TOCFuture* futureResponseToRingWithInterpretedFailures = [futureResponseToRing catchTry:^(id error) { TOCFuture* futureResponseToRingWithInterpretedFailures = [futureResponseToRing catchTry:^(id error) {
if ([error isKindOfClass:[HttpResponse class]]) { if ([error isKindOfClass:HttpResponse.class]) {
HttpResponse* badResponse = error; HttpResponse* badResponse = error;
return [TOCFuture futureWithFailure:[self callTerminationForBadResponse:badResponse return [TOCFuture futureWithFailure:[self callTerminationForBadResponse:badResponse
toRingRequest:ringRequest]]; toRingRequest:ringRequest]];
@ -74,7 +74,7 @@
require(badResponse != nil); require(badResponse != nil);
require(ringRequest != nil); require(ringRequest != nil);
switch ([badResponse getStatusCode]) { switch (badResponse.getStatusCode) {
case SIGNAL_STATUS_CODE_STALE_SESSION: case SIGNAL_STATUS_CODE_STALE_SESSION:
return [CallTermination callTerminationOfType:CallTerminationType_StaleSession return [CallTermination callTerminationOfType:CallTerminationType_StaleSession
withFailure:badResponse withFailure:badResponse
@ -124,7 +124,7 @@
return [self asyncOkResponseFor:busyRequest return [self asyncOkResponseFor:busyRequest
fromSignalingServerNamed:sessionDescriptor.relayServerName fromSignalingServerNamed:sessionDescriptor.relayServerName
unlessCancelled:nil unlessCancelled:nil
andErrorHandler:[Environment errorNoter]]; andErrorHandler:Environment.errorNoter];
} }
+(TOCFuture*) asyncOkResponseFor:(HttpRequest*)request +(TOCFuture*) asyncOkResponseFor:(HttpRequest*)request

View File

@ -17,7 +17,7 @@
@implementation CallConnectUtil_Server @implementation CallConnectUtil_Server
+(TOCFuture*) asyncConnectToDefaultSignalingServerUntilCancelled:(TOCCancelToken*)untilCancelledToken { +(TOCFuture*) asyncConnectToDefaultSignalingServerUntilCancelled:(TOCCancelToken*)untilCancelledToken {
return [self asyncConnectToSignalingServerAt:[Environment getSecureEndPointToDefaultRelayServer] return [self asyncConnectToSignalingServerAt:Environment.getSecureEndPointToDefaultRelayServer
untilCancelled:untilCancelledToken]; untilCancelled:untilCancelledToken];
} }
@ -55,7 +55,7 @@
NSArray* interopOptions = session.interopVersion == 0 NSArray* interopOptions = session.interopVersion == 0
? @[ENVIRONMENT_LEGACY_OPTION_RTP_PADDING_BIT_IMPLIES_EXTENSION_BIT_AND_TWELVE_EXTRA_ZERO_BYTES_IN_HEADER] ? @[ENVIRONMENT_LEGACY_OPTION_RTP_PADDING_BIT_IMPLIES_EXTENSION_BIT_AND_TWELVE_EXTRA_ZERO_BYTES_IN_HEADER]
: @[]; : @[];
if (session.interopVersion > 1) [Environment errorNoter](@"Newer-than-code interop version specified.", session, false); if (session.interopVersion > 1) Environment.errorNoter(@"Newer-than-code interop version specified.", session, false);
return [self asyncConnectCallOverRelayDescribedInInitiatorSessionDescriptor:equivalentSession return [self asyncConnectCallOverRelayDescribedInInitiatorSessionDescriptor:equivalentSession
withCallController:callController withCallController:callController
@ -95,7 +95,7 @@
TOCUntilOperation operation = ^(TOCCancelToken* internalUntilCancelledToken) { TOCUntilOperation operation = ^(TOCCancelToken* internalUntilCancelledToken) {
return [self asyncAttemptResolveThenConnectToUdpRelayDescribedBy:sessionDescriptor return [self asyncAttemptResolveThenConnectToUdpRelayDescribedBy:sessionDescriptor
untilCancelled:internalUntilCancelledToken untilCancelled:internalUntilCancelledToken
withErrorHandler:[callController errorHandler]]; withErrorHandler:callController.errorHandler];
}; };
TOCFuture* futureRelayedUdpSocket = [TOCFuture retry:[TOCFuture operationTry:operation] TOCFuture* futureRelayedUdpSocket = [TOCFuture retry:[TOCFuture operationTry:operation]
@ -118,7 +118,7 @@
require(sessionDescriptor != nil); require(sessionDescriptor != nil);
require(errorHandler != nil); require(errorHandler != nil);
NSString* domain = [Environment relayServerNameToHostName:[sessionDescriptor relayServerName]]; NSString* domain = [Environment relayServerNameToHostName:sessionDescriptor.relayServerName];
TOCFuture* futureDnsResult = [DnsManager asyncQueryAddressesForDomainName:domain TOCFuture* futureDnsResult = [DnsManager asyncQueryAddressesForDomainName:domain
unlessCancelled:untilCancelledToken]; unlessCancelled:untilCancelledToken];
@ -149,7 +149,7 @@
UdpSocket* udpSocket = [UdpSocket udpSocketTo:remoteEndPoint]; UdpSocket* udpSocket = [UdpSocket udpSocketTo:remoteEndPoint];
id<OccurrenceLogger> logger = [[Environment logging] getOccurrenceLoggerForSender:self withKey:@"relay setup"]; id<OccurrenceLogger> logger = [Environment.logging getOccurrenceLoggerForSender:self withKey:@"relay setup"];
TOCFuture* futureFirstResponseData = [self asyncFirstPacketReceivedAfterStartingSocket:udpSocket TOCFuture* futureFirstResponseData = [self asyncFirstPacketReceivedAfterStartingSocket:udpSocket
untilCancelled:untilCancelledToken untilCancelled:untilCancelledToken

View File

@ -28,9 +28,9 @@
id jsonSessionId = fields[SessionIdKey]; id jsonSessionId = fields[SessionIdKey];
id jsonRelayPort = fields[RelayPortKey]; id jsonRelayPort = fields[RelayPortKey];
id jsonRelayName = fields[RelayHostKey]; id jsonRelayName = fields[RelayHostKey];
checkOperationDescribe([jsonSessionId isKindOfClass:[NSNumber class]], @"Unexpected json data"); checkOperationDescribe([jsonSessionId isKindOfClass:NSNumber.class], @"Unexpected json data");
checkOperationDescribe([jsonRelayPort isKindOfClass:[NSNumber class]], @"Unexpected json data"); checkOperationDescribe([jsonRelayPort isKindOfClass:NSNumber.class], @"Unexpected json data");
checkOperationDescribe([jsonRelayName isKindOfClass:[NSString class]], @"Unexpected json data"); checkOperationDescribe([jsonRelayName isKindOfClass:NSString.class], @"Unexpected json data");
checkOperationDescribe([jsonRelayPort unsignedShortValue] > 0, @"Unexpected json data"); checkOperationDescribe([jsonRelayPort unsignedShortValue] > 0, @"Unexpected json data");
int64_t sessionId = [[jsonSessionId description] longLongValue]; // workaround: asking for longLongValue directly causes rounding-through-double int64_t sessionId = [[jsonSessionId description] longLongValue]; // workaround: asking for longLongValue directly causes rounding-through-double

View File

@ -89,7 +89,7 @@
checkOperation(data.length >= HMAC_TRUNCATED_SIZE); checkOperation(data.length >= HMAC_TRUNCATED_SIZE);
NSData* includedMac = [data takeLast:HMAC_TRUNCATED_SIZE]; NSData* includedMac = [data takeLast:HMAC_TRUNCATED_SIZE];
NSData* payload = [data skipLast:HMAC_TRUNCATED_SIZE]; NSData* payload = [data skipLast:HMAC_TRUNCATED_SIZE];
NSData* signalingMacKey = [SGNKeychainUtil signalingMacKey]; NSData* signalingMacKey = SGNKeychainUtil.signalingMacKey;
require(signalingMacKey != nil); require(signalingMacKey != nil);
NSData* computedMac = [[payload hmacWithSha1WithKey:signalingMacKey] takeLast:HMAC_TRUNCATED_SIZE]; NSData* computedMac = [[payload hmacWithSha1WithKey:signalingMacKey] takeLast:HMAC_TRUNCATED_SIZE];
checkOperation([includedMac isEqualToData_TimingSafe:computedMac]); checkOperation([includedMac isEqualToData_TimingSafe:computedMac]);
@ -98,7 +98,7 @@
+(NSData*) decryptRemoteNotificationData:(NSData*)data { +(NSData*) decryptRemoteNotificationData:(NSData*)data {
require(data != nil); require(data != nil);
checkOperation(data.length >= VERSION_SIZE + IV_SIZE); checkOperation(data.length >= VERSION_SIZE + IV_SIZE);
NSData* cipherKey = [SGNKeychainUtil signalingCipherKey]; NSData* cipherKey = SGNKeychainUtil.signalingCipherKey;
require(cipherKey != nil); require(cipherKey != nil);
NSData* iv = [data subdataWithRange:NSMakeRange(VERSION_SIZE, IV_SIZE)]; NSData* iv = [data subdataWithRange:NSMakeRange(VERSION_SIZE, IV_SIZE)];
NSData* cipherText = [data skip:VERSION_SIZE+IV_SIZE]; NSData* cipherText = [data skip:VERSION_SIZE+IV_SIZE];

View File

@ -19,7 +19,7 @@
if (![self.location hasPrefix:@"/session/"]) return nil; if (![self.location hasPrefix:@"/session/"]) return nil;
NSString* sessionIdText = [self.location substringFromIndex:@"/session/".length]; NSString* sessionIdText = [self.location substringFromIndex:@"/session/".length];
sessionIdText = [sessionIdText stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]]; sessionIdText = [sessionIdText stringByTrimmingCharactersInSet:NSCharacterSet.whitespaceCharacterSet];
NSNumber* sessionIdNumber = [sessionIdText tryParseAsDecimalNumber]; NSNumber* sessionIdNumber = [sessionIdText tryParseAsDecimalNumber];
if (sessionIdNumber.hasLongLongValue) return sessionIdNumber; if (sessionIdNumber.hasLongLongValue) return sessionIdNumber;
@ -32,15 +32,15 @@
} }
-(bool) isRingingForSession:(int64_t)targetSessionId { -(bool) isRingingForSession:(int64_t)targetSessionId {
return [self.method isEqualToString:@"RING"] && [@(targetSessionId) isEqualToNumber:[self tryGetSessionId]]; return [self.method isEqualToString:@"RING"] && [@(targetSessionId) isEqualToNumber:self.tryGetSessionId];
} }
-(bool) isHangupForSession:(int64_t)targetSessionId { -(bool) isHangupForSession:(int64_t)targetSessionId {
return [self.method isEqualToString:@"DELETE"] && [@(targetSessionId) isEqualToNumber:[self tryGetSessionId]]; return [self.method isEqualToString:@"DELETE"] && [@(targetSessionId) isEqualToNumber:self.tryGetSessionId];
} }
-(bool) isBusyForSession:(int64_t)targetSessionId { -(bool) isBusyForSession:(int64_t)targetSessionId {
return [self.method isEqualToString:@"BUSY"] && [@(targetSessionId) isEqualToNumber:[self tryGetSessionId]]; return [self.method isEqualToString:@"BUSY"] && [@(targetSessionId) isEqualToNumber:self.tryGetSessionId];
} }
+(HttpRequest*) httpRequestToOpenPortWithSessionId:(int64_t)sessionId { +(HttpRequest*) httpRequestToOpenPortWithSessionId:(int64_t)sessionId {
@ -84,11 +84,11 @@
NSString* query = [NSString stringWithFormat:@"/users/verification/%@", localPhoneNumber.toE164]; NSString* query = [NSString stringWithFormat:@"/users/verification/%@", localPhoneNumber.toE164];
[SGNKeychainUtil generateSignaling]; [SGNKeychainUtil generateSignaling];
NSData* signalingCipherKey = [SGNKeychainUtil signalingCipherKey]; NSData* signalingCipherKey = SGNKeychainUtil.signalingCipherKey;
NSData* signalingMacKey = [SGNKeychainUtil signalingMacKey]; NSData* signalingMacKey = SGNKeychainUtil.signalingMacKey;
NSData* signalingExtraKeyData = [SGNKeychainUtil signalingCipherKey]; NSData* signalingExtraKeyData = SGNKeychainUtil.signalingCipherKey;
NSString* encodedSignalingKey = [[@[signalingCipherKey, signalingMacKey, signalingExtraKeyData] concatDatas] encodedAsBase64]; NSString* encodedSignalingKey = @[signalingCipherKey, signalingMacKey, signalingExtraKeyData].concatDatas.encodedAsBase64;
NSString* body = [@{@"key" : encodedSignalingKey, @"challenge" : challenge} encodedAsJson]; NSString* body = @{@"key" : encodedSignalingKey, @"challenge" : challenge}.encodedAsJson;
return [HttpRequest httpRequestWithBasicAuthenticationAndMethod:@"PUT" return [HttpRequest httpRequestWithBasicAuthenticationAndMethod:@"PUT"
andLocation:query andLocation:query

View File

@ -37,13 +37,13 @@
checkOperation(response.isOkResponse); checkOperation(response.isOkResponse);
NSString* hashCountHeader = [response getHeaders][HASH_COUNT_HEADER_KEY]; NSString* hashCountHeader = response.getHeaders[HASH_COUNT_HEADER_KEY];
checkOperation(hashCountHeader != nil); checkOperation(hashCountHeader != nil);
int hashCountValue = [hashCountHeader intValue]; int hashCountValue = [hashCountHeader intValue];
checkOperation(hashCountValue > 0); checkOperation(hashCountValue > 0);
NSData* responseBody = [response getOptionalBodyData]; NSData* responseBody = response.getOptionalBodyData;
checkOperation(responseBody.length > 0); checkOperation(responseBody.length > 0);
BloomFilter* bloomFilter = [BloomFilter bloomFilterWithHashCount:(NSUInteger)hashCountValue BloomFilter* bloomFilter = [BloomFilter bloomFilterWithHashCount:(NSUInteger)hashCountValue

View File

@ -19,16 +19,16 @@
-(id) init { -(id) init {
if (self = [super init]) { if (self = [super init]) {
phoneNumberDirectoryFilter = [PhoneNumberDirectoryFilter phoneNumberDirectoryFilterDefault]; phoneNumberDirectoryFilter = PhoneNumberDirectoryFilter.phoneNumberDirectoryFilterDefault;
} }
return self; return self;
} }
-(void) startUntilCancelled:(TOCCancelToken*)cancelToken { -(void) startUntilCancelled:(TOCCancelToken*)cancelToken {
lifetimeToken = cancelToken; lifetimeToken = cancelToken;
phoneNumberDirectoryFilter = [[Environment preferences] tryGetSavedPhoneNumberDirectory]; phoneNumberDirectoryFilter = [Environment.preferences tryGetSavedPhoneNumberDirectory];
if (phoneNumberDirectoryFilter == nil) { if (phoneNumberDirectoryFilter == nil) {
phoneNumberDirectoryFilter = [PhoneNumberDirectoryFilter phoneNumberDirectoryFilterDefault]; phoneNumberDirectoryFilter = PhoneNumberDirectoryFilter.phoneNumberDirectoryFilterDefault;
} }
[self scheduleUpdate]; [self scheduleUpdate];
@ -65,7 +65,7 @@
TOCFuture* futureDirectoryResponse = [HttpManager asyncOkResponseFromMasterServer:directoryRequest TOCFuture* futureDirectoryResponse = [HttpManager asyncOkResponseFromMasterServer:directoryRequest
unlessCancelled:untilCancelledToken unlessCancelled:untilCancelledToken
andErrorHandler:[Environment errorNoter]]; andErrorHandler:Environment.errorNoter];
return [futureDirectoryResponse thenTry:^(HttpResponse* response) { return [futureDirectoryResponse thenTry:^(HttpResponse* response) {
return [PhoneNumberDirectoryFilter phoneNumberDirectoryFilterFromHttpResponse:response]; return [PhoneNumberDirectoryFilter phoneNumberDirectoryFilterFromHttpResponse:response];
@ -87,7 +87,7 @@
-(void) signalDirectoryQueryFailed:(id)failure { -(void) signalDirectoryQueryFailed:(id)failure {
NSString* desc = [NSString stringWithFormat:@"Failed to retrieve directory. Retrying in %f hours.", NSString* desc = [NSString stringWithFormat:@"Failed to retrieve directory. Retrying in %f hours.",
DIRECTORY_UPDATE_RETRY_PERIOD/HOUR]; DIRECTORY_UPDATE_RETRY_PERIOD/HOUR];
[Environment errorNoter](desc, failure, false); Environment.errorNoter(desc, failure, false);
} }
-(TOCFuture*) asyncQueryCurrentDirectoryWithDefaultOnFail { -(TOCFuture*) asyncQueryCurrentDirectoryWithDefaultOnFail {
TOCFuture* futureDirectory = [self asyncQueryCurrentDirectory]; TOCFuture* futureDirectory = [self asyncQueryCurrentDirectory];
@ -105,7 +105,7 @@
@synchronized(self) { @synchronized(self) {
phoneNumberDirectoryFilter = directory; phoneNumberDirectoryFilter = directory;
} }
[[Environment preferences] setSavedPhoneNumberDirectory:directory]; [Environment.preferences setSavedPhoneNumberDirectory:directory];
[[NSNotificationCenter defaultCenter] postNotificationName:NOTIFICATION_DIRECTORY_WAS_UPDATED object:nil]; [[NSNotificationCenter defaultCenter] postNotificationName:NOTIFICATION_DIRECTORY_WAS_UPDATED object:nil];
[self scheduleUpdate]; [self scheduleUpdate];
}]; }];

View File

@ -63,7 +63,7 @@
id<ValueLogger> norm = [logging getValueLoggerForValue:valueIdentity from:sender]; id<ValueLogger> norm = [logging getValueLoggerForValue:valueIdentity from:sender];
return [AnonymousValueLogger anonymousValueLogger:^(double value) { return [AnonymousValueLogger anonymousValueLogger:^(double value) {
[estimator updateWithNextSample:value]; [estimator updateWithNextSample:value];
[norm logValue:[estimator currentEstimate]]; [norm logValue:estimator.currentEstimate];
}]; }];
} }
+(id<ValueLogger>) getMagnitudeDecayingToZeroValueLoggerTo:(id<Logging>)logging named:(id)valueIdentity from:(id)sender withDecayFactor:(double)decayFactorPerSample { +(id<ValueLogger>) getMagnitudeDecayingToZeroValueLoggerTo:(id<Logging>)logging named:(id)valueIdentity from:(id)sender withDecayFactor:(double)decayFactorPerSample {

View File

@ -14,7 +14,7 @@
-(NSData*) concatDatas { -(NSData*) concatDatas {
NSUInteger t = 0; NSUInteger t = 0;
for (id d in self) { for (id d in self) {
require([d isKindOfClass:[NSData class]]); require([d isKindOfClass:NSData.class]);
t += [(NSData*)d length]; t += [(NSData*)d length];
} }
@ -29,7 +29,7 @@
-(NSArray*) concatArrays { -(NSArray*) concatArrays {
NSMutableArray* r = [NSMutableArray array]; NSMutableArray* r = [NSMutableArray array];
for (id e in self) { for (id e in self) {
require([e isKindOfClass:[NSArray class]]); require([e isKindOfClass:NSArray.class]);
[r addObjectsFromArray:e]; [r addObjectsFromArray:e];
} }
return r; return r;

View File

@ -60,7 +60,7 @@
@try { @try {
action(); action();
} @catch (id ex) { } @catch (id ex) {
[[[Environment logging] getConditionLoggerForSender:self] [[Environment.logging getConditionLoggerForSender:self]
logError:@"A queued action failed and may have stalled an ObservableValue."]; logError:@"A queued action failed and may have stalled an ObservableValue."];
@synchronized(self) { @synchronized(self) {
isRunningActions = false; isRunningActions = false;

View File

@ -39,7 +39,7 @@
-(void) performOnThread:(NSThread*)thread { -(void) performOnThread:(NSThread*)thread {
require(thread != nil); require(thread != nil);
[self performSelector:@selector(run) onThread:thread withObject:nil waitUntilDone:thread == [NSThread currentThread]]; [self performSelector:@selector(run) onThread:thread withObject:nil waitUntilDone:thread == NSThread.currentThread];
} }
-(void) performOnThreadAndWaitUntilDone:(NSThread*)thread { -(void) performOnThreadAndWaitUntilDone:(NSThread*)thread {

View File

@ -9,7 +9,7 @@
+ (NSString *)countryNameFromCountryCode:(NSString *)code { + (NSString *)countryNameFromCountryCode:(NSString *)code {
NSDictionary *countryCodeComponent = @{NSLocaleCountryCode: code}; NSDictionary *countryCodeComponent = @{NSLocaleCountryCode: code};
NSString *identifier = [NSLocale localeIdentifierFromComponents:countryCodeComponent]; NSString *identifier = [NSLocale localeIdentifierFromComponents:countryCodeComponent];
NSString *country = [[NSLocale currentLocale] displayNameForKey:NSLocaleIdentifier NSString *country = [NSLocale.currentLocale displayNameForKey:NSLocaleIdentifier
value:identifier]; value:identifier];
return country; return country;
} }

View File

@ -11,7 +11,7 @@
} }
- (void)sendSMSInviteToNumber:(PhoneNumber *)number{ - (void)sendSMSInviteToNumber:(PhoneNumber *)number{
if ([MFMessageComposeViewController canSendText] && [[UIDevice currentDevice].model isEqualToString:@"iPhone"]){ if (MFMessageComposeViewController.canSendText && [UIDevice.currentDevice.model isEqualToString:@"iPhone"]){
MFMessageComposeViewController *messageController = [MFMessageComposeViewController new]; MFMessageComposeViewController *messageController = [MFMessageComposeViewController new];
NSString *inviteMessage = INVITE_USERS_MESSAGE; NSString *inviteMessage = INVITE_USERS_MESSAGE;

View File

@ -68,14 +68,14 @@
NSError* jsonParseError = nil; NSError* jsonParseError = nil;
id parsedJson = [NSJSONSerialization dataWithJSONObject:self.encodedAsUtf8 options:0 error:&jsonParseError]; id parsedJson = [NSJSONSerialization dataWithJSONObject:self.encodedAsUtf8 options:0 error:&jsonParseError];
checkOperationDescribe(jsonParseError == nil, ([NSString stringWithFormat:@"Invalid json: %@", self])); checkOperationDescribe(jsonParseError == nil, ([NSString stringWithFormat:@"Invalid json: %@", self]));
checkOperationDescribe([parsedJson isKindOfClass:[NSData class]], @"Unexpected json data"); checkOperationDescribe([parsedJson isKindOfClass:NSData.class], @"Unexpected json data");
return parsedJson; return parsedJson;
} }
-(NSDictionary*) decodedAsJsonIntoDictionary { -(NSDictionary*) decodedAsJsonIntoDictionary {
NSError* jsonParseError = nil; NSError* jsonParseError = nil;
id parsedJson = [NSJSONSerialization JSONObjectWithData:self.encodedAsUtf8 options:0 error:&jsonParseError]; id parsedJson = [NSJSONSerialization JSONObjectWithData:self.encodedAsUtf8 options:0 error:&jsonParseError];
checkOperationDescribe(jsonParseError == nil, ([NSString stringWithFormat:@"Json parse error: %@, on json: %@", jsonParseError, self])); checkOperationDescribe(jsonParseError == nil, ([NSString stringWithFormat:@"Json parse error: %@, on json: %@", jsonParseError, self]));
checkOperationDescribe([parsedJson isKindOfClass:[NSDictionary class]], @"Unexpected json data"); checkOperationDescribe([parsedJson isKindOfClass:NSDictionary.class], @"Unexpected json data");
return parsedJson; return parsedJson;
} }
-(NSData*) decodedAsBase64Data { -(NSData*) decodedAsBase64Data {

View File

@ -18,7 +18,7 @@
[instance->thread start]; [instance->thread start];
[Operation asyncRunAndWaitUntilDone:^{ [Operation asyncRunAndWaitUntilDone:^{
instance->runLoop = [NSRunLoop currentRunLoop]; instance->runLoop = NSRunLoop.currentRunLoop;
} onThread:instance->thread]; } onThread:instance->thread];
return instance; return instance;
@ -27,8 +27,8 @@
[thread cancel]; [thread cancel];
} }
-(void) runLoopUntilCancelled { -(void) runLoopUntilCancelled {
NSThread* curThread = [NSThread currentThread]; NSThread* curThread = NSThread.currentThread;
NSRunLoop* curRunLoop = [NSRunLoop currentRunLoop]; NSRunLoop* curRunLoop = NSRunLoop.currentRunLoop;
while (!curThread.isCancelled) { while (!curThread.isCancelled) {
[curRunLoop runUntilDate:[NSDate dateWithTimeIntervalSinceNow:5]]; [curRunLoop runUntilDate:[NSDate dateWithTimeIntervalSinceNow:5]];
} }

View File

@ -55,11 +55,11 @@ typedef NSComparisonResult (^CallComparator)(RecentCall*, RecentCall*);
} }
- (void)observeRecentCalls { - (void)observeRecentCalls {
ObservableValue *observableRecents = [[[Environment getCurrent] recentCallManager] getObservableRecentCalls]; ObservableValue *observableRecents = Environment.getCurrent.recentCallManager.getObservableRecentCalls;
[observableRecents watchLatestValue:^(NSArray *latestRecents) { [observableRecents watchLatestValue:^(NSArray *latestRecents) {
if (_searchTerm) { if (_searchTerm) {
_recents = [[[Environment getCurrent] recentCallManager] recentsForSearchString:_searchTerm _recents = [Environment.getCurrent.recentCallManager recentsForSearchString:_searchTerm
andExcludeArchived:NO]; andExcludeArchived:NO];
} else { } else {
_recents = latestRecents; _recents = latestRecents;
@ -68,7 +68,7 @@ typedef NSComparisonResult (^CallComparator)(RecentCall*, RecentCall*);
if (!_tableViewContentMutating) { if (!_tableViewContentMutating) {
[_recentCallsTableView reloadData]; [_recentCallsTableView reloadData];
} }
} onThread:[NSThread mainThread] untilCancelled:nil]; } onThread:NSThread.mainThread untilCancelled:nil];
} }
- (void)deleteRecentCallAtIndexPath:(NSIndexPath *)indexPath { - (void)deleteRecentCallAtIndexPath:(NSIndexPath *)indexPath {
@ -79,7 +79,7 @@ typedef NSComparisonResult (^CallComparator)(RecentCall*, RecentCall*);
RecentCall *recent; RecentCall *recent;
[[[Environment getCurrent] recentCallManager] removeRecentCall:recent]; [Environment.getCurrent.recentCallManager removeRecentCall:recent];
[_recentCallsTableView endUpdates]; [_recentCallsTableView endUpdates];
} }
@ -118,7 +118,7 @@ typedef NSComparisonResult (^CallComparator)(RecentCall*, RecentCall*);
withRowAnimation:UITableViewRowAnimationLeft]; withRowAnimation:UITableViewRowAnimationLeft];
RecentCall *recent = _recents[(NSUInteger)indexPath.row]; RecentCall *recent = _recents[(NSUInteger)indexPath.row];
[[[Environment getCurrent] recentCallManager] removeRecentCall:recent]; [Environment.getCurrent.recentCallManager removeRecentCall:recent];
[_recentCallsTableView endUpdates]; [_recentCallsTableView endUpdates];
_tableViewContentMutating = NO; _tableViewContentMutating = NO;
@ -134,7 +134,7 @@ typedef NSComparisonResult (^CallComparator)(RecentCall*, RecentCall*);
- (void)searchBarTitleView:(SearchBarTitleView *)view didSearchForTerm:(NSString *)term { - (void)searchBarTitleView:(SearchBarTitleView *)view didSearchForTerm:(NSString *)term {
_searchTerm = term; _searchTerm = term;
_recents = [[[Environment getCurrent] recentCallManager] recentsForSearchString:term _recents = [Environment.getCurrent.recentCallManager recentsForSearchString:term
andExcludeArchived:NO]; andExcludeArchived:NO];
[_recentCallsTableView reloadData]; [_recentCallsTableView reloadData];
} }
@ -147,7 +147,7 @@ typedef NSComparisonResult (^CallComparator)(RecentCall*, RecentCall*);
- (void)searchBarTitleViewDidEndSearching:(SearchBarTitleView *)view { - (void)searchBarTitleViewDidEndSearching:(SearchBarTitleView *)view {
_searchTerm = nil; _searchTerm = nil;
_recents = [[[Environment getCurrent] recentCallManager] recentsForSearchString:nil _recents = [Environment.getCurrent.recentCallManager recentsForSearchString:nil
andExcludeArchived:NO]; andExcludeArchived:NO];
[_recentCallsTableView reloadData]; [_recentCallsTableView reloadData];
} }

View File

@ -50,7 +50,7 @@ static NSString *const CONTACT_BROWSE_TABLE_CELL_IDENTIFIER = @"ContactTableView
[self.navigationController setNavigationBarHidden:YES animated:NO]; [self.navigationController setNavigationBarHidden:YES animated:NO];
[_contactTableView reloadData]; [_contactTableView reloadData];
[_searchBarTitleView updateAutoCorrectionType]; [_searchBarTitleView updateAutoCorrectionType];
[[Environment getCurrent].contactsManager enableNewUserNotifications]; [Environment.getCurrent.contactsManager enableNewUserNotifications];
BOOL showNotificationView = _newWhisperUsers != nil; BOOL showNotificationView = _newWhisperUsers != nil;
if (showNotificationView) { if (showNotificationView) {
@ -152,12 +152,12 @@ static NSString *const CONTACT_BROWSE_TABLE_CELL_IDENTIFIER = @"ContactTableView
#pragma mark - Contact functions #pragma mark - Contact functions
- (void)setupContacts { - (void)setupContacts {
ObservableValue *observableContacts = [[[Environment getCurrent] contactsManager] getObservableWhisperUsers]; ObservableValue *observableContacts = Environment.getCurrent.contactsManager.getObservableWhisperUsers;
[observableContacts watchLatestValue:^(NSArray *latestContacts) { [observableContacts watchLatestValue:^(NSArray *latestContacts) {
_latestContacts = latestContacts; _latestContacts = latestContacts;
[self onSearchOrContactChange:nil]; [self onSearchOrContactChange:nil];
} onThread:[NSThread mainThread] untilCancelled:nil]; } onThread:NSThread.mainThread untilCancelled:nil];
} }
- (NSArray *)contactsForSectionIndex:(NSUInteger)index { - (NSArray *)contactsForSectionIndex:(NSUInteger)index {
@ -251,7 +251,7 @@ static NSString *const CONTACT_BROWSE_TABLE_CELL_IDENTIFIER = @"ContactTableView
#pragma mark - Refresh controls #pragma mark - Refresh controls
- (void)refreshContacts{ - (void)refreshContacts{
[[[Environment getCurrent] phoneDirectoryManager] forceUpdate]; [Environment.getCurrent.phoneDirectoryManager forceUpdate];
self.refreshTimer = [NSTimer scheduledTimerWithTimeInterval:REFRESH_TIMEOUT target:self selector:@selector(contactRefreshDidTimeout) userInfo:nil repeats:NO]; self.refreshTimer = [NSTimer scheduledTimerWithTimeInterval:REFRESH_TIMEOUT target:self selector:@selector(contactRefreshDidTimeout) userInfo:nil repeats:NO];
} }

View File

@ -29,7 +29,7 @@ static NSString *const FAVOURITE_FALSE_ICON_NAME = @"favourite_false_icon";
if (_contact) { if (_contact) {
self.navigationController.navigationBar.barTintColor = [UIUtil darkBackgroundColor]; self.navigationController.navigationBar.barTintColor = [UIUtil darkBackgroundColor];
self.navigationController.navigationBar.tintColor = [UIColor whiteColor]; self.navigationController.navigationBar.tintColor = UIColor.whiteColor;
self.navigationController.navigationBar.translucent = NO; self.navigationController.navigationBar.translucent = NO;
_contactNameLabel.text = _contact.fullName; _contactNameLabel.text = _contact.fullName;
if (_contact.image) { if (_contact.image) {
@ -68,7 +68,7 @@ static NSString *const FAVOURITE_FALSE_ICON_NAME = @"favourite_false_icon";
if ((NSUInteger)indexPath.row < _contact.userTextPhoneNumbers.count) { if ((NSUInteger)indexPath.row < _contact.userTextPhoneNumbers.count) {
PhoneNumber *phoneNumber = [PhoneNumber tryParsePhoneNumberFromUserSpecifiedText:_contact.userTextPhoneNumbers[(NSUInteger)indexPath.row]]; PhoneNumber *phoneNumber = [PhoneNumber tryParsePhoneNumberFromUserSpecifiedText:_contact.userTextPhoneNumbers[(NSUInteger)indexPath.row]];
BOOL isSecure = [[[[Environment getCurrent] phoneDirectoryManager] getCurrentFilter] containsPhoneNumber:phoneNumber]; BOOL isSecure = [Environment.getCurrent.phoneDirectoryManager.getCurrentFilter containsPhoneNumber:phoneNumber];
[cell configureWithPhoneNumber:phoneNumber isSecure:isSecure]; [cell configureWithPhoneNumber:phoneNumber isSecure:isSecure];
} else if ((NSUInteger)indexPath.row < _contact.userTextPhoneNumbers.count + _contact.emails.count) { } else if ((NSUInteger)indexPath.row < _contact.userTextPhoneNumbers.count + _contact.emails.count) {
@ -118,7 +118,7 @@ static NSString *const FAVOURITE_FALSE_ICON_NAME = @"favourite_false_icon";
} }
- (void)favouriteButtonTapped { - (void)favouriteButtonTapped {
[[[Environment getCurrent] contactsManager] toggleFavourite:_contact]; [Environment.getCurrent.contactsManager toggleFavourite:_contact];
[self configureFavouritesButton]; [self configureFavouritesButton];
} }
@ -136,7 +136,7 @@ static NSString *const FAVOURITE_FALSE_ICON_NAME = @"favourite_false_icon";
style:UIBarButtonItemStylePlain style:UIBarButtonItemStylePlain
target:self target:self
action:@selector(favouriteButtonTapped)]; action:@selector(favouriteButtonTapped)];
self.navigationItem.rightBarButtonItem.tintColor = [UIColor whiteColor]; self.navigationItem.rightBarButtonItem.tintColor = UIColor.whiteColor;
} }
} }
@ -152,11 +152,11 @@ static NSString *const FAVOURITE_FALSE_ICON_NAME = @"favourite_false_icon";
} }
- (void)startSecureCallWithNumber:(PhoneNumber *)number { - (void)startSecureCallWithNumber:(PhoneNumber *)number {
[[Environment phoneManager] initiateOutgoingCallToContact:_contact atRemoteNumber:number]; [Environment.phoneManager initiateOutgoingCallToContact:_contact atRemoteNumber:number];
} }
- (BOOL)phoneNumberIsSecure:(PhoneNumber *)phoneNumber { - (BOOL)phoneNumberIsSecure:(PhoneNumber *)phoneNumber {
PhoneNumberDirectoryFilter* directory = [[[Environment getCurrent] phoneDirectoryManager] getCurrentFilter]; PhoneNumberDirectoryFilter* directory = Environment.getCurrent.phoneDirectoryManager.getCurrentFilter;
return phoneNumber != nil && [directory containsPhoneNumber:phoneNumber]; return phoneNumber != nil && [directory containsPhoneNumber:phoneNumber];
} }

View File

@ -111,9 +111,9 @@
} }
- (void)callButtonTapped { - (void)callButtonTapped {
PhoneNumber *phoneNumber = [self phoneNumberForCurrentInput]; PhoneNumber *phoneNumber = self.phoneNumberForCurrentInput;
BOOL shouldTryCall = [[[[Environment getCurrent] phoneDirectoryManager] getCurrentFilter] containsPhoneNumber:phoneNumber] || [[Environment getCurrent].recentCallManager isPhoneNumberPresentInRecentCalls:phoneNumber]; BOOL shouldTryCall = [Environment.getCurrent.phoneDirectoryManager.getCurrentFilter containsPhoneNumber:phoneNumber] || [Environment.getCurrent.recentCallManager isPhoneNumberPresentInRecentCalls:phoneNumber];
if( shouldTryCall){ if( shouldTryCall){
[self initiateCallToPhoneNumber:phoneNumber]; [self initiateCallToPhoneNumber:phoneNumber];
@ -124,10 +124,10 @@
-(void) initiateCallToPhoneNumber:(PhoneNumber*) phoneNumber { -(void) initiateCallToPhoneNumber:(PhoneNumber*) phoneNumber {
if (_contact) { if (_contact) {
[[Environment phoneManager] initiateOutgoingCallToContact:_contact [Environment.phoneManager initiateOutgoingCallToContact:_contact
atRemoteNumber:phoneNumber]; atRemoteNumber:phoneNumber];
} else { } else {
[[Environment phoneManager] initiateOutgoingCallToRemoteNumber:phoneNumber]; [Environment.phoneManager initiateOutgoingCallToRemoteNumber:phoneNumber];
} }
} }
@ -150,7 +150,7 @@
- (void)tryUpdateContactForNumber:(PhoneNumber *)number { - (void)tryUpdateContactForNumber:(PhoneNumber *)number {
if (number) { if (number) {
_contact = [[[Environment getCurrent] contactsManager] latestContactForPhoneNumber:number]; _contact = [Environment.getCurrent.contactsManager latestContactForPhoneNumber:number];
} else { } else {
_contact = nil; _contact = nil;
} }

View File

@ -43,13 +43,13 @@ static NSString *const CONTACT_TABLE_VIEW_CELL_IDENTIFIER = @"ContactTableViewCe
} }
- (void)observeLatestFavourites { - (void)observeLatestFavourites {
ObservableValue *observableFavourites = [[[Environment getCurrent] contactsManager] getObservableFavourites]; ObservableValue *observableFavourites = Environment.getCurrent.contactsManager.getObservableFavourites;
[observableFavourites watchLatestValue:^(NSArray *latestFavourites) { [observableFavourites watchLatestValue:^(NSArray *latestFavourites) {
_favourites = latestFavourites; _favourites = latestFavourites;
[_favouriteTableView reloadData]; [_favouriteTableView reloadData];
[self hideTableViewIfNoFavourites]; [self hideTableViewIfNoFavourites];
} onThread:[NSThread mainThread] untilCancelled:nil]; } onThread:NSThread.mainThread untilCancelled:nil];
} }
- (void)hideTableViewIfNoFavourites { - (void)hideTableViewIfNoFavourites {
@ -80,7 +80,7 @@ static NSString *const CONTACT_TABLE_VIEW_CELL_IDENTIFIER = @"ContactTableViewCe
- (void)favouriteTapped:(Contact *)contact { - (void)favouriteTapped:(Contact *)contact {
PhoneNumberDirectoryFilter *filter = [[[Environment getCurrent] phoneDirectoryManager] getCurrentFilter]; PhoneNumberDirectoryFilter *filter = Environment.getCurrent.phoneDirectoryManager.getCurrentFilter;
for (PhoneNumber *number in contact.parsedPhoneNumbers) { for (PhoneNumber *number in contact.parsedPhoneNumbers) {
if ([filter containsPhoneNumber:number]) { if ([filter containsPhoneNumber:number]) {

View File

@ -50,7 +50,7 @@ static NSInteger connectingFlashCounter = 0;
[self pauseMusicIfPlaying]; [self pauseMusicIfPlaying];
[self setupButtonBorders]; [self setupButtonBorders];
[self localizeButtons]; [self localizeButtons];
[[UIDevice currentDevice] setProximityMonitoringEnabled:YES]; [UIDevice.currentDevice setProximityMonitoringEnabled:YES];
} }
- (void)viewDidAppear:(BOOL)animated { - (void)viewDidAppear:(BOOL)animated {
@ -66,7 +66,7 @@ static NSInteger connectingFlashCounter = 0;
} }
- (void)dealloc { - (void)dealloc {
[[UIDevice currentDevice] setProximityMonitoringEnabled:NO]; [UIDevice.currentDevice setProximityMonitoringEnabled:NO];
} }
-(void) showCallState { -(void) showCallState {
@ -192,7 +192,7 @@ static NSInteger connectingFlashCounter = 0;
} }
} }
-(void) handleIncomingDetails { -(void) handleIncomingDetails {
[[_callState futureShortAuthenticationString] thenDo:^(NSString* sas) { [_callState.futureShortAuthenticationString thenDo:^(NSString* sas) {
_authenicationStringLabel.hidden = NO; _authenicationStringLabel.hidden = NO;
_authenicationStringLabel.text = sas; _authenicationStringLabel.text = sas;
[self performCallInSessionAnimation]; [self performCallInSessionAnimation];
@ -200,7 +200,7 @@ static NSInteger connectingFlashCounter = 0;
[[_callState observableProgress] watchLatestValue:^(CallProgress* latestProgress) { [[_callState observableProgress] watchLatestValue:^(CallProgress* latestProgress) {
[self onCallProgressed:latestProgress]; [self onCallProgressed:latestProgress];
} onThread:[NSThread mainThread] untilCancelled:nil]; } onThread:NSThread.mainThread untilCancelled:nil];
} }
-(void) onCallProgressed:(CallProgress*)latestProgress { -(void) onCallProgressed:(CallProgress*)latestProgress {
@ -214,7 +214,7 @@ static NSInteger connectingFlashCounter = 0;
} }
if ([latestProgress type] == CallProgressType_Terminated) { if ([latestProgress type] == CallProgressType_Terminated) {
[[_callState futureTermination] thenDo:^(CallTermination* termination) { [_callState.futureTermination thenDo:^(CallTermination* termination) {
[self onCallEnded:termination]; [self onCallEnded:termination];
[AppAudioManager.sharedInstance respondToTerminationType:[termination type]]; [AppAudioManager.sharedInstance respondToTerminationType:[termination type]];
}]; }];
@ -225,7 +225,7 @@ static NSInteger connectingFlashCounter = 0;
-(void) onCallEnded:(CallTermination*)termination { -(void) onCallEnded:(CallTermination*)termination {
[self updateViewForTermination:termination]; [self updateViewForTermination:termination];
[[Environment phoneManager] hangupOrDenyCall]; [Environment.phoneManager hangupOrDenyCall];
[self dismissViewWithOptionalDelay: [termination type] != CallTerminationType_ReplacedByNext ]; [self dismissViewWithOptionalDelay: [termination type] != CallTerminationType_ReplacedByNext ];
@ -235,12 +235,12 @@ static NSInteger connectingFlashCounter = 0;
} }
- (void)endCallTapped { - (void)endCallTapped {
[[Environment phoneManager] hangupOrDenyCall]; [Environment.phoneManager hangupOrDenyCall];
[self dismissViewControllerAnimated:YES completion:nil]; [self dismissViewControllerAnimated:YES completion:nil];
} }
- (void)muteButtonTapped { - (void)muteButtonTapped {
_muteButton.selected = [[Environment phoneManager] toggleMute]; _muteButton.selected = [Environment.phoneManager toggleMute];
} }
- (void)speakerButtonTapped { - (void)speakerButtonTapped {
@ -249,12 +249,12 @@ static NSInteger connectingFlashCounter = 0;
- (void)answerButtonTapped { - (void)answerButtonTapped {
[self displayAcceptRejectButtons:NO]; [self displayAcceptRejectButtons:NO];
[[Environment phoneManager] answerCall]; [Environment.phoneManager answerCall];
} }
- (void)rejectButtonTapped { - (void)rejectButtonTapped {
[self displayAcceptRejectButtons:NO]; [self displayAcceptRejectButtons:NO];
[[Environment phoneManager] hangupOrDenyCall]; [Environment.phoneManager hangupOrDenyCall];
[self dismissViewControllerAnimated:YES completion:nil]; [self dismissViewControllerAnimated:YES completion:nil];
} }

View File

@ -79,14 +79,14 @@ static NSString *const FOOTER_TABLE_CELL_IDENTIFIER = @"InboxFeedFooterCell";
} }
- (void)observeRecentCalls { - (void)observeRecentCalls {
ObservableValue *observableContacts = [[[Environment getCurrent] contactsManager] getObservableContacts]; ObservableValue *observableContacts = Environment.getCurrent.contactsManager.getObservableContacts;
[observableContacts watchLatestValue:^(id latestValue) { [observableContacts watchLatestValue:^(id latestValue) {
ObservableValue *observableRecents = [[[Environment getCurrent] recentCallManager] getObservableRecentCalls]; ObservableValue *observableRecents = Environment.getCurrent.recentCallManager.getObservableRecentCalls;
[observableRecents watchLatestValue:^(NSArray *latestRecents) { [observableRecents watchLatestValue:^(NSArray *latestRecents) {
_inboxFeed = [[[Environment getCurrent] recentCallManager] recentsForSearchString:nil _inboxFeed = [Environment.getCurrent.recentCallManager recentsForSearchString:nil
andExcludeArchived:YES]; andExcludeArchived:YES];
[self updateTutorialVisibility]; [self updateTutorialVisibility];
if (!_tableViewContentMutating) { if (!_tableViewContentMutating) {
@ -97,10 +97,10 @@ static NSString *const FOOTER_TABLE_CELL_IDENTIFIER = @"InboxFeedFooterCell";
shouldChangeCharactersInRange:NSMakeRange(0, 0) shouldChangeCharactersInRange:NSMakeRange(0, 0)
replacementString:SEARCH_BAR_DEFAULT_EMPTY_STRING]; replacementString:SEARCH_BAR_DEFAULT_EMPTY_STRING];
} }
} onThread:[NSThread mainThread] untilCancelled:nil]; } onThread:NSThread.mainThread untilCancelled:nil];
} onThread:[NSThread mainThread] untilCancelled:nil]; } onThread:NSThread.mainThread untilCancelled:nil];
} }
- (void)observeKeyboardNotifications { - (void)observeKeyboardNotifications {
@ -132,7 +132,7 @@ static NSString *const FOOTER_TABLE_CELL_IDENTIFIER = @"InboxFeedFooterCell";
} }
} }
if (needsSave) { if (needsSave) {
[[[Environment getCurrent] recentCallManager] saveContactsToDefaults]; [Environment.getCurrent.recentCallManager saveContactsToDefaults];
[(TabBarParentViewController *)self.mm_drawerController.centerViewController updateMissedCallCountLabel]; [(TabBarParentViewController *)self.mm_drawerController.centerViewController updateMissedCallCountLabel];
[_inboxFeedTableView reloadData]; [_inboxFeedTableView reloadData];
} }
@ -169,10 +169,10 @@ static NSString *const FOOTER_TABLE_CELL_IDENTIFIER = @"InboxFeedFooterCell";
if (delete) { if (delete) {
animation = UITableViewRowAnimationLeft; animation = UITableViewRowAnimationLeft;
[[[Environment getCurrent] recentCallManager] removeRecentCall:recent]; [Environment.getCurrent.recentCallManager removeRecentCall:recent];
} else { } else {
animation = UITableViewRowAnimationRight; animation = UITableViewRowAnimationRight;
[[[Environment getCurrent] recentCallManager] archiveRecentCall:recent]; [Environment.getCurrent.recentCallManager archiveRecentCall:recent];
} }
[_inboxFeedTableView deleteRowsAtIndexPaths:@[indexPath] [_inboxFeedTableView deleteRowsAtIndexPaths:@[indexPath]
@ -183,7 +183,7 @@ static NSString *const FOOTER_TABLE_CELL_IDENTIFIER = @"InboxFeedFooterCell";
} }
- (void)updateTutorialVisibility { - (void)updateTutorialVisibility {
_freshInboxView.hidden = ![[Environment preferences] getFreshInstallTutorialsEnabled]; _freshInboxView.hidden = !Environment.preferences.getFreshInstallTutorialsEnabled;
_inboxFeedTableView.hidden = !_freshInboxView.hidden; _inboxFeedTableView.hidden = !_freshInboxView.hidden;
} }
@ -346,7 +346,7 @@ static NSString *const FOOTER_TABLE_CELL_IDENTIFIER = @"InboxFeedFooterCell";
if (searching) { if (searching) {
_freshInboxView.hidden = YES; _freshInboxView.hidden = YES;
_inboxFeedTableView.hidden = NO; _inboxFeedTableView.hidden = NO;
_searchInboxFeed = [[[Environment getCurrent] recentCallManager] recentsForSearchString:term _searchInboxFeed = [Environment.getCurrent.recentCallManager recentsForSearchString:term
andExcludeArchived:YES]; andExcludeArchived:YES];
[self reloadSearchContactsForTerm:term]; [self reloadSearchContactsForTerm:term];
@ -372,7 +372,7 @@ static NSString *const FOOTER_TABLE_CELL_IDENTIFIER = @"InboxFeedFooterCell";
- (void)reloadSearchContactsForTerm:(NSString *)term { - (void)reloadSearchContactsForTerm:(NSString *)term {
NSArray *contacts = [[[Environment getCurrent] contactsManager] latestContactsWithSearchString:term]; NSArray *contacts = [Environment.getCurrent.contactsManager latestContactsWithSearchString:term];
NSMutableArray *registeredContacts = [NSMutableArray array]; NSMutableArray *registeredContacts = [NSMutableArray array];
NSMutableArray *unregisteredContacts = [NSMutableArray array]; NSMutableArray *unregisteredContacts = [NSMutableArray array];
@ -381,7 +381,7 @@ static NSString *const FOOTER_TABLE_CELL_IDENTIFIER = @"InboxFeedFooterCell";
BOOL registeredContact = NO; BOOL registeredContact = NO;
for (PhoneNumber *phoneNumber in contact.parsedPhoneNumbers) { for (PhoneNumber *phoneNumber in contact.parsedPhoneNumbers) {
if ([[[[Environment getCurrent] phoneDirectoryManager] getCurrentFilter] containsPhoneNumber:phoneNumber]) { if ([Environment.getCurrent.phoneDirectoryManager.getCurrentFilter containsPhoneNumber:phoneNumber]) {
registeredContact = YES; registeredContact = YES;
} }
} }

View File

@ -71,17 +71,17 @@ static NSString *const INVITE_CONTACTS_TABLE_CELL_IDENTIFIER = @"ContactTableVie
} }
- (void)setupContacts { - (void)setupContacts {
ObservableValue *observableContacts = [[[Environment getCurrent] contactsManager] getObservableContacts]; ObservableValue *observableContacts = Environment.getCurrent.contactsManager.getObservableContacts;
[observableContacts watchLatestValue:^(NSArray *latestContacts) { [observableContacts watchLatestValue:^(NSArray *latestContacts) {
_latestContacts = [self getUnregisteredUsersFromAllUsers:latestContacts searchTerm:nil]; _latestContacts = [self getUnregisteredUsersFromAllUsers:latestContacts searchTerm:nil];
_displayedContacts = _latestContacts; _displayedContacts = _latestContacts;
[_contactTableView reloadData]; [_contactTableView reloadData];
} onThread:[NSThread mainThread] untilCancelled:nil]; } onThread:NSThread.mainThread untilCancelled:nil];
} }
- (NSArray *)getUnregisteredUsersFromAllUsers:(NSArray *)users searchTerm:(NSString *)searchTerm { - (NSArray *)getUnregisteredUsersFromAllUsers:(NSArray *)users searchTerm:(NSString *)searchTerm {
ContactsManager *contactsManager = [[Environment getCurrent] contactsManager]; ContactsManager *contactsManager = Environment.getCurrent.contactsManager;
return [users filter:^int(Contact *contact) { return [users filter:^int(Contact *contact) {

View File

@ -96,7 +96,7 @@
} }
- (void)populateDefaultCountryNameAndCode { - (void)populateDefaultCountryNameAndCode {
NSLocale *locale = [NSLocale currentLocale]; NSLocale *locale = NSLocale.currentLocale;
NSString *countryCode = [locale objectForKey:NSLocaleCountryCode]; NSString *countryCode = [locale objectForKey:NSLocaleCountryCode];
NSNumber *cc = [NBPhoneNumberUtil.sharedInstance getCountryCodeForRegion:countryCode]; NSNumber *cc = [NBPhoneNumberUtil.sharedInstance getCountryCodeForRegion:countryCode];
@ -123,7 +123,7 @@
return [HttpManager asyncOkResponseFromMasterServer:registerRequest return [HttpManager asyncOkResponseFromMasterServer:registerRequest
unlessCancelled:internalUntilCancelledToken unlessCancelled:internalUntilCancelledToken
andErrorHandler:[Environment errorNoter]]; andErrorHandler:Environment.errorNoter];
}; };
TOCFuture *futurePhoneRegistrationStarted = [TOCFuture futureFromUntilOperation:[TOCFuture operationTry:regStarter] TOCFuture *futurePhoneRegistrationStarted = [TOCFuture futureFromUntilOperation:[TOCFuture operationTry:regStarter]
withOperationTimeout:SERVER_TIMEOUT_SECONDS withOperationTimeout:SERVER_TIMEOUT_SECONDS
@ -176,12 +176,12 @@
HttpRequest *verifyRequest = [HttpRequest httpRequestToVerifyAccessToPhoneNumberWithChallenge:_challengeTextField.text]; HttpRequest *verifyRequest = [HttpRequest httpRequestToVerifyAccessToPhoneNumberWithChallenge:_challengeTextField.text];
TOCFuture *futureDone = [HttpManager asyncOkResponseFromMasterServer:verifyRequest TOCFuture *futureDone = [HttpManager asyncOkResponseFromMasterServer:verifyRequest
unlessCancelled:nil unlessCancelled:nil
andErrorHandler:[Environment errorNoter]]; andErrorHandler:Environment.errorNoter];
[futureDone catchDo:^(id error) { [futureDone catchDo:^(id error) {
if ([error isKindOfClass:[HttpResponse class]]) { if ([error isKindOfClass:HttpResponse.class]) {
HttpResponse* badResponse = error; HttpResponse* badResponse = error;
if ([badResponse getStatusCode] == 401) { if (badResponse.getStatusCode == 401) {
UIAlertView *incorrectChallengeCodeAV = [[UIAlertView alloc]initWithTitle:REGISTER_CHALLENGE_ALERT_VIEW_TITLE message:REGISTER_CHALLENGE_ALERT_VIEW_BODY delegate:nil cancelButtonTitle:REGISTER_CHALLENGE_ALERT_DISMISS otherButtonTitles:nil, nil]; UIAlertView *incorrectChallengeCodeAV = [[UIAlertView alloc]initWithTitle:REGISTER_CHALLENGE_ALERT_VIEW_TITLE message:REGISTER_CHALLENGE_ALERT_VIEW_BODY delegate:nil cancelButtonTitle:REGISTER_CHALLENGE_ALERT_DISMISS otherButtonTitles:nil, nil];
[incorrectChallengeCodeAV show]; [incorrectChallengeCodeAV show];
_challengeButton.enabled = YES; _challengeButton.enabled = YES;
@ -191,7 +191,7 @@
} }
_challengeButton.enabled = YES; _challengeButton.enabled = YES;
[_challengeActivityIndicator stopAnimating]; [_challengeActivityIndicator stopAnimating];
[Environment errorNoter](error, @"While Verifying Challenge.", NO); Environment.errorNoter(error, @"While Verifying Challenge.", NO);
}]; }];
[futureDone thenDo:^(id result) { [futureDone thenDo:^(id result) {
@ -202,7 +202,7 @@
[PushManager.sharedManager askForPushRegistrationWithSuccess:^{ [PushManager.sharedManager askForPushRegistrationWithSuccess:^{
[Environment setRegistered:YES]; [Environment setRegistered:YES];
[registered trySetResult:@YES]; [registered trySetResult:@YES];
[[[Environment getCurrent] phoneDirectoryManager] forceUpdate]; [Environment.getCurrent.phoneDirectoryManager forceUpdate];
[self dismissView]; [self dismissView];
} failure:^{ } failure:^{
UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:REGISTER_ERROR_ALERT_VIEW_TITLE message:REGISTER_ERROR_ALERT_VIEW_BODY delegate:nil cancelButtonTitle:REGISTER_ERROR_ALERT_VIEW_DISMISS otherButtonTitles:nil, nil]; UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:REGISTER_ERROR_ALERT_VIEW_TITLE message:REGISTER_ERROR_ALERT_VIEW_BODY delegate:nil cancelButtonTitle:REGISTER_ERROR_ALERT_VIEW_DISMISS otherButtonTitles:nil, nil];
@ -241,7 +241,7 @@
NSTimeInterval smsTimeoutTimeInterval = SMS_VERIFICATION_TIMEOUT_SECONDS; NSTimeInterval smsTimeoutTimeInterval = SMS_VERIFICATION_TIMEOUT_SECONDS;
NSDate *now = [[NSDate alloc] init]; NSDate *now = [NSDate new];
timeoutDate = [[NSDate alloc] initWithTimeInterval:smsTimeoutTimeInterval sinceDate:now]; timeoutDate = [[NSDate alloc] initWithTimeInterval:smsTimeoutTimeInterval sinceDate:now];
countdownTimer = [NSTimer scheduledTimerWithTimeInterval:1 countdownTimer = [NSTimer scheduledTimerWithTimeInterval:1
@ -255,9 +255,9 @@
} }
- (void) countdowntimerFired { - (void) countdowntimerFired {
NSDate *now = [[NSDate alloc] init]; NSDate *now = [NSDate new];
NSCalendar *sysCalendar = [NSCalendar currentCalendar]; NSCalendar *sysCalendar = NSCalendar.currentCalendar;
unsigned int unitFlags = NSHourCalendarUnit | NSMinuteCalendarUnit | NSSecondCalendarUnit; unsigned int unitFlags = NSHourCalendarUnit | NSMinuteCalendarUnit | NSSecondCalendarUnit;
NSDateComponents *conversionInfo = [sysCalendar components:unitFlags fromDate:now toDate:timeoutDate options:0]; NSDateComponents *conversionInfo = [sysCalendar components:unitFlags fromDate:now toDate:timeoutDate options:0];
NSString* timeLeft = [NSString stringWithFormat:@"%ld:%02ld",(long)[conversionInfo minute],(long)[conversionInfo second]]; NSString* timeLeft = [NSString stringWithFormat:@"%ld:%02ld",(long)[conversionInfo minute],(long)[conversionInfo second]];
@ -278,14 +278,14 @@
[self.voiceChallengeTextLabel setText:NSLocalizedString(@"REGISTER_CALL_CALLING", @"")]; [self.voiceChallengeTextLabel setText:NSLocalizedString(@"REGISTER_CALL_CALLING", @"")];
return [HttpManager asyncOkResponseFromMasterServer:voiceVerifyReq return [HttpManager asyncOkResponseFromMasterServer:voiceVerifyReq
unlessCancelled:internalUntilCancelledToken unlessCancelled:internalUntilCancelledToken
andErrorHandler:[Environment errorNoter]]; andErrorHandler:Environment.errorNoter];
}; };
TOCFuture *futureVoiceVerificationStarted = [TOCFuture futureFromUntilOperation:[TOCFuture operationTry:callStarter] TOCFuture *futureVoiceVerificationStarted = [TOCFuture futureFromUntilOperation:[TOCFuture operationTry:callStarter]
withOperationTimeout:SERVER_TIMEOUT_SECONDS withOperationTimeout:SERVER_TIMEOUT_SECONDS
until:life.token]; until:life.token];
[futureVoiceVerificationStarted catchDo:^(id errorId) { [futureVoiceVerificationStarted catchDo:^(id errorId) {
HttpResponse* error = (HttpResponse*)errorId; HttpResponse* error = (HttpResponse*)errorId;
[self.voiceChallengeTextLabel setText:[error getStatusText]]; [self.voiceChallengeTextLabel setText:error.getStatusText];
}]; }];
[futureVoiceVerificationStarted finallyTry:^(id _id) { [futureVoiceVerificationStarted finallyTry:^(id _id) {

View File

@ -109,12 +109,12 @@ static NSString *const CHECKBOX_EMPTY_IMAGE_NAME = @"checkbox_empty";
[button setImage:[UIImage imageNamed:CHECKBOX_CHECKMARK_IMAGE_NAME] [button setImage:[UIImage imageNamed:CHECKBOX_CHECKMARK_IMAGE_NAME]
forState:UIControlStateSelected]; forState:UIControlStateSelected];
} }
PropertyListPreferences *prefs = [Environment preferences]; PropertyListPreferences *prefs = Environment.preferences;
_hideContactImagesButton.selected = ![prefs getContactImagesEnabled]; _hideContactImagesButton.selected = !prefs.getContactImagesEnabled;
_enableScreenSecurityButton.selected = [prefs screenSecurityIsEnabled]; _enableScreenSecurityButton.selected = prefs.screenSecurityIsEnabled;
_disableAutocorrectButton.selected = ![prefs getAutocorrectEnabled]; _disableAutocorrectButton.selected = !prefs.getAutocorrectEnabled;
_disableHistoryButton.selected = ![prefs getHistoryLogEnabled]; _disableHistoryButton.selected = !prefs.getHistoryLogEnabled;
_disableLogsCell.selected = ![prefs loggingIsEnabled]; _disableLogsCell.selected = !prefs.loggingIsEnabled;
} }
- (void)configureAllCells { - (void)configureAllCells {
@ -146,7 +146,7 @@ static NSString *const CHECKBOX_EMPTY_IMAGE_NAME = @"checkbox_empty";
NSMutableArray *cells = [@[_disableLogsCell] mutableCopy]; NSMutableArray *cells = [@[_disableLogsCell] mutableCopy];
if ([[Environment preferences] loggingIsEnabled]) { if (Environment.preferences.loggingIsEnabled) {
[cells addObject:_sendDebugLog]; [cells addObject:_sendDebugLog];
} }
@ -207,22 +207,22 @@ static NSString *const CHECKBOX_EMPTY_IMAGE_NAME = @"checkbox_empty";
- (IBAction)hideContactImagesButtonTapped { - (IBAction)hideContactImagesButtonTapped {
_hideContactImagesButton.selected = !_hideContactImagesButton.selected; _hideContactImagesButton.selected = !_hideContactImagesButton.selected;
[[Environment preferences] setContactImagesEnabled:!_hideContactImagesButton.selected]; [Environment.preferences setContactImagesEnabled:!_hideContactImagesButton.selected];
} }
- (IBAction)disableAutocorrectButtonTapped { - (IBAction)disableAutocorrectButtonTapped {
_disableAutocorrectButton.selected = !_disableAutocorrectButton.selected; _disableAutocorrectButton.selected = !_disableAutocorrectButton.selected;
[[Environment preferences] setAutocorrectEnabled:!_disableAutocorrectButton.selected]; [Environment.preferences setAutocorrectEnabled:!_disableAutocorrectButton.selected];
} }
- (IBAction)disableHistoryButtonTapped { - (IBAction)disableHistoryButtonTapped {
_disableHistoryButton.selected = !_disableHistoryButton.selected; _disableHistoryButton.selected = !_disableHistoryButton.selected;
[[Environment preferences] setHistoryLogEnabled:!_disableHistoryButton.selected]; [Environment.preferences setHistoryLogEnabled:!_disableHistoryButton.selected];
} }
- (IBAction)enableScreenSecurityTapped:(id)sender{ - (IBAction)enableScreenSecurityTapped:(id)sender{
_enableScreenSecurityButton.selected = !_enableScreenSecurityButton.selected; _enableScreenSecurityButton.selected = !_enableScreenSecurityButton.selected;
[[Environment preferences] setScreenSecurity:_enableScreenSecurityButton.selected]; [Environment.preferences setScreenSecurity:_enableScreenSecurityButton.selected];
} }
- (IBAction)disableLogTapped:(id)sender{ - (IBAction)disableLogTapped:(id)sender{
@ -237,13 +237,13 @@ static NSString *const CHECKBOX_EMPTY_IMAGE_NAME = @"checkbox_empty";
[DebugLogger.sharedInstance enableFileLogging]; [DebugLogger.sharedInstance enableFileLogging];
} }
[[Environment preferences] setLoggingEnabled:loggingEnabled]; [Environment.preferences setLoggingEnabled:loggingEnabled];
_debuggingTableViewCells = [self debugCells]; _debuggingTableViewCells = [self debugCells];
[_settingsTableView reloadData]; [_settingsTableView reloadData];
} }
- (void)clearHistory { - (void)clearHistory {
[[[Environment getCurrent] recentCallManager] clearRecentCalls]; [Environment.getCurrent.recentCallManager clearRecentCalls];
UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:SETTINGS_LOG_CLEAR_TITLE UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:SETTINGS_LOG_CLEAR_TITLE
message:SETTINGS_LOG_CLEAR_MESSAGE message:SETTINGS_LOG_CLEAR_MESSAGE
delegate:nil delegate:nil

View File

@ -55,10 +55,10 @@
} }
_whisperUserUpdateImageView.hidden = [self hideUserUpdateNotification]; _whisperUserUpdateImageView.hidden = [self hideUserUpdateNotification];
ObservableValue *recentCallObservable = [[[Environment getCurrent] recentCallManager] getObservableRecentCalls]; ObservableValue *recentCallObservable = Environment.getCurrent.recentCallManager.getObservableRecentCalls;
[recentCallObservable watchLatestValue:^(NSArray *latestRecents) { [recentCallObservable watchLatestValue:^(NSArray *latestRecents) {
[self updateMissedCallCountLabel]; [self updateMissedCallCountLabel];
} onThread:[NSThread mainThread] untilCancelled:nil]; } onThread:NSThread.mainThread untilCancelled:nil];
[[NSNotificationCenter defaultCenter] addObserver:self [[NSNotificationCenter defaultCenter] addObserver:self
selector:@selector(newUsersDetected:) selector:@selector(newUsersDetected:)
@ -166,7 +166,7 @@
} }
- (void)updateMissedCallCountLabel { - (void)updateMissedCallCountLabel {
NSUInteger missedCallCount = [[[Environment getCurrent] recentCallManager] missedCallCount]; NSUInteger missedCallCount = Environment.getCurrent.recentCallManager.missedCallCount;
if (missedCallCount > 0) { if (missedCallCount > 0) {
_tabBarInboxButton.frame = CGRectMake(CGRectGetMinX(_tabBarInboxButton.frame), _tabBarInboxButton.frame = CGRectMake(CGRectGetMinX(_tabBarInboxButton.frame),
CGRectGetMinY(_tabBarInboxButton.frame), CGRectGetMinY(_tabBarInboxButton.frame),
@ -199,12 +199,12 @@
} }
- (void)setNewWhisperUsersAsSeen:(NSArray *)users { - (void)setNewWhisperUsersAsSeen:(NSArray *)users {
[[[Environment getCurrent] contactsManager] addContactsToKnownWhisperUsers:users]; [Environment.getCurrent.contactsManager addContactsToKnownWhisperUsers:users];
[_contactsViewController showNotificationForNewWhisperUsers:nil]; [_contactsViewController showNotificationForNewWhisperUsers:nil];
_whisperUserUpdateImageView.hidden = [self hideUserUpdateNotification]; _whisperUserUpdateImageView.hidden = [self hideUserUpdateNotification];
} }
-(BOOL) hideUserUpdateNotification { -(BOOL) hideUserUpdateNotification {
return (0 == [[[Environment getCurrent] contactsManager] getNumberOfUnacknowledgedCurrentUsers]); return (0 == Environment.getCurrent.contactsManager.getNumberOfUnacknowledgedCurrentUsers);
} }
@end @end

View File

@ -11,7 +11,7 @@
- (id)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier { - (id)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier {
self = [[NSBundle mainBundle] loadNibNamed:NSStringFromClass([self class]) self = [NSBundle.mainBundle loadNibNamed:NSStringFromClass(self.class)
owner:self owner:self
options:nil][0]; options:nil][0];
if (self) { if (self) {
@ -23,7 +23,7 @@
} }
- (NSString *)reuseIdentifier { - (NSString *)reuseIdentifier {
return NSStringFromClass([self class]); return NSStringFromClass(self.class);
} }
- (void)prepareForReuse { - (void)prepareForReuse {
@ -32,7 +32,7 @@
} }
- (void)configureWithRecentCall:(RecentCall *)recentCall { - (void)configureWithRecentCall:(RecentCall *)recentCall {
Contact *contact = [[[Environment getCurrent] contactsManager] latestContactWithRecordId:recentCall.contactRecordID]; Contact *contact = [Environment.getCurrent.contactsManager latestContactWithRecordId:recentCall.contactRecordID];
if (contact) { if (contact) {
_contactNameLabel.text = contact.fullName; _contactNameLabel.text = contact.fullName;
} else { } else {
@ -74,7 +74,7 @@
_deleteImageView.bounds.origin.y, _deleteImageView.bounds.origin.y,
(CGFloat)newWidth, (CGFloat)newWidth,
_deleteImageView.bounds.size.height); _deleteImageView.bounds.size.height);
_deleteImageView.tintColor = [UIColor whiteColor]; _deleteImageView.tintColor = UIColor.whiteColor;
} }
} }

View File

@ -9,12 +9,12 @@
@implementation ContactDetailTableViewCell @implementation ContactDetailTableViewCell
- (id)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier { - (id)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier {
self = [[NSBundle mainBundle] loadNibNamed:NSStringFromClass([self class]) owner:self options:nil][0]; self = [NSBundle.mainBundle loadNibNamed:NSStringFromClass(self.class) owner:self options:nil][0];
return self; return self;
} }
- (NSString *)reuseIdentifier { - (NSString *)reuseIdentifier {
return NSStringFromClass([self class]); return NSStringFromClass(self.class);
} }
- (void)configureWithPhoneNumber:(PhoneNumber *)phoneNumber isSecure:(BOOL)isSecure { - (void)configureWithPhoneNumber:(PhoneNumber *)phoneNumber isSecure:(BOOL)isSecure {

View File

@ -5,14 +5,14 @@
@implementation ContactTableViewCell @implementation ContactTableViewCell
- (id)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier { - (id)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier {
self = [[NSBundle mainBundle] loadNibNamed:NSStringFromClass([self class]) owner:self options:nil][0]; self = [NSBundle.mainBundle loadNibNamed:NSStringFromClass(self.class) owner:self options:nil][0];
_contactPictureView.layer.borderColor = [[UIColor lightGrayColor] CGColor]; _contactPictureView.layer.borderColor = [[UIColor lightGrayColor] CGColor];
_contactPictureView.layer.masksToBounds = YES; _contactPictureView.layer.masksToBounds = YES;
return self; return self;
} }
- (NSString *)reuseIdentifier { - (NSString *)reuseIdentifier {
return NSStringFromClass([self class]); return NSStringFromClass(self.class);
} }
- (void)configureWithContact:(Contact *)contact { - (void)configureWithContact:(Contact *)contact {

View File

@ -3,14 +3,14 @@
@implementation CountryCodeTableViewCell @implementation CountryCodeTableViewCell
- (id)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier { - (id)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier {
self = [[[NSBundle mainBundle] loadNibNamed:NSStringFromClass([self class]) self = [[NSBundle.mainBundle loadNibNamed:NSStringFromClass(self.class)
owner:self owner:self
options:nil] firstObject]; options:nil] firstObject];
return self; return self;
} }
- (NSString *)reuseIdentifier { - (NSString *)reuseIdentifier {
return NSStringFromClass([self class]); return NSStringFromClass(self.class);
} }
- (void)configureWithCountryCode:(NSString *)code andCountryName:(NSString *)name { - (void)configureWithCountryCode:(NSString *)code andCountryName:(NSString *)name {

View File

@ -5,14 +5,14 @@
@implementation FavouriteTableViewCell @implementation FavouriteTableViewCell
- (id)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier { - (id)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier {
self = [[NSBundle mainBundle] loadNibNamed:NSStringFromClass([self class]) owner:self options:nil][0]; self = [NSBundle.mainBundle loadNibNamed:NSStringFromClass(self.class) owner:self options:nil][0];
_contactPictureView.layer.borderColor = [[UIColor lightGrayColor] CGColor]; _contactPictureView.layer.borderColor = [[UIColor lightGrayColor] CGColor];
_contactPictureView.layer.masksToBounds = YES; _contactPictureView.layer.masksToBounds = YES;
return self; return self;
} }
- (NSString *)reuseIdentifier { - (NSString *)reuseIdentifier {
return NSStringFromClass([self class]); return NSStringFromClass(self.class);
} }
- (void)configureWithContact:(Contact *)contact { - (void)configureWithContact:(Contact *)contact {

View File

@ -5,11 +5,11 @@
@implementation InboxFeedFooterCell @implementation InboxFeedFooterCell
- (id)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier { - (id)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier {
self = [[NSBundle mainBundle] loadNibNamed:NSStringFromClass([self class]) owner:self options:nil][0]; self = [NSBundle.mainBundle loadNibNamed:NSStringFromClass(self.class) owner:self options:nil][0];
if (self) { if (self) {
ObservableValue *recentCallObserver = [[[Environment getCurrent] recentCallManager] getObservableRecentCalls]; ObservableValue *recentCallObserver = Environment.getCurrent.recentCallManager.getObservableRecentCalls;
[recentCallObserver watchLatestValue:^(id latestValue) { [recentCallObserver watchLatestValue:^(id latestValue) {
NSUInteger inboxCount = [[[[Environment getCurrent] recentCallManager] recentsForSearchString:nil andExcludeArchived:YES] count]; NSUInteger inboxCount = [[Environment.getCurrent.recentCallManager recentsForSearchString:nil andExcludeArchived:YES] count];
if (inboxCount == 0) { if (inboxCount == 0) {
_inboxCountLabel.text = @""; _inboxCountLabel.text = @"";
_inboxMessageLabelFirst.text = HOME_FOOTER_FIRST_MESSAGE_CALLS_NIL; _inboxMessageLabelFirst.text = HOME_FOOTER_FIRST_MESSAGE_CALLS_NIL;
@ -19,13 +19,13 @@
_inboxMessageLabelFirst.text = HOME_FOOTER_FIRST_MESSAGE_CALLS_UNSORTED; _inboxMessageLabelFirst.text = HOME_FOOTER_FIRST_MESSAGE_CALLS_UNSORTED;
_inboxMessageLabelSecond.text = inboxCount == 1 ? HOME_FOOTER_SECOND_MESSAGE_CALL_UNSORTED : HOME_FOOTER_SECOND_MESSAGE_CALLS_UNSORTED; _inboxMessageLabelSecond.text = inboxCount == 1 ? HOME_FOOTER_SECOND_MESSAGE_CALL_UNSORTED : HOME_FOOTER_SECOND_MESSAGE_CALLS_UNSORTED;
} }
} onThread:[NSThread mainThread] untilCancelled:nil]; } onThread:NSThread.mainThread untilCancelled:nil];
} }
return self; return self;
} }
- (NSString *)reuseIdentifier { - (NSString *)reuseIdentifier {
return NSStringFromClass([self class]); return NSStringFromClass(self.class);
} }
@end @end

View File

@ -13,7 +13,7 @@
@implementation InboxFeedTableViewCell @implementation InboxFeedTableViewCell
- (id)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier { - (id)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier {
self = [[NSBundle mainBundle] loadNibNamed:NSStringFromClass([self class]) self = [NSBundle.mainBundle loadNibNamed:NSStringFromClass(self.class)
owner:self owner:self
options:nil][0]; options:nil][0];
@ -33,11 +33,11 @@
} }
- (NSString *)reuseIdentifier { - (NSString *)reuseIdentifier {
return NSStringFromClass([self class]); return NSStringFromClass(self.class);
} }
- (void)configureWithRecentCall:(RecentCall *)recentCall { - (void)configureWithRecentCall:(RecentCall *)recentCall {
Contact *contact = [[[Environment getCurrent] contactsManager] latestContactWithRecordId:recentCall.contactRecordID]; Contact *contact = [Environment.getCurrent.contactsManager latestContactWithRecordId:recentCall.contactRecordID];
if (contact) { if (contact) {
_nameLabel.text = contact.fullName; _nameLabel.text = contact.fullName;
@ -115,7 +115,7 @@
_archiveImageView.bounds.origin.y, _archiveImageView.bounds.origin.y,
(CGFloat)newWidth, (CGFloat)newWidth,
_archiveImageView.bounds.size.height); _archiveImageView.bounds.size.height);
_archiveImageView.tintColor = [UIColor whiteColor]; _archiveImageView.tintColor = UIColor.whiteColor;
} }
@ -134,7 +134,7 @@
_deleteImageView.bounds.origin.y, _deleteImageView.bounds.origin.y,
(CGFloat)newWidth, (CGFloat)newWidth,
_deleteImageView.bounds.size.height); _deleteImageView.bounds.size.height);
_deleteImageView.tintColor = [UIColor whiteColor]; _deleteImageView.tintColor = UIColor.whiteColor;
} }
} }

View File

@ -4,7 +4,7 @@
@implementation LeftSideMenuCell @implementation LeftSideMenuCell
- (id)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier { - (id)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier {
self = [[[NSBundle mainBundle] loadNibNamed:NSStringFromClass([self class]) self = [[NSBundle.mainBundle loadNibNamed:NSStringFromClass(self.class)
owner:self owner:self
options:nil] firstObject]; options:nil] firstObject];
return self; return self;
@ -15,12 +15,12 @@
if (highlighted) { if (highlighted) {
_menuTitleLabel.textColor = [UIUtil darkBackgroundColor]; _menuTitleLabel.textColor = [UIUtil darkBackgroundColor];
} else { } else {
_menuTitleLabel.textColor = [UIUtil whiteColor]; _menuTitleLabel.textColor = UIUtil.whiteColor;
} }
} }
- (NSString *)reuseIdentifier { - (NSString *)reuseIdentifier {
return NSStringFromClass([self class]); return NSStringFromClass(self.class);
} }
@end @end

View File

@ -3,11 +3,11 @@
@implementation PreferenceListTableViewCell @implementation PreferenceListTableViewCell
- (id)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier { - (id)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier {
return [[[NSBundle mainBundle] loadNibNamed:NSStringFromClass([self class]) owner:self options:nil] firstObject]; return [[NSBundle.mainBundle loadNibNamed:NSStringFromClass(self.class) owner:self options:nil] firstObject];
} }
- (NSString *)reuseIdentifier { - (NSString *)reuseIdentifier {
return NSStringFromClass([self class]); return NSStringFromClass(self.class);
} }
@end @end

View File

@ -65,7 +65,7 @@
} }
- (void)updateAutoCorrectionType { - (void)updateAutoCorrectionType {
BOOL autoCorrectEnabled = [[Environment preferences] getAutocorrectEnabled]; BOOL autoCorrectEnabled = Environment.preferences.getAutocorrectEnabled;
_searchTextField.autocorrectionType = autoCorrectEnabled ? UITextAutocorrectionTypeYes : UITextAutocorrectionTypeNo; _searchTextField.autocorrectionType = autoCorrectEnabled ? UITextAutocorrectionTypeYes : UITextAutocorrectionTypeNo;
} }

View File

@ -6,18 +6,18 @@
@implementation UnseenWhisperUserCell @implementation UnseenWhisperUserCell
- (id)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier { - (id)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier {
self = [[[NSBundle mainBundle] loadNibNamed:NSStringFromClass([self class]) owner:self options:nil] firstObject]; self = [[NSBundle.mainBundle loadNibNamed:NSStringFromClass(self.class) owner:self options:nil] firstObject];
return self; return self;
} }
- (NSString *)restorationIdentifier { - (NSString *)restorationIdentifier {
return NSStringFromClass([self class]); return NSStringFromClass(self.class);
} }
- (void)configureWithContact:(Contact *)contact { - (void)configureWithContact:(Contact *)contact {
_nameLabel.text = contact.fullName; _nameLabel.text = contact.fullName;
PhoneNumberDirectoryFilter *filter = [[[Environment getCurrent] phoneDirectoryManager] getCurrentFilter]; PhoneNumberDirectoryFilter *filter = Environment.getCurrent.phoneDirectoryManager.getCurrentFilter;
BOOL foundPhoneNumber = NO; BOOL foundPhoneNumber = NO;
for (PhoneNumber *number in contact.parsedPhoneNumbers) { for (PhoneNumber *number in contact.parsedPhoneNumbers) {

View File

@ -21,7 +21,7 @@
wave[i] = (int16_t)(sin(t)*INT16_MAX); wave[i] = (int16_t)(sin(t)*INT16_MAX);
double curFrequency = (sin(t/400)+1)/2*500+200; double curFrequency = (sin(t/400)+1)/2*500+200;
@synchronized(a) { @synchronized(a) {
t += 2*3.14159*curFrequency/[a getSampleRateInHertz]; t += 2*3.14159*curFrequency/a.getSampleRateInHertz;
} }
} }
[a populatePlaybackQueueWithData:[NSData dataWithBytesNoCopy:wave length:sizeof(wave) freeWhenDone:NO]]; [a populatePlaybackQueueWithData:[NSData dataWithBytesNoCopy:wave length:sizeof(wave) freeWhenDone:NO]];

View File

@ -224,27 +224,27 @@
[q tryEnqueue:[EncodedAudioPacket encodedAudioPacketWithAudioData:increasingData(20) [q tryEnqueue:[EncodedAudioPacket encodedAudioPacketWithAudioData:increasingData(20)
andTimeStamp:1*TICK andTimeStamp:1*TICK
andSequenceNumber:1]]; andSequenceNumber:1]];
test([q currentBufferDepth] == 0); test(q.currentBufferDepth == 0);
[q tryEnqueue:[EncodedAudioPacket encodedAudioPacketWithAudioData:increasingData(20) [q tryEnqueue:[EncodedAudioPacket encodedAudioPacketWithAudioData:increasingData(20)
andTimeStamp:2*TICK andTimeStamp:2*TICK
andSequenceNumber:2]]; andSequenceNumber:2]];
test([q currentBufferDepth] == 1); test(q.currentBufferDepth == 1);
[q tryEnqueue:[EncodedAudioPacket encodedAudioPacketWithAudioData:increasingData(20) [q tryEnqueue:[EncodedAudioPacket encodedAudioPacketWithAudioData:increasingData(20)
andTimeStamp:4*TICK andTimeStamp:4*TICK
andSequenceNumber:4]]; andSequenceNumber:4]];
test([q currentBufferDepth] == 3); test(q.currentBufferDepth == 3);
[q tryDequeue]; [q tryDequeue];
test([q currentBufferDepth] == 2); test(q.currentBufferDepth == 2);
[q tryDequeue]; [q tryDequeue];
test([q currentBufferDepth] == 1); test(q.currentBufferDepth == 1);
[q tryDequeue]; [q tryDequeue];
test([q currentBufferDepth] == 0); test(q.currentBufferDepth == 0);
[q tryDequeue]; [q tryDequeue];
test([q currentBufferDepth] == -1); test(q.currentBufferDepth == -1);
[q tryEnqueue:[EncodedAudioPacket encodedAudioPacketWithAudioData:increasingData(20) [q tryEnqueue:[EncodedAudioPacket encodedAudioPacketWithAudioData:increasingData(20)
andTimeStamp:8*TICK andTimeStamp:8*TICK
andSequenceNumber:8]]; andSequenceNumber:8]];
test([q currentBufferDepth] == 3); test(q.currentBufferDepth == 3);
// resyncs to 0 // resyncs to 0
for (int i = 0; i < 500; i++) { for (int i = 0; i < 500; i++) {
@ -253,6 +253,6 @@
[q tryEnqueue:[EncodedAudioPacket encodedAudioPacketWithAudioData:increasingData(20) [q tryEnqueue:[EncodedAudioPacket encodedAudioPacketWithAudioData:increasingData(20)
andTimeStamp:9000*TICK andTimeStamp:9000*TICK
andSequenceNumber:9000]]; andSequenceNumber:9000]];
test([q currentBufferDepth] == 0); test(q.currentBufferDepth == 0);
} }
@end @end

View File

@ -20,7 +20,7 @@
// [Environment setCurrent:testEnv]; // [Environment setCurrent:testEnv];
// [SGNKeychainUtil setLocalNumberTo:[PhoneNumber phoneNumberFromE164:@"+12211231235"]]; // [SGNKeychainUtil setLocalNumberTo:[PhoneNumber phoneNumberFromE164:@"+12211231235"]];
// [UICKeyChainStore setString:@"shall_not_password" forKey:@"Password"]; // [UICKeyChainStore setString:@"shall_not_password" forKey:@"Password"];
// [[Environment preferences] setValueForKey:@"PasswordCounter" toValue:@2357]; // [Environment.preferences setValueForKey:@"PasswordCounter" toValue:@2357];
// HttpRequest* h = [HttpRequest httpRequestToInitiateToRemoteNumber:[PhoneNumber phoneNumberFromE164:@"+19023334444"]]; // HttpRequest* h = [HttpRequest httpRequestToInitiateToRemoteNumber:[PhoneNumber phoneNumberFromE164:@"+19023334444"]];
// test([[h method] isEqualToString:@"GET"]); // test([[h method] isEqualToString:@"GET"]);
// test([[h location] isEqualToString:@"/session/1/+19023334444"]); // test([[h location] isEqualToString:@"/session/1/+19023334444"]);
@ -73,24 +73,24 @@
} }
-(void) testResponseOk { -(void) testResponseOk {
HttpResponse* h = [HttpResponse httpResponse200Ok]; HttpResponse* h = [HttpResponse httpResponse200Ok];
test([h getStatusCode] == 200); test(h.getStatusCode == 200);
test([h getOptionalBodyText] == nil); test(h.getOptionalBodyText == nil);
test([[h getHeaders] count] == 0); test([h.getHeaders count] == 0);
} }
-(void) testResponseFromData { -(void) testResponseFromData {
HttpResponse* h = [HttpResponse httpResponseFromData:@"HTTP/1.1 200 OK\r\n\r\n".encodedAsUtf8]; HttpResponse* h = [HttpResponse httpResponseFromData:@"HTTP/1.1 200 OK\r\n\r\n".encodedAsUtf8];
test(h.isOkResponse); test(h.isOkResponse);
test([h getStatusCode] == 200); test(h.getStatusCode == 200);
test([[h getStatusText] isEqualToString: @"OK"]); test([h.getStatusText isEqualToString: @"OK"]);
test([h getOptionalBodyText] == nil); test(h.getOptionalBodyText == nil);
test([[h getHeaders] count] == 0); test([h.getHeaders count] == 0);
HttpResponse* h2 = [HttpResponse httpResponseFromData:@"HTTP/1.1 404 Not Found\r\n\r\n".encodedAsUtf8]; HttpResponse* h2 = [HttpResponse httpResponseFromData:@"HTTP/1.1 404 Not Found\r\n\r\n".encodedAsUtf8];
test(!h2.isOkResponse); test(!h2.isOkResponse);
test([h2 getStatusCode] == 404); test(h2.getStatusCode == 404);
test([[h2 getStatusText] isEqualToString:@"Not Found"]); test([h2.getStatusText isEqualToString:@"Not Found"]);
test([h2 getOptionalBodyText] == nil); test(h2.getOptionalBodyText == nil);
test([[h2 getHeaders] count] == 0); test([h2.getHeaders count] == 0);
testThrows([HttpResponse httpResponseFromData:@"HTTP/1.1 200 OK\r\n".encodedAsUtf8]); testThrows([HttpResponse httpResponseFromData:@"HTTP/1.1 200 OK\r\n".encodedAsUtf8]);
testThrows([HttpResponse httpResponseFromData:@"HTTP/1.1 200\r\n\r\n".encodedAsUtf8]); testThrows([HttpResponse httpResponseFromData:@"HTTP/1.1 200\r\n\r\n".encodedAsUtf8]);

View File

@ -15,8 +15,8 @@
id<KeyAgreementParticipant> ec2 = [protocol generateParticipantWithNewKeys]; id<KeyAgreementParticipant> ec2 = [protocol generateParticipantWithNewKeys];
id<KeyAgreementParticipant> ec3 = [protocol generateParticipantWithNewKeys]; id<KeyAgreementParticipant> ec3 = [protocol generateParticipantWithNewKeys];
NSData* pub_1 = [ec1 getPublicKeyData]; NSData* pub_1 = ec1.getPublicKeyData;
NSData* pub_2 = [ec2 getPublicKeyData]; NSData* pub_2 = ec2.getPublicKeyData;
NSData* shared_1 = [ec1 calculateKeyAgreementAgainstRemotePublicKey:pub_2]; NSData* shared_1 = [ec1 calculateKeyAgreementAgainstRemotePublicKey:pub_2];
NSData* shared_2 = [ec2 calculateKeyAgreementAgainstRemotePublicKey:pub_1]; NSData* shared_2 = [ec2 calculateKeyAgreementAgainstRemotePublicKey:pub_1];
@ -34,8 +34,8 @@
id<KeyAgreementParticipant> ec1 = [protocol generateParticipantWithNewKeys]; id<KeyAgreementParticipant> ec1 = [protocol generateParticipantWithNewKeys];
id<KeyAgreementParticipant> ec2 = [protocol generateParticipantWithNewKeys]; id<KeyAgreementParticipant> ec2 = [protocol generateParticipantWithNewKeys];
NSData* pub_1 = [ec1 getPublicKeyData]; NSData* pub_1 = ec1.getPublicKeyData;
NSData* pub_2 = [ec2 getPublicKeyData]; NSData* pub_2 = ec2.getPublicKeyData;
NSData* shared_1 = [ec1 calculateKeyAgreementAgainstRemotePublicKey:pub_2]; NSData* shared_1 = [ec1 calculateKeyAgreementAgainstRemotePublicKey:pub_2];
NSData* shared_2 = [ec2 calculateKeyAgreementAgainstRemotePublicKey:pub_1]; NSData* shared_2 = [ec2 calculateKeyAgreementAgainstRemotePublicKey:pub_1];

View File

@ -16,7 +16,7 @@ bool pm(HandshakePacket* p1, HandshakePacket* p2);
bool pm(HandshakePacket* p1, HandshakePacket* p2) { bool pm(HandshakePacket* p1, HandshakePacket* p2) {
return p1 != nil return p1 != nil
&& p2 != nil && p2 != nil
&& [p1 class] == [p2 class] && p1.class == p2.class
&& [[p1 embeddedIntoRtpPacketWithSequenceNumber:0 usingInteropOptions:@[]] isEqualToRtpPacket:[p2 embeddedIntoRtpPacketWithSequenceNumber:0 usingInteropOptions:@[]]]; && [[p1 embeddedIntoRtpPacketWithSequenceNumber:0 usingInteropOptions:@[]] isEqualToRtpPacket:[p2 embeddedIntoRtpPacketWithSequenceNumber:0 usingInteropOptions:@[]]];
} }
#define AssertPacketsMatch(p1, p2) STAssertTrue(pm(p1, p2), @"") #define AssertPacketsMatch(p1, p2) STAssertTrue(pm(p1, p2), @"")

View File

@ -12,7 +12,7 @@
return participant; return participant;
} }
-(NSData*) getId { -(NSData*) getId {
return [[participant getProtocol] getId]; return participant.getProtocol.getId;
} }
@end @end

View File

@ -101,7 +101,7 @@
-(void) testAuthenticationFail_WrongCert { -(void) testAuthenticationFail_WrongCert {
[Environment setCurrent:testEnv]; [Environment setCurrent:testEnv];
NSString *certPath = [[[NSBundle bundleForClass:[NetworkStream class]] resourcePath] stringByAppendingPathComponent:@"whisperFake.cer"]; NSString *certPath = [[[NSBundle bundleForClass:NetworkStream.class] resourcePath] stringByAppendingPathComponent:@"whisperFake.cer"];
NSData *certData = [[NSData alloc] initWithContentsOfFile:certPath]; NSData *certData = [[NSData alloc] initWithContentsOfFile:certPath];
checkOperation(certData != nil); checkOperation(certData != nil);

View File

@ -17,19 +17,19 @@
andRelayPort:6]; andRelayPort:6];
test([d sessionId] == 5); test([d sessionId] == 5);
test([d relayUdpPort] == 6); test([d relayUdpPort] == 6);
test([[d relayServerName] isEqualToString:@"example.com"]); test([d.relayServerName isEqualToString:@"example.com"]);
// roundtrip // roundtrip
InitiatorSessionDescriptor* d2 = [InitiatorSessionDescriptor initiatorSessionDescriptorFromJson:d.toJson]; InitiatorSessionDescriptor* d2 = [InitiatorSessionDescriptor initiatorSessionDescriptorFromJson:d.toJson];
test([d2 sessionId] == 5); test([d2 sessionId] == 5);
test([d2 relayUdpPort] == 6); test([d2 relayUdpPort] == 6);
test([[d2 relayServerName] isEqualToString:@"example.com"]); test([d2.relayServerName isEqualToString:@"example.com"]);
// constant // constant
InitiatorSessionDescriptor* d3 = [InitiatorSessionDescriptor initiatorSessionDescriptorFromJson:@"{\"sessionId\":5,\"serverName\":\"example.com\",\"relayPort\":6}"]; InitiatorSessionDescriptor* d3 = [InitiatorSessionDescriptor initiatorSessionDescriptorFromJson:@"{\"sessionId\":5,\"serverName\":\"example.com\",\"relayPort\":6}"];
test([d3 sessionId] == 5); test([d3 sessionId] == 5);
test([d3 relayUdpPort] == 6); test([d3 relayUdpPort] == 6);
test([[d3 relayServerName] isEqualToString:@"example.com"]); test([d3.relayServerName isEqualToString:@"example.com"]);
} }
-(void) testResponderSessionDescriptorFromEncryptedRemoteNotification2 { -(void) testResponderSessionDescriptorFromEncryptedRemoteNotification2 {

View File

@ -9,36 +9,36 @@
@implementation DecayingSampleEstimatorTest @implementation DecayingSampleEstimatorTest
-(void) testDecayingSampleEstimator { -(void) testDecayingSampleEstimator {
DecayingSampleEstimator* e = [DecayingSampleEstimator decayingSampleEstimatorWithInitialEstimate:1.0 andDecayPerUnitSample:0.5]; DecayingSampleEstimator* e = [DecayingSampleEstimator decayingSampleEstimatorWithInitialEstimate:1.0 andDecayPerUnitSample:0.5];
test([e currentEstimate] == 1.0); test(e.currentEstimate == 1.0);
test([e decayRatePerUnitSample] == 0.5); test([e decayRatePerUnitSample] == 0.5);
[e updateWithNextSample:2.0]; [e updateWithNextSample:2.0];
test([e currentEstimate] == 1.5); test(e.currentEstimate == 1.5);
test([e decayRatePerUnitSample] == 0.5); test([e decayRatePerUnitSample] == 0.5);
[e updateWithNextSample:2.0]; [e updateWithNextSample:2.0];
test([e currentEstimate] == 1.75); test(e.currentEstimate == 1.75);
test([e decayRatePerUnitSample] == 0.5); test([e decayRatePerUnitSample] == 0.5);
[e updateWithNextSample:1.75]; [e updateWithNextSample:1.75];
test([e currentEstimate] == 1.75); test(e.currentEstimate == 1.75);
[e updateWithNextSample:1.75]; [e updateWithNextSample:1.75];
test([e currentEstimate] == 1.75); test(e.currentEstimate == 1.75);
} }
-(void) testDecayingSampleEstimatorForce { -(void) testDecayingSampleEstimatorForce {
DecayingSampleEstimator* e = [DecayingSampleEstimator decayingSampleEstimatorWithInitialEstimate:1.0 andDecayPerUnitSample:0.5]; DecayingSampleEstimator* e = [DecayingSampleEstimator decayingSampleEstimatorWithInitialEstimate:1.0 andDecayPerUnitSample:0.5];
test([e currentEstimate] == 1.0); test(e.currentEstimate == 1.0);
[e forceEstimateTo:5]; [e forceEstimateTo:5];
test([e currentEstimate] == 5); test(e.currentEstimate == 5);
test([e decayRatePerUnitSample] == 0.5); test([e decayRatePerUnitSample] == 0.5);
} }
-(void) testDecayingSampleEstimatorQuarter { -(void) testDecayingSampleEstimatorQuarter {
DecayingSampleEstimator* e = [DecayingSampleEstimator decayingSampleEstimatorWithInitialEstimate:1.0 andDecayPerUnitSample:0.75]; DecayingSampleEstimator* e = [DecayingSampleEstimator decayingSampleEstimatorWithInitialEstimate:1.0 andDecayPerUnitSample:0.75];
test([e currentEstimate] == 1.0); test(e.currentEstimate == 1.0);
test([e decayRatePerUnitSample] == 0.75); test([e decayRatePerUnitSample] == 0.75);
[e updateWithNextSample:2.0]; [e updateWithNextSample:2.0];
test([e currentEstimate] == 1.75); test(e.currentEstimate == 1.75);
} }
-(void) testDecayingSampleEstimatorCustomDecayPeriod { -(void) testDecayingSampleEstimatorCustomDecayPeriod {
DecayingSampleEstimator* e = [DecayingSampleEstimator decayingSampleEstimatorWithInitialEstimate:0 andDecayFactor:0.75 perNSamples:2]; DecayingSampleEstimator* e = [DecayingSampleEstimator decayingSampleEstimatorWithInitialEstimate:0 andDecayFactor:0.75 perNSamples:2];
@ -46,7 +46,7 @@
[e updateWithNextSample:4]; [e updateWithNextSample:4];
[e updateWithNextSample:4]; [e updateWithNextSample:4];
test([e currentEstimate] == 3); test(e.currentEstimate == 3);
} }
-(void) testDecayingSampleEstimatorWeighted { -(void) testDecayingSampleEstimatorWeighted {
DecayingSampleEstimator* e1 = [DecayingSampleEstimator decayingSampleEstimatorWithInitialEstimate:0.0 andDecayPerUnitSample:0.25]; DecayingSampleEstimator* e1 = [DecayingSampleEstimator decayingSampleEstimatorWithInitialEstimate:0.0 andDecayPerUnitSample:0.25];
@ -55,60 +55,60 @@
[e1 updateWithNextSample:2.0 withSampleWeight:0.5]; [e1 updateWithNextSample:2.0 withSampleWeight:0.5];
[e1 updateWithNextSample:2.0 withSampleWeight:0.5]; [e1 updateWithNextSample:2.0 withSampleWeight:0.5];
[e2 updateWithNextSample:2.0]; [e2 updateWithNextSample:2.0];
test(ABS([e1 currentEstimate] - [e2 currentEstimate]) < 0.00001); test(ABS(e1.currentEstimate - e2.currentEstimate) < 0.00001);
[e1 updateWithNextSample:-1.0 withSampleWeight:2.0]; [e1 updateWithNextSample:-1.0 withSampleWeight:2.0];
[e2 updateWithNextSample:-1.0]; [e2 updateWithNextSample:-1.0];
[e2 updateWithNextSample:-1.0]; [e2 updateWithNextSample:-1.0];
test(ABS([e1 currentEstimate] - [e2 currentEstimate]) < 0.00001); test(ABS(e1.currentEstimate - e2.currentEstimate) < 0.00001);
} }
-(void) testDecayingSampleEstimatorCornerCase0 { -(void) testDecayingSampleEstimatorCornerCase0 {
DecayingSampleEstimator* e = [DecayingSampleEstimator decayingSampleEstimatorWithInitialEstimate:1.0 andDecayPerUnitSample:0]; DecayingSampleEstimator* e = [DecayingSampleEstimator decayingSampleEstimatorWithInitialEstimate:1.0 andDecayPerUnitSample:0];
test([e decayRatePerUnitSample] == 0); test([e decayRatePerUnitSample] == 0);
test([e currentEstimate] == 1.0); test(e.currentEstimate == 1.0);
[e updateWithNextSample:5.0]; [e updateWithNextSample:5.0];
test([e currentEstimate] == 1.0); test(e.currentEstimate == 1.0);
[e updateWithNextSample:535325.0]; [e updateWithNextSample:535325.0];
test([e currentEstimate] == 1.0); test(e.currentEstimate == 1.0);
[e updateWithNextSample:-535325.0]; [e updateWithNextSample:-535325.0];
test([e currentEstimate] == 1.0); test(e.currentEstimate == 1.0);
[e updateWithNextSample:100.0 withSampleWeight:0]; [e updateWithNextSample:100.0 withSampleWeight:0];
test([e currentEstimate] == 1.0); test(e.currentEstimate == 1.0);
[e updateWithNextSample:200.0 withSampleWeight:100]; [e updateWithNextSample:200.0 withSampleWeight:100];
test([e currentEstimate] == 1.0); test(e.currentEstimate == 1.0);
[e updateWithNextSample:300.0 withSampleWeight:1]; [e updateWithNextSample:300.0 withSampleWeight:1];
test([e currentEstimate] == 1.0); test(e.currentEstimate == 1.0);
} }
-(void) testDecayingSampleEstimatorCornerCase1 { -(void) testDecayingSampleEstimatorCornerCase1 {
DecayingSampleEstimator* e = [DecayingSampleEstimator decayingSampleEstimatorWithInitialEstimate:1.0 andDecayPerUnitSample:1]; DecayingSampleEstimator* e = [DecayingSampleEstimator decayingSampleEstimatorWithInitialEstimate:1.0 andDecayPerUnitSample:1];
test([e decayRatePerUnitSample] == 1); test([e decayRatePerUnitSample] == 1);
test([e currentEstimate] == 1.0); test(e.currentEstimate == 1.0);
[e updateWithNextSample:5.0]; [e updateWithNextSample:5.0];
test([e currentEstimate] == 5.0); test(e.currentEstimate == 5.0);
[e updateWithNextSample:535325.0]; [e updateWithNextSample:535325.0];
test([e currentEstimate] == 535325.0); test(e.currentEstimate == 535325.0);
[e updateWithNextSample:-535325.0]; [e updateWithNextSample:-535325.0];
test([e currentEstimate] == -535325.0); test(e.currentEstimate == -535325.0);
[e updateWithNextSample:100.0 withSampleWeight:0.0001]; [e updateWithNextSample:100.0 withSampleWeight:0.0001];
test([e currentEstimate] == 100.0); test(e.currentEstimate == 100.0);
[e updateWithNextSample:200.0 withSampleWeight:100]; [e updateWithNextSample:200.0 withSampleWeight:100];
test([e currentEstimate] == 200.0); test(e.currentEstimate == 200.0);
[e updateWithNextSample:300.0 withSampleWeight:1]; [e updateWithNextSample:300.0 withSampleWeight:1];
test([e currentEstimate] == 300.0); test(e.currentEstimate == 300.0);
[e updateWithNextSample:400.0 withSampleWeight:0]; [e updateWithNextSample:400.0 withSampleWeight:0];
test([e currentEstimate] == 300.0); test(e.currentEstimate == 300.0);
} }
@end @end