forked from adjust/ios_sdk
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathADJPackageHandler.m
348 lines (288 loc) · 11.7 KB
/
ADJPackageHandler.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
//
// ADJPackageHandler.m
// Adjust
//
// Created by Christian Wellenbrock on 2013-07-03.
// Copyright (c) 2013 adjust GmbH. All rights reserved.
//
#import "ADJPackageHandler.h"
#import "ADJActivityPackage.h"
#import "ADJLogger.h"
#import "ADJUtil.h"
#import "ADJAdjustFactory.h"
#import "ADJBackoffStrategy.h"
#import "ADJPackageBuilder.h"
#import "ADJUserDefaults.h"
static NSString * const kPackageQueueFilename = @"AdjustIoPackageQueue";
static const char * const kInternalQueueName = "io.adjust.PackageQueue";
#pragma mark - private
@interface ADJPackageHandler()
@property (nonatomic, strong) dispatch_queue_t internalQueue;
@property (nonatomic, strong) dispatch_semaphore_t sendingSemaphore;
@property (nonatomic, strong) ADJRequestHandler *requestHandler;
@property (nonatomic, strong) NSMutableArray *packageQueue;
@property (nonatomic, strong) ADJBackoffStrategy *backoffStrategy;
@property (nonatomic, strong) ADJBackoffStrategy *backoffStrategyForInstallSession;
@property (nonatomic, assign) BOOL paused;
@property (nonatomic, weak) id<ADJActivityHandler> activityHandler;
@property (nonatomic, weak) id<ADJLogger> logger;
@property (nonatomic, assign) NSInteger lastPackageRetriesCount;
@end
#pragma mark -
@implementation ADJPackageHandler
- (id)initWithActivityHandler:(id<ADJActivityHandler>)activityHandler
startsSending:(BOOL)startsSending
userAgent:(NSString *)userAgent
urlStrategy:(ADJUrlStrategy *)urlStrategy
{
self = [super init];
if (self == nil) return nil;
self.internalQueue = dispatch_queue_create(kInternalQueueName, DISPATCH_QUEUE_SERIAL);
self.backoffStrategy = [ADJAdjustFactory packageHandlerBackoffStrategy];
self.backoffStrategyForInstallSession = [ADJAdjustFactory installSessionBackoffStrategy];
self.lastPackageRetriesCount = 0;
[ADJUtil launchInQueue:self.internalQueue
selfInject:self
block:^(ADJPackageHandler * selfI) {
[selfI initI:selfI
activityHandler:activityHandler
startsSending:startsSending
userAgent:userAgent
urlStrategy:urlStrategy];
}];
return self;
}
- (void)addPackage:(ADJActivityPackage *)package {
[ADJUtil launchInQueue:self.internalQueue
selfInject:self
block:^(ADJPackageHandler* selfI) {
[selfI addI:selfI package:package];
}];
}
- (void)sendFirstPackage {
[ADJUtil launchInQueue:self.internalQueue
selfInject:self
block:^(ADJPackageHandler* selfI) {
[selfI sendFirstI:selfI];
}];
}
- (void)responseCallback:(ADJResponseData *)responseData {
if (responseData.jsonResponse) {
[self.logger debug:@"Got JSON response with message: %@", responseData.message];
} else {
[self.logger error:@"Could not get JSON response with message: %@", responseData.message];
}
// Check if any package response contains information that user has opted out.
// If yes, disable SDK and flush any potentially stored packages that happened afterwards.
if (responseData.trackingState == ADJTrackingStateOptedOut) {
[self.activityHandler setTrackingStateOptedOut];
return;
}
if (responseData.jsonResponse == nil) {
[self closeFirstPackage:responseData];
} else {
[self sendNextPackage:responseData];
}
}
- (void)sendNextPackage:(ADJResponseData *)responseData {
self.lastPackageRetriesCount = 0;
[ADJUtil launchInQueue:self.internalQueue
selfInject:self
block:^(ADJPackageHandler* selfI) {
[selfI sendNextI:selfI];
}];
[self.activityHandler finishedTracking:responseData];
}
- (void)closeFirstPackage:(ADJResponseData *)responseData
{
responseData.willRetry = YES;
[self.activityHandler finishedTracking:responseData];
self.lastPackageRetriesCount++;
NSTimeInterval waitTime;
if (responseData.activityKind == ADJActivityKindSession && [ADJUserDefaults getInstallTracked] == NO) {
waitTime = [ADJUtil waitingTime:self.lastPackageRetriesCount backoffStrategy:self.backoffStrategyForInstallSession];
} else {
waitTime = [ADJUtil waitingTime:self.lastPackageRetriesCount backoffStrategy:self.backoffStrategy];
}
NSString *waitTimeFormatted = [ADJUtil secondsNumberFormat:waitTime];
[self.logger verbose:@"Waiting for %@ seconds before retrying the %d time", waitTimeFormatted, self.lastPackageRetriesCount];
dispatch_after
(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(waitTime * NSEC_PER_SEC)),
self.internalQueue,
^{
[self.logger verbose:@"Package handler finished waiting"];
dispatch_semaphore_signal(self.sendingSemaphore);
[self sendFirstPackage];
});
}
- (void)pauseSending {
self.paused = YES;
}
- (void)resumeSending {
self.paused = NO;
}
- (void)updatePackages:(ADJSessionParameters *)sessionParameters
{
// make copy to prevent possible Activity Handler changes of it
ADJSessionParameters * sessionParametersCopy = [sessionParameters copy];
[ADJUtil launchInQueue:self.internalQueue
selfInject:self
block:^(ADJPackageHandler* selfI) {
[selfI updatePackagesI:selfI sessionParameters:sessionParametersCopy];
}];
}
- (void)flush {
[ADJUtil launchInQueue:self.internalQueue selfInject:self block:^(ADJPackageHandler *selfI) {
[selfI flushI:selfI];
}];
}
- (void)teardown {
[ADJAdjustFactory.logger verbose:@"ADJPackageHandler teardown"];
if (self.sendingSemaphore != nil) {
dispatch_semaphore_signal(self.sendingSemaphore);
}
[self teardownPackageQueueS];
self.internalQueue = nil;
self.sendingSemaphore = nil;
self.requestHandler = nil;
self.backoffStrategy = nil;
self.activityHandler = nil;
self.logger = nil;
}
+ (void)deleteState {
[ADJPackageHandler deletePackageQueue];
}
+ (void)deletePackageQueue {
[ADJUtil deleteFileWithName:kPackageQueueFilename];
}
#pragma mark - internal
- (void)
initI:(ADJPackageHandler *)selfI
activityHandler:(id<ADJActivityHandler>)activityHandler
startsSending:(BOOL)startsSending
userAgent:(NSString *)userAgent
urlStrategy:(ADJUrlStrategy *)urlStrategy
{
selfI.activityHandler = activityHandler;
selfI.paused = !startsSending;
selfI.requestHandler = [[ADJRequestHandler alloc]
initWithResponseCallback:self
urlStrategy:urlStrategy
userAgent:userAgent
requestTimeout:[ADJAdjustFactory requestTimeout]];
selfI.logger = ADJAdjustFactory.logger;
selfI.sendingSemaphore = dispatch_semaphore_create(1);
[selfI readPackageQueueI:selfI];
}
- (void)addI:(ADJPackageHandler *)selfI
package:(ADJActivityPackage *)newPackage
{
[selfI.packageQueue addObject:newPackage];
[selfI.logger debug:@"Added package %d (%@)", selfI.packageQueue.count, newPackage];
[selfI.logger verbose:@"%@", newPackage.extendedString];
[selfI writePackageQueueS:selfI];
}
- (void)sendFirstI:(ADJPackageHandler *)selfI
{
NSUInteger queueSize = selfI.packageQueue.count;
if (queueSize == 0) return;
if (selfI.paused) {
[selfI.logger debug:@"Package handler is paused"];
return;
}
if (dispatch_semaphore_wait(selfI.sendingSemaphore, DISPATCH_TIME_NOW) != 0) {
[selfI.logger verbose:@"Package handler is already sending"];
return;
}
ADJActivityPackage *activityPackage = [selfI.packageQueue objectAtIndex:0];
if (![activityPackage isKindOfClass:[ADJActivityPackage class]]) {
[selfI.logger error:@"Failed to read activity package"];
[selfI sendNextI:selfI];
return;
}
NSMutableDictionary *sendingParameters = [NSMutableDictionary dictionaryWithCapacity:2];
if (queueSize - 1 > 0) {
[ADJPackageBuilder parameters:sendingParameters
setInt:(int)queueSize - 1
forKey:@"queue_size"];
}
[ADJPackageBuilder parameters:sendingParameters
setString:[ADJUtil formatSeconds1970:[NSDate.date timeIntervalSince1970]]
forKey:@"sent_at"];
[selfI.requestHandler sendPackageByPOST:activityPackage
sendingParameters:[sendingParameters copy]];
}
- (void)sendNextI:(ADJPackageHandler *)selfI {
if ([selfI.packageQueue count] > 0) {
[selfI.packageQueue removeObjectAtIndex:0];
[selfI writePackageQueueS:selfI];
}
dispatch_semaphore_signal(selfI.sendingSemaphore);
[selfI sendFirstI:selfI];
}
- (void)updatePackagesI:(ADJPackageHandler *)selfI
sessionParameters:(ADJSessionParameters *)sessionParameters
{
[selfI.logger debug:@"Updating package handler queue"];
[selfI.logger verbose:@"Session callback parameters: %@", sessionParameters.callbackParameters];
[selfI.logger verbose:@"Session partner parameters: %@", sessionParameters.partnerParameters];
for (ADJActivityPackage * activityPackage in selfI.packageQueue) {
// callback parameters
NSDictionary * mergedCallbackParameters = [ADJUtil mergeParameters:sessionParameters.callbackParameters
source:activityPackage.callbackParameters
parameterName:@"Callback"];
[ADJPackageBuilder parameters:activityPackage.parameters
setDictionary:mergedCallbackParameters
forKey:@"callback_params"];
// partner parameters
NSDictionary * mergedPartnerParameters = [ADJUtil mergeParameters:sessionParameters.partnerParameters
source:activityPackage.partnerParameters
parameterName:@"Partner"];
[ADJPackageBuilder parameters:activityPackage.parameters
setDictionary:mergedPartnerParameters
forKey:@"partner_params"];
}
[selfI writePackageQueueS:selfI];
}
- (void)flushI:(ADJPackageHandler *)selfI {
[selfI.packageQueue removeAllObjects];
[selfI writePackageQueueS:selfI];
}
#pragma mark - private
- (void)readPackageQueueI:(ADJPackageHandler *)selfI {
[NSKeyedUnarchiver setClass:[ADJActivityPackage class] forClassName:@"AIActivityPackage"];
id object = [ADJUtil readObject:kPackageQueueFilename
objectName:@"Package queue"
class:[NSArray class]
syncObject:[ADJPackageHandler class]];
if (object != nil) {
selfI.packageQueue = object;
} else {
selfI.packageQueue = [NSMutableArray array];
}
}
- (void)writePackageQueueS:(ADJPackageHandler *)selfS {
if (selfS.packageQueue == nil) {
return;
}
[ADJUtil writeObject:selfS.packageQueue
fileName:kPackageQueueFilename
objectName:@"Package queue"
syncObject:[ADJPackageHandler class]];
}
- (void)teardownPackageQueueS {
@synchronized ([ADJPackageHandler class]) {
if (self.packageQueue == nil) {
return;
}
[self.packageQueue removeAllObjects];
self.packageQueue = nil;
}
}
- (void)dealloc {
// Cleanup code
if (self.sendingSemaphore != nil) {
dispatch_semaphore_signal(self.sendingSemaphore);
}
}
@end