From e18825141e46be27cb3adc788755039b9f9638ea Mon Sep 17 00:00:00 2001 From: giomfo Date: Mon, 14 Oct 2019 19:48:53 +0200 Subject: [PATCH 01/25] Bug Fix: Room members who left are listed with the actual members (#734) https://github.com/vector-im/riot-ios/issues/2737 --- CHANGES.rst | 6 ++++++ MatrixSDK/Data/MXEventTimeline.m | 18 ++++++++++++++++-- 2 files changed, 22 insertions(+), 2 deletions(-) diff --git a/CHANGES.rst b/CHANGES.rst index 8732d4b0b8..03ef775929 100644 --- a/CHANGES.rst +++ b/CHANGES.rst @@ -1,3 +1,9 @@ +Changes in Matrix iOS SDK in 0.xx.xx (2019-xx-xx) +=============================================== + +Bug fix: + * Room members who left are listed with the actual members (vector-im/riot-ios#2737). + Changes in Matrix iOS SDK in 0.14.0 (2019-10-11) =============================================== diff --git a/MatrixSDK/Data/MXEventTimeline.m b/MatrixSDK/Data/MXEventTimeline.m index 59c0706be6..d5746cafc2 100644 --- a/MatrixSDK/Data/MXEventTimeline.m +++ b/MatrixSDK/Data/MXEventTimeline.m @@ -522,8 +522,22 @@ - (void)handlePaginationResponse:(MXPaginationResponse*)paginatedResponse direct { if (direction == MXTimelineDirectionBackwards) { - // Enrich the timeline root state with the additional state events observed during back pagination - [self handleStateEvents:paginatedResponse.state direction:MXTimelineDirectionForwards]; + // Enrich the timeline root state with the additional state events observed during back pagination. + // Check that it is a member state event (it should always be the case) and + // that this memeber is not already known in our live room state + NSMutableArray *selectedStateEvents = [NSMutableArray array]; + for (MXEvent *stateEvent in paginatedResponse.state) + { + if ((stateEvent.eventType == MXEventTypeRoomMember) + && ![_state.members memberWithUserId: stateEvent.stateKey]) { + [selectedStateEvents addObject:stateEvent]; + } + } + + if (selectedStateEvents.count) + { + [self handleStateEvents:selectedStateEvents direction:MXTimelineDirectionForwards]; + } } // Enrich intermediate room state while paginating From 9f77ce8e7892d016d64c1aecaf6d16f5fa707461 Mon Sep 17 00:00:00 2001 From: manuroe Date: Thu, 24 Oct 2019 09:35:50 +0200 Subject: [PATCH 02/25] MX3PidAddManager: Add User-Interactive Auth to /account/3pid/add vector-im/riot-ios#2744 --- CHANGES.rst | 3 + MatrixSDK/Contrib/Swift/MXRestClient.swift | 5 +- .../Swift/ThreePidAdd/MX3PidAddManager.swift | 15 ++ MatrixSDK/MXRestClient.h | 2 + MatrixSDK/MXRestClient.m | 10 +- MatrixSDK/ThreePidAdd/MX3PidAddManager.h | 35 ++++ MatrixSDK/ThreePidAdd/MX3PidAddManager.m | 149 +++++++++++++++++- MatrixSDK/Utils/MXHTTPClient.m | 2 +- 8 files changed, 214 insertions(+), 7 deletions(-) diff --git a/CHANGES.rst b/CHANGES.rst index 03ef775929..64ae80c914 100644 --- a/CHANGES.rst +++ b/CHANGES.rst @@ -1,6 +1,9 @@ Changes in Matrix iOS SDK in 0.xx.xx (2019-xx-xx) =============================================== +Improvements: + * MX3PidAddManager: Add User-Interactive Auth to /account/3pid/add (vector-im/riot-ios#2744). + Bug fix: * Room members who left are listed with the actual members (vector-im/riot-ios#2737). diff --git a/MatrixSDK/Contrib/Swift/MXRestClient.swift b/MatrixSDK/Contrib/Swift/MXRestClient.swift index 0c7fabac27..bbdb6368c3 100644 --- a/MatrixSDK/Contrib/Swift/MXRestClient.swift +++ b/MatrixSDK/Contrib/Swift/MXRestClient.swift @@ -1381,13 +1381,14 @@ public extension MXRestClient { - parameters: - sid: the session id provided during the 3PID validation session. - clientSecret: the same secret key used in the validation session. + - authParameters: The additional authentication information for the user-interactive authentication API. - completion: A block object called when the operation completes. - response: Indicates whether the operation was successful. - returns: a `MXHTTPOperation` instance. */ - @nonobjc @discardableResult func addThirdPartyIdentifierOnly(withSessionId sid: String, clientSecret: String, completion: @escaping (_ response: MXResponse) -> Void) -> MXHTTPOperation { - return __add3PIDOnly(withSessionId: sid, clientSecret: clientSecret, success: currySuccess(completion), failure: curryFailure(completion)) + @nonobjc @discardableResult func addThirdPartyIdentifierOnly(withSessionId sid: String, clientSecret: String, authParameters: [String: Any]?, completion: @escaping (_ response: MXResponse) -> Void) -> MXHTTPOperation { + return __add3PIDOnly(withSessionId: sid, clientSecret: clientSecret, authParams: authParameters, success: currySuccess(completion), failure: curryFailure(completion)) } /** diff --git a/MatrixSDK/Contrib/Swift/ThreePidAdd/MX3PidAddManager.swift b/MatrixSDK/Contrib/Swift/ThreePidAdd/MX3PidAddManager.swift index 89b02a30e5..b50422f643 100644 --- a/MatrixSDK/Contrib/Swift/ThreePidAdd/MX3PidAddManager.swift +++ b/MatrixSDK/Contrib/Swift/ThreePidAdd/MX3PidAddManager.swift @@ -36,6 +36,13 @@ public extension MX3PidAddManager { return __tryFinaliseAddEmailSession(session, success: currySuccess(completion), failure: curryFailure(completion)) } + @nonobjc func tryFinaliseAddEmailSession(_ session: MX3PidAddSession, password: String?, completion: @escaping (_ response: MXResponse) -> Void) -> Void { + return __tryFinaliseAddEmailSession(session, withPassword: password, success: currySuccess(completion), failure: curryFailure(completion)) + } + + @nonobjc func tryFinaliseAddEmailSession(_ session: MX3PidAddSession, authParams: [String: Any]?, completion: @escaping (_ response: MXResponse) -> Void) -> Void { + return __tryFinaliseAddEmailSession(session, authParams: authParams, success: currySuccess(completion), failure: curryFailure(completion)) + } // MARK: - Add MSISDN @nonobjc @discardableResult func startAddPhoneNumberSession(_ phoneNumber: String, countryCode: String?, completion: @escaping (_ response: MXResponse) -> Void) -> MX3PidAddSession { @@ -46,6 +53,14 @@ public extension MX3PidAddManager { return __finaliseAddPhoneNumber(session, withToken: token, success: currySuccess(completion), failure: curryFailure(completion)) } + @nonobjc func finaliseAddPhoneNumberSession(_ session: MX3PidAddSession, token: String, password: String?, completion: @escaping (_ response: MXResponse) -> Void) -> Void { + return __finaliseAddPhoneNumber(session, withToken: token, password: password, success: currySuccess(completion), failure: curryFailure(completion)) + } + + @nonobjc func finaliseAddPhoneNumberSession(_ session: MX3PidAddSession, token: String, authParams: [String: Any]?, completion: @escaping (_ response: MXResponse) -> Void) -> Void { + return __finaliseAddPhoneNumber(session, withToken: token, authParams: authParams, success: currySuccess(completion), failure: curryFailure(completion)) + } + // MARK: - Bind Email @nonobjc @discardableResult func startIdentityServerSession(withEmail email: String, bind: Bool, completion: @escaping (_ response: MXResponse) -> Void) -> MX3PidAddSession { diff --git a/MatrixSDK/MXRestClient.h b/MatrixSDK/MXRestClient.h index f4d5b0e71f..5454c38ab8 100644 --- a/MatrixSDK/MXRestClient.h +++ b/MatrixSDK/MXRestClient.h @@ -1606,6 +1606,7 @@ typedef MXHTTPOperation* (^MXRestClientIdentityServerAccessTokenHandler)(void (^ @param sid the session id provided during the 3PID validation session. @param clientSecret the same secret key used in the validation session. + @param authParameters The additional authentication information for the user-interactive authentication API. @param success A block object called when the operation succeeds. @param failure A block object called when the operation fails. @@ -1614,6 +1615,7 @@ typedef MXHTTPOperation* (^MXRestClientIdentityServerAccessTokenHandler)(void (^ */ - (MXHTTPOperation*)add3PIDOnlyWithSessionId:(NSString*)sid clientSecret:(NSString*)clientSecret + authParams:(NSDictionary*)authParameters success:(void (^)(void))success failure:(void (^)(NSError *error))failure NS_REFINED_FOR_SWIFT; diff --git a/MatrixSDK/MXRestClient.m b/MatrixSDK/MXRestClient.m index b94358ae48..62924970a1 100644 --- a/MatrixSDK/MXRestClient.m +++ b/MatrixSDK/MXRestClient.m @@ -2991,15 +2991,21 @@ - (MXHTTPOperation*)add3PID:(NSString*)sid - (MXHTTPOperation*)add3PIDOnlyWithSessionId:(NSString*)sid clientSecret:(NSString*)clientSecret + authParams:(NSDictionary*)authParameters success:(void (^)(void))success failure:(void (^)(NSError *error))failure { NSString *path = [NSString stringWithFormat:@"%@/account/3pid/add", kMXAPIPrefixPathUnstable]; - NSDictionary *parameters = @{ + NSMutableDictionary *parameters = [@{ @"sid": sid, @"client_secret": clientSecret - }; + } mutableCopy]; + + if (authParameters) + { + parameters[@"auth"] = authParameters; + } MXWeakify(self); return [httpClient requestWithMethod:@"POST" diff --git a/MatrixSDK/ThreePidAdd/MX3PidAddManager.h b/MatrixSDK/ThreePidAdd/MX3PidAddManager.h index cdf333f63c..d9ff1bf740 100644 --- a/MatrixSDK/ThreePidAdd/MX3PidAddManager.h +++ b/MatrixSDK/ThreePidAdd/MX3PidAddManager.h @@ -59,6 +59,20 @@ NS_ERROR_ENUM(MX3PidAddManagerErrorDomain) - (void)cancel3PidAddSession:(MX3PidAddSession*)threePidAddSession NS_REFINED_FOR_SWIFT; +#pragma mark - Add 3rd-Party Identifier + +/** + Get the authentication flow required to add a 3rd party id to the user homeserver account. + + @param success A block object called when the operation succeeds. If the returned flows is nil, no auth is required. + @param failure A block object called when the operation fails. + + @return a MXHTTPOperation instance. + */ +- (MXHTTPOperation*)authenticationFlowForAdd3PidWithSuccess:(void (^)(NSArray * _Nullable flows))success + failure:(void (^)(NSError * _Nonnull))failure; + + #pragma mark - Add Email /** @@ -95,6 +109,15 @@ NS_ERROR_ENUM(MX3PidAddManagerErrorDomain) success:(void (^)(void))success failure:(void (^)(NSError * _Nonnull))failure NS_REFINED_FOR_SWIFT; +- (void)tryFinaliseAddEmailSession:(MX3PidAddSession*)threePidAddSession + withPassword:(nullable NSString*)password + success:(void (^)(void))success + failure:(void (^)(NSError * _Nonnull))failure NS_REFINED_FOR_SWIFT; + +- (void)tryFinaliseAddEmailSession:(MX3PidAddSession*)threePidAddSession + authParams:(nullable NSDictionary*)authParams + success:(void (^)(void))success + failure:(void (^)(NSError * _Nonnull))failure NS_REFINED_FOR_SWIFT; #pragma mark - Add MSISDN @@ -131,6 +154,18 @@ NS_ERROR_ENUM(MX3PidAddManagerErrorDomain) success:(void (^)(void))success failure:(void (^)(NSError * _Nonnull))failure NS_REFINED_FOR_SWIFT; +- (void)finaliseAddPhoneNumberSession:(MX3PidAddSession*)threePidAddSession + withToken:(NSString*)token + password:(nullable NSString*)password + success:(void (^)(void))success + failure:(void (^)(NSError * _Nonnull))failure NS_REFINED_FOR_SWIFT; + +- (void)finaliseAddPhoneNumberSession:(MX3PidAddSession*)threePidAddSession + withToken:(NSString*)token + authParams:(nullable NSDictionary*)authParams + success:(void (^)(void))success + failure:(void (^)(NSError * _Nonnull))failure NS_REFINED_FOR_SWIFT; + #pragma mark - Bind Email diff --git a/MatrixSDK/ThreePidAdd/MX3PidAddManager.m b/MatrixSDK/ThreePidAdd/MX3PidAddManager.m index b1c18e77c9..b32980d91f 100644 --- a/MatrixSDK/ThreePidAdd/MX3PidAddManager.m +++ b/MatrixSDK/ThreePidAdd/MX3PidAddManager.m @@ -51,6 +51,50 @@ - (void)cancel3PidAddSession:(MX3PidAddSession*)threePidAddSession } + +#pragma mark - Add 3rd-Party Identifier + +- (MXHTTPOperation*)authenticationFlowForAdd3PidWithSuccess:(void (^)(NSArray * _Nullable flows))success + failure:(void (^)(NSError * _Nonnull))failure +{ + // Trigger a random request to the API + // If authentication is required, it will provide the flow in the error response + return [self->mxSession.matrixRestClient add3PIDOnlyWithSessionId:@"" clientSecret:@"" authParams:nil success:^{ + // This should not happen + success(nil); + } failure:^(NSError *error) { + NSHTTPURLResponse *urlResponse = [MXHTTPOperation urlResponseFromError:error]; + if (urlResponse) + { + switch (urlResponse.statusCode) + { + case 400: + // No required authentication + success(nil); + break; + + case 401: + { + // Extract authentication flows + MXAuthenticationSession *authSession; + MXJSONModelSetMXJSONModel(authSession, MXAuthenticationSession, error.userInfo[MXHTTPClientErrorResponseDataKey]); + success(authSession.flows); + break; + } + + default: + failure(error); + break; + } + } + else + { + failure(error); + } + }]; +} + + #pragma mark - Add Email - (MX3PidAddSession*)startAddEmailSessionWithEmail:(NSString*)email @@ -94,6 +138,37 @@ - (MX3PidAddSession*)startAddEmailSessionWithEmail:(NSString*)email - (void)tryFinaliseAddEmailSession:(MX3PidAddSession*)threePidAddSession success:(void (^)(void))success failure:(void (^)(NSError * _Nonnull))failure +{ + [self tryFinaliseAddEmailSession:threePidAddSession authParams:nil success:success failure:failure]; +} + +- (void)tryFinaliseAddEmailSession:(MX3PidAddSession*)threePidAddSession + withPassword:(nullable NSString*)password + success:(void (^)(void))success + failure:(void (^)(NSError * _Nonnull))failure +{ + // Make a first request to start user-interactive authentication + MXWeakify(self); + [self tryFinaliseAddEmailSession:threePidAddSession authParams:nil success:success failure:^(NSError * _Nonnull error) { + MXStrongifyAndReturnIfNil(self); + + NSDictionary *authParams = [self authParamsFromError:error andPassword:password]; + if (authParams) + { + // Retry but authenticated + [self tryFinaliseAddEmailSession:threePidAddSession authParams:authParams success:success failure:failure]; + } + else + { + failure(error); + } + }]; +} + +- (void)tryFinaliseAddEmailSession:(MX3PidAddSession*)threePidAddSession + authParams:(nullable NSDictionary*)authParams + success:(void (^)(void))success + failure:(void (^)(NSError * _Nonnull))failure { NSLog(@"[MX3PidAddManager] tryFinaliseAddEmailSession: threePid: %@", threePidAddSession); @@ -111,7 +186,7 @@ - (void)tryFinaliseAddEmailSession:(MX3PidAddSession*)threePidAddSession if (doesServerSupportSeparateAddAndBind) { // https://gist.github.com/jryans/839a09bf0c5a70e2f36ed990d50ed928#2b-adding-a-3pid-to-hs-account-after-registration-post-msc2290 - threePidAddSession.httpOperation = [mxSession.matrixRestClient add3PIDOnlyWithSessionId:threePidAddSession.sid clientSecret:threePidAddSession.clientSecret success:^{ + threePidAddSession.httpOperation = [mxSession.matrixRestClient add3PIDOnlyWithSessionId:threePidAddSession.sid clientSecret:threePidAddSession.clientSecret authParams:authParams success:^{ NSLog(@"[MX3PidAddManager] tryFinaliseAddEmailSession: DONE: threePid: %@", threePidAddSession); @@ -187,6 +262,39 @@ - (void)finaliseAddPhoneNumberSession:(MX3PidAddSession*)threePidAddSession withToken:(NSString*)token success:(void (^)(void))success failure:(void (^)(NSError * _Nonnull))failure +{ + [self finaliseAddPhoneNumberSession:threePidAddSession withToken:token authParams:nil success:success failure:failure]; +} + +- (void)finaliseAddPhoneNumberSession:(MX3PidAddSession*)threePidAddSession + withToken:(NSString*)token + password:(nullable NSString*)password + success:(void (^)(void))success + failure:(void (^)(NSError * _Nonnull))failure +{ + // Make a first request to start user-interactive authentication + MXWeakify(self); + [self finaliseAddPhoneNumberSession:threePidAddSession withToken:token authParams:nil success:success failure:^(NSError * _Nonnull error) { + MXStrongifyAndReturnIfNil(self); + + NSDictionary *authParams = [self authParamsFromError:error andPassword:password]; + if (authParams) + { + // Retry but authenticated + [self finaliseAddPhoneNumberSession:threePidAddSession withToken:token authParams:authParams success:success failure:failure]; + } + else + { + failure(error); + } + }]; +} + +- (void)finaliseAddPhoneNumberSession:(MX3PidAddSession*)threePidAddSession + withToken:(NSString*)token + authParams:(nullable NSDictionary*)authParams + success:(void (^)(void))success + failure:(void (^)(NSError * _Nonnull))failure { NSLog(@"[MX3PidAddManager] finaliseAddPhoneNumberSession: threePid: %@", threePidAddSession); @@ -209,7 +317,7 @@ - (void)finaliseAddPhoneNumberSession:(MX3PidAddSession*)threePidAddSession if (self->doesServerSupportSeparateAddAndBind) { // https://gist.github.com/jryans/839a09bf0c5a70e2f36ed990d50ed928#2b-adding-a-3pid-to-hs-account-after-registration-post-msc2290 - operation = [self->mxSession.matrixRestClient add3PIDOnlyWithSessionId:threePidAddSession.sid clientSecret:threePidAddSession.clientSecret success:^{ + operation = [self->mxSession.matrixRestClient add3PIDOnlyWithSessionId:threePidAddSession.sid clientSecret:threePidAddSession.clientSecret authParams:authParams success:^{ NSLog(@"[MX3PidAddManager] finaliseAddPhoneNumberSession: DONE: threePid: %@", threePidAddSession); @@ -483,6 +591,43 @@ - (MXHTTPOperation *)submitMsisdnTokenOtherUrl:(NSString *)url failure:failure]; } +/** + Build auth params when User-Interactive Authentication is required. + + The supported auth flow is "m.login.password". + + @param error the error got from the API request. + @param password the password to use. + @return the params to make an authenticated API request. + */ +- (NSDictionary*)authParamsFromError:(NSError*)error andPassword:(NSString*)password +{ + NSDictionary *authParams; + NSHTTPURLResponse *urlResponse = [MXHTTPOperation urlResponseFromError:error]; + + if (urlResponse && urlResponse.statusCode == 401) + { + + MXAuthenticationSession *authSession; + MXJSONModelSetMXJSONModel(authSession, MXAuthenticationSession, error.userInfo[MXHTTPClientErrorResponseDataKey]); + if (authSession && password) + { + NSString *userId = self->mxSession.matrixRestClient.credentials.userId; + authParams = @{ + @"type": kMXLoginFlowTypePassword, + @"identifier": @{ + @"type": kMXLoginIdentifierTypeUser, + @"user": userId + }, + @"password": password, + @"user": userId + }; + } + } + + return authParams; +} + #pragma mark - Bind to Identity Server - diff --git a/MatrixSDK/Utils/MXHTTPClient.m b/MatrixSDK/Utils/MXHTTPClient.m index 5f47310fc4..c729df3898 100644 --- a/MatrixSDK/Utils/MXHTTPClient.m +++ b/MatrixSDK/Utils/MXHTTPClient.m @@ -38,7 +38,7 @@ */ #define MXHTTPCLIENT_RETRY_JITTER_MS 3000 -NSString * const MXHTTPClientErrorResponseDataKey = @"com.matrixsdk.httpclient.error.response.data"; +NSString* const MXHTTPClientErrorResponseDataKey = @"com.matrixsdk.httpclient.error.response.data"; NSString* const kMXHTTPClientUserConsentNotGivenErrorNotification = @"kMXHTTPClientUserConsentNotGivenErrorNotification"; NSString* const kMXHTTPClientUserConsentNotGivenErrorNotificationConsentURIKey = @"kMXHTTPClientUserConsentNotGivenErrorNotificationConsentURIKey"; NSString* const kMXHTTPClientMatrixErrorNotification = @"kMXHTTPClientMatrixErrorNotification"; From 934869a69bd9e333ab4e65d99a5ccfa8d078eaba Mon Sep 17 00:00:00 2001 From: manuroe Date: Thu, 24 Oct 2019 11:41:52 +0200 Subject: [PATCH 03/25] MX3PidAddManager: Fix missing session in user interactive auth --- MatrixSDK/ThreePidAdd/MX3PidAddManager.m | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/MatrixSDK/ThreePidAdd/MX3PidAddManager.m b/MatrixSDK/ThreePidAdd/MX3PidAddManager.m index b32980d91f..231f910c27 100644 --- a/MatrixSDK/ThreePidAdd/MX3PidAddManager.m +++ b/MatrixSDK/ThreePidAdd/MX3PidAddManager.m @@ -600,7 +600,7 @@ - (MXHTTPOperation *)submitMsisdnTokenOtherUrl:(NSString *)url @param password the password to use. @return the params to make an authenticated API request. */ -- (NSDictionary*)authParamsFromError:(NSError*)error andPassword:(NSString*)password +- (NSDictionary*)authParamsFromError:(NSError*)error andPassword:(nullable NSString*)password { NSDictionary *authParams; NSHTTPURLResponse *urlResponse = [MXHTTPOperation urlResponseFromError:error]; @@ -619,6 +619,7 @@ - (NSDictionary*)authParamsFromError:(NSError*)error andPassword:(NSString*)pass @"type": kMXLoginIdentifierTypeUser, @"user": userId }, + @"session": authSession.session, @"password": password, @"user": userId }; From ae4ccd47619570cbd9e639d144c7f7ace0158ca8 Mon Sep 17 00:00:00 2001 From: manuroe Date: Thu, 24 Oct 2019 16:14:04 +0200 Subject: [PATCH 04/25] MXHTTPOperation: Make urlResponseFromError return the url response in case of MXError --- CHANGES.rst | 2 ++ MatrixSDK/Utils/MXHTTPOperation.m | 13 ++++++++++++- 2 files changed, 14 insertions(+), 1 deletion(-) diff --git a/CHANGES.rst b/CHANGES.rst index 64ae80c914..bfc2d5b065 100644 --- a/CHANGES.rst +++ b/CHANGES.rst @@ -6,6 +6,8 @@ Improvements: Bug fix: * Room members who left are listed with the actual members (vector-im/riot-ios#2737). + * MX3PidAddManager: Add User-Interactive Auth to /account/3pid/add (vector-im/riot-ios#2744). + * MXHTTPOperation: Make urlResponseFromError return the url response in case of MXError. Changes in Matrix iOS SDK in 0.14.0 (2019-10-11) =============================================== diff --git a/MatrixSDK/Utils/MXHTTPOperation.m b/MatrixSDK/Utils/MXHTTPOperation.m index 1df916cc62..56a4f1623d 100644 --- a/MatrixSDK/Utils/MXHTTPOperation.m +++ b/MatrixSDK/Utils/MXHTTPOperation.m @@ -18,6 +18,7 @@ #import "MXHTTPOperation.h" #import +#import "MXError.h" #pragma mark - Constants definitions @@ -88,7 +89,17 @@ - (void)mutateTo:(MXHTTPOperation *)operation + (NSHTTPURLResponse *)urlResponseFromError:(NSError*)error { - return error.userInfo[AFNetworkingOperationFailingURLResponseErrorKey]; + NSHTTPURLResponse *response; + if ([MXError isMXError:error]) + { + MXError *mxError = [[MXError alloc] initWithNSError:error]; + response = mxError.httpResponse; + } + else + { + response = error.userInfo[AFNetworkingOperationFailingURLResponseErrorKey]; + } + return response; } @end From d9905df50ba3bc2deedd9d8b599b05be097107a0 Mon Sep 17 00:00:00 2001 From: manuroe Date: Fri, 25 Oct 2019 13:41:29 +0200 Subject: [PATCH 05/25] MXHTTPClient: Track HTTP operations when they are requested and when they complete --- MatrixSDK/Utils/MXHTTPClient.m | 10 ++++++++++ 1 file changed, 10 insertions(+) diff --git a/MatrixSDK/Utils/MXHTTPClient.m b/MatrixSDK/Utils/MXHTTPClient.m index c729df3898..8119e9ddd9 100644 --- a/MatrixSDK/Utils/MXHTTPClient.m +++ b/MatrixSDK/Utils/MXHTTPClient.m @@ -45,6 +45,9 @@ NSString* const kMXHTTPClientMatrixErrorNotificationErrorKey = @"kMXHTTPClientMatrixErrorNotificationErrorKey"; +static NSUInteger requestCount = 0; + + @interface MXHTTPClient () { /** @@ -359,6 +362,11 @@ - (void)tryRequest:(MXHTTPOperation*)mxHTTPOperation MXWeakify(self); + NSDate *startDate = [NSDate date]; + NSUInteger requestNumber = requestCount++; + + NSLog(@"[MXHTTPClient] #%@ - %@", @(requestNumber), path); + mxHTTPOperation.numberOfTries++; mxHTTPOperation.operation = [httpManager dataTaskWithRequest:request uploadProgress:^(NSProgress * _Nonnull theUploadProgress) { @@ -373,6 +381,8 @@ - (void)tryRequest:(MXHTTPOperation*)mxHTTPOperation } downloadProgress:nil completionHandler:^(NSURLResponse * _Nonnull theResponse, NSDictionary *JSONResponse, NSError * _Nullable error) { NSHTTPURLResponse *response = (NSHTTPURLResponse*)theResponse; + NSLog(@"[MXHTTPClient] #%@ - %@ completed in %.0fms" ,@(requestNumber), path, [[NSDate date] timeIntervalSinceDate:startDate] * 1000); + if (!weakself) { // Log which request failed because of a potentiel unexpected object release From 476769c7ee4ba68094853aac1169f247c30f6b8a Mon Sep 17 00:00:00 2001 From: manuroe Date: Fri, 25 Oct 2019 13:55:45 +0200 Subject: [PATCH 06/25] MXSession: On resume, make the first /sync request trigger earlier vector-im/riot-ios#2793 There is no need to wait that crypto makes all its requests on a resume because it already made it (is, posting its device ids and one time keys) on a previous initial sync. --- CHANGES.rst | 1 + MatrixSDK/MXSession.m | 36 ++++++++++-------------------------- 2 files changed, 11 insertions(+), 26 deletions(-) diff --git a/CHANGES.rst b/CHANGES.rst index bfc2d5b065..1c2984e99a 100644 --- a/CHANGES.rst +++ b/CHANGES.rst @@ -3,6 +3,7 @@ Changes in Matrix iOS SDK in 0.xx.xx (2019-xx-xx) Improvements: * MX3PidAddManager: Add User-Interactive Auth to /account/3pid/add (vector-im/riot-ios#2744). + * MXSession: On resume, make the first /sync request trigger earlier (vector-im/riot-ios#2793). Bug fix: * Room members who left are listed with the actual members (vector-im/riot-ios#2737). diff --git a/MatrixSDK/MXSession.m b/MatrixSDK/MXSession.m index 7f40fe617a..26d908ebe3 100644 --- a/MatrixSDK/MXSession.m +++ b/MatrixSDK/MXSession.m @@ -503,36 +503,20 @@ - (void)startWithSyncFilterId:(NSString *)syncFilterId onServerSyncDone:(void (^ // Can we resume from data available in the cache if (_store.isPermanent && self.isEventStreamInitialised && 0 < _store.rooms.count) { - // Start crypto if enabled - MXWeakify(self); - [self startCrypto:^{ - MXStrongifyAndReturnIfNil(self); - - // Resume the stream (presence will be retrieved during server sync) - NSLog(@"[MXSession] Resuming the events stream from %@...", self.store.eventStreamToken); - NSDate *startDate2 = [NSDate date]; - [self resume:^{ - NSLog(@"[MXSession] Events stream resumed in %.0fms", [[NSDate date] timeIntervalSinceDate:startDate2] * 1000); + // Resume the stream (presence will be retrieved during server sync) + NSLog(@"[MXSession] Resuming the events stream from %@...", self.store.eventStreamToken); + NSDate *startDate2 = [NSDate date]; + [self resume:^{ + NSLog(@"[MXSession] Events stream resumed in %.0fms", [[NSDate date] timeIntervalSinceDate:startDate2] * 1000); - onServerSyncDone(); - }]; + onServerSyncDone(); + }]; + // Start crypto if enabled + [self startCrypto:^{ + NSLog(@"[MXSession] Crypto has been started"); } failure:^(NSError *error) { - NSLog(@"[MXSession] Crypto failed to start. Error: %@", error); - - // Check whether the token is valid - if ([self isUnknownTokenError:error]) - { - // Do nothing more because without a valid access_token, the session is useless - return; - } - - // Else consider the sync has failed - [self setState:MXSessionStateInitialSyncFailed]; - // Inform the caller that an error has occurred - failure(error); - }]; } else From 6d5332cc6ce1426a3453382db14cd4558ae84826 Mon Sep 17 00:00:00 2001 From: SBiOSoftWhare Date: Tue, 29 Oct 2019 18:19:28 +0100 Subject: [PATCH 07/25] Update Realm dependency to ~> 3.17.3 --- MatrixSDK.podspec | 2 +- Podfile | 4 +--- Podfile.lock | 14 +++++++------- SwiftMatrixSDK.podspec | 2 +- 4 files changed, 10 insertions(+), 12 deletions(-) diff --git a/MatrixSDK.podspec b/MatrixSDK.podspec index 550cc2c562..0d33fc5f27 100644 --- a/MatrixSDK.podspec +++ b/MatrixSDK.podspec @@ -36,7 +36,7 @@ Pod::Spec.new do |s| # Requirements for e2e encryption ss.dependency 'OLMKit', '~> 3.1.0' - ss.dependency 'Realm', '~> 3.13.1' + ss.dependency 'Realm', '~> 3.17.3' ss.dependency 'libbase58', '~> 0.1.4' end diff --git a/Podfile b/Podfile index 12b8de27e1..5c6f72bac3 100644 --- a/Podfile +++ b/Podfile @@ -1,8 +1,6 @@ # Uncomment this line to define a global platform for your project platform :ios, "9.0" -source 'https://github.com/CocoaPods/Specs.git' - target "MatrixSDK" do pod 'AFNetworking', '~> 3.2.0' pod 'GZIP', '~> 1.2.2' @@ -10,7 +8,7 @@ pod 'GZIP', '~> 1.2.2' pod 'OLMKit', '~> 3.1.0', :inhibit_warnings => true #pod 'OLMKit', :path => '../olm/OLMKit.podspec' -pod 'Realm', '~> 3.13.1' +pod 'Realm', '~> 3.17.3' pod 'libbase58', '~> 0.1.4' end diff --git a/Podfile.lock b/Podfile.lock index b7dd21e9f4..257225c170 100644 --- a/Podfile.lock +++ b/Podfile.lock @@ -34,9 +34,9 @@ PODS: - OLMKit/olmcpp (= 3.1.0) - OLMKit/olmc (3.1.0) - OLMKit/olmcpp (3.1.0) - - Realm (3.13.1): - - Realm/Headers (= 3.13.1) - - Realm/Headers (3.13.1) + - Realm (3.17.3): + - Realm/Headers (= 3.17.3) + - Realm/Headers (3.17.3) DEPENDENCIES: - AFNetworking (~> 3.2.0) @@ -44,7 +44,7 @@ DEPENDENCIES: - libbase58 (~> 0.1.4) - OHHTTPStubs (~> 6.1.0) - OLMKit (~> 3.1.0) - - Realm (~> 3.13.1) + - Realm (~> 3.17.3) SPEC REPOS: https://github.com/CocoaPods/Specs.git: @@ -61,8 +61,8 @@ SPEC CHECKSUMS: libbase58: 7c040313537b8c44b6e2d15586af8e21f7354efd OHHTTPStubs: 1e21c7d2c084b8153fc53d48400d8919d2d432d0 OLMKit: 4ee0159d63feeb86d836fdcfefe418e163511639 - Realm: 50071da38fe079e0735e47c9f2eae738c68c5996 + Realm: 5a1d9d47bfc101dd597668b1a8af4288a2557f6d -PODFILE CHECKSUM: 278135edad062bc27b69b9d91c26249e8c3bb9b6 +PODFILE CHECKSUM: a3d1ca57b0ed793a3a7ee01236209a432c74692c -COCOAPODS: 1.8.3 +COCOAPODS: 1.8.4 diff --git a/SwiftMatrixSDK.podspec b/SwiftMatrixSDK.podspec index f594758861..f84ce5cc61 100644 --- a/SwiftMatrixSDK.podspec +++ b/SwiftMatrixSDK.podspec @@ -32,7 +32,7 @@ Pod::Spec.new do |s| # Requirements for e2e encryption s.dependency 'OLMKit', '~> 3.1.0' - s.dependency 'Realm', '~> 3.13.1' + s.dependency 'Realm', '~> 3.17.3' s.dependency 'libbase58', '~> 0.1.4' end From deb14c131b3100ad69694a4cf0c1e52cce9fc101 Mon Sep 17 00:00:00 2001 From: SBiOSoftWhare Date: Tue, 29 Oct 2019 18:45:57 +0100 Subject: [PATCH 08/25] MXHTTPOperation: Fix a crash in `-mutateTo:` method when operation parameter is nil. --- MatrixSDK/Utils/MXHTTPOperation.m | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/MatrixSDK/Utils/MXHTTPOperation.m b/MatrixSDK/Utils/MXHTTPOperation.m index 56a4f1623d..1eb1c59c0b 100644 --- a/MatrixSDK/Utils/MXHTTPOperation.m +++ b/MatrixSDK/Utils/MXHTTPOperation.m @@ -72,6 +72,11 @@ - (NSUInteger)age - (void)mutateTo:(MXHTTPOperation *)operation { + if (!operation) + { + return; + } + // Apply all data from the other MXHTTPOperation _operation = operation.operation; creationDate = operation->creationDate; From d6a66aa43077fea7e23821f38282ea43b984f0d8 Mon Sep 17 00:00:00 2001 From: SBiOSoftWhare Date: Tue, 29 Oct 2019 18:46:47 +0100 Subject: [PATCH 09/25] Update changes --- CHANGES.rst | 1 + 1 file changed, 1 insertion(+) diff --git a/CHANGES.rst b/CHANGES.rst index 1c2984e99a..77b7f6d117 100644 --- a/CHANGES.rst +++ b/CHANGES.rst @@ -9,6 +9,7 @@ Bug fix: * Room members who left are listed with the actual members (vector-im/riot-ios#2737). * MX3PidAddManager: Add User-Interactive Auth to /account/3pid/add (vector-im/riot-ios#2744). * MXHTTPOperation: Make urlResponseFromError return the url response in case of MXError. + * MXHTTPOperation: Fix a crash in `-mutateTo:` method when operation parameter is nil. Changes in Matrix iOS SDK in 0.14.0 (2019-10-11) =============================================== From 60e9b85f34333ff3460a86542b89f864ec2667ba Mon Sep 17 00:00:00 2001 From: manuroe Date: Wed, 30 Oct 2019 08:58:43 +0100 Subject: [PATCH 10/25] MXCrypto: Do not fail to decrypt when there is nothing to decrypt (redacted events) --- CHANGES.rst | 1 + MatrixSDK/Crypto/MXCrypto.m | 13 +++++++++++-- 2 files changed, 12 insertions(+), 2 deletions(-) diff --git a/CHANGES.rst b/CHANGES.rst index 1c2984e99a..3bce4dfaf7 100644 --- a/CHANGES.rst +++ b/CHANGES.rst @@ -4,6 +4,7 @@ Changes in Matrix iOS SDK in 0.xx.xx (2019-xx-xx) Improvements: * MX3PidAddManager: Add User-Interactive Auth to /account/3pid/add (vector-im/riot-ios#2744). * MXSession: On resume, make the first /sync request trigger earlier (vector-im/riot-ios#2793). + * MXCrypto: Do not fail to decrypt when there is nothing to decrypt (redacted events). Bug fix: * Room members who left are listed with the actual members (vector-im/riot-ios#2737). diff --git a/MatrixSDK/Crypto/MXCrypto.m b/MatrixSDK/Crypto/MXCrypto.m index 3422c099f4..aaa3843dac 100644 --- a/MatrixSDK/Crypto/MXCrypto.m +++ b/MatrixSDK/Crypto/MXCrypto.m @@ -451,10 +451,19 @@ - (MXEventDecryptionResult *)decryptEvent:(MXEvent *)event inTimeline:(NSString* // At the moment, we lock the main thread while decrypting events. // Fortunately, decrypting is far quicker that encrypting. dispatch_sync(_decryptionQueue, ^{ + + if (!event.content.count) + { + NSLog(@"[MXCrypto] decryptEvent: No content to decrypt in event %@ (isRedacted: %@). Event: %@", event.eventId, @(event.isRedactedEvent), event.JSONDictionary); + result = [[MXEventDecryptionResult alloc] init]; + result.clearEvent = event.content; + return; + } + id alg = [self getRoomDecryptor:event.roomId algorithm:event.content[@"algorithm"]]; if (!alg) { - NSLog(@"[MXCrypto] decryptEvent: Unable to decrypt %@", event.content[@"algorithm"]); + NSLog(@"[MXCrypto] decryptEvent: Unable to decrypt %@ with algorithm %@. Event: %@", event.eventId, event.content[@"algorithm"], event.JSONDictionary); if (error) { @@ -471,7 +480,7 @@ - (MXEventDecryptionResult *)decryptEvent:(MXEvent *)event inTimeline:(NSString* result = [alg decryptEvent:event inTimeline:timeline error:error]; if (error && *error) { - NSLog(@"[MXCrypto] decryptEvent: Error: %@", *error); + NSLog(@"[MXCrypto] decryptEvent: Error for %@: %@\nEvent: %@", event.eventId, *error, event.JSONDictionary); } } }); From 56233fcb2e195b9b0a3dbdd61de709a200adc700 Mon Sep 17 00:00:00 2001 From: manuroe Date: Wed, 30 Oct 2019 08:59:53 +0100 Subject: [PATCH 11/25] Crypto: Avoid useless log "[MXTimeline] addEvent: Warning: Unable to decrypt event: null" --- MatrixSDK/Crypto/Algorithms/MXDecryptionResult.m | 2 +- MatrixSDK/Data/MXEventTimeline.m | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/MatrixSDK/Crypto/Algorithms/MXDecryptionResult.m b/MatrixSDK/Crypto/Algorithms/MXDecryptionResult.m index 5b8a8750a1..1b23739f65 100644 --- a/MatrixSDK/Crypto/Algorithms/MXDecryptionResult.m +++ b/MatrixSDK/Crypto/Algorithms/MXDecryptionResult.m @@ -22,7 +22,7 @@ NSString* const MXDecryptingErrorUnableToEncrypt = @"Unable to encrypt"; NSString* const MXDecryptingErrorUnableToEncryptReason = @"Unable to encrypt %@"; NSString* const MXDecryptingErrorUnableToDecrypt = @"Unable to decrypt"; -NSString* const MXDecryptingErrorUnableToDecryptReason = @"Unable to decrypt %@. Algoritm: %@"; +NSString* const MXDecryptingErrorUnableToDecryptReason = @"Unable to decrypt %@. Algorithm: %@"; NSString* const MXDecryptingErrorOlm = @"Error: OLM.%@"; NSString* const MXDecryptingErrorOlmReason = @"Unable to decrypt %@. OLM error: %@"; NSString* const MXDecryptingErrorUnknownInboundSessionIdReason = @"Unknown inbound session id"; diff --git a/MatrixSDK/Data/MXEventTimeline.m b/MatrixSDK/Data/MXEventTimeline.m index d5746cafc2..95670fabd8 100644 --- a/MatrixSDK/Data/MXEventTimeline.m +++ b/MatrixSDK/Data/MXEventTimeline.m @@ -611,7 +611,7 @@ - (void)addEvent:(MXEvent*)event direction:(MXTimelineDirection)direction fromSt if (![room.mxSession decryptEvent:event inTimeline:timelineId]) { - NSLog(@"[MXTimeline] addEvent: Warning: Unable to decrypt event: %@\nError: %@", event.content[@"body"], event.decryptionError); + NSLog(@"[MXTimeline] addEvent: Warning: Unable to decrypt event %@\nError: %@", event.eventId, event.decryptionError); } } From 67d8bf9ec559bcd9b0184c5f762af5891cf6f5ef Mon Sep 17 00:00:00 2001 From: SBiOSoftWhare Date: Wed, 30 Oct 2019 10:48:02 +0100 Subject: [PATCH 12/25] MXHTTPOperation: Remove nullability check before using `mutateTo:` method where needed. --- .../Algorithms/Megolm/MXMegolmEncryption.m | 7 +-- MatrixSDK/Crypto/KeyBackup/MXKeyBackup.m | 21 +++----- MatrixSDK/Crypto/MXCrypto.m | 24 +++------ MatrixSDK/Data/MXRoom.m | 18 ++----- MatrixSDK/IdentityServer/MXIdentityService.m | 6 +-- MatrixSDK/MXRestClient.m | 41 +++++--------- MatrixSDK/MXSession.m | 31 +++-------- MatrixSDK/ThreePidAdd/MX3PidAddManager.m | 54 ++++++------------- MatrixSDK/Utils/MXHTTPOperation.h | 2 +- 9 files changed, 58 insertions(+), 146 deletions(-) diff --git a/MatrixSDK/Crypto/Algorithms/Megolm/MXMegolmEncryption.m b/MatrixSDK/Crypto/Algorithms/Megolm/MXMegolmEncryption.m index d7eec7594b..f1ac42f85b 100644 --- a/MatrixSDK/Crypto/Algorithms/Megolm/MXMegolmEncryption.m +++ b/MatrixSDK/Crypto/Algorithms/Megolm/MXMegolmEncryption.m @@ -165,11 +165,8 @@ - (MXHTTPOperation*)ensureSessionForUsers:(NSArray*)users } } failure:failure]; - - if (operation2) - { - [operation mutateTo:operation2]; - } + + [operation mutateTo:operation2]; } failure:failure]; diff --git a/MatrixSDK/Crypto/KeyBackup/MXKeyBackup.m b/MatrixSDK/Crypto/KeyBackup/MXKeyBackup.m index c0a42334c6..22521e83de 100644 --- a/MatrixSDK/Crypto/KeyBackup/MXKeyBackup.m +++ b/MatrixSDK/Crypto/KeyBackup/MXKeyBackup.m @@ -482,11 +482,8 @@ - (MXHTTPOperation*)createKeyBackupVersion:(MXMegolmBackupCreationInfo*)keyBacku }); } }]; - - if (operation2) - { - [operation mutateTo:operation2]; - } + + [operation mutateTo:operation2]; }); return operation; @@ -541,11 +538,8 @@ - (MXHTTPOperation*)deleteKeyBackupVersion:(NSString*)version }); } }]; - - if (operation2) - { - [operation mutateTo:operation2]; - } + + [operation mutateTo:operation2]; }); return operation; @@ -806,11 +800,8 @@ - (MXHTTPOperation*)restoreKeyBackup:(MXKeyBackupVersion*)keyBackupVersion }); } }]; - - if (operation2) - { - [operation mutateTo:operation2]; - } + + [operation mutateTo:operation2]; }); return operation; diff --git a/MatrixSDK/Crypto/MXCrypto.m b/MatrixSDK/Crypto/MXCrypto.m index 3422c099f4..5c8897df31 100644 --- a/MatrixSDK/Crypto/MXCrypto.m +++ b/MatrixSDK/Crypto/MXCrypto.m @@ -409,10 +409,7 @@ - (MXHTTPOperation *)encryptEventContent:(NSDictionary *)eventContent withType:( }]; // Mutate the HTTP operation if an HTTP is required for the encryption - if (operation2) - { - [operation mutateTo:operation2]; - } + [operation mutateTo:operation2]; } else { @@ -548,11 +545,8 @@ - (MXHTTPOperation*)ensureEncryptionInRoom:(NSString*)roomId }); } }]; - - if (operation2) - { - [operation mutateTo:operation2]; - } + + [operation mutateTo:operation2]; } else if (failure) { @@ -859,11 +853,8 @@ - (MXHTTPOperation*)downloadKeys:(NSArray*)userIds }); } }]; - - if (operation2) - { - [operation mutateTo:operation2]; - } + + [operation mutateTo:operation2]; }); return operation; @@ -2194,10 +2185,7 @@ - (void)maybeUploadOneTimeKeys:(void (^)(void))success failure:(void (^)(NSError }]; // Mutate MXHTTPOperation so that the user can cancel this new operation - if (operation2) - { - [self->uploadOneTimeKeysOperation mutateTo:operation2]; - } + [self->uploadOneTimeKeysOperation mutateTo:operation2]; } else { diff --git a/MatrixSDK/Data/MXRoom.m b/MatrixSDK/Data/MXRoom.m index dc718c75bf..cd38db90cb 100644 --- a/MatrixSDK/Data/MXRoom.m +++ b/MatrixSDK/Data/MXRoom.m @@ -313,10 +313,7 @@ - (MXHTTPOperation*)members:(void (^)(MXRoomMembers *members))success NSLog(@"[MXRoom] get members failed. Pending requesters: %@", @(pendingRequesters.count)); }]; - if (operation2) - { - [operation mutateTo:operation2]; - } + [operation mutateTo:operation2]; } if (success) @@ -1709,11 +1706,8 @@ - (MXHTTPOperation*)setPowerLevelOfUserWithUserID:(NSString *)userId powerLevel: MXHTTPOperation *operation2 = [self sendStateEventOfType:kMXEventTypeStringRoomPowerLevels content:newPowerLevelsEventContent stateKey:nil success:^(NSString *eventId) { success(); } failure:failure]; - - if (operation2) - { - [operation mutateTo:operation2]; - } + + [operation mutateTo:operation2]; }]; return operation; @@ -3026,11 +3020,7 @@ - (MXHTTPOperation*)setIsDirect:(BOOL)isDirect // Retry the operation with a user id MXHTTPOperation *operation2 = [self setIsDirect:isDirect withUserId:newDirectUserId success:success failure:failure]; - - if (operation2) - { - [operation mutateTo:operation2]; - } + [operation mutateTo:operation2]; } failure:failure]; } } diff --git a/MatrixSDK/IdentityServer/MXIdentityService.m b/MatrixSDK/IdentityServer/MXIdentityService.m index 651775487a..56cff6c978 100644 --- a/MatrixSDK/IdentityServer/MXIdentityService.m +++ b/MatrixSDK/IdentityServer/MXIdentityService.m @@ -178,7 +178,7 @@ - (MXHTTPOperation*)lookup3pids:(NSArray*)threepids failure:failure]; } - if (operation && operation2) + if (operation) { [operation mutateTo:operation2]; } @@ -352,7 +352,7 @@ - (MXHTTPOperation*)checkAPIVersionAvailabilityAndPerformOperationOnSuccess:(MXH MXHTTPOperation *operation2 = operationOnSuccess(); - if (operation && operation2) + if (operation) { [operation mutateTo:operation2]; } @@ -414,7 +414,7 @@ - (MXHTTPOperation*)v2_lookup3pids:(NSArray*)threepids }]; - if (operation && operation2) + if (operation) { [operation mutateTo:operation2]; } diff --git a/MatrixSDK/MXRestClient.m b/MatrixSDK/MXRestClient.m index 62924970a1..309b55e62e 100644 --- a/MatrixSDK/MXRestClient.m +++ b/MatrixSDK/MXRestClient.m @@ -1011,26 +1011,18 @@ - (MXHTTPOperation*)requestTokenFromEndpoint:(NSString *)path MXStrongifyAndReturnIfNil(self); MXHTTPOperation *operation3 = [self requestTokenFromEndpoint2:path parameters:updatedParameters success:success failure:failure]; - if (operation3) - { - [operation mutateTo:operation3]; - } - + + [operation mutateTo:operation3]; + } failure:failure]; - - if (operation2) - { - [operation mutateTo:operation2]; - } + + [operation mutateTo:operation2]; } else { MXHTTPOperation *operation2 = [self requestTokenFromEndpoint2:path parameters:parameters success:success failure:failure]; - - if (operation2) - { - [operation mutateTo:operation2]; - } + + [operation mutateTo:operation2]; } } failure:failure]; @@ -1101,11 +1093,8 @@ - (MXHTTPOperation*)addIdentityAccessTokenToParameters:(NSDictionary *)parameter { success(parameters); } - - if (operation2) - { - [operation mutateTo:operation2]; - } + + [operation mutateTo:operation2]; } failure:failure]; @@ -2072,10 +2061,8 @@ - (MXHTTPOperation*)inviteByThreePid:(NSString*)medium MXStrongifyAndReturnIfNil(self); MXHTTPOperation *operation2 = [self inviteByThreePidToRoom:roomId parameters:parameters success:success failure:failure]; - if (operation2) - { - [operation mutateTo:operation2]; - } + + [operation mutateTo:operation2]; } failure:failure]; @@ -3116,10 +3103,8 @@ - (MXHTTPOperation*)bind3PidWithSessionId:(NSString*)sid MXStrongifyAndReturnIfNil(self); [self dispatchFailure:error inBlock:failure]; }]; - if (operation2) - { - [operation mutateTo:operation2]; - } + + [operation mutateTo:operation2]; } failure:^(NSError *error) { MXStrongifyAndReturnIfNil(self); diff --git a/MatrixSDK/MXSession.m b/MatrixSDK/MXSession.m index 26d908ebe3..3f14d4a6a4 100644 --- a/MatrixSDK/MXSession.m +++ b/MatrixSDK/MXSession.m @@ -2101,10 +2101,7 @@ - (MXHTTPOperation*)setRoom:(NSString*)roomId } MXHTTPOperation *operation2 = [self uploadDirectRoomsInOperationsQueue:newDirectRooms success:success failure:failure]; - if (operation2) - { - [operation mutateTo:operation2]; - } + [operation mutateTo:operation2]; }]; return operation; @@ -2121,10 +2118,7 @@ - (MXHTTPOperation*)uploadDirectRooms:(NSDictionarydoesServerSupportSeparateAddAndBind); } failure:failure]; - - if (operation2) - { - [operation mutateTo:operation2]; - } + + [operation mutateTo:operation2]; } else { @@ -689,11 +678,8 @@ - (void)startIdentityServer3PidSession:(MX3PidAddSession*)threePidAddSession failure(error); }]; } - - if (operation) - { - [threePidAddSession.httpOperation mutateTo:operation]; - } + + [threePidAddSession.httpOperation mutateTo:operation]; } failure:^(NSError * _Nonnull error) { threePidAddSession.httpOperation = nil; @@ -790,10 +776,7 @@ - (void)tryFinaliseIdentityServer3PidSessionWithNewHomeserver:(MX3PidAddSession* failure(error); }]; - if (operation) - { - [threePidAddSession.httpOperation mutateTo:operation]; - } + [threePidAddSession.httpOperation mutateTo:operation]; } failure:^(NSError *error) { threePidAddSession.httpOperation = nil; @@ -849,12 +832,8 @@ - (MXHTTPOperation *)startBind3PidSessionWithOldHomeserver:(MX3PidAddSession*)th failure(error); }]; } - - if (operation2) - { - [operation mutateTo:operation2]; - } - + + [operation mutateTo:operation2]; } failure:^(NSError *error) { @@ -911,11 +890,8 @@ - (void)tryFinaliseIdentityServer3PidSessionWithOldHomeserver:(MX3PidAddSession* threePidAddSession.httpOperation = nil; failure(error); }]; - - if (operation) - { - [threePidAddSession.httpOperation mutateTo:operation]; - } + + [threePidAddSession.httpOperation mutateTo:operation]; } failure:^(NSError *error) { threePidAddSession.httpOperation = nil; diff --git a/MatrixSDK/Utils/MXHTTPOperation.h b/MatrixSDK/Utils/MXHTTPOperation.h index 6f8b2640ce..0f3cce98fb 100644 --- a/MatrixSDK/Utils/MXHTTPOperation.h +++ b/MatrixSDK/Utils/MXHTTPOperation.h @@ -72,7 +72,7 @@ This allows to chain HTTP requests and let the user keep the control on consecutive requests, ie he will able to cancel subsequent http requests. - @param operation the other operation to copy data from. + @param operation the other operation to copy data from. If the other operation is nil do nothing. */ - (void)mutateTo:(MXHTTPOperation*)operation; From 3f6ad72f45b5e55c72ab9d9dfb7a57868a520581 Mon Sep 17 00:00:00 2001 From: SBiOSoftWhare Date: Wed, 30 Oct 2019 11:31:02 +0100 Subject: [PATCH 13/25] Fix Xcode 11 compilation errors. --- MatrixSDK/Crypto/Data/MXDeviceList.m | 2 +- .../Crypto/Data/Store/MXRealmCryptoStore/MXRealmCryptoStore.m | 4 ++-- MatrixSDK/Crypto/Utils/MXMegolmExportEncryption.m | 2 +- MatrixSDK/Utils/MXLogger.m | 2 +- MatrixSDK/Utils/MXTools.m | 2 +- 5 files changed, 6 insertions(+), 6 deletions(-) diff --git a/MatrixSDK/Crypto/Data/MXDeviceList.m b/MatrixSDK/Crypto/Data/MXDeviceList.m index 6b0e1679cc..9db49b52e5 100644 --- a/MatrixSDK/Crypto/Data/MXDeviceList.m +++ b/MatrixSDK/Crypto/Data/MXDeviceList.m @@ -92,7 +92,7 @@ - (MXHTTPOperation*)downloadKeys:(NSArray*)userIds forceDownload:(BOO success:(void (^)(MXUsersDevicesMap *usersDevicesInfoMap))success failure:(void (^)(NSError *error))failure { - NSLog(@"[MXDeviceList] downloadKeys(forceDownload: %tu) for %tu users", forceDownload, userIds.count); + NSLog(@"[MXDeviceList] downloadKeys(forceDownload: %d) for %tu users", forceDownload, userIds.count); NSMutableArray *usersToDownload = [NSMutableArray array]; BOOL doANewQuery = NO; diff --git a/MatrixSDK/Crypto/Data/Store/MXRealmCryptoStore/MXRealmCryptoStore.m b/MatrixSDK/Crypto/Data/Store/MXRealmCryptoStore/MXRealmCryptoStore.m index 989c6ab0c3..d3ebe7ace3 100644 --- a/MatrixSDK/Crypto/Data/Store/MXRealmCryptoStore/MXRealmCryptoStore.m +++ b/MatrixSDK/Crypto/Data/Store/MXRealmCryptoStore/MXRealmCryptoStore.m @@ -325,7 +325,7 @@ - (instancetype)initWithCredentials:(MXCredentials *)credentials } } - NSLog(@"[MXRealmCryptoStore] Schema version: %tu", account.realm.configuration.schemaVersion); + NSLog(@"[MXRealmCryptoStore] Schema version: %llu", account.realm.configuration.schemaVersion); } return self; } @@ -1129,7 +1129,7 @@ + (RLMRealm*)realmForUser:(NSString*)userId if (oldSchemaVersion < kMXRealmCryptoStoreVersion) { - NSLog(@"[MXRealmCryptoStore] Required migration detected. oldSchemaVersion: %tu - current: %tu", oldSchemaVersion, kMXRealmCryptoStoreVersion); + NSLog(@"[MXRealmCryptoStore] Required migration detected. oldSchemaVersion: %llu - current: %tu", oldSchemaVersion, kMXRealmCryptoStoreVersion); switch (oldSchemaVersion) { diff --git a/MatrixSDK/Crypto/Utils/MXMegolmExportEncryption.m b/MatrixSDK/Crypto/Utils/MXMegolmExportEncryption.m index 4f8d4205df..b32a8a3b49 100644 --- a/MatrixSDK/Crypto/Utils/MXMegolmExportEncryption.m +++ b/MatrixSDK/Crypto/Utils/MXMegolmExportEncryption.m @@ -465,7 +465,7 @@ + (void)logBytesDec:(NSData*)data NSMutableString *s = [NSMutableString string]; for (NSUInteger i = 0; i < data.length; i++) { - [s appendFormat:@"%tu, ", bytes[i]]; + [s appendFormat:@"%hhu, ", bytes[i]]; } NSLog(@"%tu bytes:\n%@", data.length, s); diff --git a/MatrixSDK/Utils/MXLogger.m b/MatrixSDK/Utils/MXLogger.m index 8369f1e6f7..011279a16a 100644 --- a/MatrixSDK/Utils/MXLogger.m +++ b/MatrixSDK/Utils/MXLogger.m @@ -183,7 +183,7 @@ static void handleUncaughtException(NSException *exception) NSString *version = [[NSProcessInfo processInfo] operatingSystemVersionString]; #endif NSArray *backtrace = [exception callStackSymbols]; - NSString *description = [NSString stringWithFormat:@"%tu - %@\n%@\nApplication: %@ (%@)\nApplication version: %@\nMatrix SDK version: %@\nBuild: %@\n%@ %@\n\nMain thread: %@\n%@\n", + NSString *description = [NSString stringWithFormat:@"%.0f - %@\n%@\nApplication: %@ (%@)\nApplication version: %@\nMatrix SDK version: %@\nBuild: %@\n%@ %@\n\nMain thread: %@\n%@\n", [[NSDate date] timeIntervalSince1970], [NSDate date], exception.description, diff --git a/MatrixSDK/Utils/MXTools.m b/MatrixSDK/Utils/MXTools.m index 8a96e7b625..1fb905384e 100644 --- a/MatrixSDK/Utils/MXTools.m +++ b/MatrixSDK/Utils/MXTools.m @@ -276,7 +276,7 @@ + (NSString *)generateSecret + (NSString *)generateTransactionId { - return [NSString stringWithFormat:@"m%tu.%tu", arc4random_uniform(INT32_MAX), transactionIdCount++]; + return [NSString stringWithFormat:@"m%u.%tu", arc4random_uniform(INT32_MAX), transactionIdCount++]; } + (NSString*)stripNewlineCharacters:(NSString *)inputString From b69b6610e7e4cd5de17fa5c510d96ffeaae0720e Mon Sep 17 00:00:00 2001 From: SBiOSoftWhare Date: Wed, 30 Oct 2019 12:29:36 +0100 Subject: [PATCH 14/25] Update JitsiMeetSDK dependency to ~> 2.3.1. --- MatrixSDK.podspec | 2 +- MatrixSDKExtensions/VoIP/Jingle/MXJingleVideoView.h | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/MatrixSDK.podspec b/MatrixSDK.podspec index 0d33fc5f27..6255370fa0 100644 --- a/MatrixSDK.podspec +++ b/MatrixSDK.podspec @@ -53,7 +53,7 @@ Pod::Spec.new do |s| #ss.ios.dependency 'GoogleWebRTC', '~>1.1.21820' # Use WebRTC framework included in Jitsi Meet SDK - ss.ios.dependency 'JitsiMeetSDK', '~> 2.1.0' + ss.ios.dependency 'JitsiMeetSDK', '~> 2.3.1' end diff --git a/MatrixSDKExtensions/VoIP/Jingle/MXJingleVideoView.h b/MatrixSDKExtensions/VoIP/Jingle/MXJingleVideoView.h index 21de730a8b..8a876ad413 100644 --- a/MatrixSDKExtensions/VoIP/Jingle/MXJingleVideoView.h +++ b/MatrixSDKExtensions/VoIP/Jingle/MXJingleVideoView.h @@ -27,7 +27,7 @@ NS_ASSUME_NONNULL_BEGIN @see https://developers.google.com/talk/libjingle/developer_guide */ NS_EXTENSION_UNAVAILABLE_IOS("Rendering not available in app extensions.") -@interface MXJingleVideoView : RTCEAGLVideoView +@interface MXJingleVideoView : RTCEAGLVideoView - (instancetype)initWithContainerView:(UIView *)containerView NS_DESIGNATED_INITIALIZER; From 19d49b0b31da6c499206c462c3ae18f03a14322c Mon Sep 17 00:00:00 2001 From: manuroe Date: Thu, 31 Oct 2019 09:17:25 +0100 Subject: [PATCH 15/25] MXSession: Log the event stream token --- MatrixSDK/MXSession.m | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/MatrixSDK/MXSession.m b/MatrixSDK/MXSession.m index 3f14d4a6a4..78614860b8 100644 --- a/MatrixSDK/MXSession.m +++ b/MatrixSDK/MXSession.m @@ -933,10 +933,11 @@ - (void)serverSyncWithServerTimeout:(NSUInteger)serverTimeout // Determine if we are catching up _catchingUp = (0 == serverTimeout); - NSLog(@"[MXSession] Do a server sync%@", _catchingUp ? @" (catching up)" : @""); + NSString * streamToken = _store.eventStreamToken; + NSLog(@"[MXSession] Do a server sync%@: %@", _catchingUp ? @" (catching up)" : @"", streamToken); MXWeakify(self); - eventStreamRequest = [matrixRestClient syncFromToken:_store.eventStreamToken serverTimeout:serverTimeout clientTimeout:clientTimeout setPresence:setPresence filter:self.syncFilterId success:^(MXSyncResponse *syncResponse) { + eventStreamRequest = [matrixRestClient syncFromToken:streamToken serverTimeout:serverTimeout clientTimeout:clientTimeout setPresence:setPresence filter:self.syncFilterId success:^(MXSyncResponse *syncResponse) { MXStrongifyAndReturnIfNil(self); // Make sure [MXSession close] or [MXSession pause] has not been called before the server response From 85f0dda998fcdbc40f3f107095d0002cc11bb1e5 Mon Sep 17 00:00:00 2001 From: manuroe Date: Mon, 4 Nov 2019 16:48:17 +0100 Subject: [PATCH 16/25] VoIP: Fix regression when using a TURN server vector-im/riot-ios#2796 --- CHANGES.rst | 1 + MatrixSDKExtensions/VoIP/Jingle/MXJingleCallStackCall.m | 9 +++++---- 2 files changed, 6 insertions(+), 4 deletions(-) diff --git a/CHANGES.rst b/CHANGES.rst index 1fbc49f360..2a6a70c139 100644 --- a/CHANGES.rst +++ b/CHANGES.rst @@ -11,6 +11,7 @@ Bug fix: * MX3PidAddManager: Add User-Interactive Auth to /account/3pid/add (vector-im/riot-ios#2744). * MXHTTPOperation: Make urlResponseFromError return the url response in case of MXError. * MXHTTPOperation: Fix a crash in `-mutateTo:` method when operation parameter is nil. + * VoIP: Fix regression when using a TURN server (vector-im/riot-ios#2796). Changes in Matrix iOS SDK in 0.14.0 (2019-10-11) =============================================== diff --git a/MatrixSDKExtensions/VoIP/Jingle/MXJingleCallStackCall.m b/MatrixSDKExtensions/VoIP/Jingle/MXJingleCallStackCall.m index 2976924aa7..2541fb8501 100644 --- a/MatrixSDKExtensions/VoIP/Jingle/MXJingleCallStackCall.m +++ b/MatrixSDKExtensions/VoIP/Jingle/MXJingleCallStackCall.m @@ -124,14 +124,13 @@ - (void)end - (void)addTURNServerUris:(NSArray *)uris withUsername:(nullable NSString *)username password:(nullable NSString *)password { - RTCConfiguration *configuration = [[RTCConfiguration alloc] init]; RTCIceServer *ICEServer; if (uris) { - RTCIceServer *ICEServer = [[RTCIceServer alloc] initWithURLStrings:uris - username:username - credential:password]; + ICEServer = [[RTCIceServer alloc] initWithURLStrings:uris + username:username + credential:password]; if (!ICEServer) { @@ -144,6 +143,8 @@ - (void)addTURNServerUris:(NSArray *)uris withUsername:(nullable NSS optionalConstraints:@{ @"RtpDataChannels": @"true" }]; + + RTCConfiguration *configuration = [[RTCConfiguration alloc] init]; if (ICEServer) { configuration.iceServers = @[ICEServer]; From 2de6fb635e73a1001a264998620e17dcdb900b53 Mon Sep 17 00:00:00 2001 From: SBiOSoftWhare Date: Tue, 5 Nov 2019 16:36:18 +0100 Subject: [PATCH 17/25] Create MXBackgroundTask a protocol describing a background task regardless of the platform used. --- MatrixSDK/Utils/MXBackgroundTask.h | 46 ++++++++++++++++++++++++++++++ 1 file changed, 46 insertions(+) create mode 100644 MatrixSDK/Utils/MXBackgroundTask.h diff --git a/MatrixSDK/Utils/MXBackgroundTask.h b/MatrixSDK/Utils/MXBackgroundTask.h new file mode 100644 index 0000000000..da0cc34b01 --- /dev/null +++ b/MatrixSDK/Utils/MXBackgroundTask.h @@ -0,0 +1,46 @@ +/* + Copyright 2019 The Matrix.org Foundation C.I.C + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + */ + +#ifndef MXBackgroundTask_h +#define MXBackgroundTask_h + +#import + +NS_ASSUME_NONNULL_BEGIN + +typedef void (^MXBackgroundTaskExpirationHandler)(void); + +/** + MXBackgroundTask is protocol describing a background task regardless of the platform used. + */ +@protocol MXBackgroundTask + +// Name of the background task for debug. +@property (nonatomic, strong, readonly) NSString *name; + +// Yes if the background task is currently running. +@property (nonatomic, readonly) BOOL isRunning; + +/** + Stop the background task. Cannot be started anymore. + */ +- (void)stop; + +@end + +NS_ASSUME_NONNULL_END + +#endif /* MXBackgroundTask_h */ From 9d7f1ed79d7524982bf83822fd550cb476633eec Mon Sep 17 00:00:00 2001 From: SBiOSoftWhare Date: Tue, 5 Nov 2019 16:37:57 +0100 Subject: [PATCH 18/25] Create MXUIKitBackgroundTask a concrete implementation of MXBackgroundTask using UIApplication background task. --- MatrixSDK.xcodeproj/project.pbxproj | 10 ++ MatrixSDK/Utils/MXUIKitBackgroundTask.h | 35 +++++ MatrixSDK/Utils/MXUIKitBackgroundTask.m | 187 ++++++++++++++++++++++++ 3 files changed, 232 insertions(+) create mode 100644 MatrixSDK/Utils/MXUIKitBackgroundTask.h create mode 100644 MatrixSDK/Utils/MXUIKitBackgroundTask.m diff --git a/MatrixSDK.xcodeproj/project.pbxproj b/MatrixSDK.xcodeproj/project.pbxproj index fdbe838576..80c2303d08 100644 --- a/MatrixSDK.xcodeproj/project.pbxproj +++ b/MatrixSDK.xcodeproj/project.pbxproj @@ -430,6 +430,8 @@ B17982FB2119E4A2001FD722 /* MXRoomPredecessorInfo.m in Sources */ = {isa = PBXBuildFile; fileRef = B17982F32119E4A1001FD722 /* MXRoomPredecessorInfo.m */; }; B17982FC2119E4A2001FD722 /* MXRoomPowerLevels.m in Sources */ = {isa = PBXBuildFile; fileRef = B17982F42119E4A2001FD722 /* MXRoomPowerLevels.m */; }; B1798304211B3649001FD722 /* MXRoomSummary.swift in Sources */ = {isa = PBXBuildFile; fileRef = B1798303211B3649001FD722 /* MXRoomSummary.swift */; }; + B17B2BDC2369FC81009D6650 /* MXUIKitBackgroundTask.h in Headers */ = {isa = PBXBuildFile; fileRef = B17B2BDA2369FC81009D6650 /* MXUIKitBackgroundTask.h */; }; + B17B2BDD2369FC81009D6650 /* MXUIKitBackgroundTask.m in Sources */ = {isa = PBXBuildFile; fileRef = B17B2BDB2369FC81009D6650 /* MXUIKitBackgroundTask.m */; }; B182B08723167A640057972E /* MXIdentityServerHashDetails.h in Headers */ = {isa = PBXBuildFile; fileRef = B182B08523167A640057972E /* MXIdentityServerHashDetails.h */; settings = {ATTRIBUTES = (Public, ); }; }; B182B08823167A640057972E /* MXIdentityServerHashDetails.m in Sources */ = {isa = PBXBuildFile; fileRef = B182B08623167A640057972E /* MXIdentityServerHashDetails.m */; }; B18D18C22152B8E4003677D1 /* MXRoomMember.swift in Sources */ = {isa = PBXBuildFile; fileRef = B18D18C12152B8E4003677D1 /* MXRoomMember.swift */; }; @@ -876,6 +878,7 @@ B1136961230AC9D900E2B2FA /* MXIdentityService.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = MXIdentityService.m; sourceTree = ""; }; B1136966230C1E8600E2B2FA /* MXIdentityService.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = MXIdentityService.swift; sourceTree = ""; }; B11556ED230C45C600B2A2CF /* MXIdentityServerRestClient.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = MXIdentityServerRestClient.swift; sourceTree = ""; }; + B11976FD236B27220001EC86 /* MXBackgroundTask.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = MXBackgroundTask.h; sourceTree = ""; }; B11BD44622CB56790064D8B0 /* MXReplyEventParser.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = MXReplyEventParser.h; sourceTree = ""; }; B11BD44722CB56790064D8B0 /* MXReplyEventParser.m */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.objc; path = MXReplyEventParser.m; sourceTree = ""; }; B11BD44A22CB56E80064D8B0 /* MXReplyEventParts.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = MXReplyEventParts.h; sourceTree = ""; }; @@ -931,6 +934,8 @@ B17982F32119E4A1001FD722 /* MXRoomPredecessorInfo.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = MXRoomPredecessorInfo.m; sourceTree = ""; }; B17982F42119E4A2001FD722 /* MXRoomPowerLevels.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = MXRoomPowerLevels.m; sourceTree = ""; }; B1798303211B3649001FD722 /* MXRoomSummary.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = MXRoomSummary.swift; sourceTree = ""; }; + B17B2BDA2369FC81009D6650 /* MXUIKitBackgroundTask.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = MXUIKitBackgroundTask.h; sourceTree = ""; }; + B17B2BDB2369FC81009D6650 /* MXUIKitBackgroundTask.m */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.objc; path = MXUIKitBackgroundTask.m; sourceTree = ""; }; B182B08523167A640057972E /* MXIdentityServerHashDetails.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = MXIdentityServerHashDetails.h; sourceTree = ""; }; B182B08623167A640057972E /* MXIdentityServerHashDetails.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = MXIdentityServerHashDetails.m; sourceTree = ""; }; B18D18C12152B8E4003677D1 /* MXRoomMember.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = MXRoomMember.swift; sourceTree = ""; }; @@ -1136,6 +1141,9 @@ 32A9E8231EF4026E0081358A /* MXUIKitBackgroundModeHandler.m */, 32A9770221626E5C00919CC0 /* MXServerNotices.h */, 32A9770321626E5C00919CC0 /* MXServerNotices.m */, + B11976FD236B27220001EC86 /* MXBackgroundTask.h */, + B17B2BDA2369FC81009D6650 /* MXUIKitBackgroundTask.h */, + B17B2BDB2369FC81009D6650 /* MXUIKitBackgroundTask.m */, ); path = Utils; sourceTree = ""; @@ -2089,6 +2097,7 @@ 3294FD9F22F321B0007F1E60 /* MXServiceTermsRestClient.h in Headers */, 32954019216385F100E300FC /* MXServerNoticeContent.h in Headers */, 327187851DA7D0220071C818 /* MXOlmDecryption.h in Headers */, + B17B2BDC2369FC81009D6650 /* MXUIKitBackgroundTask.h in Headers */, 32D7767D1A27860600FC4AA2 /* MXMemoryStore.h in Headers */, 327E9AD72284803100A98BC1 /* MXEventAnnotationChunk.h in Headers */, 3252DCBD224D144C0032264F /* MXKeyVerificationAccept.h in Headers */, @@ -2494,6 +2503,7 @@ B11BD45522CB583E0064D8B0 /* MXReplyEventBodyParts.m in Sources */, 32F945F51FAB83D900622468 /* MXIncomingRoomKeyRequestCancellation.m in Sources */, 32D776821A27877300FC4AA2 /* MXMemoryRoomStore.m in Sources */, + B17B2BDD2369FC81009D6650 /* MXUIKitBackgroundTask.m in Sources */, 3293C701214BBA4F009B3DDB /* MXPeekingRoomSummary.m in Sources */, C602B58C1F2268F700B67D87 /* MXRoom.swift in Sources */, 32E402BA21C957D2004E87A6 /* MXOlmSession.m in Sources */, diff --git a/MatrixSDK/Utils/MXUIKitBackgroundTask.h b/MatrixSDK/Utils/MXUIKitBackgroundTask.h new file mode 100644 index 0000000000..02a91f8986 --- /dev/null +++ b/MatrixSDK/Utils/MXUIKitBackgroundTask.h @@ -0,0 +1,35 @@ +/* + Copyright 2019 The Matrix.org Foundation C.I.C + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + */ + +#import +#import "MXBackgroundTask.h" + +#if TARGET_OS_IPHONE + +NS_ASSUME_NONNULL_BEGIN + +/** + MXUIKitBackgroundTask is a concrete implementation of MXBackgroundTask using UIApplication background task. + */ +@interface MXUIKitBackgroundTask : NSObject + +- (instancetype)initAndStartWithName:(NSString*)name expirationHandler:(nullable MXBackgroundTaskExpirationHandler)expirationHandler; + +@end + +NS_ASSUME_NONNULL_END + +#endif diff --git a/MatrixSDK/Utils/MXUIKitBackgroundTask.m b/MatrixSDK/Utils/MXUIKitBackgroundTask.m new file mode 100644 index 0000000000..552dbd3c81 --- /dev/null +++ b/MatrixSDK/Utils/MXUIKitBackgroundTask.m @@ -0,0 +1,187 @@ +/* + Copyright 2019 The Matrix.org Foundation C.I.C + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + */ + +#import "MXUIKitBackgroundTask.h" + +#if TARGET_OS_IPHONE + +#import +#import "MXTools.h" + +@interface MXUIKitBackgroundTask () + +@property (nonatomic) UIBackgroundTaskIdentifier identifier; +@property (nonatomic, strong) NSString *name; +@property (nonatomic, copy, nullable) MXBackgroundTaskExpirationHandler expirationHandler; +@property (nonatomic, strong, nullable) NSDate *startDate; + +@end + +@implementation MXUIKitBackgroundTask + +#pragma Setup + +- (instancetype)initWithName:(NSString*)name expirationHandler:(MXBackgroundTaskExpirationHandler)expirationHandler +{ + self = [super init]; + if (self) + { + self.identifier = UIBackgroundTaskInvalid; + self.name = name; + self.expirationHandler = expirationHandler; + } + return self; +} + + +- (instancetype)initAndStartWithName:(NSString*)name expirationHandler:(MXBackgroundTaskExpirationHandler)expirationHandler +{ + self = [super init]; + if (self) + { + self.name = name; + + UIApplication *sharedApplication = [self sharedApplication]; + if (sharedApplication) + { + self.startDate = [NSDate date]; + + MXWeakify(self); + + self.identifier = [sharedApplication beginBackgroundTaskWithName:self.name expirationHandler:^{ + + MXStrongifyAndReturnIfNil(self); + + NSLog(@"[MXBackgroundTask] Background task expired #%lu - %@ after %.0fms", (unsigned long)self.identifier, self.name, self.elapsedTime); + + if (self.expirationHandler) + { + self.expirationHandler(); + } + + [self stop]; + }]; + + NSLog(@"[MXBackgroundTask] Start background task #%lu - %@", (unsigned long)self.identifier, self.name); + + // Note: -[UIApplication applicationState] and -[UIApplication backgroundTimeRemaining] must be must be used from main thread only + dispatch_async(dispatch_get_main_queue(), ^{ + NSString *readableAppState = [[self class] readableApplicationState:sharedApplication.applicationState]; + NSString *readableBackgroundTimeRemaining = [[self class] readableEstimatedBackgroundTimeRemaining:sharedApplication.backgroundTimeRemaining]; + + NSLog(@"[MXBackgroundTask] Background task #%lu - %@ started with app state: %@ and estimated background time remaining: %@", (unsigned long)self.identifier, self.name, readableAppState, readableBackgroundTimeRemaining); + }); + } + else + { + self.identifier = UIBackgroundTaskInvalid; + } + } + return self; +} + +- (void)dealloc +{ + [self stop]; +} + +- (BOOL)isRunning +{ + return self.identifier != UIBackgroundTaskInvalid; +} + +- (NSString *)description +{ + return [NSString stringWithFormat:@"<%@: %p, #%lu - %@>", NSStringFromClass([self class]), self, (unsigned long)self.identifier, self.name]; +} + +#pragma Public + +- (void)stop +{ + if (self.identifier != UIBackgroundTaskInvalid) + { + UIApplication *sharedApplication = [self sharedApplication]; + if (sharedApplication) + { + NSLog(@"[MXBackgroundTask] Stop background task #%lu - %@ after %.0fms", (unsigned long)self.identifier, self.name, self.elapsedTime); + + [sharedApplication endBackgroundTask:self.identifier]; + self.identifier = UIBackgroundTaskInvalid; + } + } +} + +#pragma Private + +- (NSTimeInterval)elapsedTime +{ + NSTimeInterval elapasedTime = 0; + + if (self.startDate) + { + elapasedTime = [[NSDate date] timeIntervalSinceDate:self.startDate] * 1000.0; + } + + return elapasedTime; +} + +- (UIApplication*)sharedApplication +{ + return [UIApplication performSelector:@selector(sharedApplication)]; +} + ++ (NSString*)readableEstimatedBackgroundTimeRemaining:(NSTimeInterval)backgroundTimeRemaining +{ + NSString *backgroundTimeRemainingValueString; + + if (backgroundTimeRemaining == DBL_MAX) + { + backgroundTimeRemainingValueString = @"undetermined"; + } + else + { + backgroundTimeRemainingValueString = [NSString stringWithFormat:@"%.0f seconds", backgroundTimeRemaining]; + } + + return backgroundTimeRemainingValueString; +} + ++ (NSString*)readableApplicationState:(UIApplicationState)applicationState +{ + NSString *applicationStateDescription; + + switch (applicationState) { + case UIApplicationStateActive: + applicationStateDescription = @"active"; + break; + case UIApplicationStateInactive: + applicationStateDescription = @"inactive"; + break; + case UIApplicationStateBackground: + applicationStateDescription = @"background"; + break; + default: + applicationStateDescription = @"unknown"; + break; + } + + return applicationStateDescription; +} + +@end + +#endif From 0dfada082a5b8456739b2570a821943fffe03113 Mon Sep 17 00:00:00 2001 From: SBiOSoftWhare Date: Tue, 5 Nov 2019 16:39:15 +0100 Subject: [PATCH 19/25] MXBackgroundTaskExpirationHandler: Update interface and now return a MXBackgroundTask instead of NSUInteger identifier. --- MatrixSDK/Utils/MXBackgroundModeHandler.h | 15 +++++++++++---- 1 file changed, 11 insertions(+), 4 deletions(-) diff --git a/MatrixSDK/Utils/MXBackgroundModeHandler.h b/MatrixSDK/Utils/MXBackgroundModeHandler.h index e728d1f67c..d9013fbd5f 100644 --- a/MatrixSDK/Utils/MXBackgroundModeHandler.h +++ b/MatrixSDK/Utils/MXBackgroundModeHandler.h @@ -1,6 +1,7 @@ /* Copyright 2017 Samuel Gallet Copyright 2017 Vector Creations Ltd + Copyright 2019 The Matrix.org Foundation C.I.C Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. @@ -19,15 +20,21 @@ #define MXBackgroundModeHandler_h #import +#import "MXBackgroundTask.h" + +typedef void (^MXBackgroundTaskExpirationHandler)(void); + +NS_ASSUME_NONNULL_BEGIN /** Interface to handle enabling background mode */ @protocol MXBackgroundModeHandler -- (NSUInteger)invalidIdentifier; -- (NSUInteger)startBackgroundTask; -- (NSUInteger)startBackgroundTaskWithName:(NSString *)name completion:(void(^)(void))completion; -- (void)endBackgrounTaskWithIdentifier:(NSUInteger)identifier; + +- (id)startBackgroundTaskWithName:(NSString *)name expirationHandler:(nullable MXBackgroundTaskExpirationHandler)expirationHandler; + @end +NS_ASSUME_NONNULL_END + #endif /* MXBackgroundModeHandler_h */ From b5566ff67257d0487f44a5544c0c14004df460cf Mon Sep 17 00:00:00 2001 From: SBiOSoftWhare Date: Tue, 5 Nov 2019 16:41:40 +0100 Subject: [PATCH 20/25] MXUIKitBackgroundModeHandler: Use MXUIKitBackgroundTask. --- .../Utils/MXUIKitBackgroundModeHandler.m | 40 ++----------------- 1 file changed, 4 insertions(+), 36 deletions(-) diff --git a/MatrixSDK/Utils/MXUIKitBackgroundModeHandler.m b/MatrixSDK/Utils/MXUIKitBackgroundModeHandler.m index 014c99c8d7..1844c52c16 100644 --- a/MatrixSDK/Utils/MXUIKitBackgroundModeHandler.m +++ b/MatrixSDK/Utils/MXUIKitBackgroundModeHandler.m @@ -1,5 +1,6 @@ /* Copyright 2017 Vector Creations Ltd + Copyright 2019 The Matrix.org Foundation C.I.C Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. @@ -19,48 +20,15 @@ #if TARGET_OS_IPHONE #import +#import "MXUIKitBackgroundTask.h" @implementation MXUIKitBackgroundModeHandler #pragma mark - MXBackgroundModeHandler -- (NSUInteger)invalidIdentifier +- (id)startBackgroundTaskWithName:(NSString *)name expirationHandler:(nullable MXBackgroundTaskExpirationHandler)expirationHandler { - return UIBackgroundTaskInvalid; -} - -- (NSUInteger)startBackgroundTask -{ - return [self startBackgroundTaskWithName:nil completion:nil]; -} - -- (NSUInteger)startBackgroundTaskWithName:(NSString *)name completion:(void(^)(void))completion -{ - NSUInteger token = UIBackgroundTaskInvalid; - - UIApplication *sharedApplication = [UIApplication performSelector:@selector(sharedApplication)]; - if (sharedApplication) - { - if (name) - { - token = [sharedApplication beginBackgroundTaskWithName:name expirationHandler:completion]; - } - else - { - token = [sharedApplication beginBackgroundTaskWithExpirationHandler:completion]; - } - } - - return token; -} - -- (void)endBackgrounTaskWithIdentifier:(NSUInteger)identifier -{ - UIApplication *sharedApplication = [UIApplication performSelector:@selector(sharedApplication)]; - if (sharedApplication) - { - [sharedApplication endBackgroundTask:identifier]; - } + return [[MXUIKitBackgroundTask alloc] initAndStartWithName:name expirationHandler:expirationHandler];; } @end From 62f2f85b4f52a8b9502095de2fe1922f70f0ea70 Mon Sep 17 00:00:00 2001 From: SBiOSoftWhare Date: Tue, 5 Nov 2019 16:42:23 +0100 Subject: [PATCH 21/25] MXSession: Update with MXBackgroundTask. --- MatrixSDK/MXSession.m | 53 +++++++++++++++++-------------------------- 1 file changed, 21 insertions(+), 32 deletions(-) diff --git a/MatrixSDK/MXSession.m b/MatrixSDK/MXSession.m index 78614860b8..00a3fb0a40 100644 --- a/MatrixSDK/MXSession.m +++ b/MatrixSDK/MXSession.m @@ -143,12 +143,6 @@ The list of global events listeners (`MXSessionEventListener`). */ NSMutableArray *peekingRooms; - /** - The background task used when the session continue to run the events stream when - the app goes in background. - */ - NSUInteger backgroundTaskIdentifier; - /** For debug, indicate if the first sync after the MXSession startup is done. */ @@ -179,6 +173,12 @@ Queue of requested direct room change operations ([MXSession setRoom:directWithU @property (nonatomic, readwrite) MXScanManager *scanManager; +/** + The background task used when the session continue to run the events stream when + the app goes in background. + */ +@property (nonatomic, strong) id backgroundTask; + @end @implementation MXSession @@ -207,12 +207,6 @@ - (id)initWithMatrixRestClient:(MXRestClient*)mxRestClient firstSyncDone = NO; - id handler = [MXSDKOptions sharedInstance].backgroundModeHandler; - if (handler) - { - backgroundTaskIdentifier = [handler invalidIdentifier]; - } - _acknowledgableEventTypes = @[kMXEventTypeStringRoomName, kMXEventTypeStringRoomTopic, kMXEventTypeStringRoomAvatar, @@ -600,18 +594,17 @@ - (void)pause NSLog(@"[MXSession pause] Prevent the session from being paused. preventPauseCount: %tu", _preventPauseCount); id handler = [MXSDKOptions sharedInstance].backgroundModeHandler; - if (handler && backgroundTaskIdentifier == [handler invalidIdentifier]) + + if (handler && !self.backgroundTask.isRunning) { MXWeakify(self); - backgroundTaskIdentifier = [handler startBackgroundTaskWithName:@"MXSessionBackgroundTask" completion:^{ + + self.backgroundTask = [handler startBackgroundTaskWithName:@"[MXSession] pause" expirationHandler:^{ MXStrongifyAndReturnIfNil(self); - - NSLog(@"[MXSession pause] Background task #%tu is going to expire - ending it", self->backgroundTaskIdentifier); // We cannot continue to run in background. Pause the session for real self.preventPauseCount = 0; }]; - NSLog(@"[MXSession pause] Created background task #%tu", backgroundTaskIdentifier); } [self setState:MXSessionStatePauseRequested]; @@ -644,13 +637,11 @@ - (void)pause - (void)resume:(void (^)(void))resumeDone { NSLog(@"[MXSession] resume the event stream from state %tu", _state); - - id handler = [MXSDKOptions sharedInstance].backgroundModeHandler; - if (handler && backgroundTaskIdentifier != [handler invalidIdentifier]) + + if (self.backgroundTask.isRunning) { - NSLog(@"[MXSession resume] Stop background task #%tu", backgroundTaskIdentifier); - [handler endBackgrounTaskWithIdentifier:backgroundTaskIdentifier]; - backgroundTaskIdentifier = [handler invalidIdentifier]; + [self.backgroundTask stop]; + self.backgroundTask = nil; } // Check whether no request is already in progress @@ -790,11 +781,10 @@ - (void)close userIdsWithOutdatedPublicisedGroups = nil; // Stop background task - id handler = [MXSDKOptions sharedInstance].backgroundModeHandler; - if (handler && backgroundTaskIdentifier != [handler invalidIdentifier]) + if (self.backgroundTask.isRunning) { - [handler endBackgrounTaskWithIdentifier:backgroundTaskIdentifier]; - backgroundTaskIdentifier = [handler invalidIdentifier]; + [self.backgroundTask stop]; + self.backgroundTask = nil; } _myUser = nil; @@ -902,12 +892,11 @@ - (void)setPreventPauseCount:(NSUInteger)preventPauseCount if (_preventPauseCount == 0) { // The background task can be released - id handler = [MXSDKOptions sharedInstance].backgroundModeHandler; - if (handler && backgroundTaskIdentifier != [handler invalidIdentifier]) + if (self.backgroundTask.isRunning) { - NSLog(@"[MXSession pause] Stop background task #%tu", backgroundTaskIdentifier); - [handler endBackgrounTaskWithIdentifier:backgroundTaskIdentifier]; - backgroundTaskIdentifier = [handler invalidIdentifier]; + NSLog(@"[MXSession pause] Stop background task %@", self.backgroundTask); + [self.backgroundTask stop]; + self.backgroundTask = nil; } // And the session can be paused for real if it was not resumed before From 6caa632f8f8d2af21d19d79e3262247f71cb50a9 Mon Sep 17 00:00:00 2001 From: SBiOSoftWhare Date: Tue, 5 Nov 2019 16:42:44 +0100 Subject: [PATCH 22/25] MXFileStore: Update with MXBackgroundTask. --- .../Data/Store/MXFileStore/MXFileStore.m | 82 +++++++------------ 1 file changed, 31 insertions(+), 51 deletions(-) diff --git a/MatrixSDK/Data/Store/MXFileStore/MXFileStore.m b/MatrixSDK/Data/Store/MXFileStore/MXFileStore.m index 241c35d00c..49c05473f6 100644 --- a/MatrixSDK/Data/Store/MXFileStore/MXFileStore.m +++ b/MatrixSDK/Data/Store/MXFileStore/MXFileStore.m @@ -107,14 +107,16 @@ @interface MXFileStore () // The number of commits being done NSUInteger pendingCommits; - - // The current background task id if any - NSUInteger backgroundTaskIdentifier; + NSDate *backgroundTaskStartDate; // The evenst stream token that corresponds to the data being backed up. NSString *backupEventStreamToken; } + +// The commit to file store background task +@property (nonatomic, strong) id commitBackgroundTask; + @end @implementation MXFileStore @@ -152,9 +154,6 @@ - (instancetype)init; dispatchQueue = dispatch_queue_create("MXFileStoreDispatchQueue", DISPATCH_QUEUE_SERIAL); pendingCommits = 0; - - id handler = [MXSDKOptions sharedInstance].backgroundModeHandler; - backgroundTaskIdentifier = [handler invalidIdentifier]; } return self; } @@ -178,11 +177,8 @@ - (void)openWithCredentials:(MXCredentials*)someCredentials onComplete:(void (^) [self setUpStoragePaths]; id handler = [MXSDKOptions sharedInstance].backgroundModeHandler; - __block NSUInteger bgTaskId = [handler startBackgroundTaskWithName:@"openWithCredentials" completion:^{ - NSLog(@"[MXFileStore] Background task is going to expire in openWithCredentials"); - [handler endBackgrounTaskWithIdentifier:bgTaskId]; - bgTaskId = [handler invalidIdentifier]; - }]; + + id backgroundTask = [handler startBackgroundTaskWithName:@"[MXFileStore] openWithCredentials:onComplete:failure:" expirationHandler:nil]; /* Mount data corresponding to the account credentials. @@ -263,12 +259,7 @@ - (void)openWithCredentials:(MXCredentials*)someCredentials onComplete:(void (^) } dispatch_async(dispatch_get_main_queue(), ^{ - id handler = [MXSDKOptions sharedInstance].backgroundModeHandler; - if (handler && bgTaskId != [handler invalidIdentifier]) - { - [handler endBackgrounTaskWithIdentifier:bgTaskId]; - bgTaskId = [handler invalidIdentifier]; - } + [backgroundTask stop]; onComplete(); }); @@ -666,30 +657,26 @@ - (void)commit MXWeakify(self); NSDate *startDate = [NSDate date]; - - id handler = [MXSDKOptions sharedInstance].backgroundModeHandler; - if (handler) + + // Create a bg task if none is available + if (self.commitBackgroundTask.isRunning) + { + NSLog(@"[MXFileStore commit] Background task %@ reused", self.commitBackgroundTask); + } + else { - // Create a bg task if none is available - if (backgroundTaskIdentifier == [handler invalidIdentifier]) + MXWeakify(self); + + id handler = [MXSDKOptions sharedInstance].backgroundModeHandler; + if (handler) { backgroundTaskStartDate = startDate; - - backgroundTaskIdentifier = [handler startBackgroundTaskWithName:@"commit" completion:^{ + + self.commitBackgroundTask = [handler startBackgroundTaskWithName:@"[MXStore] commit" expirationHandler:^{ MXStrongifyAndReturnIfNil(self); - - NSLog(@"[MXFileStore commit] Background task #%tu is going to expire after %.0fms - ending it. pendingCommits: %tu", - self->backgroundTaskIdentifier, [[NSDate date] timeIntervalSinceDate:self->backgroundTaskStartDate] * 1000, self->pendingCommits); - - [handler endBackgrounTaskWithIdentifier:self->backgroundTaskIdentifier]; - self->backgroundTaskIdentifier = [handler invalidIdentifier]; + + NSLog(@"[MXFileStore commit] Background task %@ is going to expire - ending it. pendingCommits: %tu", self.commitBackgroundTask, self->pendingCommits); }]; - - NSLog(@"[MXFileStore commit] Background task #%tu started", backgroundTaskIdentifier); - } - else - { - NSLog(@"[MXFileStore commit] Background task #%tu reused", backgroundTaskIdentifier); } } @@ -708,22 +695,15 @@ - (void)commit NSLog(@"[MXFileStore commit] lasted %.0fms", [[NSDate date] timeIntervalSinceDate:startDate] * 1000); self->pendingCommits--; - - if (handler) + + if (self.commitBackgroundTask.isRunning && self->pendingCommits == 0) { - if (self->pendingCommits == 0) - { - NSLog(@"[MXFileStore commit] Background task #%tu is complete - lasted %.0fms", - self->backgroundTaskIdentifier, [[NSDate date] timeIntervalSinceDate:self->backgroundTaskStartDate] * 1000); - - [handler endBackgrounTaskWithIdentifier:self->backgroundTaskIdentifier]; - self->backgroundTaskIdentifier = [handler invalidIdentifier]; - } - else - { - NSLog(@"[MXFileStore commit] Background task #%tu is kept - running since %.0fms", - self->backgroundTaskIdentifier, [[NSDate date] timeIntervalSinceDate:self->backgroundTaskStartDate] * 1000); - } + [self.commitBackgroundTask stop]; + self.commitBackgroundTask = nil; + } + else if (self.commitBackgroundTask.isRunning) + { + NSLog(@"[MXFileStore commit] Background task %@ is kept - running since %.0fms", self.commitBackgroundTask, [[NSDate date] timeIntervalSinceDate:self->backgroundTaskStartDate] * 1000); } }); }); From 610977649a7ddd21b0c21300791a3980ae334cb7 Mon Sep 17 00:00:00 2001 From: SBiOSoftWhare Date: Tue, 5 Nov 2019 16:43:09 +0100 Subject: [PATCH 23/25] MXHTTPClient: Update with MXBackgroundTask. --- MatrixSDK/Utils/MXHTTPClient.m | 43 ++++++++++------------------------ 1 file changed, 13 insertions(+), 30 deletions(-) diff --git a/MatrixSDK/Utils/MXHTTPClient.m b/MatrixSDK/Utils/MXHTTPClient.m index 8119e9ddd9..38c6497bf8 100644 --- a/MatrixSDK/Utils/MXHTTPClient.m +++ b/MatrixSDK/Utils/MXHTTPClient.m @@ -70,11 +70,6 @@ @interface MXHTTPClient () */ MXHTTPClientOnUnrecognizedCertificate onUnrecognizedCertificateBlock; - /** - The current background task id if any. - */ - NSUInteger backgroundTaskIdentifier; - /** Flag to indicate that the underlying NSURLSession has been invalidated. In this state, we can not use anymore NSURLSession else it crashes. @@ -87,6 +82,11 @@ @interface MXHTTPClient () */ @property (nonatomic, strong) NSString *accessToken; +/** + The current background task id if any. + */ +@property (nonatomic, strong) id backgroundTask; + @end @implementation MXHTTPClient @@ -123,12 +123,6 @@ -(id)initWithBaseURL:(NSString *)baseURL accessToken:(NSString *)accessToken and onUnrecognizedCertificateBlock = onUnrecognizedCertBlock; - id handler = [MXSDKOptions sharedInstance].backgroundModeHandler; - if (handler) - { - backgroundTaskIdentifier = [handler invalidIdentifier]; - } - // Send requests parameters in JSON format by default self.requestParametersInJSON = YES; @@ -696,27 +690,20 @@ - (void)startBackgroundTask @synchronized(self) { id handler = [MXSDKOptions sharedInstance].backgroundModeHandler; - if (handler && backgroundTaskIdentifier == [handler invalidIdentifier]) + if (handler && !self.backgroundTask.isRunning) { MXWeakify(self); - backgroundTaskIdentifier = [handler startBackgroundTaskWithName:nil completion:^{ - - NSLog(@"[MXHTTPClient] Background task #%tu is going to expire - Try to end it", - self->backgroundTaskIdentifier); - + self.backgroundTask = [handler startBackgroundTaskWithName:@"[MXHTTPClient] startBackgroundTask" expirationHandler:^{ + MXStrongifyAndReturnIfNil(self); - + // Cancel all the tasks currently run by the managed session NSArray *tasks = self->httpManager.tasks; for (NSURLSessionTask *sessionTask in tasks) { [sessionTask cancel]; } - - [self cleanupBackgroundTask]; }]; - - NSLog(@"[MXHTTPClient] Background task #%tu started", backgroundTaskIdentifier); } } } @@ -730,17 +717,13 @@ - (void)startBackgroundTask - (void)cleanupBackgroundTask { NSLog(@"[MXHTTPClient] cleanupBackgroundTask"); - + @synchronized(self) { - id handler = [MXSDKOptions sharedInstance].backgroundModeHandler; - if (handler && backgroundTaskIdentifier != [handler invalidIdentifier] && httpManager.tasks.count == 0) + if (self.backgroundTask.isRunning && httpManager.tasks.count == 0) { - NSLog(@"[MXHTTPClient] Background task #%tu is complete", - backgroundTaskIdentifier); - - [handler endBackgrounTaskWithIdentifier:backgroundTaskIdentifier]; - backgroundTaskIdentifier = [handler invalidIdentifier]; + [self.backgroundTask stop]; + self.backgroundTask = nil; } } } From 2421fe18b50e4fd8a7e50ab4ffd8fe9df0068f8d Mon Sep 17 00:00:00 2001 From: SBiOSoftWhare Date: Tue, 5 Nov 2019 16:49:04 +0100 Subject: [PATCH 24/25] Update changes --- CHANGES.rst | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/CHANGES.rst b/CHANGES.rst index 2a6a70c139..8af2b8d893 100644 --- a/CHANGES.rst +++ b/CHANGES.rst @@ -5,6 +5,7 @@ Improvements: * MX3PidAddManager: Add User-Interactive Auth to /account/3pid/add (vector-im/riot-ios#2744). * MXSession: On resume, make the first /sync request trigger earlier (vector-im/riot-ios#2793). * MXCrypto: Do not fail to decrypt when there is nothing to decrypt (redacted events). + * MXBackgroundModeHandler: Update interface and now return a MXBackgroundTask, a protocol describing a background task regardless of the plartform used. Bug fix: * Room members who left are listed with the actual members (vector-im/riot-ios#2737). @@ -13,6 +14,9 @@ Bug fix: * MXHTTPOperation: Fix a crash in `-mutateTo:` method when operation parameter is nil. * VoIP: Fix regression when using a TURN server (vector-im/riot-ios#2796). +API break: + * MXBackgroundModeHandler: Update interface and now use a single method that return a MXBackgroundTask. + Changes in Matrix iOS SDK in 0.14.0 (2019-10-11) =============================================== From b6df05414e2022a84c9ce4606e446e53ab1e2d91 Mon Sep 17 00:00:00 2001 From: SBiOSoftWhare Date: Wed, 6 Nov 2019 19:53:58 +0100 Subject: [PATCH 25/25] version++ --- CHANGES.rst | 2 +- Gemfile.lock | 26 +++++++++++++------------- MatrixSDK.podspec | 2 +- MatrixSDK/MXSession.m | 2 +- Podfile.lock | 8 ++++---- SwiftMatrixSDK.podspec | 2 +- 6 files changed, 21 insertions(+), 21 deletions(-) diff --git a/CHANGES.rst b/CHANGES.rst index 8af2b8d893..b06ab19e93 100644 --- a/CHANGES.rst +++ b/CHANGES.rst @@ -1,4 +1,4 @@ -Changes in Matrix iOS SDK in 0.xx.xx (2019-xx-xx) +Changes in Matrix iOS SDK in 0.15.0 (2019-11-06) =============================================== Improvements: diff --git a/Gemfile.lock b/Gemfile.lock index f2c63a42a3..e7ff0d866c 100644 --- a/Gemfile.lock +++ b/Gemfile.lock @@ -15,10 +15,10 @@ GEM atomos (0.1.3) babosa (1.0.3) claide (1.0.3) - cocoapods (1.8.3) + cocoapods (1.8.4) activesupport (>= 4.0.2, < 5) claide (>= 1.0.2, < 2.0) - cocoapods-core (= 1.8.3) + cocoapods-core (= 1.8.4) cocoapods-deintegrate (>= 1.0.3, < 2.0) cocoapods-downloader (>= 1.2.2, < 2.0) cocoapods-plugins (>= 1.0.0, < 2.0) @@ -34,7 +34,7 @@ GEM nap (~> 1.0) ruby-macho (~> 1.4) xcodeproj (>= 1.11.1, < 2.0) - cocoapods-core (1.8.3) + cocoapods-core (1.8.4) activesupport (>= 4.0.2, < 6) algoliasearch (~> 1.0) concurrent-ruby (~> 1.1) @@ -63,8 +63,8 @@ GEM dotenv (2.7.5) emoji_regex (1.0.1) escape (0.0.4) - excon (0.67.0) - faraday (0.15.4) + excon (0.68.0) + faraday (0.17.0) multipart-post (>= 1.2, < 3) faraday-cookie_jar (0.0.6) faraday (>= 0.7.4) @@ -72,7 +72,7 @@ GEM faraday_middleware (0.13.1) faraday (>= 0.7.4, < 1.0) fastimage (2.1.7) - fastlane (2.133.0) + fastlane (2.134.0) CFPropertyList (>= 2.3, < 4.0.0) addressable (>= 2.3, < 3.0.0) babosa (>= 1.0.2, < 2.0.0) @@ -82,9 +82,9 @@ GEM dotenv (>= 2.1.1, < 3.0.0) emoji_regex (>= 0.1, < 2.0) excon (>= 0.45.0, < 1.0.0) - faraday (< 0.16.0) + faraday (~> 0.17) faraday-cookie_jar (~> 0.0.6) - faraday_middleware (< 0.16.0) + faraday_middleware (~> 0.13.1) fastimage (>= 2.1.0, < 3.0.0) gh_inspector (>= 1.1.2, < 2.0.0) google-api-client (>= 0.21.2, < 0.24.0) @@ -120,7 +120,7 @@ GEM representable (~> 3.0) retriable (>= 2.0, < 4.0) signet (~> 0.9) - google-cloud-core (1.3.1) + google-cloud-core (1.3.2) google-cloud-env (~> 1.0) google-cloud-env (1.2.1) faraday (~> 0.11) @@ -147,11 +147,11 @@ GEM memoist (0.16.0) mime-types (3.3) mime-types-data (~> 3.2015) - mime-types-data (3.2019.0904) + mime-types-data (3.2019.1009) mini_magick (4.9.5) - minitest (5.12.2) + minitest (5.13.0) molinillo (0.6.6) - multi_json (1.13.1) + multi_json (1.14.1) multi_xml (0.6.0) multipart-post (2.0.0) nanaimo (0.2.6) @@ -195,7 +195,7 @@ GEM unf_ext (0.0.7.6) unicode-display_width (1.6.0) word_wrap (1.0.0) - xcodeproj (1.12.0) + xcodeproj (1.13.0) CFPropertyList (>= 2.3.3, < 4.0) atomos (~> 0.1.3) claide (>= 1.0.2, < 2.0) diff --git a/MatrixSDK.podspec b/MatrixSDK.podspec index 6255370fa0..75e5c2d589 100644 --- a/MatrixSDK.podspec +++ b/MatrixSDK.podspec @@ -1,7 +1,7 @@ Pod::Spec.new do |s| s.name = "MatrixSDK" - s.version = "0.14.0" + s.version = "0.15.0" s.summary = "The iOS SDK to build apps compatible with Matrix (https://www.matrix.org)" s.description = <<-DESC diff --git a/MatrixSDK/MXSession.m b/MatrixSDK/MXSession.m index 00a3fb0a40..6f3d29c1cf 100644 --- a/MatrixSDK/MXSession.m +++ b/MatrixSDK/MXSession.m @@ -47,7 +47,7 @@ #pragma mark - Constants definitions -const NSString *MatrixSDKVersion = @"0.14.0"; +const NSString *MatrixSDKVersion = @"0.15.0"; NSString *const kMXSessionStateDidChangeNotification = @"kMXSessionStateDidChangeNotification"; NSString *const kMXSessionNewRoomNotification = @"kMXSessionNewRoomNotification"; NSString *const kMXSessionWillLeaveRoomNotification = @"kMXSessionWillLeaveRoomNotification"; diff --git a/Podfile.lock b/Podfile.lock index 257225c170..318d7bdd4f 100644 --- a/Podfile.lock +++ b/Podfile.lock @@ -14,7 +14,7 @@ PODS: - AFNetworking/Serialization (3.2.1) - AFNetworking/UIKit (3.2.1): - AFNetworking/NSURLSession - - GZIP (1.2.2) + - GZIP (1.2.3) - libbase58 (0.1.4) - OHHTTPStubs (6.1.0): - OHHTTPStubs/Default (= 6.1.0) @@ -47,7 +47,7 @@ DEPENDENCIES: - Realm (~> 3.17.3) SPEC REPOS: - https://github.com/CocoaPods/Specs.git: + trunk: - AFNetworking - GZIP - libbase58 @@ -57,12 +57,12 @@ SPEC REPOS: SPEC CHECKSUMS: AFNetworking: b6f891fdfaed196b46c7a83cf209e09697b94057 - GZIP: 12374d285e3b5d46cfcd480700fcfc7e16caf4f1 + GZIP: af5c90ef903776a7e9afe6ebebd794a84a2929d4 libbase58: 7c040313537b8c44b6e2d15586af8e21f7354efd OHHTTPStubs: 1e21c7d2c084b8153fc53d48400d8919d2d432d0 OLMKit: 4ee0159d63feeb86d836fdcfefe418e163511639 Realm: 5a1d9d47bfc101dd597668b1a8af4288a2557f6d -PODFILE CHECKSUM: a3d1ca57b0ed793a3a7ee01236209a432c74692c +PODFILE CHECKSUM: d69c3d22d9b1c54e6559db65160f6af8f81c45dd COCOAPODS: 1.8.4 diff --git a/SwiftMatrixSDK.podspec b/SwiftMatrixSDK.podspec index f84ce5cc61..dae66bd263 100644 --- a/SwiftMatrixSDK.podspec +++ b/SwiftMatrixSDK.podspec @@ -1,7 +1,7 @@ Pod::Spec.new do |s| s.name = "SwiftMatrixSDK" - s.version = "0.14.0" + s.version = "0.15.0" s.summary = "The iOS SDK to build apps compatible with Matrix (https://www.matrix.org)" s.description = <<-DESC