-
Notifications
You must be signed in to change notification settings - Fork 30
Expand file tree
/
Copy pathARTPushActivationStateMachine.m
More file actions
472 lines (416 loc) · 20.5 KB
/
Copy pathARTPushActivationStateMachine.m
File metadata and controls
472 lines (416 loc) · 20.5 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
#import "ARTPushActivationStateMachine+Private.h"
#import "ARTPush.h"
#import "ARTPushActivationEvent.h"
#import "ARTPushActivationState.h"
#import "ARTRest+Private.h"
#import "ARTInternalLog.h"
#import "ARTJsonEncoder.h"
#import "ARTJsonLikeEncoder.h"
#import "ARTTypes.h"
#import "ARTTypes+Private.h"
#import "ARTLocalDevice+Private.h"
#import "ARTDeviceStorage.h"
#import "ARTDevicePushDetails.h"
#import "ARTDeviceIdentityTokenDetails.h"
#import "ARTNSMutableRequest+ARTPush.h"
#import "ARTAuth+Private.h"
#import "ARTGCD.h"
#if TARGET_OS_IOS
#import <UIKit/UIKit.h>
NSString *const ARTPushActivationCurrentStateKey = @"ARTPushActivationCurrentState";
NSString *const ARTPushActivationPendingEventsKey = @"ARTPushActivationPendingEvents";
NS_ASSUME_NONNULL_BEGIN
@interface ARTPushActivationStateMachine ()
@property (nonatomic, readonly) ARTInternalLog *logger;
@end
NS_ASSUME_NONNULL_END
@implementation ARTPushActivationStateMachine {
ARTPushActivationEvent *_lastHandledEvent;
ARTPushActivationState *_current;
dispatch_queue_t _queue;
dispatch_queue_t _userQueue;
NSMutableArray<ARTPushActivationEvent *> *_pendingEvents;
}
- (instancetype)initWithRest:(ARTRestInternal *const)rest
delegate:(const id<ARTPushRegistererDelegate, NSObject>)delegate
logger:(ARTInternalLog *)logger {
if (self = [super init]) {
_rest = rest;
_delegate = delegate;
_queue = _rest.queue;
_userQueue = _rest.userQueue;
_logger = logger;
// Unarchiving
NSData *stateData = [rest.storage objectForKey:ARTPushActivationCurrentStateKey];
_current = [ARTPushActivationState art_unarchiveFromData:stateData withLogger:logger];
if (!_current) {
_current = [[ARTPushActivationStateNotActivated alloc] initWithMachine:self logger:logger];
} else {
if ([_current isKindOfClass:[ARTPushActivationDeprecatedPersistentState class]]) {
_current = [((ARTPushActivationDeprecatedPersistentState *) _current) migrate];
}
_current.machine = self;
}
NSData *pendingEventsData = [rest.storage objectForKey:ARTPushActivationPendingEventsKey];
_pendingEvents = [ARTPushActivationEvent art_unarchiveFromData:pendingEventsData withLogger:logger];
if (!_pendingEvents) {
_pendingEvents = [NSMutableArray array];
}
// Due to bug #966, old versions of the library might have led us to an illegal
// persisted state: we have a deviceToken, but the persisted push state is WaitingForPushDeviceDetails.
// So we need to re-emit the GotPushDeviceDetails event that led us there.
if ([_current isKindOfClass:[ARTPushActivationStateWaitingForPushDeviceDetails class]] && rest.device_nosync.apnsDeviceToken != nil) {
ARTLogDebug(logger, @"ARTPush: re-emitting stored device details for stuck state machine");
[self handleEvent:[ARTPushActivationEventGotPushDeviceDetails new]];
}
}
return self;
}
- (NSArray<ARTPushActivationEvent *> *)pendingEvents {
__block NSArray<ARTPushActivationEvent *> *ret;
art_dispatch_sync(_queue, ^{
ret = [self->_pendingEvents copy];
});
return ret;
}
- (ARTPushActivationEvent *)lastEvent {
__block ARTPushActivationEvent *ret;
art_dispatch_sync(_queue, ^{
ret = [self lastEvent_nosync];
});
return ret;
}
- (ARTPushActivationEvent *)lastEvent_nosync {
return _lastHandledEvent;
}
- (ARTPushActivationState *)current {
__block ARTPushActivationState *ret;
art_dispatch_sync(_queue, ^{
ret = [self current_nosync];
});
return ret;
}
- (ARTPushActivationState *)current_nosync {
return _current;
}
- (void)sendEvent:(ARTPushActivationEvent *)event {
art_dispatch_async(_queue, ^{
[self handleEvent:event];
});
}
- (void)handleEvent:(nonnull ARTPushActivationEvent *)event {
ARTLogDebug(_logger, @"%@: handling event %@ from %@", NSStringFromClass(self.class), NSStringFromClass(event.class), NSStringFromClass(_current.class));
_lastHandledEvent = event;
if (self.onEvent) self.onEvent(event, _current);
ARTPushActivationState *maybeNext = [_current transition:event];
if (maybeNext == nil) {
ARTLogDebug(_logger, @"%@: enqueuing event: %@", NSStringFromClass(self.class), NSStringFromClass(event.class));
[_pendingEvents addObject:event];
return;
}
ARTLogDebug(_logger, @"%@: transition: %@ -> %@", NSStringFromClass(self.class), NSStringFromClass(_current.class), NSStringFromClass(maybeNext.class));
if (self.transitions) self.transitions(event, _current, maybeNext);
_current = maybeNext;
while (true) {
ARTPushActivationEvent *pending = [_pendingEvents art_peek];
if (pending == nil) {
break;
}
ARTLogDebug(_logger, @"%@: attempting to consume pending event: %@", NSStringFromClass(self.class), NSStringFromClass(pending.class));
maybeNext = [_current transition:pending];
if (maybeNext == nil) {
break;
}
[_pendingEvents art_dequeue]; // consuming event
ARTLogDebug(_logger, @"%@: transition: %@ -> %@", NSStringFromClass(self.class), NSStringFromClass(_current.class), NSStringFromClass(maybeNext.class));
if (self.transitions) self.transitions(event, _current, maybeNext);
_current = maybeNext;
}
[self persist];
}
- (void)persist {
// Archiving
if ([_current isKindOfClass:[ARTPushActivationPersistentState class]]) {
[self.rest.storage setObject:[_current art_archiveWithLogger:_logger]
forKey:ARTPushActivationCurrentStateKey];
}
[self.rest.storage setObject:[_pendingEvents art_archiveWithLogger:_logger]
forKey:ARTPushActivationPendingEventsKey];
}
- (void)deviceRegistration:(ARTErrorInfo *)error {
#if TARGET_OS_IOS
ARTLocalDevice *local = _rest.device_nosync;
const id<ARTPushRegistererDelegate, NSObject> delegate = self.delegate;
// Custom register
if ([delegate respondsToSelector:@selector(ablyPushCustomRegister:deviceDetails:callback:)]) {
art_dispatch_async(_userQueue, ^{
[delegate ablyPushCustomRegister:error deviceDetails:local callback:^(ARTDeviceIdentityTokenDetails *identityTokenDetails, ARTErrorInfo *error) {
if (error) {
// Failed
[self sendEvent:[ARTPushActivationEventGettingDeviceRegistrationFailed newWithError:error]];
}
else if (identityTokenDetails) {
// Success
[self sendEvent:[ARTPushActivationEventGotDeviceRegistration newWithIdentityTokenDetails:identityTokenDetails]];
}
else {
ARTErrorInfo *missingIdentityTokenError = [ARTErrorInfo createWithCode:0 message:@"Device Identity Token Details is expected"];
[self sendEvent:[ARTPushActivationEventGettingDeviceRegistrationFailed newWithError:missingIdentityTokenError]];
}
}];
});
return;
}
void (^doDeviceRegistration)(void) = ^{
NSError *error = nil;
NSMutableURLRequest *request = [self->_rest buildRequest:@"POST"
path:@"/push/deviceRegistrations"
baseUrl:self->_rest.baseUrl
params:nil
body:[self->_rest.defaultEncoder encodeLocalDevice:local error:nil]
headers:nil
error:&error];
if (error) {
ARTLogError(self->_logger, @"%@: device registration failed (%@)", NSStringFromClass(self.class), error.localizedDescription);
[self sendEvent:[ARTPushActivationEventGettingDeviceRegistrationFailed newWithError:[ARTErrorInfo createFromNSError:error]]];
return;
}
ARTLogDebug(self->_logger, @"%@: device registration with request %@", NSStringFromClass(self.class), request);
[self->_rest executeAblyRequest:request withAuthOption:ARTAuthenticationOn wrapperSDKAgents:nil completion:^(NSHTTPURLResponse *response, NSData *data, NSError *error) {
if (error) {
ARTLogError(self->_logger, @"%@: device registration failed (%@)", NSStringFromClass(self.class), error.localizedDescription);
[self sendEvent:[ARTPushActivationEventGettingDeviceRegistrationFailed newWithError:[ARTErrorInfo createFromNSError:error]]];
return;
}
NSError *decodeError = nil;
ARTDeviceIdentityTokenDetails *identityTokenDetails = [[self->_rest defaultEncoder] decodeDeviceIdentityTokenDetails:data error:&decodeError];
if (decodeError != nil) {
ARTLogError(self->_logger, @"%@: decode identity token details failed (%@)", NSStringFromClass(self.class), error.localizedDescription);
[self sendEvent:[ARTPushActivationEventGettingDeviceRegistrationFailed newWithError:[ARTErrorInfo createFromNSError:decodeError]]];
return;
}
[self sendEvent:[ARTPushActivationEventGotDeviceRegistration newWithIdentityTokenDetails:identityTokenDetails]];
}];
};
if (_rest.auth.method == ARTAuthMethodToken) {
[_rest.auth authorize:^(ARTTokenDetails *tokenDetails, NSError *error) {
doDeviceRegistration();
}];
}
else {
doDeviceRegistration();
}
#endif
}
- (void)deviceUpdateRegistration:(ARTErrorInfo *)error {
#if TARGET_OS_IOS
ARTLocalDevice *local = _rest.device_nosync;
const id<ARTPushRegistererDelegate, NSObject> delegate = self.delegate;
// Custom register
if ([delegate respondsToSelector:@selector(ablyPushCustomRegister:deviceDetails:callback:)]) {
art_dispatch_async(_userQueue, ^{
[delegate ablyPushCustomRegister:error deviceDetails:local callback:^(ARTDeviceIdentityTokenDetails *identityTokenDetails, ARTErrorInfo *error) {
if (error) {
// Failed
[self sendEvent:[ARTPushActivationEventSyncRegistrationFailed newWithError:error]];
}
else if (identityTokenDetails) {
// Success
[self sendEvent:[ARTPushActivationEventRegistrationSynced newWithIdentityTokenDetails:identityTokenDetails]];
}
else {
ARTErrorInfo *missingIdentityTokenError = [ARTErrorInfo createWithCode:0 message:@"Device Identity Token Details is expected"];
[self sendEvent:[ARTPushActivationEventSyncRegistrationFailed newWithError:missingIdentityTokenError]];
}
}];
});
return;
}
NSDictionary *bodyDict = @{
@"push": @{
@"recipient": local.push.recipient
}
};
NSError *requestError = nil;
NSMutableURLRequest *request = [_rest buildRequest:@"PATCH"
path:[@"/push/deviceRegistrations" stringByAppendingPathComponent:local.id]
baseUrl:_rest.baseUrl
params:nil
body:bodyDict
headers:nil
error:&requestError];
if (requestError) {
ARTLogError(self->_logger, @"%@: device update failed (%@)", NSStringFromClass(self.class), requestError.localizedDescription);
[self sendEvent:[ARTPushActivationEventSyncRegistrationFailed newWithError:[ARTErrorInfo createFromNSError:requestError]]];
return;
}
[request setDeviceAuthentication:local];
ARTLogDebug(_logger, @"%@: update device with request %@", NSStringFromClass(self.class), request);
[_rest executeAblyRequest:request withAuthOption:ARTAuthenticationOn wrapperSDKAgents:nil completion:^(NSHTTPURLResponse *response, NSData *data, NSError *error) {
if (error) {
ARTLogError(self->_logger, @"%@: update device failed (%@)", NSStringFromClass(self.class), error.localizedDescription);
[self sendEvent:[ARTPushActivationEventSyncRegistrationFailed newWithError:[ARTErrorInfo createFromNSError:error]]];
return;
}
[self sendEvent:[ARTPushActivationEventRegistrationSynced new]];
}];
#endif
}
- (void)syncDevice {
#if TARGET_OS_IOS
ARTLocalDevice *const local = _rest.device_nosync;
const id<ARTPushRegistererDelegate, NSObject> delegate = self.delegate;
// Custom register
if ([delegate respondsToSelector:@selector(ablyPushCustomRegister:deviceDetails:callback:)]) {
art_dispatch_async(_userQueue, ^{
[delegate ablyPushCustomRegister:nil deviceDetails:local callback:^(ARTDeviceIdentityTokenDetails *identityTokenDetails, ARTErrorInfo *error) {
if (error) {
// Failed
[self sendEvent:[ARTPushActivationEventSyncRegistrationFailed newWithError:error]];
}
else if (identityTokenDetails) {
// Success
[self sendEvent:[ARTPushActivationEventRegistrationSynced newWithIdentityTokenDetails:identityTokenDetails]];
}
else {
ARTErrorInfo *const missingIdentityTokenError = [ARTErrorInfo createWithCode:0 message:@"Device Identity Token Details is expected"];
[self sendEvent:[ARTPushActivationEventSyncRegistrationFailed newWithError:missingIdentityTokenError]];
}
}];
});
return;
}
void (^doDeviceSync)(void) = ^{
// Asynchronous HTTP request
NSError *requestError = nil;
NSMutableURLRequest *request = [self->_rest buildRequest:@"PUT"
path:[@"/push/deviceRegistrations" stringByAppendingPathComponent:local.id]
baseUrl:self->_rest.baseUrl
params:nil
body:[self->_rest.defaultEncoder encodeDeviceDetails:local error:nil]
headers:nil
error:&requestError];
if (requestError) {
ARTLogError(self->_logger, @"%@: device sync failed (%@)", NSStringFromClass(self.class), requestError.localizedDescription);
[self sendEvent:[ARTPushActivationEventSyncRegistrationFailed newWithError:[ARTErrorInfo createFromNSError:requestError]]];
return;
}
[request setDeviceAuthentication:local];
ARTLogDebug(self->_logger, @"%@: sync device with request %@", NSStringFromClass(self.class), request);
[self->_rest executeAblyRequest:request withAuthOption:ARTAuthenticationOn wrapperSDKAgents:nil completion:^(NSHTTPURLResponse *response, NSData *data, NSError *error) {
if (error) {
ARTLogError(self->_logger, @"%@: device sync failed (%@)", NSStringFromClass(self.class), error.localizedDescription);
[self sendEvent:[ARTPushActivationEventSyncRegistrationFailed newWithError:[ARTErrorInfo createFromNSError:error]]];
return;
}
[self sendEvent:[ARTPushActivationEventRegistrationSynced newWithIdentityTokenDetails:local.identityTokenDetails]];
}];
};
if (_rest.auth.method == ARTAuthMethodToken) {
[_rest.auth authorize:^(ARTTokenDetails *tokenDetails, NSError *error) {
doDeviceSync();
}];
}
else {
doDeviceSync();
}
#endif
}
- (void)deviceUnregistration:(ARTErrorInfo *)error {
#if TARGET_OS_IOS
ARTLocalDevice *local = _rest.device_nosync;
__block id delegate = self.delegate;
// Custom register
SEL customDeregisterMethodSelector = @selector(ablyPushCustomDeregister:deviceId:callback:);
if ([delegate respondsToSelector:customDeregisterMethodSelector]) {
art_dispatch_async(_userQueue, ^{
[delegate ablyPushCustomDeregister:error deviceId:local.id callback:^(ARTErrorInfo *error) {
if (error) {
// RSH3d2c1: ignore unauthorized or invalid credentials errors
if (error.statusCode == 401 || error.code == 40005) {
[self sendEvent:[ARTPushActivationEventDeregistered new]];
} else {
[self sendEvent:[ARTPushActivationEventDeregistrationFailed newWithError:error]];
}
}
else {
// Success
[self sendEvent:[ARTPushActivationEventDeregistered new]];
}
}];
});
return;
}
// Asynchronous HTTP request
NSError *requestError = nil;
NSMutableURLRequest *request = [_rest buildRequest:@"DELETE"
path:[@"/push/deviceRegistrations" stringByAppendingPathComponent:local.id]
baseUrl:_rest.baseUrl
params:nil
body:nil
headers:nil
error:&requestError];
if (requestError) {
ARTLogError(self->_logger, @"%@: device deregistration failed (%@)", NSStringFromClass(self.class), requestError.localizedDescription);
[self sendEvent:[ARTPushActivationEventDeregistrationFailed newWithError:[ARTErrorInfo createFromNSError:requestError]]];
return;
}
[request setDeviceAuthentication:local];
ARTLogDebug(_logger, @"%@: device deregistration with request %@", NSStringFromClass(self.class), request);
[_rest executeAblyRequest:request withAuthOption:ARTAuthenticationOn wrapperSDKAgents:nil completion:^(NSHTTPURLResponse *response, NSData *data, NSError *error) {
if (error) {
// RSH3d2c1: ignore unauthorized or invalid credentials errors
if (response.statusCode == 401 || error.code == 40005) {
ARTLogError(self->_logger, @"%@: unauthorized error during deregistration (%@)", NSStringFromClass(self.class), error.localizedDescription);
[self sendEvent:[ARTPushActivationEventDeregistered new]];
} else {
ARTLogError(self->_logger, @"%@: device deregistration failed (%@)", NSStringFromClass(self.class), error.localizedDescription);
[self sendEvent:[ARTPushActivationEventDeregistrationFailed newWithError:[ARTErrorInfo createFromNSError:error]]];
}
return;
}
ARTLogDebug(self->_logger, @"successfully deactivate device");
[self sendEvent:[ARTPushActivationEventDeregistered new]];
}];
#endif
}
- (void)callActivatedCallback:(ARTErrorInfo *)error {
#if TARGET_OS_IOS
art_dispatch_async(_userQueue, ^{
const id<ARTPushRegistererDelegate, NSObject> delegate = self.delegate;
if ([delegate respondsToSelector:@selector(didActivateAblyPush:)]) {
[delegate didActivateAblyPush:error];
}
});
#endif
}
- (void)callDeactivatedCallback:(ARTErrorInfo *)error {
#if TARGET_OS_IOS
art_dispatch_async(_userQueue, ^{
const id<ARTPushRegistererDelegate, NSObject> delegate = self.delegate;
if ([delegate respondsToSelector:@selector(didDeactivateAblyPush:)]) {
[delegate didDeactivateAblyPush:error];
}
});
#endif
}
- (void)callUpdatedCallback:(nullable ARTErrorInfo *)error {
#if TARGET_OS_IOS
art_dispatch_async(_userQueue, ^{
const id<ARTPushRegistererDelegate, NSObject> delegate = self.delegate;
if ([delegate respondsToSelector:@selector(didUpdateAblyPush:)]) {
[delegate didUpdateAblyPush:error];
}
else if (error && [delegate respondsToSelector:@selector(didAblyPushRegistrationFail:)]) {
[delegate didAblyPushRegistrationFail:error];
}
});
#endif
}
- (void)registerForAPNS {
art_dispatch_async(dispatch_get_main_queue(), ^{
[[UIApplication sharedApplication] registerForRemoteNotifications];
});
}
@end
#endif