forked from matrix-org/matrix-ios-sdk
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathMXRestClient.m
6099 lines (5429 loc) · 276 KB
/
MXRestClient.m
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
Copyright 2014 OpenMarket Ltd
Copyright 2017 Vector Creations Ltd
Copyright 2018 New Vector 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.
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 "MXRestClient.h"
#import "MXSDKOptions.h"
#import "MXJSONModel.h"
#import "MXRefreshResponse.h"
#import "MXTools.h"
#import "MXError.h"
#import "MXEvent.h"
#import "MXAllowedCertificates.h"
#import "MXThirdpartyProtocolsResponse.h"
#import "MXThirdPartyUsersResponse.h"
#import "MXRefreshTokenData.h"
#import "MatrixSDKSwiftHeader.h"
#pragma mark - Constants definitions
/**
Prefix used in path of home server API requests.
*/
NSString *const kMXAPIPrefixPathR0 = @"_matrix/client/r0";
NSString *const kMXAPIPrefixPathV1 = @"_matrix/client/v1";
NSString *const kMXAPIPrefixPathV3 = @"_matrix/client/v3";
NSString *const kMXAPIPrefixPathUnstable = @"_matrix/client/unstable";
/**
Account data types
*/
NSString *const kMXAccountDataTypeIgnoredUserList = @"m.ignored_user_list";
NSString *const kMXAccountDataTypePushRules = @"m.push_rules";
NSString *const kMXAccountDataTypeDirect = @"m.direct";
NSString *const kMXAccountDataTypeUserWidgets = @"m.widgets";
NSString *const kMXAccountDataTypeIdentityServer = @"m.identity_server";
NSString *const kMXAccountDataTypeAcceptedTerms = @"m.accepted_terms";
NSString *const kMXAccountDataTypeBreadcrumbs = @"im.vector.setting.breadcrumbs";
/**
Account data keys
*/
NSString *const kMXAccountDataKeyIgnoredUser = @"ignored_users";
NSString *const kMXAccountDataKeyIdentityServer = @"base_url";
NSString *const kMXAccountDataTypeAcceptedTermsKey = @"accepted";
NSString *const kMXAccountDataTypeRecentRoomsKey = @"recent_rooms";
/**
Types of third party media.
The list is not exhautive and depends on the Identity server capabilities.
*/
NSString *const kMX3PIDMediumEmail = @"email";
NSString *const kMX3PIDMediumMSISDN = @"msisdn";
// Room creation dictionary key for third party id invites.
NSString *const kMXInvite3PIDKey = @"invite_3pid";
// Third party id invite key for access token.
NSString *const kMX3PIDAccessTokenKey = @"id_access_token";
/**
MXRestClient error domain
*/
NSString *const kMXRestClientErrorDomain = @"kMXRestClientErrorDomain";
/**
Parameters that can be used in [MXRestClient membersOfRoom:withParameters:...].
*/
NSString *const kMXMembersOfRoomParametersAt = @"at";
NSString *const kMXMembersOfRoomParametersMembership = @"membership";
NSString *const kMXMembersOfRoomParametersNotMembership = @"not_membership";
/**
Timeline direction constants can be used in `-[MXRestClient messagesForRoom:...]` or `-[MXRestClient relationsForEvent:...]` methods.
*/
NSString *const kMXTimelineDirectionForwards = @"f";
NSString *const kMXTimelineDirectionBackwards = @"b";
NSString *const MXCredentialsUpdateTokensNotification = @"MXCredentialsUpdateTokensNotification";
NSString *const kMXCredentialsNewRefreshTokenDataKey = @"refresh_token_data";
/**
The time interval before the access token expires that we will start trying to refresh the token.
This avoids us having to block other users requests while the token refreshes.
Choosing a value larger than SERVER_TIMEOUT_MS guarantees an authenticated request will be attempted(causing a refresh) before the token expires.
*/
#define PREEMPT_REFRESH_EXPIRATION_INTERVAL 60000
/**
Authentication flow: register or login
*/
typedef enum
{
MXAuthActionRegister,
MXAuthActionLogin
}
MXAuthAction;
#pragma mark - MXRestClient
@interface MXRestClient ()
{
/**
HTTP client to the home server.
*/
MXHTTPClient *httpClient;
/**
HTTP client to the antivirus server.
*/
MXHTTPClient *antivirusHttpClient;
/**
The queue to process server response.
This queue is used to create models from JSON dictionary without blocking the main thread.
*/
dispatch_queue_t processingQueue;
}
@end
@implementation MXRestClient
@synthesize credentials, apiPathPrefix, contentPathPrefix, completionQueue, antivirusServerPathPrefix;
+ (dispatch_queue_t)refreshQueue
{
static dispatch_once_t pred = 0;
static id _refreshQueue = nil;
dispatch_once(&pred, ^{
_refreshQueue = dispatch_queue_create("MXRestClient.refreshQueue", DISPATCH_QUEUE_SERIAL);
});
return _refreshQueue;
}
+ (dispatch_group_t)refreshDispatchGroup
{
static dispatch_once_t pred = 0;
static id _refreshDispatchGroup = nil;
dispatch_once(&pred, ^{
_refreshDispatchGroup = dispatch_group_create();
});
return _refreshDispatchGroup;
}
-(id)initWithHomeServer:(NSString *)homeserver andOnUnrecognizedCertificateBlock:(MXHTTPClientOnUnrecognizedCertificate)onUnrecognizedCertBlock
{
MXCredentials *credentials = [MXCredentials new];
credentials.homeServer = homeserver;
return [self initWithCredentials:credentials andOnUnrecognizedCertificateBlock:onUnrecognizedCertBlock andPersistentTokenDataHandler:nil andUnauthenticatedHandler:nil];
}
-(id)initWithCredentials:(MXCredentials*)inCredentials
andOnUnrecognizedCertificateBlock:(MXHTTPClientOnUnrecognizedCertificate)onUnrecognizedCertBlock
{
return [self initWithCredentials:inCredentials andOnUnrecognizedCertificateBlock:onUnrecognizedCertBlock andPersistentTokenDataHandler:nil andUnauthenticatedHandler:nil];
}
-(id)initWithCredentials:(MXCredentials*)inCredentials
{
return [self initWithCredentials:inCredentials andOnUnrecognizedCertificateBlock:nil andPersistentTokenDataHandler:nil andUnauthenticatedHandler:nil];
}
-(id)initWithCredentials:(MXCredentials*)inCredentials
andOnUnrecognizedCertificateBlock:(MXHTTPClientOnUnrecognizedCertificate)onUnrecognizedCertBlock
andPersistentTokenDataHandler: (MXRestClientPersistTokenDataHandler)persistentTokenDataHandler
andUnauthenticatedHandler: (MXRestClientUnauthenticatedHandler)unauthenticatedHandler
{
self = [super init];
if (self)
{
apiPathPrefix = kMXAPIPrefixPathR0;
antivirusServerPathPrefix = kMXAntivirusAPIPrefixPathUnstable;
contentPathPrefix = kMXContentPrefixPath;
credentials = inCredentials;
_identityServer = credentials.identityServer;
_unauthenticatedHandler = unauthenticatedHandler;
_persistTokenDataHandler = persistentTokenDataHandler;
if (credentials.homeServer)
{
httpClient = [[MXHTTPClient alloc] initWithBaseURL:credentials.homeServer
authenticated: credentials.accessToken != nil
andOnUnrecognizedCertificateBlock:^BOOL(NSData *certificate)
{
// Check whether the provided certificate has been already trusted
if ([[MXAllowedCertificates sharedInstance] isCertificateAllowed:certificate])
{
return YES;
}
// Check whether the provided certificate is the already trusted by the user.
if (inCredentials.allowedCertificate && [inCredentials.allowedCertificate isEqualToData:certificate])
{
// Store the allowed certificate for further requests (from MXMediaManager)
[[MXAllowedCertificates sharedInstance] addCertificate:certificate];
return YES;
}
// Check whether the user has already ignored this certificate change.
if (inCredentials.ignoredCertificate && [inCredentials.ignoredCertificate isEqualToData:certificate])
{
return NO;
}
// Let the app ask the end user to verify it
if (onUnrecognizedCertBlock)
{
BOOL allowed = onUnrecognizedCertBlock(certificate);
if (allowed)
{
// Store the allowed certificate for further requests
[[MXAllowedCertificates sharedInstance] addCertificate:certificate];
}
return allowed;
}
else
{
return NO;
}
}];
httpClient.tokenValidationResponseHandler = ^BOOL(NSError *error) {
if (![MXError isMXError:error])
{
return NO;
}
MXError *mxError = [[MXError alloc] initWithNSError:error];
return [mxError.errcode isEqualToString:kMXErrCodeStringUnknownToken];
};
MXWeakify(self);
httpClient.tokenProviderHandler = ^(NSError *error, void (^success)(NSString *accessToken), void (^failure)(NSError *error)) {
MXStrongifyAndReturnIfNil(self);
dispatch_async([MXRestClient refreshQueue], ^{
NSString *logId = [NSString stringWithFormat:@"%d-%@", [[NSProcessInfo processInfo] processIdentifier], [[NSUUID UUID] UUIDString]];
MXLogDebug(@"[MXRestClient] tokenProviderHandler: %@ refreshQueue enter - %@", logId, [MXRestClient refreshDispatchGroup]);
// If refreshDispatchGroup is unmatched(a request for a new access token is in-flight) wait.
dispatch_group_wait([MXRestClient refreshDispatchGroup], DISPATCH_TIME_FOREVER);
if(!weakself.completionQueue) {
MXLogError(@"[MXRestClient] tokenProviderHandler: %@ Client closed, exit tokenProviderHandler early", logId);
return;
}
MXLogDebug(@"[MXRestClient] tokenProviderHandler: %@ Wait finished", logId);
if(self.credentials.accessTokenExpiresAt)
{
NSDate *expiry = [NSDate dateWithTimeIntervalSince1970:self.credentials.accessTokenExpiresAt/1000];
NSDate *preemptiveExpiry = [NSDate dateWithTimeIntervalSince1970:(self.credentials.accessTokenExpiresAt - PREEMPT_REFRESH_EXPIRATION_INTERVAL)/1000];
MXLogDebug(@"[MXRestClient] tokenProviderHandler: %@ - server expiry: %@ preemptive expiry %@", logId, expiry, preemptiveExpiry);
}
MXError *mxError = [[MXError alloc] initWithNSError:error];
BOOL isTokenUnknownResponse = mxError && [mxError.errcode isEqualToString:kMXErrCodeStringUnknownToken];
if(!self.credentials.refreshToken && isTokenUnknownResponse)
{
// non-refresh token auth failed
dispatch_async(self.completionQueue, ^{
BOOL isSoftLogout = [MXRestClient isSoftLogout:mxError];
MXLogDebug(@"[MXRestClient] tokenProviderHandler: %@: non-refresh(access token) token auth failed", logId);
if (unauthenticatedHandler) {
self.unauthenticatedHandler(mxError, isSoftLogout, NO, ^{
failure(error);
});
}
});
return;
}
if (!self.credentials.refreshToken || (!isTokenUnknownResponse && (!self.credentials.accessTokenExpiresAt || [NSDate date].timeIntervalSince1970 * 1000 < (self.credentials.accessTokenExpiresAt - PREEMPT_REFRESH_EXPIRATION_INTERVAL)))) {
// If it's non-refresh token auth return the access token,
// or if it is refresh token auth and access token is valid also return it.
MXLogDebug(@"[MXRestClient] tokenProviderHandler: %@ success token %@, %tu", logId, self.credentials.refreshToken, (NSUInteger)self.credentials.accessTokenExpiresAt)
if (self.completionQueue) {
dispatch_async(self.completionQueue, ^{
success(self.credentials.accessToken);
});
}
return;
}
// Continue with token refresh if access token is not valid(indicated by server response or the expiry date)
NSAssert(self.persistTokenDataHandler, @"If we are attempting to refresh there must be a way to persist the tokens to share across processes.");
dispatch_group_enter([MXRestClient refreshDispatchGroup]);
MXWeakify(self);
[self startTokenRefreshWithLogId:logId andRefreshCompletion:^(NSString *accessToken) {
if(!weakself || !weakself.completionQueue) {
dispatch_group_leave([MXRestClient refreshDispatchGroup]);
MXLogWarning(@"[MXRestClient] tokenProviderHandler: %@ Client closed, exit tokenProviderHandler early.", logId);
return;
}
MXStrongifyAndReturnIfNil(self);
dispatch_group_leave([MXRestClient refreshDispatchGroup]);
dispatch_async(self.completionQueue, ^{
if(accessToken)
{
success(self.credentials.accessToken);
}
else
{
MXError *mxError = [[MXError alloc] initWithErrorCode:kMXErrCodeStringClientError error: @"Token refresh failed"];
failure(mxError.createNSError);
}
});
}];
});
};
}
completionQueue = dispatch_get_main_queue();
processingQueue = dispatch_queue_create("MXRestClient", DISPATCH_QUEUE_SERIAL);
}
return self;
}
- (void)startTokenRefreshWithLogId:(NSString*)logId andRefreshCompletion:(void (^)(NSString *accessToken))refreshCompletion
{
MXWeakify(self);
// check persisted credentials (could have been updated in another process)
self.persistTokenDataHandler(^(NSArray<MXCredentials *> *credentials, void (^shouldPersistCompletion)(BOOL didUpdateCredentials)) {
if(!weakself || !weakself.completionQueue) {
shouldPersistCompletion(NO);
refreshCompletion(nil);
MXLogWarning(@"[MXRestClient] %@: Client closed, exit tokenProviderHandler early.", logId);
return;
}
MXStrongifyAndReturnIfNil(self);
MXCredentials *credential = [MXRestClient findMatchingCredential:self.credentials inCredentials:credentials];
if (!credential) {
MXLogWarning(@"[MXRestClient] %@: Could not find rest client credential in persisted credentials.", logId);
shouldPersistCompletion(NO);
refreshCompletion(nil);
return;
}
// We found the matching, persisted credential.
if([NSDate date].timeIntervalSince1970 * 1000 < (credential.accessTokenExpiresAt - PREEMPT_REFRESH_EXPIRATION_INTERVAL)) {
MXLogDebug(@"[MXRestClient] %@: found valid persisted token, using.", logId)
// There exists a persisted credential that is not expired, use it.
MXRefreshTokenData *tokenData = [[MXRefreshTokenData alloc] initWithUserId:credential.userId
homeserver:credential.homeServer
accessToken:credential.accessToken
refreshToken:credential.refreshToken
accessTokenExpiresAt:credential.accessTokenExpiresAt
];
[[NSNotificationCenter defaultCenter] postNotificationName:MXCredentialsUpdateTokensNotification object:nil userInfo:@{
kMXCredentialsNewRefreshTokenDataKey: tokenData
}];
shouldPersistCompletion(NO);
refreshCompletion(credential.accessToken);
} else {
// refresh token and use the new values.
MXLogDebug(@"[MXRestClient] %@: refreshQueue refresh token start", logId)
MXWeakify(self);
id operation = [self refreshAccessToken:self.credentials.refreshToken success:^(MXRefreshResponse *refreshResponse) {
MXLogDebug(@"[MXRestClient] %@: refreshQueue refresh token request success", logId)
uint64_t accessTokenExpiresAt = ((uint64_t)[NSDate date].timeIntervalSince1970 * 1000) + refreshResponse.expiresInMs;
MXRefreshTokenData *tokenData = [[MXRefreshTokenData alloc] initWithUserId:credential.userId
homeserver:credential.homeServer
accessToken:refreshResponse.accessToken
refreshToken:refreshResponse.refreshToken
accessTokenExpiresAt:accessTokenExpiresAt
];
[[NSNotificationCenter defaultCenter] postNotificationName:MXCredentialsUpdateTokensNotification object:nil userInfo:@{
kMXCredentialsNewRefreshTokenDataKey: tokenData
}];
credential.accessToken = refreshResponse.accessToken;
credential.refreshToken = refreshResponse.refreshToken;
credential.accessTokenExpiresAt = accessTokenExpiresAt;
shouldPersistCompletion(YES);
MXLogDebug(@"[MXRestClient] %@: refreshQueue refresh token success", logId)
refreshCompletion(refreshResponse.accessToken);
} failure:^(NSError *error) {
if (!weakself) {
shouldPersistCompletion(NO);
refreshCompletion(nil);
}
MXStrongifyAndReturnIfNil(self);
MXLogDebug(@"[MXRestClient] %@: refreshQueue refresh token request failure", logId)
shouldPersistCompletion(NO);
MXError *mxError = [[MXError alloc] initWithNSError:error];
if (self.unauthenticatedHandler &&
([mxError.errcode isEqualToString:kMXErrCodeStringForbidden] ||
[mxError.errcode isEqualToString:kMXErrCodeStringUnknownToken]))
{
dispatch_async(self.completionQueue, ^{
BOOL isSoftLogout = [MXRestClient isSoftLogout:mxError];
MXLogDebug(@"[MXRestClient] %@: refreshQueue unauthenticatedHandler", logId)
self.unauthenticatedHandler(mxError, isSoftLogout, YES,^{
refreshCompletion(nil);
});
});
} else {
refreshCompletion(nil);
}
}];
if(!operation)
{
MXLogWarning(@"[MXRestClient] %@: Did not start refresh as http client was nil", logId);
shouldPersistCompletion(NO);
refreshCompletion(nil);
}
}
});
}
+ (BOOL)isSoftLogout:(MXError*)error
{
return error.httpResponse.statusCode == 401
&& [error.userInfo[kMXErrorSoftLogoutKey] isEqual:@(YES)];
}
+ (MXCredentials*)findMatchingCredential:(MXCredentials*)credential inCredentials:(NSArray<MXCredentials *> *)credentials
{
for (MXCredentials *nextCredential in credentials)
{
if (nextCredential.homeServer && [nextCredential.homeServer isEqualToString:credential.homeServer]
&& nextCredential.userId && [nextCredential.userId isEqualToString:credential.userId] ) {
return nextCredential;
}
}
return nil;
}
- (void)close
{
credentials = nil;
httpClient = nil;
antivirusHttpClient = nil;
processingQueue = nil;
completionQueue = nil;
}
- (NSString *)homeserver
{
return self.credentials.homeServer;
}
- (NSString *)homeserverSuffix
{
NSString *homeserverSuffix;
// Extract homeserver suffix from userId
NSArray *components = [credentials.userId componentsSeparatedByString:@":"];
if (components.count > 1)
{
// Remove first component
NSString *matrixId = components.firstObject;
NSRange range = NSMakeRange(0, matrixId.length);
homeserverSuffix = [credentials.userId stringByReplacingCharactersInRange:range withString:@""];
}
else
{
MXLogDebug(@"[MXRestClient] Warning: the userId is not correctly formatted: %@", credentials.userId);
}
return homeserverSuffix;
}
- (NSData*)allowedCertificate
{
return httpClient.allowedCertificate;
}
- (NSSet<NSString *> *)acceptableContentTypes
{
return httpClient.acceptableContentTypes;
}
- (void)setAcceptableContentTypes:(NSSet<NSString *> *)acceptableContentTypes
{
httpClient.acceptableContentTypes = acceptableContentTypes;
}
#pragma mark - Server administration
- (MXHTTPOperation*)supportedMatrixVersions:(void (^)(MXMatrixVersions *matrixVersions))success
failure:(void (^)(NSError *error))failure
{
// There is no versioning in the path of this API
NSString *path = @"_matrix/client/versions";
MXWeakify(self);
return [httpClient requestWithMethod:@"GET"
path:path
parameters:nil
success:^(NSDictionary *JSONResponse) {
MXStrongifyAndReturnIfNil(self);
if (success)
{
__block MXMatrixVersions *matrixVersions;
[self dispatchProcessing:^{
MXJSONModelSetMXJSONModel(matrixVersions, MXMatrixVersions, JSONResponse);
} andCompletion:^{
success(matrixVersions);
}];
}
}
failure:^(NSError *error) {
MXStrongifyAndReturnIfNil(self);
[self dispatchFailure:error inBlock:failure];
}];
}
- (MXHTTPOperation*)wellKnow:(void (^)(MXWellKnown *wellKnown))success
failure:(void (^)(NSError *error))failure
{
NSString *path = @".well-known/matrix/client";
MXWeakify(self);
MXHTTPOperation *operation = [httpClient requestWithMethod:@"GET"
path:path
parameters:nil
success:^(NSDictionary *JSONResponse) {
MXStrongifyAndReturnIfNil(self);
if (success)
{
__block MXWellKnown *wellKnown;
[self dispatchProcessing:^{
MXJSONModelSetMXJSONModel(wellKnown, MXWellKnown, JSONResponse);
} andCompletion:^{
success(wellKnown);
}];
}
}
failure:^(NSError *error) {
MXStrongifyAndReturnIfNil(self);
[self dispatchFailure:error inBlock:failure];
}];
return operation;
}
- (MXHTTPOperation *)capabilities:(void (^)(MXCapabilities *))success
failure:(void (^)(NSError *))failure
{
NSString *path = [NSString stringWithFormat:@"%@/capabilities", kMXAPIPrefixPathV3];
MXWeakify(self);
MXHTTPOperation *operation = [httpClient requestWithMethod:@"GET"
path:path
parameters:nil
success:^(NSDictionary *JSONResponse) {
MXStrongifyAndReturnIfNil(self);
if (success)
{
__block MXCapabilities *capabilities;
[self dispatchProcessing:^{
MXJSONModelSetMXJSONModel(capabilities, MXCapabilities, JSONResponse);
} andCompletion:^{
success(capabilities);
}];
}
}
failure:^(NSError *error) {
MXStrongifyAndReturnIfNil(self);
[self dispatchFailure:error inBlock:failure];
}];
return operation;
}
#pragma mark - Registration operations
- (MXHTTPOperation *)testUserRegistration:(NSString *)username callback:(void (^)(MXError *mxError))callback
{
// Trigger a fake registration to know whether the user name can be registered
return [self registerWithParameters:@{@"username": username}
success:nil
failure:^(NSError *error)
{
// Retrieve the matrix error back
MXError *mxError = [[MXError alloc] initWithNSError:error];
callback(mxError);
}];
}
- (MXHTTPOperation*)isUserNameInUse:(NSString*)username
callback:(void (^)(BOOL isUserNameInUse))callback
{
return [self testUserRegistration:username callback:^(MXError *mxError) {
BOOL isUserNameInUse = ([mxError.errcode isEqualToString:kMXErrCodeStringUserInUse]);
callback(isUserNameInUse);
}];
}
- (MXHTTPOperation*)isUsernameAvailable:(NSString*)username
success:(void (^)(MXUsernameAvailability *availability))success
failure:(void (^)(NSError *error))failure
{
NSDictionary* parameters = @{@"username": username};
MXWeakify(self);
return [httpClient requestWithMethod:@"GET"
path:[NSString stringWithFormat:@"%@/register/available", apiPathPrefix]
parameters:parameters
success:^(NSDictionary *JSONResponse) {
MXStrongifyAndReturnIfNil(self);
if (success)
{
__block MXUsernameAvailability *availability;
[self dispatchProcessing:^{
MXJSONModelSetMXJSONModel(availability, MXUsernameAvailability, JSONResponse);
} andCompletion:^{
success(availability);
}];
}
}
failure:^(NSError *error) {
[self dispatchFailure:error inBlock:failure];
}];
}
- (MXHTTPOperation*)getRegisterSession:(void (^)(MXAuthenticationSession *authSession))success
failure:(void (^)(NSError *error))failure
{
// For registration, use POST with no params to get the login mechanism to use
// The request will fail with Unauthorized status code, but the login mechanism will be available in response data.
NSDictionary* parameters = nil;
// Patch: Add the temporary `x_show_msisdn` flag to not filter the msisdn login type in the supported authentication flows.
parameters = @{@"x_show_msisdn":@(YES)};
MXWeakify(self);
return [httpClient requestWithMethod:@"POST"
path:[self authActionPath:MXAuthActionRegister]
parameters:parameters
success:^(NSDictionary *JSONResponse) {
MXStrongifyAndReturnIfNil(self);
if (success)
{
__block MXAuthenticationSession *authSession;
[self dispatchProcessing:^{
MXJSONModelSetMXJSONModel(authSession, MXAuthenticationSession, JSONResponse);
} andCompletion:^{
success(authSession);
}];
}
}
failure:^(NSError *error) {
MXStrongifyAndReturnIfNil(self);
__block MXAuthenticationSession *authSession;
[self dispatchProcessing:^{
if (error.userInfo[MXHTTPClientErrorResponseDataKey])
{
// The auth session should be available in response data in case of unauthorized request.
NSDictionary *JSONResponse = error.userInfo[MXHTTPClientErrorResponseDataKey];
if (JSONResponse)
{
MXJSONModelSetMXJSONModel(authSession, MXAuthenticationSession, JSONResponse);
}
}
} andCompletion:^{
if (authSession)
{
if (success)
{
success(authSession);
}
}
else if (failure)
{
failure(error);
}
}];
}];
}
- (MXHTTPOperation*)registerWithParameters:(NSDictionary*)parameters
success:(void (^)(NSDictionary *JSONResponse))success
failure:(void (^)(NSError *error))failure
{
return [self registerOrLogin:MXAuthActionRegister parameters:parameters success:success failure:failure];
}
- (MXHTTPOperation *)registerWithLoginType:(NSString *)loginType username:(NSString *)username password:(NSString *)password
success:(void (^)(MXCredentials *))success
failure:(void (^)(NSError *))failure
{
if (![loginType isEqualToString:kMXLoginFlowTypePassword] && ![loginType isEqualToString:kMXLoginFlowTypeDummy])
{
[self dispatchFailure:nil inBlock:failure];
return nil;
}
MXHTTPOperation *operation;
MXWeakify(self);
operation = [self getRegisterSession:^(MXAuthenticationSession *authSession) {
MXStrongifyAndReturnIfNil(self);
NSMutableDictionary *parameters = [NSMutableDictionary dictionaryWithDictionary:
@{
@"auth": @{
@"type": loginType,
@"session": authSession.session
},
@"password": password
}];
if (username)
{
parameters[@"username"] = username;
}
MXWeakify(self);
MXHTTPOperation *operation2 = [self registerWithParameters: parameters success:^(NSDictionary *JSONResponse) {
MXStrongifyAndReturnIfNil(self);
[self dispatchProcessing:nil andCompletion:^{
MXLoginResponse *loginResponse;
MXJSONModelSetMXJSONModel(loginResponse, MXLoginResponse, JSONResponse);
// Update our credentials
self->credentials = [[MXCredentials alloc] initWithLoginResponse:loginResponse
andDefaultCredentials:self.credentials];
// Report the certificate trusted by user (if any)
self->credentials.allowedCertificate = self->httpClient.allowedCertificate;
// sanity check
if (success)
{
success(self->credentials);
}
}];
} failure:^(NSError *error) {
MXStrongifyAndReturnIfNil(self);
[self dispatchFailure:error inBlock:failure];
}];
// Mutate MXHTTPOperation so that the user can cancel this new operation
[operation mutateTo:operation2];
} failure:^(NSError *error) {
MXStrongifyAndReturnIfNil(self);
[self dispatchFailure:error inBlock:failure];
}];
return operation;
}
- (NSString*)registerFallback;
{
NSString *registerFallback;
if (self.credentials.homeServer)
{
registerFallback = [[NSURL URLWithString:@"_matrix/static/client/register/" relativeToURL:[NSURL URLWithString:self.credentials.homeServer]] absoluteString];
}
return registerFallback;
}
- (MXHTTPOperation *)forgetPasswordForEmail:(NSString *)email
clientSecret:(NSString *)clientSecret
sendAttempt:(NSUInteger)sendAttempt
success:(void (^)(NSString *sid))success
failure:(void (^)(NSError *error))failure
{
NSString *path = [NSString stringWithFormat:@"%@/account/password/email/requestToken", apiPathPrefix];
NSDictionary *parameters = @{
@"email" : email,
@"client_secret" : clientSecret,
@"send_attempt" : @(sendAttempt),
};
MXWeakify(self);
return [self requestTokenFromEndpoint:path parameters:parameters success:^(NSDictionary *JSONResponse) {
MXStrongifyAndReturnIfNil(self);
if (success)
{
__block NSString *sid;
[self dispatchProcessing:^{
MXJSONModelSetString(sid, JSONResponse[@"sid"]);
} andCompletion:^{
success(sid);
}];
}
} failure:failure];
}
#pragma mark - Login operations
- (MXHTTPOperation*)getLoginSession:(void (^)(MXAuthenticationSession *authSession))success
failure:(void (^)(NSError *error))failure
{
MXWeakify(self);
return [httpClient requestWithMethod:@"GET"
path:[self authActionPath:MXAuthActionLogin]
parameters:nil
success:^(NSDictionary *JSONResponse) {
MXStrongifyAndReturnIfNil(self);
if (success)
{
__block MXAuthenticationSession *authSession;
[self dispatchProcessing:^{
MXJSONModelSetMXJSONModel(authSession, MXAuthenticationSession, JSONResponse);
} andCompletion:^{
success(authSession);
}];
}
}
failure:^(NSError *error) {
[self dispatchFailure:error inBlock:failure];
}];
}
- (MXHTTPOperation*)login:(NSDictionary*)parameters
success:(void (^)(NSDictionary *JSONResponse))success
failure:(void (^)(NSError *error))failure
{
return [self registerOrLogin:MXAuthActionLogin parameters:parameters success:success failure:failure];
}
- (MXHTTPOperation *)loginWithLoginType:(NSString *)loginType username:(NSString *)username password:(NSString *)password
success:(void (^)(MXCredentials *))success
failure:(void (^)(NSError *))failure
{
if (![loginType isEqualToString:kMXLoginFlowTypePassword])
{
[self dispatchFailure:nil inBlock:failure];
return nil;
}
NSDictionary *parameters = @{
@"type": loginType,
@"identifier": @{
@"type": kMXLoginIdentifierTypeUser,
@"user": username
},
@"password": password,
// Patch: add the old login api parameters to make dummy login
// still working
@"user": username
};
MXWeakify(self);
return [self login:parameters
success:^(NSDictionary *JSONResponse) {
[self dispatchProcessing:nil andCompletion:^{
MXStrongifyAndReturnIfNil(self);
MXLoginResponse *loginResponse;
MXJSONModelSetMXJSONModel(loginResponse, MXLoginResponse, JSONResponse);
// Update our credentials
self->credentials = [[MXCredentials alloc] initWithLoginResponse:loginResponse
andDefaultCredentials:self.credentials];
// Report the certificate trusted by user (if any)
self->credentials.allowedCertificate = self->httpClient.allowedCertificate;
// sanity check
if (success)
{
success(self->credentials);
}
}];
} failure:^(NSError *error) {
[self dispatchFailure:error inBlock:failure];
}];
}
- (NSString*)loginFallback;
{
NSString *loginFallback;
if (self.credentials.homeServer)
{
loginFallback = [[NSURL URLWithString:@"/_matrix/static/client/login/" relativeToURL:[NSURL URLWithString:self.credentials.homeServer]] absoluteString];
}
return loginFallback;
}
#pragma mark - password update operation
- (MXHTTPOperation*)resetPasswordWithParameters:(NSDictionary*)parameters
success:(void (^)(void))success
failure:(void (^)(NSError *error))failure
{
// sanity check
if (!parameters)
{
NSError *error = [NSError errorWithDomain:kMXRestClientErrorDomain code:MXRestClientErrorInvalidParameters userInfo:nil];
[self dispatchFailure:error inBlock:failure];
return nil;
}
MXWeakify(self);
return [httpClient requestWithMethod:@"POST"
path:[NSString stringWithFormat:@"%@/account/password", apiPathPrefix]
parameters:parameters
success:^(NSDictionary *JSONResponse) {
MXStrongifyAndReturnIfNil(self);
[self dispatchSuccess:success];
}
failure:^(NSError *error) {
MXStrongifyAndReturnIfNil(self);
[self dispatchFailure:error inBlock:failure];
}];
}
- (MXHTTPOperation*)changePassword:(NSString*)oldPassword
with:(NSString*)newPassword
logoutDevices:(BOOL)logoutDevices
success:(void (^)(void))success
failure:(void (^)(NSError *error))failure
{
// sanity check
if (!oldPassword || !newPassword)
{
NSError *error = [NSError errorWithDomain:kMXRestClientErrorDomain code:MXRestClientErrorInvalidParameters userInfo:nil];
[self dispatchFailure:error inBlock:failure];
return nil;
}
NSDictionary *parameters = @{
@"auth": @{
@"type": kMXLoginFlowTypePassword,
@"user": self.credentials.userId,
@"password": oldPassword,
},
@"new_password": newPassword,
@"logout_devices": @(logoutDevices)
};
MXWeakify(self);
return [httpClient requestWithMethod:@"POST"
path:[NSString stringWithFormat:@"%@/account/password", apiPathPrefix]
parameters:parameters
success:^(NSDictionary *JSONResponse) {
MXStrongifyAndReturnIfNil(self);
[self dispatchSuccess:success];
}
failure:^(NSError *error) {
MXStrongifyAndReturnIfNil(self);
[self dispatchFailure:error inBlock:failure];
}];
}
#pragma mark - Common operations for register and login
/*
The only difference between register and login request are the path of the requests.
The parameters and the responses are of the same types.
So, use common functions to implement their functions.
*/
/**
Return the home server path to use for register or for login actions.
*/
- (NSString*)authActionPath:(MXAuthAction)authAction
{
NSString *authActionPath = @"login";
if (MXAuthActionRegister == authAction)
{
authActionPath = @"register";
}
return [NSString stringWithFormat:@"%@/%@", apiPathPrefix, authActionPath];
}
- (MXHTTPOperation*)registerOrLogin:(MXAuthAction)authAction parameters:(NSDictionary *)parameters success:(void (^)(NSDictionary *JSONResponse))success failure:(void (^)(NSError *))failure
{
// If the caller does not provide it, fill the device display name field with the device name
// Do it only if parameters contains the password field, do make homeserver happy.
if (parameters[@"password"])
{
NSMutableDictionary *newParameters;