diff --git a/Classes/LinphoneAppDelegate.m b/Classes/LinphoneAppDelegate.m index edcaea1b1..13306562c 100644 --- a/Classes/LinphoneAppDelegate.m +++ b/Classes/LinphoneAppDelegate.m @@ -431,7 +431,7 @@ NSString *sipInstance = [aps objectForKey:@"uuid"]; if (sipInstance && uuid && ![sipInstance isEqualToString:uuid]) { LOGE(@"Notification [%p] was intended for another device, ignoring it.", userInfo); - LOGD(@"My sip instance is: [%@], push was intended for: [%@].", uuid, sipInstance); + LOGD(@"My sip instance is: [%@], push was intended for: [%@].", uuid, sipInstance); return; } @@ -443,8 +443,6 @@ // As a result, break it and refresh registers in order to make sure to receive incoming INVITE or MESSAGE if (!linphone_core_is_network_reachable(LC)) { LOGI(@"Notification [%p] network is down, restarting it.", userInfo); - LinphoneManager.instance.connectivity = none; // Force connectivity to be discovered again - [LinphoneManager.instance setupNetworkReachabilityCallback]; } if ([callId isEqualToString:@""]) { @@ -543,7 +541,6 @@ - (void)processPush:(NSDictionary *)userInfo { LOGI(@"[PushKit] Notification [%p] received with pay load : %@", userInfo, userInfo.description); [self configureUINotification]; - [LinphoneManager.instance setupNetworkReachabilityCallback]; //to avoid IOS to suspend the app before being able to launch long running task [self processRemoteNotification:userInfo]; } diff --git a/Classes/LinphoneCoreSettingsStore.m b/Classes/LinphoneCoreSettingsStore.m index 6b9679e71..00ab58d35 100644 --- a/Classes/LinphoneCoreSettingsStore.m +++ b/Classes/LinphoneCoreSettingsStore.m @@ -502,16 +502,12 @@ if (username && [username length] > 0 && domain && [domain length] > 0) { int expire = [self integerForKey:@"account_expire_preference"]; - BOOL isWifiOnly = [self boolForKey:@"wifi_only_preference"]; BOOL pushnotification = [self boolForKey:@"account_pushnotification_preference"]; NSString *prefix = [self stringForKey:@"account_prefix_preference"]; NSString *proxyAddress = [self stringForKey:@"account_proxy_preference"]; const char *route = NULL; - if (isWifiOnly && LinphoneManager.instance.connectivity == wwan) - expire = 0; - if ((!proxyAddress || [proxyAddress length] < 1) && domain) { proxyAddress = domain; } @@ -810,8 +806,6 @@ BOOL wifiOnly = [self boolForKey:@"wifi_only_preference"]; [lm lpConfigSetInt:wifiOnly forKey:@"wifi_only_preference"]; - if ([self valueChangedForKey:@"wifi_only_preference"]) - [LinphoneManager.instance setupNetworkReachabilityCallback]; LinphoneNatPolicy *LNP = linphone_core_get_nat_policy(LC); diff --git a/Classes/LinphoneManager.h b/Classes/LinphoneManager.h index 4fc4ffef2..99c1739aa 100644 --- a/Classes/LinphoneManager.h +++ b/Classes/LinphoneManager.h @@ -68,12 +68,6 @@ typedef enum _NetworkType { network_wifi } NetworkType; -typedef enum _Connectivity { - wifi, - wwan, - none -} Connectivity; - extern const int kLinphoneAudioVbrCodecDefaultBitrate; /* Application specific call context */ @@ -82,11 +76,6 @@ typedef struct _CallContext { bool_t cameraIsEnabled; } CallContext; -struct NetworkReachabilityContext { - bool_t testWifi, testWWan; - void (*networkStateChanged) (Connectivity newConnectivity); -}; - @interface LinphoneCallAppData :NSObject { @public bool_t batteryWarningShown; @@ -107,8 +96,8 @@ typedef struct _LinphoneManagerSounds { @private NSTimer* mIterateTimer; - NSMutableArray* pushCallIDs; - Connectivity connectivity; + NSMutableArray* pushCallIDs; + UIBackgroundTaskIdentifier pausedCallBgTask; UIBackgroundTaskIdentifier incallBgTask; UIBackgroundTaskIdentifier pushBgTaskRefer; @@ -148,8 +137,6 @@ typedef struct _LinphoneManagerSounds { - (void)alertLIME:(LinphoneChatRoom *)room; - (void)startPushLongRunningTask:(NSString *)loc_key callId:(NSString *)callId; + (BOOL)langageDirectionIsRTL; -+ (void)kickOffNetworkConnection; -- (void)setupNetworkReachabilityCallback; - (void)refreshRegisters; @@ -220,7 +207,6 @@ typedef struct _LinphoneManagerSounds { @property (readonly) BOOL isTesting; @property(readonly, strong) FastAddressBook *fastAddressBook; -@property Connectivity connectivity; @property (readonly) NetworkType network; @property (readonly) const char* frontCamId; @property (readonly) const char* backCamId; diff --git a/Classes/LinphoneManager.m b/Classes/LinphoneManager.m index f11a54225..1976ac434 100644 --- a/Classes/LinphoneManager.m +++ b/Classes/LinphoneManager.m @@ -1,4 +1,3 @@ - /* LinphoneManager.h * * Copyright (C) 2011 Belledonne Comunications, Grenoble, France @@ -88,9 +87,9 @@ extern void libmssilk_init(MSFactory *factory); extern void libmswebrtc_init(MSFactory *factory); extern void libmscodec2_init(MSFactory *factory); -#define FRONT_CAM_NAME \ +#define FRONT_CAM_NAME \ "AV Capture: com.apple.avfoundation.avcapturedevice.built-in_video:1" /*"AV Capture: Front Camera"*/ -#define BACK_CAM_NAME \ +#define BACK_CAM_NAME \ "AV Capture: com.apple.avfoundation.avcapturedevice.built-in_video:0" /*"AV Capture: Back Camera"*/ NSString *const kLinphoneOldChatDBFilename = @"chat_database.sqlite"; @@ -110,13 +109,11 @@ NSString *const kLinphoneInternalChatDBFilename = @"linphone_chats.db"; @end @interface LinphoneManager () -@property(strong, nonatomic) AVAudioPlayer *messagePlayer; + @property(strong, nonatomic) AVAudioPlayer *messagePlayer; @end @implementation LinphoneManager -@synthesize connectivity; - struct codec_name_pref_table { const char *name; int rate; @@ -124,30 +121,30 @@ struct codec_name_pref_table { }; struct codec_name_pref_table codec_pref_table[] = {{"speex", 8000, "speex_8k_preference"}, - {"speex", 16000, "speex_16k_preference"}, - {"silk", 24000, "silk_24k_preference"}, - {"silk", 16000, "silk_16k_preference"}, - {"amr", 8000, "amr_preference"}, - {"gsm", 8000, "gsm_preference"}, - {"ilbc", 8000, "ilbc_preference"}, - {"isac", 16000, "isac_preference"}, - {"pcmu", 8000, "pcmu_preference"}, - {"pcma", 8000, "pcma_preference"}, - {"g722", 8000, "g722_preference"}, - {"g729", 8000, "g729_preference"}, - {"mp4v-es", 90000, "mp4v-es_preference"}, - {"h264", 90000, "h264_preference"}, - {"h265", 90000, "h265_preference"}, - {"vp8", 90000, "vp8_preference"}, - {"mpeg4-generic", 16000, "aaceld_16k_preference"}, - {"mpeg4-generic", 22050, "aaceld_22k_preference"}, - {"mpeg4-generic", 32000, "aaceld_32k_preference"}, - {"mpeg4-generic", 44100, "aaceld_44k_preference"}, - {"mpeg4-generic", 48000, "aaceld_48k_preference"}, - {"opus", 48000, "opus_preference"}, - {"BV16", 8000, "bv16_preference"}, - {"CODEC2", 8000, "codec2_preference"}, - {NULL, 0, Nil}}; + {"speex", 16000, "speex_16k_preference"}, + {"silk", 24000, "silk_24k_preference"}, + {"silk", 16000, "silk_16k_preference"}, + {"amr", 8000, "amr_preference"}, + {"gsm", 8000, "gsm_preference"}, + {"ilbc", 8000, "ilbc_preference"}, + {"isac", 16000, "isac_preference"}, + {"pcmu", 8000, "pcmu_preference"}, + {"pcma", 8000, "pcma_preference"}, + {"g722", 8000, "g722_preference"}, + {"g729", 8000, "g729_preference"}, + {"mp4v-es", 90000, "mp4v-es_preference"}, + {"h264", 90000, "h264_preference"}, + {"h265", 90000, "h265_preference"}, + {"vp8", 90000, "vp8_preference"}, + {"mpeg4-generic", 16000, "aaceld_16k_preference"}, + {"mpeg4-generic", 22050, "aaceld_22k_preference"}, + {"mpeg4-generic", 32000, "aaceld_32k_preference"}, + {"mpeg4-generic", 44100, "aaceld_44k_preference"}, + {"mpeg4-generic", 48000, "aaceld_48k_preference"}, + {"opus", 48000, "opus_preference"}, + {"BV16", 8000, "bv16_preference"}, + {"CODEC2", 8000, "codec2_preference"}, + {NULL, 0, Nil}}; + (NSString *)getPreferenceForCodec:(const char *)name withRate:(int)rate { int i; @@ -162,11 +159,11 @@ struct codec_name_pref_table codec_pref_table[] = {{"speex", 8000, "speex_8k_pre NSMutableSet *set = [NSMutableSet set]; for (int i = 0; codec_pref_table[i].name != NULL; ++i) { PayloadType *available = linphone_core_find_payload_type( - theLinphoneCore, codec_pref_table[i].name, codec_pref_table[i].rate, LINPHONE_FIND_PAYLOAD_IGNORE_CHANNELS); + theLinphoneCore, codec_pref_table[i].name, codec_pref_table[i].rate, LINPHONE_FIND_PAYLOAD_IGNORE_CHANNELS); if ((available == NULL) - // these two codecs should not be hidden, even if not supported - && strcmp(codec_pref_table[i].prefname, "h264_preference") != 0 && - strcmp(codec_pref_table[i].prefname, "mp4v-es_preference") != 0) { + // these two codecs should not be hidden, even if not supported + && strcmp(codec_pref_table[i].prefname, "h264_preference") != 0 && + strcmp(codec_pref_table[i].prefname, "mp4v-es_preference") != 0) { [set addObject:[NSString stringWithUTF8String:codec_pref_table[i].prefname]]; } } @@ -175,8 +172,8 @@ struct codec_name_pref_table codec_pref_table[] = {{"speex", 8000, "speex_8k_pre + (BOOL)isCodecSupported:(const char *)codecName { return (codecName != NULL) && - (NULL != linphone_core_find_payload_type(theLinphoneCore, codecName, LINPHONE_FIND_PAYLOAD_IGNORE_RATE, - LINPHONE_FIND_PAYLOAD_IGNORE_CHANNELS)); + (NULL != linphone_core_find_payload_type(theLinphoneCore, codecName, LINPHONE_FIND_PAYLOAD_IGNORE_RATE, + LINPHONE_FIND_PAYLOAD_IGNORE_CHANNELS)); } + (BOOL)runningOnIpad { @@ -210,9 +207,9 @@ struct codec_name_pref_table codec_pref_table[] = {{"speex", 8000, "speex_8k_pre + (NSString *)getUserAgent { return [NSString stringWithFormat:@"LinphoneIphone/%@ (Linphone/%s; Apple %@/%@)", - [[NSBundle mainBundle] objectForInfoDictionaryKey:(NSString *)kCFBundleVersionKey], - linphone_core_get_version(), [UIDevice currentDevice].systemName, - [UIDevice currentDevice].systemVersion]; + [[NSBundle mainBundle] objectForInfoDictionaryKey:(NSString *)kCFBundleVersionKey], + linphone_core_get_version(), [UIDevice currentDevice].systemName, + [UIDevice currentDevice].systemVersion]; } + (LinphoneManager *)instance { @@ -236,8 +233,8 @@ struct codec_name_pref_table codec_pref_table[] = {{"speex", 8000, "speex_8k_pre static NSLocaleLanguageDirection dir = NSLocaleLanguageDirectionLeftToRight; static dispatch_once_t onceToken; dispatch_once(&onceToken, ^{ - dir = [NSLocale characterDirectionForLanguage:[[NSLocale currentLocale] objectForKey:NSLocaleLanguageCode]]; - }); + dir = [NSLocale characterDirectionForLanguage:[[NSLocale currentLocale] objectForKey:NSLocaleLanguageCode]]; + }); return dir == NSLocaleLanguageDirectionRightToLeft; } @@ -246,9 +243,9 @@ struct codec_name_pref_table codec_pref_table[] = {{"speex", 8000, "speex_8k_pre - (id)init { if ((self = [super init])) { [NSNotificationCenter.defaultCenter addObserver:self - selector:@selector(audioRouteChangeListenerCallback:) - name:AVAudioSessionRouteChangeNotification - object:nil]; + selector:@selector(audioRouteChangeListenerCallback:) + name:AVAudioSessionRouteChangeNotification + object:nil]; NSString *path = [[NSBundle mainBundle] pathForResource:@"msg" ofType:@"wav"]; self.messagePlayer = [[AVAudioPlayer alloc] initWithContentsOfURL:[NSURL URLWithString:path] error:nil]; @@ -266,7 +263,7 @@ struct codec_name_pref_table codec_pref_table[] = {{"speex", 8000, "speex_8k_pre _linphoneManagerAddressBookMap = [[OrderedDictionary alloc] init]; pushCallIDs = [[NSMutableArray alloc] init]; _isTesting = [LinphoneManager isRunningTests]; - [self migrateImportantFiles]; + [self migrateImportantFiles]; [self renameDefaultSettings]; [self copyDefaultSettings]; [self overrideDefaultSettings]; @@ -290,7 +287,7 @@ struct codec_name_pref_table codec_pref_table[] = {{"speex", 8000, "speex_8k_pre } [self migrateFromUserPrefs]; - [self loadAvatar]; + [self loadAvatar]; } return self; } @@ -337,8 +334,8 @@ struct codec_name_pref_table codec_pref_table[] = {{"speex", 8000, "speex_8k_pre // migrate xmlrpc URL if needed if ([self lpConfigBoolForKey:@"migration_xmlrpc"] == NO) { [self lpConfigSetString:@"https://subscribe.linphone.org:444/wizard.php" - forKey:@"xmlrpc_url" - inSection:@"assistant"]; + forKey:@"xmlrpc_url" + inSection:@"assistant"]; [self lpConfigSetString:@"sip:rls@sip.linphone.org" forKey:@"rls_uri" inSection:@"sip"]; [self lpConfigSetBool:YES forKey:@"migration_xmlrpc"]; } @@ -400,10 +397,10 @@ static int check_should_migrate_images(void *data, int argc, char **argv, char * const char *addr = linphone_proxy_config_get_addr(proxy); // we want to enable AVPF for the proxies if (addr && - strstr(addr, [LinphoneManager.instance lpConfigStringForKey:@"domain_name" - inSection:@"app" - withDefault:@"sip.linphone.org"] - .UTF8String) != 0) { + strstr(addr, [LinphoneManager.instance lpConfigStringForKey:@"domain_name" + inSection:@"app" + withDefault:@"sip.linphone.org"] + .UTF8String) != 0) { LOGI(@"Migrating proxy config to use AVPF"); linphone_proxy_config_enable_avpf(proxy, TRUE); } @@ -419,13 +416,13 @@ static int check_should_migrate_images(void *data, int argc, char **argv, char * const char *addr = linphone_proxy_config_get_addr(proxy); // we want to enable quality reporting for the proxies that are on linphone.org if (addr && - strstr(addr, [LinphoneManager.instance lpConfigStringForKey:@"domain_name" - inSection:@"app" - withDefault:@"sip.linphone.org"] - .UTF8String) != 0) { + strstr(addr, [LinphoneManager.instance lpConfigStringForKey:@"domain_name" + inSection:@"app" + withDefault:@"sip.linphone.org"] + .UTF8String) != 0) { LOGI(@"Migrating proxy config to send quality report"); linphone_proxy_config_set_quality_reporting_collector( - proxy, "sip:voip-metrics@sip.linphone.org;transport=tls"); + proxy, "sip:voip-metrics@sip.linphone.org;transport=tls"); linphone_proxy_config_set_quality_reporting_interval(proxy, 180); linphone_proxy_config_enable_quality_reporting(proxy, TRUE); } @@ -457,8 +454,8 @@ static int check_should_migrate_images(void *data, int argc, char **argv, char * - (void)migrationPerAccount { const bctbx_list_t * proxies = linphone_core_get_proxy_config_list(LC); NSString *appDomain = [LinphoneManager.instance lpConfigStringForKey:@"domain_name" - inSection:@"app" - withDefault:@"sip.linphone.org"]; + inSection:@"app" + withDefault:@"sip.linphone.org"]; while (proxies) { LinphoneProxyConfig *config = proxies->data; // can not create group chat without conference factory @@ -494,8 +491,8 @@ static void migrateWizardToAssistant(const char *entry, void *user_data) { + (LinphoneCore *)getLc { if (theLinphoneCore == nil) { @throw([NSException exceptionWithName:@"LinphoneCoreException" - reason:@"Linphone core not initialized yet" - userInfo:nil]); + reason:@"Linphone core not initialized yet" + userInfo:nil]); } return theLinphoneCore; } @@ -524,10 +521,10 @@ static void linphone_iphone_log_user_warning(struct _LinphoneCore *lc, const cha - (void)displayStatus:(NSString *)message { // Post event [NSNotificationCenter.defaultCenter postNotificationName:kLinphoneDisplayStatusUpdate - object:self - userInfo:@{ - @"message" : message - }]; + object:self + userInfo:@{ + @"message" : message + }]; } static void linphone_iphone_display_status(struct _LinphoneCore *lc, const char *message) { @@ -547,19 +544,19 @@ static void linphone_iphone_display_status(struct _LinphoneCore *lc, const char } - (void)userNotifContinue:(NSTimer *)timer { - UNNotificationContent *content = [timer userInfo]; + UNNotificationContent *content = [timer userInfo]; if (content && [UIApplication sharedApplication].applicationState != UIApplicationStateActive) { LOGI(@"cancelling/presenting user notif"); UNNotificationRequest *req = [UNNotificationRequest requestWithIdentifier:@"call_request" content:content trigger:NULL]; [[UNUserNotificationCenter currentNotificationCenter] addNotificationRequest:req - withCompletionHandler:^(NSError *_Nullable error) { - // Enable or disable features based on authorization. - if (error) { - LOGD(@"Error while adding notification request :"); - LOGD(error.description); - } - }]; + withCompletionHandler:^(NSError *_Nullable error) { + // Enable or disable features based on authorization. + if (error) { + LOGD(@"Error while adding notification request :"); + LOGD(error.description); + } + }]; } } @@ -609,7 +606,7 @@ static void linphone_iphone_display_status(struct _LinphoneCore *lc, const char /*should we reject this call ?*/ if ([lCTCallCenter currentCalls] != nil && - floor(NSFoundationVersionNumber) <= NSFoundationVersionNumber_iOS_9_x_Max) { + floor(NSFoundationVersionNumber) <= NSFoundationVersionNumber_iOS_9_x_Max) { char *tmp = linphone_call_get_remote_address_as_string(call); if (tmp) { LOGI(@"Mobile call ongoing... rejecting call from [%s]", tmp); @@ -625,16 +622,16 @@ static void linphone_iphone_display_status(struct _LinphoneCore *lc, const char [PhoneMainView.instance displayIncomingCall:call]; } else { #if !TARGET_IPHONE_SIMULATOR - NSString *callId = [NSString stringWithUTF8String:linphone_call_log_get_call_id(linphone_call_get_call_log(call))]; - NSUUID *uuid = [NSUUID UUID]; - [LinphoneManager.instance.providerDelegate.calls setObject:callId forKey:uuid]; - [LinphoneManager.instance.providerDelegate.uuids setObject:uuid forKey:callId]; - BOOL video = ([UIApplication sharedApplication].applicationState == UIApplicationStateActive && - linphone_video_activation_policy_get_automatically_accept(linphone_core_get_video_activation_policy(LC)) && - linphone_call_params_video_enabled(linphone_call_get_remote_params(call))); - [LinphoneManager.instance.providerDelegate reportIncomingCall:call withUUID:uuid handle:address video:video]; + NSString *callId = [NSString stringWithUTF8String:linphone_call_log_get_call_id(linphone_call_get_call_log(call))]; + NSUUID *uuid = [NSUUID UUID]; + [LinphoneManager.instance.providerDelegate.calls setObject:callId forKey:uuid]; + [LinphoneManager.instance.providerDelegate.uuids setObject:uuid forKey:callId]; + BOOL video = ([UIApplication sharedApplication].applicationState == UIApplicationStateActive && + linphone_video_activation_policy_get_automatically_accept(linphone_core_get_video_activation_policy(LC)) && + linphone_call_params_video_enabled(linphone_call_get_remote_params(call))); + [LinphoneManager.instance.providerDelegate reportIncomingCall:call withUUID:uuid handle:address video:video]; #else - [PhoneMainView.instance displayIncomingCall:call]; + [PhoneMainView.instance displayIncomingCall:call]; #endif } } else if ([UIApplication sharedApplication].applicationState != UIApplicationStateActive) { @@ -648,8 +645,8 @@ static void linphone_iphone_display_status(struct _LinphoneCore *lc, const char UNNotificationRequest *req = [UNNotificationRequest requestWithIdentifier:@"call_request" content:content trigger:NULL]; [[UNUserNotificationCenter currentNotificationCenter] addNotificationRequest:req - withCompletionHandler:^(NSError *err){ - }]; + withCompletionHandler:^(NSError *err){ + }]; } } else { if ([UIApplication sharedApplication].applicationState != UIApplicationStateActive) { @@ -681,29 +678,29 @@ static void linphone_iphone_display_status(struct _LinphoneCore *lc, const char NSSet *categories = [NSSet setWithObjects:callcat, nil]; UIUserNotificationSettings *set = [UIUserNotificationSettings - settingsForTypes:(UIUserNotificationTypeAlert | UIUserNotificationTypeBadge | - UIUserNotificationTypeSound) - categories:categories]; + settingsForTypes:(UIUserNotificationTypeAlert | UIUserNotificationTypeBadge | + UIUserNotificationTypeSound) + categories:categories]; [[UIApplication sharedApplication] registerUserNotificationSettings:set]; data->notification = [[UILocalNotification alloc] init]; if (data->notification) { // iOS8 doesn't need the timer trick for the local notification. data->notification.category = @"incoming_call"; if ([[UIDevice currentDevice].systemVersion floatValue] >= 8 && - [self lpConfigBoolForKey:@"repeat_call_notification"] == NO) { + [self lpConfigBoolForKey:@"repeat_call_notification"] == NO) { NSString *ring = ([LinphoneManager bundleFile:[self lpConfigStringForKey:@"local_ring" - inSection:@"sound"] - .lastPathComponent] - ?: [LinphoneManager bundleFile:@"notes_of_the_optimistic.caf"]) - .lastPathComponent; + inSection:@"sound"] + .lastPathComponent] + ?: [LinphoneManager bundleFile:@"notes_of_the_optimistic.caf"]) + .lastPathComponent; data->notification.soundName = ring; } else { data->notification.soundName = @"shortring.caf"; data->timer = [NSTimer scheduledTimerWithTimeInterval:5 - target:self - selector:@selector(localNotifContinue:) - userInfo:data->notification - repeats:TRUE]; + target:self + selector:@selector(localNotifContinue:) + userInfo:data->notification + repeats:TRUE]; } data->notification.repeatInterval = 0; @@ -720,10 +717,10 @@ static void linphone_iphone_display_status(struct _LinphoneCore *lc, const char if (!incallBgTask) { incallBgTask = [[UIApplication sharedApplication] beginBackgroundTaskWithExpirationHandler:^{ - LOGW(@"Call cannot ring any more, too late"); - [[UIApplication sharedApplication] endBackgroundTask:incallBgTask]; - incallBgTask = 0; - }]; + LOGW(@"Call cannot ring any more, too late"); + [[UIApplication sharedApplication] endBackgroundTask:incallBgTask]; + incallBgTask = 0; + }]; if (data->timer) { [[NSRunLoop currentRunLoop] addTimer:data->timer forMode:NSRunLoopCommonModes]; @@ -741,7 +738,7 @@ static void linphone_iphone_display_status(struct _LinphoneCore *lc, const char // Disable speaker when no more call if ((state == LinphoneCallEnd || state == LinphoneCallError)) { - [HistoryListTableView saveDataToUserDefaults]; + [HistoryListTableView saveDataToUserDefaults]; [[UIDevice currentDevice] setProximityMonitoringEnabled:FALSE]; speaker_already_enabled = FALSE; if (linphone_core_get_calls_nb(theLinphoneCore) == 0) { @@ -765,39 +762,38 @@ static void linphone_iphone_display_status(struct _LinphoneCore *lc, const char data->timer = nil; } LinphoneCallLog *UNlog = linphone_call_get_call_log(call); - if ((UNlog == NULL - || linphone_call_log_get_status(UNlog) == LinphoneCallMissed - || linphone_call_log_get_status(UNlog) == LinphoneCallAborted - || linphone_call_log_get_status(UNlog) == LinphoneCallEarlyAborted)) { + if ((UNlog == NULL + || linphone_call_log_get_status(UNlog) == LinphoneCallMissed + || linphone_call_log_get_status(UNlog) == LinphoneCallAborted + || linphone_call_log_get_status(UNlog) == LinphoneCallEarlyAborted)) { UNMutableNotificationContent *missed_content = [[UNMutableNotificationContent alloc] init]; - missed_content.title = NSLocalizedString(@"Missed call", nil); - missed_content.body = address; - UNNotificationRequest *missed_req = [UNNotificationRequest requestWithIdentifier:@"call_request" - content:missed_content - trigger:NULL]; - [UNUserNotificationCenter.currentNotificationCenter addNotificationRequest:missed_req - withCompletionHandler:^(NSError *_Nullable error) - {if (error) LOGD(@"Error while adding notification request : %@", error.description);}]; + missed_content.title = NSLocalizedString(@"Missed call", nil); + missed_content.body = address; + UNNotificationRequest *missed_req = [UNNotificationRequest requestWithIdentifier:@"call_request" + content:missed_content + trigger:NULL]; + [UNUserNotificationCenter.currentNotificationCenter addNotificationRequest:missed_req + withCompletionHandler:^(NSError *_Nullable error) + {if (error) LOGD(@"Error while adding notification request : %@", error.description);}]; + } + LinphoneProxyConfig *proxyCfg = linphone_core_get_default_proxy_config(theLinphoneCore); + BOOL pushNotifEnabled = false; + // handle proxy config if any + if (proxyCfg) { + const char *refkey = proxyCfg ? linphone_proxy_config_get_ref_key(proxyCfg) : NULL; + pushNotifEnabled = (refkey && strcmp(refkey, "push_notification") == 0); + } + if (![LinphoneManager.instance lpConfigBoolForKey:@"backgroundmode_preference"] || pushNotifEnabled) { + linphone_core_set_network_reachable(LC, FALSE); } - LinphoneProxyConfig *proxyCfg = linphone_core_get_default_proxy_config(theLinphoneCore); - BOOL pushNotifEnabled = false; - // handle proxy config if any - if (proxyCfg) { - const char *refkey = proxyCfg ? linphone_proxy_config_get_ref_key(proxyCfg) : NULL; - pushNotifEnabled = (refkey && strcmp(refkey, "push_notification") == 0); - } - if (![LinphoneManager.instance lpConfigBoolForKey:@"backgroundmode_preference"] || pushNotifEnabled) { - linphone_core_set_network_reachable(LC, FALSE); - LinphoneManager.instance.connectivity = none; - } } - LinphoneCallLog *callLog2 = linphone_call_get_call_log(call); - const char *call_id2 = linphone_call_log_get_call_id(callLog2); - NSString *callId2 = call_id2 - ? [NSString stringWithUTF8String:call_id2] - : @""; - NSUUID *uuid = (NSUUID *)[self.providerDelegate.uuids objectForKey:callId2]; - if (uuid) { + LinphoneCallLog *callLog2 = linphone_call_get_call_log(call); + const char *call_id2 = linphone_call_log_get_call_id(callLog2); + NSString *callId2 = call_id2 + ? [NSString stringWithUTF8String:call_id2] + : @""; + NSUUID *uuid = (NSUUID *)[self.providerDelegate.uuids objectForKey:callId2]; + if (uuid) { LinphoneCall *callKit_call = (LinphoneCall *)linphone_core_get_calls(LC) ? linphone_core_get_calls(LC)->data : NULL; @@ -806,44 +802,38 @@ static void linphone_iphone_display_status(struct _LinphoneCore *lc, const char : NULL; if (callKit_callId && !_conf) { // Create a CallKit call because there's not ! - NSString *callKit_callIdNS = [NSString stringWithUTF8String:callKit_callId]; - NSUUID *callKit_uuid = [NSUUID UUID]; - [LinphoneManager.instance.providerDelegate.uuids setObject:callKit_uuid forKey:callKit_callIdNS]; + NSString *callKit_callIdNS = [NSString stringWithUTF8String:callKit_callId]; + NSUUID *callKit_uuid = [NSUUID UUID]; + [LinphoneManager.instance.providerDelegate.uuids setObject:callKit_uuid forKey:callKit_callIdNS]; [LinphoneManager.instance.providerDelegate.calls setObject:callKit_callIdNS forKey:callKit_uuid]; - NSString *address = [FastAddressBook displayNameForAddress:linphone_call_get_remote_address(callKit_call)]; + NSString *address = [FastAddressBook displayNameForAddress:linphone_call_get_remote_address(callKit_call)]; CXHandle *handle = [[CXHandle alloc] initWithType:CXHandleTypeGeneric value:address]; CXStartCallAction *act = [[CXStartCallAction alloc] initWithCallUUID:callKit_uuid handle:handle]; - CXTransaction *tr = [[CXTransaction alloc] initWithAction:act]; - [LinphoneManager.instance.providerDelegate.controller requestTransaction:tr completion:^(NSError *err){}]; + CXTransaction *tr = [[CXTransaction alloc] initWithAction:act]; + [LinphoneManager.instance.providerDelegate.controller requestTransaction:tr completion:^(NSError *err){}]; [LinphoneManager.instance.providerDelegate.provider reportOutgoingCallWithUUID:callKit_uuid startedConnectingAtDate:nil]; - [LinphoneManager.instance.providerDelegate.provider reportOutgoingCallWithUUID:callKit_uuid connectedAtDate:nil]; + [LinphoneManager.instance.providerDelegate.provider reportOutgoingCallWithUUID:callKit_uuid connectedAtDate:nil]; } CXEndCallAction *act = [[CXEndCallAction alloc] initWithCallUUID:uuid]; - CXTransaction *tr = [[CXTransaction alloc] initWithAction:act]; - [LinphoneManager.instance.providerDelegate.controller requestTransaction:tr - completion:^(NSError *err){}]; - + CXTransaction *tr = [[CXTransaction alloc] initWithAction:act]; + [LinphoneManager.instance.providerDelegate.controller requestTransaction:tr completion:^(NSError *err){}]; LOGI(@"CallKit - clearing CK as call ended on uuid %@",uuid); [LinphoneManager.instance.providerDelegate.provider reportOutgoingCallWithUUID:uuid connectedAtDate:[NSDate date]]; [self.providerDelegate.uuids removeObjectForKey:callId2]; [self.providerDelegate.calls removeObjectForKey:uuid]; - [self.providerDelegate.provider reportCallWithUUID:uuid - endedAtDate:[NSDate date] - reason:(state == LinphoneCallError ? CXCallEndedReasonFailed : CXCallEndedReasonRemoteEnded)]; - - + [self.providerDelegate.provider reportCallWithUUID:uuid endedAtDate:[NSDate date] reason:(state == LinphoneCallError ? CXCallEndedReasonFailed : CXCallEndedReasonRemoteEnded)]; } else { // Can happen when Call-ID changes (Replaces header) if (linphone_core_get_calls_nb(LC) ==0) { // Need to clear all CK calls for (NSUUID *myUuid in self.providerDelegate.calls) { [self.providerDelegate.provider reportCallWithUUID:myUuid - endedAtDate:NULL - reason:(state == LinphoneCallError - ? CXCallEndedReasonFailed - : CXCallEndedReasonRemoteEnded)]; + endedAtDate:NULL + reason:(state == LinphoneCallError + ? CXCallEndedReasonFailed + : CXCallEndedReasonRemoteEnded)]; } - [self.providerDelegate.uuids removeAllObjects]; - [self.providerDelegate.calls removeAllObjects]; + [self.providerDelegate.uuids removeAllObjects]; + [self.providerDelegate.calls removeAllObjects]; } } } else { @@ -854,22 +844,22 @@ static void linphone_iphone_display_status(struct _LinphoneCore *lc, const char [data->timer invalidate]; data->timer = nil; } - [[UIApplication sharedApplication] cancelLocalNotification:data->notification]; + [[UIApplication sharedApplication] cancelLocalNotification:data->notification]; data->notification = nil; if (log == NULL || linphone_call_log_get_status(log) == LinphoneCallMissed) { UILocalNotification *notification = [[UILocalNotification alloc] init]; - notification.repeatInterval = 0; - notification.alertBody = [NSString stringWithFormat: - NSLocalizedString(@"You missed a call from %@",nil), address]; + notification.repeatInterval = 0; + notification.alertBody = [NSString stringWithFormat: + NSLocalizedString(@"You missed a call from %@",nil), address]; notification.alertAction = NSLocalizedString(@"Show", nil); - notification.userInfo = [NSDictionary dictionaryWithObject: [NSString stringWithUTF8String:linphone_call_log_get_call_id(log)] - forKey:@"callLog"]; + notification.userInfo = [NSDictionary dictionaryWithObject: [NSString stringWithUTF8String:linphone_call_log_get_call_id(log)] + forKey:@"callLog"]; [[UIApplication sharedApplication] presentLocalNotificationNow:notification]; } } } - if (state == LinphoneCallError) + if (state == LinphoneCallError) [PhoneMainView.instance popCurrentView]; } if (state == LinphoneCallReleased) { @@ -878,9 +868,9 @@ static void linphone_iphone_display_status(struct _LinphoneCore *lc, const char CFBridgingRelease((__bridge CFTypeRef)(data)); } } - // Enable speaker when video - if (state == LinphoneCallIncomingReceived || state == LinphoneCallOutgoingInit || - state == LinphoneCallConnected || state == LinphoneCallStreamsRunning) { + // Enable speaker when video + if (state == LinphoneCallIncomingReceived || state == LinphoneCallOutgoingInit || + state == LinphoneCallConnected || state == LinphoneCallStreamsRunning) { if (linphone_call_params_video_enabled( linphone_call_get_current_params(call)) && !speaker_already_enabled && !_bluetoothEnabled) { [self setSpeakerEnabled:TRUE]; speaker_already_enabled = TRUE; @@ -900,17 +890,17 @@ static void linphone_iphone_display_status(struct _LinphoneCore *lc, const char } // Post event - NSDictionary *dict = @{@"call" : [NSValue valueWithPointer:call], - @"state" : [NSNumber numberWithInt:state], - @"message" : [NSString stringWithUTF8String:message]}; + NSDictionary *dict = @{@"call" : [NSValue valueWithPointer:call], + @"state" : [NSNumber numberWithInt:state], + @"message" : [NSString stringWithUTF8String:message]}; [NSNotificationCenter.defaultCenter postNotificationName:kLinphoneCallUpdate - object:self - userInfo:dict]; + object:self + userInfo:dict]; } static void linphone_iphone_call_state(LinphoneCore *lc, LinphoneCall *call, LinphoneCallState state, - const char *message) { + const char *message) { [(__bridge LinphoneManager *)linphone_core_cbs_get_user_data(linphone_core_get_current_callbacks(lc)) onCall:call StateChanged:state withMessage:message]; } @@ -929,13 +919,13 @@ static void linphone_iphone_global_state_changed(LinphoneCore *lc, LinphoneGloba LOGI(@"onGlobalStateChanged: %d (message: %s)", state, message); NSDictionary *dict = [NSDictionary - dictionaryWithObjectsAndKeys:[NSNumber numberWithInt:state], @"state", - [NSString stringWithUTF8String:message ? message : ""], @"message", nil]; + dictionaryWithObjectsAndKeys:[NSNumber numberWithInt:state], @"state", + [NSString stringWithUTF8String:message ? message : ""], @"message", nil]; // dispatch the notification asynchronously dispatch_async(dispatch_get_main_queue(), ^(void) { - [NSNotificationCenter.defaultCenter postNotificationName:kLinphoneGlobalStateUpdate object:self userInfo:dict]; - }); + [NSNotificationCenter.defaultCenter postNotificationName:kLinphoneGlobalStateUpdate object:self userInfo:dict]; + }); } - (void)globalStateChangedNotificationHandler:(NSNotification *)notif { @@ -947,29 +937,28 @@ static void linphone_iphone_global_state_changed(LinphoneCore *lc, LinphoneGloba #pragma mark - Configuring status changed static void linphone_iphone_configuring_status_changed(LinphoneCore *lc, LinphoneConfiguringState status, - const char *message) { + const char *message) { [(__bridge LinphoneManager *)linphone_core_cbs_get_user_data(linphone_core_get_current_callbacks(lc)) onConfiguringStatusChanged:status withMessage:message]; } - (void)onConfiguringStatusChanged:(LinphoneConfiguringState)status withMessage:(const char *)message { LOGI(@"onConfiguringStatusChanged: %s %@", linphone_configuring_state_to_string(status), - message ? [NSString stringWithFormat:@"(message: %s)", message] : @""); - + message ? [NSString stringWithFormat:@"(message: %s)", message] : @""); NSDictionary *dict = [NSDictionary - dictionaryWithObjectsAndKeys:[NSNumber numberWithInt:status], @"state", - [NSString stringWithUTF8String:message ? message : ""], @"message", nil]; + dictionaryWithObjectsAndKeys:[NSNumber numberWithInt:status], @"state", + [NSString stringWithUTF8String:message ? message : ""], @"message", nil]; // dispatch the notification asynchronously dispatch_async(dispatch_get_main_queue(), ^(void) { - [NSNotificationCenter.defaultCenter postNotificationName:kLinphoneConfiguringStateUpdate - object:self - userInfo:dict]; - }); + [NSNotificationCenter.defaultCenter postNotificationName:kLinphoneConfiguringStateUpdate + object:self + userInfo:dict]; + }); } - (void)configuringStateChangedNotificationHandler:(NSNotification *)notif { _wasRemoteProvisioned = ((LinphoneConfiguringState)[[[notif userInfo] valueForKey:@"state"] integerValue] == - LinphoneConfiguringSuccessful); + LinphoneConfiguringSuccessful); if (_wasRemoteProvisioned) { LinphoneProxyConfig *cfg = linphone_core_get_default_proxy_config(LC); if (cfg) { @@ -981,78 +970,78 @@ static void linphone_iphone_configuring_status_changed(LinphoneCore *lc, Linphon #pragma mark - Registration State Functions - (void)onRegister:(LinphoneCore *)lc - cfg:(LinphoneProxyConfig *)cfg - state:(LinphoneRegistrationState)state - message:(const char *)cmessage { +cfg:(LinphoneProxyConfig *)cfg +state:(LinphoneRegistrationState)state +message:(const char *)cmessage { LOGI(@"New registration state: %s (message: %s)", linphone_registration_state_to_string(state), cmessage); LinphoneReason reason = linphone_proxy_config_get_error(cfg); NSString *message = nil; switch (reason) { - case LinphoneReasonBadCredentials: - message = NSLocalizedString(@"Bad credentials, check your account settings", nil); - break; - case LinphoneReasonNoResponse: - message = NSLocalizedString(@"No response received from remote", nil); - break; - case LinphoneReasonUnsupportedContent: - message = NSLocalizedString(@"Unsupported content", nil); - break; - case LinphoneReasonIOError: - message = NSLocalizedString( - @"Cannot reach the server: either it is an invalid address or it may be temporary down.", nil); - break; + case LinphoneReasonBadCredentials: + message = NSLocalizedString(@"Bad credentials, check your account settings", nil); + break; + case LinphoneReasonNoResponse: + message = NSLocalizedString(@"No response received from remote", nil); + break; + case LinphoneReasonUnsupportedContent: + message = NSLocalizedString(@"Unsupported content", nil); + break; + case LinphoneReasonIOError: + message = NSLocalizedString( + @"Cannot reach the server: either it is an invalid address or it may be temporary down.", nil); + break; - case LinphoneReasonUnauthorized: - message = NSLocalizedString(@"Operation is unauthorized because missing credential", nil); - break; - case LinphoneReasonNoMatch: - message = NSLocalizedString(@"Operation could not be executed by server or remote client because it " - @"didn't have any context for it", - nil); - break; - case LinphoneReasonMovedPermanently: - message = NSLocalizedString(@"Resource moved permanently", nil); - break; - case LinphoneReasonGone: - message = NSLocalizedString(@"Resource no longer exists", nil); - break; - case LinphoneReasonTemporarilyUnavailable: - message = NSLocalizedString(@"Temporarily unavailable", nil); - break; - case LinphoneReasonAddressIncomplete: - message = NSLocalizedString(@"Address incomplete", nil); - break; - case LinphoneReasonNotImplemented: - message = NSLocalizedString(@"Not implemented", nil); - break; - case LinphoneReasonBadGateway: - message = NSLocalizedString(@"Bad gateway", nil); - break; - case LinphoneReasonServerTimeout: - message = NSLocalizedString(@"Server timeout", nil); - break; - case LinphoneReasonNotAcceptable: - case LinphoneReasonDoNotDisturb: - case LinphoneReasonDeclined: - case LinphoneReasonNotFound: - case LinphoneReasonNotAnswered: - case LinphoneReasonBusy: - case LinphoneReasonNone: - case LinphoneReasonUnknown: - message = NSLocalizedString(@"Unknown error", nil); - break; + case LinphoneReasonUnauthorized: + message = NSLocalizedString(@"Operation is unauthorized because missing credential", nil); + break; + case LinphoneReasonNoMatch: + message = NSLocalizedString(@"Operation could not be executed by server or remote client because it " + @"didn't have any context for it", + nil); + break; + case LinphoneReasonMovedPermanently: + message = NSLocalizedString(@"Resource moved permanently", nil); + break; + case LinphoneReasonGone: + message = NSLocalizedString(@"Resource no longer exists", nil); + break; + case LinphoneReasonTemporarilyUnavailable: + message = NSLocalizedString(@"Temporarily unavailable", nil); + break; + case LinphoneReasonAddressIncomplete: + message = NSLocalizedString(@"Address incomplete", nil); + break; + case LinphoneReasonNotImplemented: + message = NSLocalizedString(@"Not implemented", nil); + break; + case LinphoneReasonBadGateway: + message = NSLocalizedString(@"Bad gateway", nil); + break; + case LinphoneReasonServerTimeout: + message = NSLocalizedString(@"Server timeout", nil); + break; + case LinphoneReasonNotAcceptable: + case LinphoneReasonDoNotDisturb: + case LinphoneReasonDeclined: + case LinphoneReasonNotFound: + case LinphoneReasonNotAnswered: + case LinphoneReasonBusy: + case LinphoneReasonNone: + case LinphoneReasonUnknown: + message = NSLocalizedString(@"Unknown error", nil); + break; } // Post event NSDictionary *dict = [NSDictionary dictionaryWithObjectsAndKeys:[NSNumber numberWithInt:state], @"state", - [NSValue valueWithPointer:cfg], @"cfg", message, @"message", nil]; + [NSValue valueWithPointer:cfg], @"cfg", message, @"message", nil]; [NSNotificationCenter.defaultCenter postNotificationName:kLinphoneRegistrationUpdate object:self userInfo:dict]; } static void linphone_iphone_registration_state(LinphoneCore *lc, LinphoneProxyConfig *cfg, - LinphoneRegistrationState state, const char *message) { + LinphoneRegistrationState state, const char *message) { [(__bridge LinphoneManager *)linphone_core_cbs_get_user_data(linphone_core_get_current_callbacks(lc)) onRegister:lc cfg:cfg state:state message:message]; } @@ -1079,39 +1068,39 @@ static void linphone_iphone_popup_password_request(LinphoneCore *lc, LinphoneAut NSString *username = [NSString stringWithUTF8String:usernameC]; NSString *domain = [NSString stringWithUTF8String:domainC]; alertView = [UIAlertController alertControllerWithTitle:NSLocalizedString(@"Authentification needed", nil) - message:[NSString stringWithFormat:NSLocalizedString(@"Connection failed because authentication is " - @"missing or invalid for %@@%@.\nYou can " - @"provide password again, or check your " - @"account configuration in the settings.", nil), username, realm] - preferredStyle:UIAlertControllerStyleAlert]; + message:[NSString stringWithFormat:NSLocalizedString(@"Connection failed because authentication is " + @"missing or invalid for %@@%@.\nYou can " + @"provide password again, or check your " + @"account configuration in the settings.", nil), username, realm] + preferredStyle:UIAlertControllerStyleAlert]; UIAlertAction* defaultAction = [UIAlertAction actionWithTitle:NSLocalizedString(@"Cancel", nil) - style:UIAlertActionStyleDefault - handler:^(UIAlertAction * action) {}]; + style:UIAlertActionStyleDefault + handler:^(UIAlertAction * action) {}]; [alertView addTextFieldWithConfigurationHandler:^(UITextField *textField) { - textField.placeholder = NSLocalizedString(@"Password", nil); - textField.clearButtonMode = UITextFieldViewModeWhileEditing; - textField.borderStyle = UITextBorderStyleRoundedRect; - textField.secureTextEntry = YES; - }]; + textField.placeholder = NSLocalizedString(@"Password", nil); + textField.clearButtonMode = UITextFieldViewModeWhileEditing; + textField.borderStyle = UITextBorderStyleRoundedRect; + textField.secureTextEntry = YES; + }]; UIAlertAction* continueAction = [UIAlertAction actionWithTitle:NSLocalizedString(@"Confirm password", nil) - style:UIAlertActionStyleDefault - handler:^(UIAlertAction * action) { - NSString *password = alertView.textFields[0].text; - LinphoneAuthInfo *info = - linphone_auth_info_new(username.UTF8String, NULL, password.UTF8String, NULL, - realm.UTF8String, domain.UTF8String); - linphone_core_add_auth_info(LC, info); - [LinphoneManager.instance refreshRegisters]; - }]; + style:UIAlertActionStyleDefault + handler:^(UIAlertAction * action) { + NSString *password = alertView.textFields[0].text; + LinphoneAuthInfo *info = + linphone_auth_info_new(username.UTF8String, NULL, password.UTF8String, NULL, + realm.UTF8String, domain.UTF8String); + linphone_core_add_auth_info(LC, info); + [LinphoneManager.instance refreshRegisters]; + }]; UIAlertAction* settingsAction = [UIAlertAction actionWithTitle:NSLocalizedString(@"Go to settings", nil) - style:UIAlertActionStyleDefault - handler:^(UIAlertAction * action) { - [PhoneMainView.instance changeCurrentView:SettingsView.compositeViewDescription]; - }]; + style:UIAlertActionStyleDefault + handler:^(UIAlertAction * action) { + [PhoneMainView.instance changeCurrentView:SettingsView.compositeViewDescription]; + }]; [alertView addAction:defaultAction]; [alertView addAction:continueAction]; @@ -1165,26 +1154,26 @@ static void linphone_iphone_popup_password_request(LinphoneCore *lc, LinphoneAut pushBgTaskMsg = 0; } - BOOL hasFile = FALSE; - // if auto_download is available and file is downloaded - if ((linphone_core_get_max_size_for_auto_download_incoming_files(LC) > -1) && linphone_chat_message_get_file_transfer_information(msg)) - hasFile = TRUE; + BOOL hasFile = FALSE; + // if auto_download is available and file is downloaded + if ((linphone_core_get_max_size_for_auto_download_incoming_files(LC) > -1) && linphone_chat_message_get_file_transfer_information(msg)) + hasFile = TRUE; if (!linphone_chat_message_is_file_transfer(msg) && !linphone_chat_message_is_text(msg) && !hasFile) return; - if (hasFile) { - ChatConversationView *view = VIEW(ChatConversationView); - [view autoDownload:msg view:nil]; - } + if (hasFile) { + ChatConversationView *view = VIEW(ChatConversationView); + [view autoDownload:msg view:nil]; + } // Post event NSDictionary *dict = @{ - @"room" : [NSValue valueWithPointer:room], - @"from_address" : [NSValue valueWithPointer:linphone_chat_message_get_from_address(msg)], - @"message" : [NSValue valueWithPointer:msg], - @"call-id" : callID - }; + @"room" : [NSValue valueWithPointer:room], + @"from_address" : [NSValue valueWithPointer:linphone_chat_message_get_from_address(msg)], + @"message" : [NSValue valueWithPointer:msg], + @"call-id" : callID + }; [NSNotificationCenter.defaultCenter postNotificationName:kLinphoneMessageReceived object:self userInfo:dict]; @@ -1203,7 +1192,7 @@ static void linphone_iphone_popup_password_request(LinphoneCore *lc, LinphoneAut if (floor(NSFoundationVersionNumber) <= NSFoundationVersionNumber_iOS_9_x_Max) { NSArray *actions; if ([[UIDevice.currentDevice systemVersion] floatValue] < 9 || - [LinphoneManager.instance lpConfigBoolForKey:@"show_msg_in_notif"] == NO) { + [LinphoneManager.instance lpConfigBoolForKey:@"show_msg_in_notif"] == NO) { UIMutableUserNotificationAction *reply = [[UIMutableUserNotificationAction alloc] init]; reply.identifier = @"reply"; @@ -1242,7 +1231,7 @@ static void linphone_iphone_popup_password_request(LinphoneCore *lc, LinphoneAut NSSet *categories = [NSSet setWithObjects:msgcat, nil]; UIUserNotificationSettings *set = [UIUserNotificationSettings settingsForTypes:(UIUserNotificationTypeAlert | UIUserNotificationTypeBadge | UIUserNotificationTypeSound) - categories:categories]; + categories:categories]; [[UIApplication sharedApplication] registerUserNotificationSettings:set]; UILocalNotification *notif = [[UILocalNotification alloc] init]; @@ -1281,53 +1270,53 @@ static void linphone_iphone_popup_password_request(LinphoneCore *lc, LinphoneAut } content.sound = [UNNotificationSound soundNamed:@"msg.caf"]; content.categoryIdentifier = @"msg_cat"; - // save data to user info for rich notification content - NSMutableArray *msgs = [NSMutableArray array]; - bctbx_list_t *history = linphone_chat_room_get_history(room, 6); - while (history) { - NSMutableDictionary *msgData = [NSMutableDictionary dictionary]; - LinphoneChatMessage *msg = history->data; - const char *state = linphone_chat_message_state_to_string(linphone_chat_message_get_state(msg)); - bool_t isOutgoing = linphone_chat_message_is_outgoing(msg); - bool_t isFileTransfer = (linphone_chat_message_get_file_transfer_information(msg) != NULL); - const LinphoneAddress *fromAddress = linphone_chat_message_get_from_address(msg); - NSString *displayNameDate = [NSString stringWithFormat:@"%@ - %@", [LinphoneUtils timeToString:linphone_chat_message_get_time(msg) - withFormat:LinphoneDateChatBubble], - [FastAddressBook displayNameForAddress:fromAddress]]; - UIImage *fromImage = [UIImage resizeImage:[FastAddressBook imageForAddress:fromAddress] - withMaxWidth:200 - andMaxHeight:200]; - NSData *fromImageData = UIImageJPEGRepresentation(fromImage, 1); - [msgData setObject:[NSString stringWithUTF8String:state] forKey:@"state"]; - [msgData setObject:displayNameDate forKey:@"displayNameDate"]; - [msgData setObject:[NSNumber numberWithBool:isFileTransfer] forKey:@"isFileTransfer"]; - [msgData setObject:fromImageData forKey:@"fromImageData"]; - if (isFileTransfer) { - LinphoneContent *file = linphone_chat_message_get_file_transfer_information(msg); - const char *filename = linphone_content_get_name(file); - [msgData setObject:[NSString stringWithUTF8String:filename] forKey:@"msg"]; - } else { - [msgData setObject:[UIChatBubbleTextCell TextMessageForChat:msg] forKey:@"msg"]; - } - [msgData setObject:[NSNumber numberWithBool:isOutgoing] forKey:@"isOutgoing"]; - [msgs addObject:msgData]; - history = bctbx_list_next(history); - } - content.userInfo = @{@"from" : from, @"peer_addr" : peer_uri, @"local_addr" : local_uri, @"CallId" : callID, @"msgs" : msgs}; + // save data to user info for rich notification content + NSMutableArray *msgs = [NSMutableArray array]; + bctbx_list_t *history = linphone_chat_room_get_history(room, 6); + while (history) { + NSMutableDictionary *msgData = [NSMutableDictionary dictionary]; + LinphoneChatMessage *msg = history->data; + const char *state = linphone_chat_message_state_to_string(linphone_chat_message_get_state(msg)); + bool_t isOutgoing = linphone_chat_message_is_outgoing(msg); + bool_t isFileTransfer = (linphone_chat_message_get_file_transfer_information(msg) != NULL); + const LinphoneAddress *fromAddress = linphone_chat_message_get_from_address(msg); + NSString *displayNameDate = [NSString stringWithFormat:@"%@ - %@", [LinphoneUtils timeToString:linphone_chat_message_get_time(msg) + withFormat:LinphoneDateChatBubble], + [FastAddressBook displayNameForAddress:fromAddress]]; + UIImage *fromImage = [UIImage resizeImage:[FastAddressBook imageForAddress:fromAddress] + withMaxWidth:200 + andMaxHeight:200]; + NSData *fromImageData = UIImageJPEGRepresentation(fromImage, 1); + [msgData setObject:[NSString stringWithUTF8String:state] forKey:@"state"]; + [msgData setObject:displayNameDate forKey:@"displayNameDate"]; + [msgData setObject:[NSNumber numberWithBool:isFileTransfer] forKey:@"isFileTransfer"]; + [msgData setObject:fromImageData forKey:@"fromImageData"]; + if (isFileTransfer) { + LinphoneContent *file = linphone_chat_message_get_file_transfer_information(msg); + const char *filename = linphone_content_get_name(file); + [msgData setObject:[NSString stringWithUTF8String:filename] forKey:@"msg"]; + } else { + [msgData setObject:[UIChatBubbleTextCell TextMessageForChat:msg] forKey:@"msg"]; + } + [msgData setObject:[NSNumber numberWithBool:isOutgoing] forKey:@"isOutgoing"]; + [msgs addObject:msgData]; + history = bctbx_list_next(history); + } + content.userInfo = @{@"from" : from, @"peer_addr" : peer_uri, @"local_addr" : local_uri, @"CallId" : callID, @"msgs" : msgs}; content.accessibilityLabel = @"Message notif"; UNNotificationRequest *req = [UNNotificationRequest requestWithIdentifier:@"call_request" content:content trigger:NULL]; [[UNUserNotificationCenter currentNotificationCenter] - addNotificationRequest:req - withCompletionHandler:^(NSError *_Nullable error) { - // Enable or disable features based on authorization. - if (error) { - LOGD(@"Error while adding notification request :"); - LOGD(error.description); - } - }]; + addNotificationRequest:req + withCompletionHandler:^(NSError *_Nullable error) { + // Enable or disable features based on authorization. + if (error) { + LOGD(@"Error while adding notification request :"); + LOGD(error.description); + } + }]; } - [ChatsListTableView saveDataToUserDefaults]; - [HistoryListTableView saveDataToUserDefaults]; + [ChatsListTableView saveDataToUserDefaults]; + [HistoryListTableView saveDataToUserDefaults]; } static void linphone_iphone_message_received(LinphoneCore *lc, LinphoneChatRoom *room, LinphoneChatMessage *message) { @@ -1335,7 +1324,7 @@ static void linphone_iphone_message_received(LinphoneCore *lc, LinphoneChatRoom } static void linphone_iphone_message_received_unable_decrypt(LinphoneCore *lc, LinphoneChatRoom *room, - LinphoneChatMessage *message) { + LinphoneChatMessage *message) { NSString *callId = [NSString stringWithUTF8String:linphone_chat_message_get_custom_header(message, "Call-ID")]; int index = [(NSNumber *)[LinphoneManager.instance.pushDict objectForKey:callId] intValue] - 1; @@ -1358,11 +1347,11 @@ static void linphone_iphone_message_received_unable_decrypt(LinphoneCore *lc, Li NSString *strAddr = [FastAddressBook displayNameForAddress:address]; NSString *title = NSLocalizedString(@"LIME warning", nil); NSString *body = [NSString - stringWithFormat:NSLocalizedString(@"You have received an encrypted message you are unable to decrypt from " - @"%@.\nYou need to call your correspondant in order to exchange your ZRTP " - @"keys if you want to decrypt the future messages you will receive.", - nil), - strAddr]; + stringWithFormat:NSLocalizedString(@"You have received an encrypted message you are unable to decrypt from " + @"%@.\nYou need to call your correspondant in order to exchange your ZRTP " + @"keys if you want to decrypt the future messages you will receive.", + nil), + strAddr]; NSString *action = NSLocalizedString(@"Call", nil); if ([UIApplication sharedApplication].applicationState != UIApplicationStateActive) { @@ -1373,14 +1362,14 @@ static void linphone_iphone_message_received_unable_decrypt(LinphoneCore *lc, Li UNNotificationRequest *req = [UNNotificationRequest requestWithIdentifier:@"decrypt_request" content:content trigger:NULL]; [[UNUserNotificationCenter currentNotificationCenter] - addNotificationRequest:req - withCompletionHandler:^(NSError *_Nullable error) { - // Enable or disable features based on authorization. - if (error) { - LOGD(@"Error while adding notification request :"); - LOGD(error.description); - } - }]; + addNotificationRequest:req + withCompletionHandler:^(NSError *_Nullable error) { + // Enable or disable features based on authorization. + if (error) { + LOGD(@"Error while adding notification request :"); + LOGD(error.description); + } + }]; } else { UILocalNotification *notification = [[UILocalNotification alloc] init]; notification.repeatInterval = 0; @@ -1393,15 +1382,15 @@ static void linphone_iphone_message_received_unable_decrypt(LinphoneCore *lc, Li [UIAlertController alertControllerWithTitle:title message:body preferredStyle:UIAlertControllerStyleAlert]; UIAlertAction *defaultAction = [UIAlertAction actionWithTitle:NSLocalizedString(@"OK", nil) - style:UIAlertActionStyleDefault - handler:^(UIAlertAction *action){ - }]; + style:UIAlertActionStyleDefault + handler:^(UIAlertAction *action){ + }]; UIAlertAction *callAction = [UIAlertAction actionWithTitle:action - style:UIAlertActionStyleDefault - handler:^(UIAlertAction *action) { - [LinphoneManager.instance call:address]; - }]; + style:UIAlertActionStyleDefault + handler:^(UIAlertAction *action) { + [LinphoneManager.instance call:address]; + }]; [errView addAction:defaultAction]; [errView addAction:callAction]; @@ -1410,9 +1399,9 @@ static void linphone_iphone_message_received_unable_decrypt(LinphoneCore *lc, Li } - (void)onNotifyReceived:(LinphoneCore *)lc - event:(LinphoneEvent *)lev - notifyEvent:(const char *)notified_event - content:(const LinphoneContent *)body { +event:(LinphoneEvent *)lev +notifyEvent:(const char *)notified_event +content:(const LinphoneContent *)body { // Post event NSMutableDictionary *dict = [NSMutableDictionary dictionary]; [dict setObject:[NSValue valueWithPointer:lev] forKey:@"event"]; @@ -1424,48 +1413,48 @@ static void linphone_iphone_message_received_unable_decrypt(LinphoneCore *lc, Li } static void linphone_iphone_notify_received(LinphoneCore *lc, LinphoneEvent *lev, const char *notified_event, - const LinphoneContent *body) { + const LinphoneContent *body) { [(__bridge LinphoneManager *)linphone_core_cbs_get_user_data(linphone_core_get_current_callbacks(lc)) onNotifyReceived:lc - event:lev - notifyEvent:notified_event - content:body]; + event:lev + notifyEvent:notified_event + content:body]; } - (void)onNotifyPresenceReceivedForUriOrTel:(LinphoneCore *)lc - friend:(LinphoneFriend *)lf - uri:(const char *)uri - presenceModel:(const LinphonePresenceModel *)model { +friend:(LinphoneFriend *)lf +uri:(const char *)uri +presenceModel:(const LinphonePresenceModel *)model { // Post event NSMutableDictionary *dict = [NSMutableDictionary dictionary]; [dict setObject:[NSValue valueWithPointer:lf] forKey:@"friend"]; [dict setObject:[NSValue valueWithPointer:uri] forKey:@"uri"]; [dict setObject:[NSValue valueWithPointer:model] forKey:@"presence_model"]; [NSNotificationCenter.defaultCenter postNotificationName:kLinphoneNotifyPresenceReceivedForUriOrTel - object:self - userInfo:dict]; + object:self + userInfo:dict]; } static void linphone_iphone_notify_presence_received_for_uri_or_tel(LinphoneCore *lc, LinphoneFriend *lf, - const char *uri_or_tel, - const LinphonePresenceModel *presence_model) { + const char *uri_or_tel, + const LinphonePresenceModel *presence_model) { [(__bridge LinphoneManager *)linphone_core_cbs_get_user_data(linphone_core_get_current_callbacks(lc)) onNotifyPresenceReceivedForUriOrTel:lc - friend:lf - uri:uri_or_tel - presenceModel:presence_model]; + friend:lf + uri:uri_or_tel + presenceModel:presence_model]; } static void linphone_iphone_call_encryption_changed(LinphoneCore *lc, LinphoneCall *call, bool_t on, - const char *authentication_token) { + const char *authentication_token) { [(__bridge LinphoneManager *)linphone_core_cbs_get_user_data(linphone_core_get_current_callbacks(lc)) onCallEncryptionChanged:lc - call:call - on:on - token:authentication_token]; + call:call + on:on + token:authentication_token]; } - (void)onCallEncryptionChanged:(LinphoneCore *)lc - call:(LinphoneCall *)call - on:(BOOL)on - token:(const char *)authentication_token { +call:(LinphoneCall *)call +on:(BOOL)on +token:(const char *)authentication_token { // Post event NSMutableDictionary *dict = [NSMutableDictionary dictionary]; [dict setObject:[NSValue valueWithPointer:call] forKey:@"call"]; @@ -1483,31 +1472,31 @@ void linphone_iphone_chatroom_state_changed(LinphoneCore *lc, LinphoneChatRoom * } void linphone_iphone_version_update_check_result_received (LinphoneCore *lc, LinphoneVersionUpdateCheckResult result, const char *version, const char *url) { - if (result == LinphoneVersionUpdateCheckUpToDate || result == LinphoneVersionUpdateCheckError) { - return; - } - NSString *title = NSLocalizedString(@"Outdated Version", nil); - NSString *body = NSLocalizedString(@"A new version of your app is available, use the button below to download it.", nil); + if (result == LinphoneVersionUpdateCheckUpToDate || result == LinphoneVersionUpdateCheckError) { + return; + } + NSString *title = NSLocalizedString(@"Outdated Version", nil); + NSString *body = NSLocalizedString(@"A new version of your app is available, use the button below to download it.", nil); - UIAlertController *versVerifView = [UIAlertController alertControllerWithTitle:title - message:body - preferredStyle:UIAlertControllerStyleAlert]; + UIAlertController *versVerifView = [UIAlertController alertControllerWithTitle:title + message:body + preferredStyle:UIAlertControllerStyleAlert]; - NSString *ObjCurl = [NSString stringWithUTF8String:url]; - UIAlertAction* defaultAction = [UIAlertAction actionWithTitle:NSLocalizedString(@"Download", nil) - style:UIAlertActionStyleDefault - handler:^(UIAlertAction * action) { - [[UIApplication sharedApplication] openURL:[NSURL URLWithString:ObjCurl]]; - }]; + NSString *ObjCurl = [NSString stringWithUTF8String:url]; + UIAlertAction* defaultAction = [UIAlertAction actionWithTitle:NSLocalizedString(@"Download", nil) + style:UIAlertActionStyleDefault + handler:^(UIAlertAction * action) { + [[UIApplication sharedApplication] openURL:[NSURL URLWithString:ObjCurl]]; + }]; - [versVerifView addAction:defaultAction]; - [PhoneMainView.instance presentViewController:versVerifView animated:YES completion:nil]; + [versVerifView addAction:defaultAction]; + [PhoneMainView.instance presentViewController:versVerifView animated:YES completion:nil]; } void linphone_iphone_qr_code_found(LinphoneCore *lc, const char *result) { - NSDictionary *eventDic = [NSDictionary dictionaryWithObject:[NSString stringWithCString:result encoding:[NSString defaultCStringEncoding]] forKey:@"qrcode"]; - LOGD(@"QRCODE FOUND"); - [NSNotificationCenter.defaultCenter postNotificationName:kLinphoneQRCodeFound object:nil userInfo:eventDic]; + NSDictionary *eventDic = [NSDictionary dictionaryWithObject:[NSString stringWithCString:result encoding:[NSString defaultCStringEncoding]] forKey:@"qrcode"]; + LOGD(@"QRCODE FOUND"); + [NSNotificationCenter.defaultCenter postNotificationName:kLinphoneQRCodeFound object:nil userInfo:eventDic]; } #pragma mark - Message composition start @@ -1515,23 +1504,23 @@ void linphone_iphone_qr_code_found(LinphoneCore *lc, const char *result) { NSString *title = NSLocalizedString(@"LIME warning", nil); NSString *body = NSLocalizedString(@"You are trying to send a message using LIME to a contact not verified by ZRTP.\n" - @"Please call this contact and verify his ZRTP key before sending your messages.", - nil); + @"Please call this contact and verify his ZRTP key before sending your messages.", + nil); if ([UIApplication sharedApplication].applicationState == UIApplicationStateActive) { UIAlertController *errView = [UIAlertController alertControllerWithTitle:title message:body preferredStyle:UIAlertControllerStyleAlert]; UIAlertAction *defaultAction = [UIAlertAction actionWithTitle:@"OK" - style:UIAlertActionStyleDefault - handler:^(UIAlertAction *action){}]; + style:UIAlertActionStyleDefault + handler:^(UIAlertAction *action){}]; [errView addAction:defaultAction]; UIAlertAction *callAction = [UIAlertAction actionWithTitle:NSLocalizedString(@"Call", nil) - style:UIAlertActionStyleDefault - handler:^(UIAlertAction *action) { - [self call:linphone_chat_room_get_peer_address(room)]; - }]; + style:UIAlertActionStyleDefault + handler:^(UIAlertAction *action) { + [self call:linphone_chat_room_get_peer_address(room)]; + }]; [errView addAction:callAction]; [PhoneMainView.instance presentViewController:errView animated:YES completion:nil]; } else { @@ -1542,18 +1531,18 @@ void linphone_iphone_qr_code_found(LinphoneCore *lc, const char *result) { content.categoryIdentifier = @"lime"; UNNotificationRequest *req = [UNNotificationRequest - requestWithIdentifier:@"lime_request" - content:content - trigger:[UNTimeIntervalNotificationTrigger triggerWithTimeInterval:1 repeats:NO]]; + requestWithIdentifier:@"lime_request" + content:content + trigger:[UNTimeIntervalNotificationTrigger triggerWithTimeInterval:1 repeats:NO]]; [[UNUserNotificationCenter currentNotificationCenter] - addNotificationRequest:req - withCompletionHandler:^(NSError *_Nullable error) { - // Enable or disable features based on authorization. - if (error) { - LOGD(@"Error while adding notification request :"); - LOGD(error.description); - } - }]; + addNotificationRequest:req + withCompletionHandler:^(NSError *_Nullable error) { + // Enable or disable features based on authorization. + if (error) { + LOGD(@"Error while adding notification request :"); + LOGD(error.description); + } + }]; } else { UILocalNotification *notification = [[UILocalNotification alloc] init]; notification.repeatInterval = 0; @@ -1566,10 +1555,10 @@ void linphone_iphone_qr_code_found(LinphoneCore *lc, const char *result) { - (void)onMessageComposeReceived:(LinphoneCore *)core forRoom:(LinphoneChatRoom *)room { [NSNotificationCenter.defaultCenter postNotificationName:kLinphoneTextComposeEvent - object:self - userInfo:@{ - @"room" : [NSValue valueWithPointer:room] - }]; + object:self + userInfo:@{ + @"room" : [NSValue valueWithPointer:room] + }]; } static void linphone_iphone_is_composing_received(LinphoneCore *lc, LinphoneChatRoom *room) { @@ -1578,223 +1567,6 @@ static void linphone_iphone_is_composing_received(LinphoneCore *lc, LinphoneChat #pragma mark - Network Functions -- (SCNetworkReachabilityRef)getProxyReachability { - return proxyReachability; -} - -+ (void)kickOffNetworkConnection { - static BOOL in_progress = FALSE; - if (in_progress) { - LOGW(@"Connection kickoff already in progress"); - return; - } - in_progress = TRUE; - /* start a new thread to avoid blocking the main ui in case of peer host failure */ - dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{ - static int sleep_us = 10000; - static int timeout_s = 5; - BOOL timeout_reached = FALSE; - int loop = 0; - CFWriteStreamRef writeStream; - CFStreamCreatePairWithSocketToHost(NULL, (CFStringRef) @"192.168.0.200" /*"linphone.org"*/, 15000, nil, - &writeStream); - BOOL res = CFWriteStreamOpen(writeStream); - const char *buff = "hello"; - time_t start = time(NULL); - time_t loop_time; - - if (res == FALSE) { - LOGI(@"Could not open write stream, backing off"); - CFRelease(writeStream); - in_progress = FALSE; - return; - } - - // check stream status and handle timeout - CFStreamStatus status = CFWriteStreamGetStatus(writeStream); - while (status != kCFStreamStatusOpen && status != kCFStreamStatusError) { - usleep(sleep_us); - status = CFWriteStreamGetStatus(writeStream); - loop_time = time(NULL); - if (loop_time - start >= timeout_s) { - timeout_reached = TRUE; - break; - } - loop++; - } - - if (status == kCFStreamStatusOpen) { - CFWriteStreamWrite(writeStream, (const UInt8 *)buff, strlen(buff)); - } else if (!timeout_reached) { - CFErrorRef error = CFWriteStreamCopyError(writeStream); - LOGD(@"CFStreamError: %@", error); - CFRelease(error); - } else if (timeout_reached) { - LOGI(@"CFStream timeout reached"); - } - CFWriteStreamClose(writeStream); - CFRelease(writeStream); - in_progress = FALSE; - }); -} - -+ (NSString *)getCurrentWifiSSID { -#if TARGET_IPHONE_SIMULATOR - return @"Sim_err_SSID_NotSupported"; -#else - NSString *data = nil; - CFDictionaryRef dict = CNCopyCurrentNetworkInfo((CFStringRef) @"en0"); - if (dict) { - LOGI(@"AP Wifi: %@", dict); - data = [NSString stringWithString:(NSString *)CFDictionaryGetValue(dict, @"SSID")]; - CFRelease(dict); - } - return data; -#endif -} - -static void showNetworkFlags(SCNetworkReachabilityFlags flags) { - NSMutableString *log = [[NSMutableString alloc] initWithString:@"Network connection flags: "]; - if (flags == 0) - [log appendString:@"no flags."]; - if (flags & kSCNetworkReachabilityFlagsTransientConnection) - [log appendString:@"kSCNetworkReachabilityFlagsTransientConnection, "]; - if (flags & kSCNetworkReachabilityFlagsReachable) - [log appendString:@"kSCNetworkReachabilityFlagsReachable, "]; - if (flags & kSCNetworkReachabilityFlagsConnectionRequired) - [log appendString:@"kSCNetworkReachabilityFlagsConnectionRequired, "]; - if (flags & kSCNetworkReachabilityFlagsConnectionOnTraffic) - [log appendString:@"kSCNetworkReachabilityFlagsConnectionOnTraffic, "]; - if (flags & kSCNetworkReachabilityFlagsConnectionOnDemand) - [log appendString:@"kSCNetworkReachabilityFlagsConnectionOnDemand, "]; - if (flags & kSCNetworkReachabilityFlagsIsLocalAddress) - [log appendString:@"kSCNetworkReachabilityFlagsIsLocalAddress, "]; - if (flags & kSCNetworkReachabilityFlagsIsDirect) - [log appendString:@"kSCNetworkReachabilityFlagsIsDirect, "]; - if (flags & kSCNetworkReachabilityFlagsIsWWAN) - [log appendString:@"kSCNetworkReachabilityFlagsIsWWAN, "]; - LOGI(@"%@", log); -} - -//This callback keeps tracks of wifi SSID changes. -static void networkReachabilityNotification(CFNotificationCenterRef center, void *observer, CFStringRef name, - const void *object, CFDictionaryRef userInfo) { - LinphoneManager *mgr = LinphoneManager.instance; - SCNetworkReachabilityFlags flags; - - // for an unknown reason, we are receiving multiple time the notification, so - // we will skip each time the SSID did not change - NSString *newSSID = [LinphoneManager getCurrentWifiSSID]; - if ([newSSID compare:mgr.SSID] == NSOrderedSame) - return; - - - if (newSSID != Nil && newSSID.length > 0 && mgr.SSID != Nil && newSSID.length > 0) { - if (SCNetworkReachabilityGetFlags([mgr getProxyReachability], &flags)) { - LOGI(@"Wifi SSID changed, resesting transports."); - mgr.connectivity=none; //this will trigger a connectivity change in networkReachabilityCallback. - networkReachabilityCallBack([mgr getProxyReachability], flags, nil); - } - } - mgr.SSID = newSSID; -} - -void networkReachabilityCallBack(SCNetworkReachabilityRef target, SCNetworkReachabilityFlags flags, void *nilCtx) { - showNetworkFlags(flags); - LinphoneManager *lm = LinphoneManager.instance; - SCNetworkReachabilityFlags networkDownFlags = kSCNetworkReachabilityFlagsConnectionRequired | - kSCNetworkReachabilityFlagsConnectionOnTraffic | - kSCNetworkReachabilityFlagsConnectionOnDemand; - - if (theLinphoneCore != nil) { - LinphoneProxyConfig *proxy = linphone_core_get_default_proxy_config(theLinphoneCore); - - struct NetworkReachabilityContext *ctx = nilCtx ? ((struct NetworkReachabilityContext *)nilCtx) : 0; - if ((flags == 0) || (flags & networkDownFlags)) { - linphone_core_set_network_reachable(theLinphoneCore, false); - lm.connectivity = none; - [LinphoneManager kickOffNetworkConnection]; - } else { - Connectivity newConnectivity; - BOOL isWifiOnly = [lm lpConfigBoolForKey:@"wifi_only_preference" withDefault:FALSE]; - if (!ctx || ctx->testWWan) - newConnectivity = flags & kSCNetworkReachabilityFlagsIsWWAN ? wwan : wifi; - else - newConnectivity = wifi; - - if (newConnectivity == wwan && proxy && isWifiOnly && - (lm.connectivity == newConnectivity || lm.connectivity == none)) { - linphone_proxy_config_expires(proxy, 0); - } else if (proxy) { - NSInteger defaultExpire = [lm lpConfigIntForKey:@"default_expires"]; - if (defaultExpire >= 0) - linphone_proxy_config_expires(proxy, (int)defaultExpire); - // else keep default value from linphonecore - } - - if (lm.connectivity != newConnectivity) { - // connectivity has changed - linphone_core_set_network_reachable(theLinphoneCore, false); - if (newConnectivity == wwan && proxy && isWifiOnly) { - linphone_proxy_config_expires(proxy, 0); - } - linphone_core_set_network_reachable(theLinphoneCore, true); - [LinphoneManager.instance iterate]; - LOGI(@"Network connectivity changed to type [%s]", (newConnectivity == wifi ? "wifi" : "wwan")); - lm.connectivity = newConnectivity; - } - } - if (ctx && ctx->networkStateChanged) { - (*ctx->networkStateChanged)(lm.connectivity); - } - } -} - -- (void)setupNetworkReachabilityCallback { - SCNetworkReachabilityContext *ctx = NULL; - // any internet cnx - struct sockaddr_in zeroAddress; - bzero(&zeroAddress, sizeof(zeroAddress)); - zeroAddress.sin_len = sizeof(zeroAddress); - zeroAddress.sin_family = AF_INET; - - if (proxyReachability) { - LOGI(@"Cancelling old network reachability"); - SCNetworkReachabilityUnscheduleFromRunLoop(proxyReachability, CFRunLoopGetCurrent(), kCFRunLoopDefaultMode); - CFRelease(proxyReachability); - proxyReachability = nil; - } - - // This notification is used to detect SSID change (switch of Wifi network). The ReachabilityCallback is - // not triggered when switching between 2 private Wifi... - // Since we cannot be sure we were already observer, remove ourself each time... to be improved - _SSID = [LinphoneManager getCurrentWifiSSID]; - CFNotificationCenterRemoveObserver(CFNotificationCenterGetDarwinNotifyCenter(), (__bridge const void *)(self), - CFSTR("com.apple.system.config.network_change"), NULL); - CFNotificationCenterAddObserver(CFNotificationCenterGetDarwinNotifyCenter(), (__bridge const void *)(self), - networkReachabilityNotification, CFSTR("com.apple.system.config.network_change"), - NULL, CFNotificationSuspensionBehaviorDeliverImmediately); - - proxyReachability = - SCNetworkReachabilityCreateWithAddress(kCFAllocatorDefault, (const struct sockaddr *)&zeroAddress); - - if (!SCNetworkReachabilitySetCallback(proxyReachability, (SCNetworkReachabilityCallBack)networkReachabilityCallBack, - ctx)) { - LOGE(@"Cannot register reachability cb: %s", SCErrorString(SCError())); - return; - } - if (!SCNetworkReachabilityScheduleWithRunLoop(proxyReachability, CFRunLoopGetCurrent(), kCFRunLoopDefaultMode)) { - LOGE(@"Cannot register schedule reachability cb: %s", SCErrorString(SCError())); - return; - } - - // this check is to know network connectivity right now without waiting for a change. Don'nt remove it unless you - // have good reason. Jehan - SCNetworkReachabilityFlags flags; - if (SCNetworkReachabilityGetFlags(proxyReachability, &flags)) { - networkReachabilityCallBack(proxyReachability, flags, nil); - } -} - (NetworkType)network { if ([[[UIDevice currentDevice] systemVersion] floatValue] < 7) { @@ -1831,9 +1603,9 @@ void networkReachabilityCallBack(SCNetworkReachabilityRef target, SCNetworkReach - (void)iterate { UIBackgroundTaskIdentifier coreIterateTaskId = 0; coreIterateTaskId = [[UIApplication sharedApplication] beginBackgroundTaskWithExpirationHandler:^{ - LOGW(@"Background task for core iteration launching expired."); - [[UIApplication sharedApplication] endBackgroundTask:coreIterateTaskId]; - }]; + LOGW(@"Background task for core iteration launching expired."); + [[UIApplication sharedApplication] endBackgroundTask:coreIterateTaskId]; + }]; linphone_core_iterate(theLinphoneCore); if (coreIterateTaskId != UIBackgroundTaskInvalid) [[UIApplication sharedApplication] endBackgroundTask:coreIterateTaskId]; @@ -1856,13 +1628,10 @@ void networkReachabilityCallBack(SCNetworkReachabilityRef target, SCNetworkReach // get default config from bundle NSString *zrtpSecretsFileName = [LinphoneManager dataFile:@"zrtp_secrets"]; NSString *chatDBFileName = [LinphoneManager dataFile:kLinphoneInternalChatDBFilename]; - - NSString *device = [[NSMutableString alloc] - initWithString:[NSString - stringWithFormat:@"%@iOS/%@ (%@) LinphoneSDK", - [NSBundle.mainBundle objectForInfoDictionaryKey:@"CFBundleDisplayName"], - [[NSBundle mainBundle] objectForInfoDictionaryKey:@"CFBundleShortVersionString"], - [[UIDevice currentDevice] name]]]; + NSString *device = [[NSMutableString alloc] initWithString:[NSString stringWithFormat:@"%@iOS/%@ (%@) LinphoneSDK", + [NSBundle.mainBundle objectForInfoDictionaryKey:@"CFBundleDisplayName"], + [[NSBundle mainBundle] objectForInfoDictionaryKey:@"CFBundleShortVersionString"], + [[UIDevice currentDevice] name]]]; linphone_core_set_user_agent(theLinphoneCore, device.UTF8String, LINPHONE_SDK_VERSION); @@ -1876,8 +1645,6 @@ void networkReachabilityCallBack(SCNetworkReachabilityRef target, SCNetworkReach //linphone_core_set_chat_database_path(theLinphoneCore, [chatDBFileName UTF8String]); linphone_core_set_call_logs_database_path(theLinphoneCore, [chatDBFileName UTF8String]); - [self setupNetworkReachabilityCallback]; - NSString *path = [LinphoneManager bundleFile:@"nowebcamCIF.jpg"]; if (path) { const char *imagePath = [path UTF8String]; @@ -1916,8 +1683,8 @@ void networkReachabilityCallBack(SCNetworkReachabilityRef target, SCNetworkReach [self enableProxyPublish:([UIApplication sharedApplication].applicationState == UIApplicationStateActive)]; - //update UserDefaults for widgets - [HistoryListTableView saveDataToUserDefaults]; + //update UserDefaults for widgets + [HistoryListTableView saveDataToUserDefaults]; LOGI(@"Linphone [%s] started on [%s]", linphone_core_get_version(), [[UIDevice currentDevice].model UTF8String]); @@ -1925,8 +1692,8 @@ void networkReachabilityCallBack(SCNetworkReachabilityRef target, SCNetworkReach NSDictionary *dict = [NSDictionary dictionaryWithObject:[NSValue valueWithPointer:theLinphoneCore] forKey:@"core"]; [NSNotificationCenter.defaultCenter postNotificationName:kLinphoneCoreUpdate - object:LinphoneManager.instance - userInfo:dict]; + object:LinphoneManager.instance + userInfo:dict]; } static BOOL libStarted = FALSE; @@ -1940,7 +1707,6 @@ static BOOL libStarted = FALSE; libStarted = TRUE; - connectivity = none; signal(SIGPIPE, SIG_IGN); // create linphone core @@ -1963,12 +1729,12 @@ static BOOL libStarted = FALSE; } if (!bAudioInputAvailable) { UIAlertController *errView = [UIAlertController alertControllerWithTitle:NSLocalizedString(@"No microphone", nil) - message:NSLocalizedString(@"You need to plug a microphone to your device to use the application.", nil) - preferredStyle:UIAlertControllerStyleAlert]; + message:NSLocalizedString(@"You need to plug a microphone to your device to use the application.", nil) + preferredStyle:UIAlertControllerStyleAlert]; UIAlertAction* defaultAction = [UIAlertAction actionWithTitle:NSLocalizedString(@"OK", nil) - style:UIAlertActionStyleDefault - handler:^(UIAlertAction * action) {}]; + style:UIAlertActionStyleDefault + handler:^(UIAlertAction * action) {}]; [errView addAction:defaultAction]; [PhoneMainView.instance presentViewController:errView animated:YES completion:nil]; @@ -1986,36 +1752,36 @@ void popup_link_account_cb(LinphoneAccountCreator *creator, LinphoneAccountCreat } else { LinphoneProxyConfig *cfg = linphone_core_get_default_proxy_config(LC); if (cfg && - strcmp(linphone_proxy_config_get_domain(cfg), - [LinphoneManager.instance lpConfigStringForKey:@"domain_name" - inSection:@"app" - withDefault:@"sip.linphone.org"] - .UTF8String) == 0) { + strcmp(linphone_proxy_config_get_domain(cfg), + [LinphoneManager.instance lpConfigStringForKey:@"domain_name" + inSection:@"app" + withDefault:@"sip.linphone.org"] + .UTF8String) == 0) { UIAlertController *errView = [UIAlertController alertControllerWithTitle:NSLocalizedString(@"Link your account", nil) - message:[NSString stringWithFormat:NSLocalizedString(@"Link your Linphone.org account %s to your phone number.", nil), - linphone_address_get_username(linphone_proxy_config_get_identity_address(cfg))] - preferredStyle:UIAlertControllerStyleAlert]; + message:[NSString stringWithFormat:NSLocalizedString(@"Link your Linphone.org account %s to your phone number.", nil), + linphone_address_get_username(linphone_proxy_config_get_identity_address(cfg))] + preferredStyle:UIAlertControllerStyleAlert]; UIAlertAction* defaultAction = [UIAlertAction actionWithTitle:NSLocalizedString(@"Maybe later", nil) - style:UIAlertActionStyleDefault - handler:^(UIAlertAction * action) {}]; + style:UIAlertActionStyleDefault + handler:^(UIAlertAction * action) {}]; UIAlertAction* continueAction = [UIAlertAction actionWithTitle:NSLocalizedString(@"Let's go", nil) - style:UIAlertActionStyleDefault - handler:^(UIAlertAction * action) { - [PhoneMainView.instance changeCurrentView:AssistantLinkView.compositeViewDescription]; - }]; + style:UIAlertActionStyleDefault + handler:^(UIAlertAction * action) { + [PhoneMainView.instance changeCurrentView:AssistantLinkView.compositeViewDescription]; + }]; defaultAction.accessibilityLabel = @"Later"; [errView addAction:defaultAction]; [errView addAction:continueAction]; [PhoneMainView.instance presentViewController:errView animated:YES completion:nil]; [LinphoneManager.instance - lpConfigSetInt:[[NSDate date] dateByAddingTimeInterval:[LinphoneManager.instance - lpConfigIntForKey:@"link_account_popup_time" - withDefault:84200]] - .timeIntervalSince1970 - forKey:@"must_link_account_time"]; + lpConfigSetInt:[[NSDate date] dateByAddingTimeInterval:[LinphoneManager.instance + lpConfigIntForKey:@"link_account_popup_time" + withDefault:84200]] + .timeIntervalSince1970 + forKey:@"must_link_account_time"]; } } } @@ -2029,12 +1795,12 @@ void popup_link_account_cb(LinphoneAccountCreator *creator, LinphoneAccountCreat if (cfg) { const char *username = linphone_address_get_username(linphone_proxy_config_get_identity_address(cfg)); LinphoneAccountCreator *account_creator = linphone_account_creator_new( - LC, - [LinphoneManager.instance lpConfigStringForKey:@"xmlrpc_url" inSection:@"assistant" withDefault:@""] - .UTF8String); + LC, + [LinphoneManager.instance lpConfigStringForKey:@"xmlrpc_url" inSection:@"assistant" withDefault:@""] + .UTF8String); linphone_account_creator_set_user_data(account_creator, (__bridge void *)(self)); linphone_account_creator_cbs_set_is_account_linked(linphone_account_creator_get_callbacks(account_creator), - popup_link_account_cb); + popup_link_account_cb); linphone_account_creator_set_username(account_creator, username); linphone_account_creator_is_account_linked(account_creator); } @@ -2048,21 +1814,20 @@ void popup_link_account_cb(LinphoneAccountCreator *creator, LinphoneAccountCreat return; } - connectivity = none; // Set audio assets NSString *ring = ([LinphoneManager bundleFile:[self lpConfigStringForKey:@"local_ring" inSection:@"sound"].lastPathComponent] - ?: [LinphoneManager bundleFile:@"notes_of_the_optimistic.caf"]) - .lastPathComponent; + ?: [LinphoneManager bundleFile:@"notes_of_the_optimistic.caf"]) + .lastPathComponent; NSString *ringback = ([LinphoneManager bundleFile:[self lpConfigStringForKey:@"remote_ring" inSection:@"sound"].lastPathComponent] - ?: [LinphoneManager bundleFile:@"ringback.wav"]) - .lastPathComponent; + ?: [LinphoneManager bundleFile:@"ringback.wav"]) + .lastPathComponent; NSString *hold = ([LinphoneManager bundleFile:[self lpConfigStringForKey:@"hold_music" inSection:@"sound"].lastPathComponent] - ?: [LinphoneManager bundleFile:@"hold.mkv"]) - .lastPathComponent; + ?: [LinphoneManager bundleFile:@"hold.mkv"]) + .lastPathComponent; [self lpConfigSetString:[LinphoneManager bundleFile:ring] forKey:@"local_ring" inSection:@"sound"]; [self lpConfigSetString:[LinphoneManager bundleFile:ringback] forKey:@"remote_ring" inSection:@"sound"]; [self lpConfigSetString:[LinphoneManager bundleFile:hold] forKey:@"hold_music" inSection:@"sound"]; @@ -2112,21 +1877,21 @@ void popup_link_account_cb(LinphoneAccountCreator *creator, LinphoneAccountCreat linphone_core_set_user_certificates_path(theLinphoneCore, [LinphoneManager cacheDirectory].UTF8String); /* The core will call the linphone_iphone_configuring_status_changed callback when the remote provisioning is loaded - (or skipped). - Wait for this to finish the code configuration */ + (or skipped). + Wait for this to finish the code configuration */ [NSNotificationCenter.defaultCenter addObserver:self - selector:@selector(audioSessionInterrupted:) - name:AVAudioSessionInterruptionNotification - object:nil]; + selector:@selector(audioSessionInterrupted:) + name:AVAudioSessionInterruptionNotification + object:nil]; [NSNotificationCenter.defaultCenter addObserver:self - selector:@selector(globalStateChangedNotificationHandler:) - name:kLinphoneGlobalStateUpdate - object:nil]; + selector:@selector(globalStateChangedNotificationHandler:) + name:kLinphoneGlobalStateUpdate + object:nil]; [NSNotificationCenter.defaultCenter addObserver:self - selector:@selector(configuringStateChangedNotificationHandler:) - name:kLinphoneConfiguringStateUpdate - object:nil]; + selector:@selector(configuringStateChangedNotificationHandler:) + name:kLinphoneConfiguringStateUpdate + object:nil]; [NSNotificationCenter.defaultCenter addObserver:self selector:@selector(inappReady:) name:kIAPReady object:nil]; /*call iterate once immediately in order to initiate background connections with sip server or remote provisioning @@ -2157,13 +1922,8 @@ void popup_link_account_cb(LinphoneAccountCreator *creator, LinphoneAccountCreat NSDictionary *dict = [NSDictionary dictionaryWithObject:[NSValue valueWithPointer:theLinphoneCore] forKey:@"core"]; [NSNotificationCenter.defaultCenter postNotificationName:kLinphoneCoreUpdate - object:LinphoneManager.instance - userInfo:dict]; - - SCNetworkReachabilityUnscheduleFromRunLoop(proxyReachability, CFRunLoopGetCurrent(), kCFRunLoopDefaultMode); - if (proxyReachability) - CFRelease(proxyReachability); - proxyReachability = nil; + object:LinphoneManager.instance + userInfo:dict]; } libStarted = FALSE; [[NSNotificationCenter defaultCenter] removeObserver:self]; @@ -2269,11 +2029,11 @@ static int comp_call_state_paused(const LinphoneCall *call, const void *param) { - (void)startCallPausedLongRunningTask { pausedCallBgTask = [[UIApplication sharedApplication] beginBackgroundTaskWithExpirationHandler:^{ - LOGW(@"Call cannot be paused any more, too late"); - [[UIApplication sharedApplication] endBackgroundTask:pausedCallBgTask]; - }]; + LOGW(@"Call cannot be paused any more, too late"); + [[UIApplication sharedApplication] endBackgroundTask:pausedCallBgTask]; + }]; LOGI(@"Long running task started, remaining [%@] because at least one call is paused", - [LinphoneUtils intervalToString:[[UIApplication sharedApplication] backgroundTimeRemaining]]); + [LinphoneUtils intervalToString:[[UIApplication sharedApplication] backgroundTimeRemaining]]); } - (void)startPushLongRunningTask:(NSString *)loc_key callId:(NSString *)callId { @@ -2287,63 +2047,63 @@ static int comp_call_state_paused(const LinphoneCall *call, const void *param) { [[UIApplication sharedApplication] endBackgroundTask:pushBgTaskMsg]; pushBgTaskMsg = 0; pushBgTaskMsg = [[UIApplication sharedApplication] beginBackgroundTaskWithExpirationHandler:^{ - if ([UIApplication sharedApplication].applicationState != UIApplicationStateActive) { - LOGW(@"Incomming message with call-id [%@] couldn't be received", callId); - UNMutableNotificationContent *content = [[UNMutableNotificationContent alloc] init]; - content.title = NSLocalizedString(@"Message received", nil); - content.body = NSLocalizedString(@"You have received a message.", nil); - content.categoryIdentifier = @"push_msg"; + if ([UIApplication sharedApplication].applicationState != UIApplicationStateActive) { + LOGW(@"Incomming message with call-id [%@] couldn't be received", callId); + UNMutableNotificationContent *content = [[UNMutableNotificationContent alloc] init]; + content.title = NSLocalizedString(@"Message received", nil); + content.body = NSLocalizedString(@"You have received a message.", nil); + content.categoryIdentifier = @"push_msg"; - UNNotificationRequest *req = - [UNNotificationRequest requestWithIdentifier:@"push_msg" content:content trigger:NULL]; - [[UNUserNotificationCenter currentNotificationCenter] - addNotificationRequest:req - withCompletionHandler:^(NSError *_Nullable error) { - // Enable or disable features based on authorization. - if (error) { - LOGD(@"Error while adding notification request :"); - LOGD(error.description); - } - }]; - } - for (NSString *key in [LinphoneManager.instance.pushDict allKeys]) { - [LinphoneManager.instance.pushDict setValue:[NSNumber numberWithInt:0] forKey:key]; - } - [[UIApplication sharedApplication] endBackgroundTask:pushBgTaskMsg]; - pushBgTaskMsg = 0; - }]; + UNNotificationRequest *req = + [UNNotificationRequest requestWithIdentifier:@"push_msg" content:content trigger:NULL]; + [[UNUserNotificationCenter currentNotificationCenter] + addNotificationRequest:req + withCompletionHandler:^(NSError *_Nullable error) { + // Enable or disable features based on authorization. + if (error) { + LOGD(@"Error while adding notification request :"); + LOGD(error.description); + } + }]; + } + for (NSString *key in [LinphoneManager.instance.pushDict allKeys]) { + [LinphoneManager.instance.pushDict setValue:[NSNumber numberWithInt:0] forKey:key]; + } + [[UIApplication sharedApplication] endBackgroundTask:pushBgTaskMsg]; + pushBgTaskMsg = 0; + }]; LOGI(@"Message long running task started for call-id [%@], remaining [%@] because a push has been received", - callId, [LinphoneUtils intervalToString:[[UIApplication sharedApplication] backgroundTimeRemaining]]); + callId, [LinphoneUtils intervalToString:[[UIApplication sharedApplication] backgroundTimeRemaining]]); } else if ([loc_key isEqualToString:@"IC_MSG"]) { [[UIApplication sharedApplication] endBackgroundTask:pushBgTaskCall]; pushBgTaskCall = 0; pushBgTaskCall = [[UIApplication sharedApplication] beginBackgroundTaskWithExpirationHandler:^{ - //does not make sens to notify user as we have no information on this missed called - for (NSString *key in [LinphoneManager.instance.pushDict allKeys]) { - [LinphoneManager.instance.pushDict setValue:[NSNumber numberWithInt:0] forKey:key]; - } - [[UIApplication sharedApplication] endBackgroundTask:pushBgTaskCall]; - pushBgTaskCall = 0; - }]; + //does not make sens to notify user as we have no information on this missed called + for (NSString *key in [LinphoneManager.instance.pushDict allKeys]) { + [LinphoneManager.instance.pushDict setValue:[NSNumber numberWithInt:0] forKey:key]; + } + [[UIApplication sharedApplication] endBackgroundTask:pushBgTaskCall]; + pushBgTaskCall = 0; + }]; LOGI(@"Call long running task started for call-id [%@], remaining [%@] because a push has been received", - callId, [LinphoneUtils intervalToString:[[UIApplication sharedApplication] backgroundTimeRemaining]]); + callId, [LinphoneUtils intervalToString:[[UIApplication sharedApplication] backgroundTimeRemaining]]); } else if ([loc_key isEqualToString:@"IC_SIL"]) { [[UIApplication sharedApplication] endBackgroundTask:pushBgTaskRefer]; pushBgTaskRefer = 0; pushBgTaskRefer = [[UIApplication sharedApplication] beginBackgroundTaskWithExpirationHandler:^{ - // Could be or not an error since the app doesn't know when to end the background task for a REFER - // TODO: Manage pushes in the SDK - if ([UIApplication sharedApplication].applicationState != UIApplicationStateActive) - LOGI(@"Incomming refer long running task with call-id [%@] has expired", callId); + // Could be or not an error since the app doesn't know when to end the background task for a REFER + // TODO: Manage pushes in the SDK + if ([UIApplication sharedApplication].applicationState != UIApplicationStateActive) + LOGI(@"Incomming refer long running task with call-id [%@] has expired", callId); - for (NSString *key in [LinphoneManager.instance.pushDict allKeys]) { - [LinphoneManager.instance.pushDict setValue:[NSNumber numberWithInt:0] forKey:key]; - } - [[UIApplication sharedApplication] endBackgroundTask:pushBgTaskRefer]; - pushBgTaskRefer = 0; - }]; + for (NSString *key in [LinphoneManager.instance.pushDict allKeys]) { + [LinphoneManager.instance.pushDict setValue:[NSNumber numberWithInt:0] forKey:key]; + } + [[UIApplication sharedApplication] endBackgroundTask:pushBgTaskRefer]; + pushBgTaskRefer = 0; + }]; LOGI(@"Refer long running task started for call-id [%@], remaining [%@] because a push has been received", - callId, [LinphoneUtils intervalToString:[[UIApplication sharedApplication] backgroundTimeRemaining]]); + callId, [LinphoneUtils intervalToString:[[UIApplication sharedApplication] backgroundTimeRemaining]]); } } @@ -2413,8 +2173,7 @@ static int comp_call_state_paused(const LinphoneCall *call, const void *param) { } linphone_core_iterate(theLinphoneCore); }]) { - - LOGI(@"keepalive handler succesfully registered"); + LOGI(@"keepalive handler succesfully registered"); } else { LOGI(@"keepalive handler cannot be registered"); } @@ -2425,8 +2184,8 @@ static int comp_call_state_paused(const LinphoneCall *call, const void *param) { LinphoneCall *currentCall = linphone_core_get_current_call(theLinphoneCore); const bctbx_list_t *callList = linphone_core_get_calls(theLinphoneCore); if (!currentCall // no active call - && callList // at least one call in a non active state - && bctbx_list_find_custom(callList, (bctbx_compare_func)comp_call_state_paused, NULL)) { + && callList // at least one call in a non active state + && bctbx_list_find_custom(callList, (bctbx_compare_func)comp_call_state_paused, NULL)) { [self startCallPausedLongRunningTask]; } if (callList) // If at least one call exist, enter normal bg mode @@ -2446,7 +2205,6 @@ static int comp_call_state_paused(const LinphoneCall *call, const void *param) { if (pushNotifEnabled) { LOGI(@"Keeping lc core to handle push"); // Destroy voip socket if any and reset connectivity mode - connectivity = none; linphone_core_set_network_reachable(theLinphoneCore, FALSE); return YES; } @@ -2458,10 +2216,10 @@ static int comp_call_state_paused(const LinphoneCall *call, const void *param) { - (void)becomeActive { linphone_core_enter_foreground(LC); - [self checkNewVersion]; + [self checkNewVersion]; // enable presence - if (floor(NSFoundationVersionNumber) <= NSFoundationVersionNumber_iOS_9_x_Max || self.connectivity == none) { + if (floor(NSFoundationVersionNumber) <= NSFoundationVersionNumber_iOS_9_x_Max) { [self refreshRegisters]; } if (pausedCallBgTask) { @@ -2476,8 +2234,8 @@ static int comp_call_state_paused(const LinphoneCall *call, const void *param) { /*IOS specific*/ linphone_core_start_dtmf_stream(theLinphoneCore); [AVCaptureDevice requestAccessForMediaType:AVMediaTypeVideo - completionHandler:^(BOOL granted){ - }]; + completionHandler:^(BOOL granted){ + }]; /*start the video preview in case we are in the main view*/ if (linphone_core_video_display_enabled(theLinphoneCore) && [self lpConfigBoolForKey:@"preview_preference"]) { @@ -2509,14 +2267,7 @@ static int comp_call_state_paused(const LinphoneCall *call, const void *param) { } - (void)refreshRegisters { - if (connectivity == none) { - // don't trust ios when he says there is no network. Create a new reachability context, the previous one might - // be mis-functionning. - LOGI(@"None connectivity"); - [self setupNetworkReachabilityCallback]; - } - LOGI(@"Network reachability callback setup"); - linphone_core_refresh_registers(theLinphoneCore); // just to make sure REGISTRATION is up to date + linphone_core_refresh_registers(theLinphoneCore); // just to make sure REGISTRATION is up to date } - (void)migrateImportantFiles { @@ -2553,7 +2304,7 @@ static int comp_call_state_paused(const LinphoneCall *call, const void *param) { if ([fileManager fileExistsAtPath:dst]) { [fileManager removeItemAtPath:src error:&fileError]; LOGW(@"%@ already exists, simply removing %@ %@", dst, src, - fileError ? fileError.localizedDescription : @"successfully"); + fileError ? fileError.localizedDescription : @"successfully"); } else { [fileManager moveItemAtPath:src toPath:dst error:&fileError]; LOGI(@"%@ moving to %@ %@", dst, src, fileError ? fileError.localizedDescription : @"successfully"); @@ -2591,8 +2342,8 @@ static int comp_call_state_paused(const LinphoneCall *call, const void *param) { if (newRoute && newRoute.outputs.count > 0) { NSString *route = newRoute.outputs[0].portType; allow = !([route isEqualToString:AVAudioSessionPortLineOut] || - [route isEqualToString:AVAudioSessionPortHeadphones] || - [[AudioHelper bluetoothRoutes] containsObject:route]); + [route isEqualToString:AVAudioSessionPortHeadphones] || + [[AudioHelper bluetoothRoutes] containsObject:route]); } return allow; } @@ -2624,8 +2375,8 @@ static int comp_call_state_paused(const LinphoneCall *call, const void *param) { NSDictionary *dict = [NSDictionary dictionaryWithObjectsAndKeys:[NSNumber numberWithBool:_bluetoothAvailable], @"available", nil]; [NSNotificationCenter.defaultCenter postNotificationName:kLinphoneBluetoothAvailabilityUpdate - object:self - userInfo:dict]; + object:self + userInfo:dict]; } } @@ -2690,11 +2441,11 @@ static int comp_call_state_paused(const LinphoneCall *call, const void *param) { } linphone_call_params_enable_video(lcallParams, video); - //We set the record file name here because we can't do it after the call is started. - NSString *writablePath = [LinphoneUtils recordingFilePathFromCall:linphone_call_log_get_from_address(linphone_call_get_call_log(call))]; - LOGD(@"record file path: %@\n", writablePath); + //We set the record file name here because we can't do it after the call is started. + NSString *writablePath = [LinphoneUtils recordingFilePathFromCall:linphone_call_log_get_from_address(linphone_call_get_call_log(call))]; + LOGD(@"record file path: %@\n", writablePath); - linphone_call_params_set_record_file(lcallParams, [writablePath cStringUsingEncoding:NSUTF8StringEncoding]); + linphone_call_params_set_record_file(lcallParams, [writablePath cStringUsingEncoding:NSUTF8StringEncoding]); linphone_call_accept_with_params(call, lcallParams); linphone_call_params_unref(lcallParams); @@ -2722,12 +2473,12 @@ static int comp_call_state_paused(const LinphoneCall *call, const void *param) { if ([callCenter currentCalls] != nil && floor(NSFoundationVersionNumber) <= NSFoundationVersionNumber_iOS_9_x_Max) { LOGE(@"GSM call in progress, cancelling outgoing SIP call request"); UIAlertController *errView = [UIAlertController alertControllerWithTitle:NSLocalizedString(@"Cannot make call", nil) - message:NSLocalizedString(@"Please terminate GSM call first.", nil) - preferredStyle:UIAlertControllerStyleAlert]; + message:NSLocalizedString(@"Please terminate GSM call first.", nil) + preferredStyle:UIAlertControllerStyleAlert]; UIAlertAction* defaultAction = [UIAlertAction actionWithTitle:NSLocalizedString(@"OK", nil) - style:UIAlertActionStyleDefault - handler:^(UIAlertAction * action) {}]; + style:UIAlertActionStyleDefault + handler:^(UIAlertAction * action) {}]; [errView addAction:defaultAction]; [PhoneMainView.instance presentViewController:errView animated:YES completion:nil]; @@ -2737,13 +2488,13 @@ static int comp_call_state_paused(const LinphoneCall *call, const void *param) { // Then check that the supplied address is valid if (!iaddr) { UIAlertController *errView = [UIAlertController alertControllerWithTitle:NSLocalizedString(@"Invalid SIP address", nil) - message:NSLocalizedString(@"Either configure a SIP proxy server from settings prior to place a " - @"call or use a valid SIP address (I.E sip:john@example.net)", nil) - preferredStyle:UIAlertControllerStyleAlert]; + message:NSLocalizedString(@"Either configure a SIP proxy server from settings prior to place a " + @"call or use a valid SIP address (I.E sip:john@example.net)", nil) + preferredStyle:UIAlertControllerStyleAlert]; UIAlertAction* defaultAction = [UIAlertAction actionWithTitle:NSLocalizedString(@"OK", nil) - style:UIAlertActionStyleDefault - handler:^(UIAlertAction * action) {}]; + style:UIAlertActionStyleDefault + handler:^(UIAlertAction * action) {}]; [errView addAction:defaultAction]; [PhoneMainView.instance presentViewController:errView animated:YES completion:nil]; @@ -2751,8 +2502,8 @@ static int comp_call_state_paused(const LinphoneCall *call, const void *param) { } if (linphone_core_get_calls_nb(theLinphoneCore) < 1 && - floor(NSFoundationVersionNumber) > NSFoundationVersionNumber_iOS_9_x_Max && - self.providerDelegate.callKitCalls < 1) { + floor(NSFoundationVersionNumber) > NSFoundationVersionNumber_iOS_9_x_Max && + self.providerDelegate.callKitCalls < 1) { self.providerDelegate.callKitCalls++; NSUUID *uuid = [NSUUID UUID]; [LinphoneManager.instance.providerDelegate.uuids setObject:uuid forKey:@""]; @@ -2763,68 +2514,68 @@ static int comp_call_state_paused(const LinphoneCall *call, const void *param) { CXStartCallAction *act = [[CXStartCallAction alloc] initWithCallUUID:uuid handle:handle]; CXTransaction *tr = [[CXTransaction alloc] initWithAction:act]; [LinphoneManager.instance.providerDelegate.controller requestTransaction:tr - completion:^(NSError *err){ - }]; + completion:^(NSError *err){ + }]; } else { [self doCall:iaddr]; } } - (BOOL)doCall:(const LinphoneAddress *)iaddr { - return [self doCallWithSas:iaddr isSas:false]; + return [self doCallWithSas:iaddr isSas:false]; } - (BOOL)doCallWithSas:(const LinphoneAddress *)iaddr isSas:(BOOL)isSas { - LinphoneAddress *addr = linphone_address_clone(iaddr); - NSString *displayName = [FastAddressBook displayNameForAddress:addr]; + LinphoneAddress *addr = linphone_address_clone(iaddr); + NSString *displayName = [FastAddressBook displayNameForAddress:addr]; - // Finally we can make the call - LinphoneCallParams *lcallParams = linphone_core_create_call_params(theLinphoneCore, NULL); - if ([self lpConfigBoolForKey:@"edge_opt_preference"] && (self.network == network_2g)) { - LOGI(@"Enabling low bandwidth mode"); - linphone_call_params_enable_low_bandwidth(lcallParams, YES); - } + // Finally we can make the call + LinphoneCallParams *lcallParams = linphone_core_create_call_params(theLinphoneCore, NULL); + if ([self lpConfigBoolForKey:@"edge_opt_preference"] && (self.network == network_2g)) { + LOGI(@"Enabling low bandwidth mode"); + linphone_call_params_enable_low_bandwidth(lcallParams, YES); + } - if (displayName != nil) { - linphone_address_set_display_name(addr, displayName.UTF8String); - } - if ([LinphoneManager.instance lpConfigBoolForKey:@"override_domain_with_default_one"]) { - linphone_address_set_domain( - addr, [[LinphoneManager.instance lpConfigStringForKey:@"domain" inSection:@"assistant"] UTF8String]); - } + if (displayName != nil) { + linphone_address_set_display_name(addr, displayName.UTF8String); + } + if ([LinphoneManager.instance lpConfigBoolForKey:@"override_domain_with_default_one"]) { + linphone_address_set_domain( + addr, [[LinphoneManager.instance lpConfigStringForKey:@"domain" inSection:@"assistant"] UTF8String]); + } - LinphoneCall *call; - if (LinphoneManager.instance.nextCallIsTransfer) { - char *caddr = linphone_address_as_string(addr); - call = linphone_core_get_current_call(theLinphoneCore); - linphone_call_transfer(call, caddr); - LinphoneManager.instance.nextCallIsTransfer = NO; - ms_free(caddr); - } else { - //We set the record file name here because we can't do it after the call is started. - NSString *writablePath = [LinphoneUtils recordingFilePathFromCall:addr]; - LOGD(@"record file path: %@\n", writablePath); - linphone_call_params_set_record_file(lcallParams, [writablePath cStringUsingEncoding:NSUTF8StringEncoding]); - if (isSas) - linphone_call_params_set_media_encryption(lcallParams, LinphoneMediaEncryptionZRTP); - call = linphone_core_invite_address_with_params(theLinphoneCore, addr, lcallParams); - if (call) { - // The LinphoneCallAppData object should be set on call creation with callback - // - (void)onCall:StateChanged:withMessage:. If not, we are in big trouble and expect it to crash - // We are NOT responsible for creating the AppData. - LinphoneCallAppData *data = (__bridge LinphoneCallAppData *)linphone_call_get_user_data(call); - if (data == nil) { - LOGE(@"New call instanciated but app data was not set. Expect it to crash."); - /* will be used later to notify user if video was not activated because of the linphone core*/ - } else { - data->videoRequested = linphone_call_params_video_enabled(lcallParams); - } - } - } - linphone_address_destroy(addr); - linphone_call_params_destroy(lcallParams); + LinphoneCall *call; + if (LinphoneManager.instance.nextCallIsTransfer) { + char *caddr = linphone_address_as_string(addr); + call = linphone_core_get_current_call(theLinphoneCore); + linphone_call_transfer(call, caddr); + LinphoneManager.instance.nextCallIsTransfer = NO; + ms_free(caddr); + } else { + //We set the record file name here because we can't do it after the call is started. + NSString *writablePath = [LinphoneUtils recordingFilePathFromCall:addr]; + LOGD(@"record file path: %@\n", writablePath); + linphone_call_params_set_record_file(lcallParams, [writablePath cStringUsingEncoding:NSUTF8StringEncoding]); + if (isSas) + linphone_call_params_set_media_encryption(lcallParams, LinphoneMediaEncryptionZRTP); + call = linphone_core_invite_address_with_params(theLinphoneCore, addr, lcallParams); + if (call) { + // The LinphoneCallAppData object should be set on call creation with callback + // - (void)onCall:StateChanged:withMessage:. If not, we are in big trouble and expect it to crash + // We are NOT responsible for creating the AppData. + LinphoneCallAppData *data = (__bridge LinphoneCallAppData *)linphone_call_get_user_data(call); + if (data == nil) { + LOGE(@"New call instanciated but app data was not set. Expect it to crash."); + /* will be used later to notify user if video was not activated because of the linphone core*/ + } else { + data->videoRequested = linphone_call_params_video_enabled(lcallParams); + } + } + } + linphone_address_destroy(addr); + linphone_call_params_destroy(lcallParams); - return TRUE; + return TRUE; } #pragma mark - Property Functions @@ -2858,18 +2609,18 @@ static int comp_call_state_paused(const LinphoneCall *call, const void *param) { for (int i = 0; i < [tokenData length]; ++i) { [tokenString appendFormat:@"%02X", (unsigned int)tokenBuffer[i]]; } -// NSLocalizedString(@"IC_MSG", nil); // Fake for genstrings -// NSLocalizedString(@"IM_MSG", nil); // Fake for genstrings -// NSLocalizedString(@"IM_FULLMSG", nil); // Fake for genstrings + // NSLocalizedString(@"IC_MSG", nil); // Fake for genstrings + // NSLocalizedString(@"IM_MSG", nil); // Fake for genstrings + // NSLocalizedString(@"IM_FULLMSG", nil); // Fake for genstrings #ifdef DEBUG #define APPMODE_SUFFIX @"dev" #else #define APPMODE_SUFFIX @"prod" #endif NSString *ring = - ([LinphoneManager bundleFile:[self lpConfigStringForKey:@"local_ring" inSection:@"sound"].lastPathComponent] - ?: [LinphoneManager bundleFile:@"notes_of_the_optimistic.caf"]) - .lastPathComponent; + ([LinphoneManager bundleFile:[self lpConfigStringForKey:@"local_ring" inSection:@"sound"].lastPathComponent] + ?: [LinphoneManager bundleFile:@"notes_of_the_optimistic.caf"]) + .lastPathComponent; NSString *timeout; if (floor(NSFoundationVersionNumber) > NSFoundationVersionNumber_iOS_9_x_Max) { @@ -2879,12 +2630,12 @@ static int comp_call_state_paused(const LinphoneCall *call, const void *param) { } NSString *params = [NSString - stringWithFormat:@"app-id=%@.voip.%@;pn-type=apple;pn-tok=%@;pn-msg-str=IM_MSG;pn-call-str=IC_MSG;pn-" - @"call-snd=%@;pn-msg-snd=msg.caf%@;pn-silent=1", - [[NSBundle mainBundle] bundleIdentifier], APPMODE_SUFFIX, tokenString, ring, timeout]; + stringWithFormat:@"app-id=%@.voip.%@;pn-type=apple;pn-tok=%@;pn-msg-str=IM_MSG;pn-call-str=IC_MSG;pn-" + @"call-snd=%@;pn-msg-snd=msg.caf%@;pn-silent=1", + [[NSBundle mainBundle] bundleIdentifier], APPMODE_SUFFIX, tokenString, ring, timeout]; LOGI(@"Proxy config %s configured for push notifications with contact: %@", - linphone_proxy_config_get_identity(proxyCfg), params); + linphone_proxy_config_get_identity(proxyCfg), params); linphone_proxy_config_set_contact_uri_parameters(proxyCfg, [params UTF8String]); linphone_proxy_config_set_contact_parameters(proxyCfg, NULL); } else { @@ -2899,14 +2650,14 @@ static int comp_call_state_paused(const LinphoneCall *call, const void *param) { #pragma mark - Misc Functions + (PHFetchResult *)getPHAssets:(NSString *)key { - PHFetchResult *assets; - if ([key hasPrefix:@"assets-library"]) { - // compability with previous linphone version - assets = [PHAsset fetchAssetsWithALAssetURLs:@[[NSURL URLWithString:key]] options:nil]; - } else { - assets = [PHAsset fetchAssetsWithLocalIdentifiers:[NSArray arrayWithObject:key] options:nil]; - } - return assets; + PHFetchResult *assets; + if ([key hasPrefix:@"assets-library"]) { + // compability with previous linphone version + assets = [PHAsset fetchAssetsWithALAssetURLs:@[[NSURL URLWithString:key]] options:nil]; + } else { + assets = [PHAsset fetchAssetsWithLocalIdentifiers:[NSArray arrayWithObject:key] options:nil]; + } + return assets; } + (NSString *)bundleFile:(NSString *)file { @@ -2914,45 +2665,45 @@ static int comp_call_state_paused(const LinphoneCall *call, const void *param) { } + (NSString *)documentFile:(NSString *)file { - NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES); - NSString *documentsPath = [paths objectAtIndex:0]; - return [documentsPath stringByAppendingPathComponent:file]; + NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES); + NSString *documentsPath = [paths objectAtIndex:0]; + return [documentsPath stringByAppendingPathComponent:file]; } + (NSString *)preferenceFile:(NSString *)file { - NSArray *paths = NSSearchPathForDirectoriesInDomains(NSLibraryDirectory, NSUserDomainMask, YES); - NSString *writablePath = [paths objectAtIndex:0]; - NSString *fullPath = [writablePath stringByAppendingString:@"/Preferences/linphone/"]; - if (![[NSFileManager defaultManager] fileExistsAtPath:fullPath]) { - NSError *error; - LOGI(@"Preference path %@ does not exist, creating it.",fullPath); - if (![[NSFileManager defaultManager] createDirectoryAtPath:fullPath - withIntermediateDirectories:YES - attributes:nil - error:&error]) { - LOGE(@"Create preference path directory error: %@",error.description); - } - } + NSArray *paths = NSSearchPathForDirectoriesInDomains(NSLibraryDirectory, NSUserDomainMask, YES); + NSString *writablePath = [paths objectAtIndex:0]; + NSString *fullPath = [writablePath stringByAppendingString:@"/Preferences/linphone/"]; + if (![[NSFileManager defaultManager] fileExistsAtPath:fullPath]) { + NSError *error; + LOGI(@"Preference path %@ does not exist, creating it.",fullPath); + if (![[NSFileManager defaultManager] createDirectoryAtPath:fullPath + withIntermediateDirectories:YES + attributes:nil + error:&error]) { + LOGE(@"Create preference path directory error: %@",error.description); + } + } - return [fullPath stringByAppendingPathComponent:file]; + return [fullPath stringByAppendingPathComponent:file]; } + (NSString *)dataFile:(NSString *)file { - NSArray *paths = NSSearchPathForDirectoriesInDomains(NSApplicationSupportDirectory, NSUserDomainMask, YES); - NSString *writablePath = [paths objectAtIndex:0]; - NSString *fullPath = [writablePath stringByAppendingString:@"/linphone/"]; - if (![[NSFileManager defaultManager] fileExistsAtPath:fullPath]) { - NSError *error; - LOGI(@"Data path %@ does not exist, creating it.",fullPath); - if (![[NSFileManager defaultManager] createDirectoryAtPath:fullPath - withIntermediateDirectories:YES - attributes:nil - error:&error]) { - LOGE(@"Create data path directory error: %@",error.description); - } - } + NSArray *paths = NSSearchPathForDirectoriesInDomains(NSApplicationSupportDirectory, NSUserDomainMask, YES); + NSString *writablePath = [paths objectAtIndex:0]; + NSString *fullPath = [writablePath stringByAppendingString:@"/linphone/"]; + if (![[NSFileManager defaultManager] fileExistsAtPath:fullPath]) { + NSError *error; + LOGI(@"Data path %@ does not exist, creating it.",fullPath); + if (![[NSFileManager defaultManager] createDirectoryAtPath:fullPath + withIntermediateDirectories:YES + attributes:nil + error:&error]) { + LOGE(@"Create data path directory error: %@",error.description); + } + } - return [fullPath stringByAppendingPathComponent:file]; + return [fullPath stringByAppendingPathComponent:file]; } + (NSString *)cacheDirectory { @@ -2963,9 +2714,9 @@ static int comp_call_state_paused(const LinphoneCall *call, const void *param) { // cache directory must be created if not existing if (![[NSFileManager defaultManager] fileExistsAtPath:cachePath isDirectory:&isDir] && isDir == NO) { [[NSFileManager defaultManager] createDirectoryAtPath:cachePath - withIntermediateDirectories:NO - attributes:nil - error:&error]; + withIntermediateDirectories:NO + attributes:nil + error:&error]; } return cachePath; } @@ -3016,8 +2767,8 @@ static int comp_call_state_paused(const LinphoneCall *call, const void *param) { - (void)configureVbrCodecs { PayloadType *pt; int bitrate = lp_config_get_int( - _configDb, "audio", "codec_bitrate_limit", - kLinphoneAudioVbrCodecDefaultBitrate); /*default value is in linphonerc or linphonerc-factory*/ + _configDb, "audio", "codec_bitrate_limit", + kLinphoneAudioVbrCodecDefaultBitrate); /*default value is in linphonerc or linphonerc-factory*/ const MSList *audio_codecs = linphone_core_get_audio_codecs(theLinphoneCore); const MSList *codec = audio_codecs; while (codec) { @@ -3039,8 +2790,8 @@ static int comp_call_state_paused(const LinphoneCall *call, const void *param) { if (appData) { NSDictionary *appDataDict = [NSJSONSerialization JSONObjectWithData:[NSData dataWithBytes:appData length:strlen(appData)] - options:0 - error:nil]; + options:0 + error:nil]; value = [appDataDict objectForKey:key]; } return value; @@ -3050,9 +2801,9 @@ static int comp_call_state_paused(const LinphoneCall *call, const void *param) { NSMutableDictionary *appDataDict = [NSMutableDictionary dictionary]; const char *appData = linphone_chat_message_get_appdata(msg); if (appData) { - appDataDict = [NSJSONSerialization JSONObjectWithData:[NSData dataWithBytes:appData length:strlen(appData)] - options:NSJSONReadingMutableContainers - error:nil]; + appDataDict = [NSJSONSerialization JSONObjectWithData:[NSData dataWithBytes:appData length:strlen(appData)] + options:NSJSONReadingMutableContainers + error:nil]; } [appDataDict setValue:value forKey:key]; @@ -3151,10 +2902,10 @@ static int comp_call_state_paused(const LinphoneCall *call, const void *param) { __block __weak LinphoneManager *weakSelf = self; __block __weak CTCallCenter *weakCCenter = mCallCenter; mCallCenter.callEventHandler = ^(CTCall *call) { - // post on main thread - [weakSelf performSelectorOnMainThread:@selector(handleGSMCallInteration:) - withObject:weakCCenter - waitUntilDone:YES]; + // post on main thread + [weakSelf performSelectorOnMainThread:@selector(handleGSMCallInteration:) + withObject:weakCCenter + waitUntilDone:YES]; }; } @@ -3184,7 +2935,7 @@ static int comp_call_state_paused(const LinphoneCall *call, const void *param) { LinphoneProxyConfig *proxy_cfg = linphone_core_get_default_proxy_config(theLinphoneCore); if (proxy_cfg && linphone_proxy_config_get_addr(proxy_cfg)) { return [NSString stringWithCString:linphone_proxy_config_get_domain(proxy_cfg) - encoding:[NSString defaultCStringEncoding]]; + encoding:[NSString defaultCStringEncoding]]; } } return filter; @@ -3228,41 +2979,41 @@ static int comp_call_state_paused(const LinphoneCall *call, const void *param) { } - (void)checkNewVersion { - if (!CHECK_VERSION_UPDATE) - return; - if (theLinphoneCore == nil) - return; - NSString *curVersion = [[NSBundle mainBundle] objectForInfoDictionaryKey:@"CFBundleShortVersionString"]; - const char *curVersionCString = [curVersion cStringUsingEncoding:NSUTF8StringEncoding]; - linphone_core_check_for_update(theLinphoneCore, curVersionCString); + if (!CHECK_VERSION_UPDATE) + return; + if (theLinphoneCore == nil) + return; + NSString *curVersion = [[NSBundle mainBundle] objectForInfoDictionaryKey:@"CFBundleShortVersionString"]; + const char *curVersionCString = [curVersion cStringUsingEncoding:NSUTF8StringEncoding]; + linphone_core_check_for_update(theLinphoneCore, curVersionCString); } - (void)loadAvatar { - NSString *assetId = [self lpConfigStringForKey:@"avatar"]; - __block UIImage *ret = nil; - if (assetId) { - PHFetchResult *assets = [PHAsset fetchAssetsWithLocalIdentifiers:[NSArray arrayWithObject:assetId] options:nil]; - if (![assets firstObject]) { - LOGE(@"Can't fetch avatar image."); - } - PHAsset *asset = [assets firstObject]; - // load avatar synchronously so that we can return UIIMage* directly - since we are - // only using thumbnail, it must be pretty fast to fetch even without cache. - PHImageRequestOptions *options = [[PHImageRequestOptions alloc] init]; - options.synchronous = TRUE; - [[PHImageManager defaultManager] requestImageForAsset:asset targetSize:PHImageManagerMaximumSize contentMode:PHImageContentModeDefault options:options - resultHandler:^(UIImage *image, NSDictionary * info) { - if (image) - ret = [UIImage UIImageThumbnail:image thumbSize:150]; - else - LOGE(@"Can't read avatar"); - }]; - } + NSString *assetId = [self lpConfigStringForKey:@"avatar"]; + __block UIImage *ret = nil; + if (assetId) { + PHFetchResult *assets = [PHAsset fetchAssetsWithLocalIdentifiers:[NSArray arrayWithObject:assetId] options:nil]; + if (![assets firstObject]) { + LOGE(@"Can't fetch avatar image."); + } + PHAsset *asset = [assets firstObject]; + // load avatar synchronously so that we can return UIIMage* directly - since we are + // only using thumbnail, it must be pretty fast to fetch even without cache. + PHImageRequestOptions *options = [[PHImageRequestOptions alloc] init]; + options.synchronous = TRUE; + [[PHImageManager defaultManager] requestImageForAsset:asset targetSize:PHImageManagerMaximumSize contentMode:PHImageContentModeDefault options:options + resultHandler:^(UIImage *image, NSDictionary * info) { + if (image) + ret = [UIImage UIImageThumbnail:image thumbSize:150]; + else + LOGE(@"Can't read avatar"); + }]; + } - if (!ret) { - ret = [UIImage imageNamed:@"avatar.png"]; - } - _avatar = ret; + if (!ret) { + ret = [UIImage imageNamed:@"avatar.png"]; + } + _avatar = ret; } @end