-
Notifications
You must be signed in to change notification settings - Fork 240
Expand file tree
/
Copy pathCountlyContentBuilderInternal.m
More file actions
446 lines (375 loc) · 16.6 KB
/
Copy pathCountlyContentBuilderInternal.m
File metadata and controls
446 lines (375 loc) · 16.6 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
// CountlyContent.m
//
// This code is provided under the MIT License.
//
// Please visit www.count.ly for more information.
#import "CountlyContentBuilderInternal.h"
#import "CountlyWebViewManager.h"
//TODO: improve logging, check edge cases
NSString* const kCountlyEndpointContent = @"/o/sdk/content";
NSString* const kCountlyCBFetchContent = @"queue";
@implementation CountlyContentBuilderInternal {
BOOL _isRequestQueueLocked;
BOOL _isCurrentlyContentShown;
BOOL _refreshRunnablePending;
NSTimer *_requestTimer;
NSTimer *_minuteTimer;
dispatch_queue_t _contentQueue;
}
#if (TARGET_OS_IOS)
+ (instancetype)sharedInstance {
static CountlyContentBuilderInternal *instance = nil;
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
instance = [[self alloc] init];
});
return instance;
}
- (instancetype)init
{
if (self = [super init])
{
self.zoneTimerInterval = 30.0;
_requestTimer = nil;
_isCurrentlyContentShown = NO;
_contentQueue = dispatch_queue_create("ly.countly.content.queue", DISPATCH_QUEUE_SERIAL);
_contentInitialDelay = 4;
}
return self;
}
#pragma mark - Thread-safe flag helpers
// Every BOOL flag below (_isRequestQueueLocked, _isCurrentlyContentShown,
// _refreshRunnablePending) is accessed only through these helpers so all reads/writes are
// serialized on the single serial _contentQueue. The blocks capture the raw ivar pointer,
// which is safe because this class is a never-released singleton (its ivars outlive any
// queued block).
- (BOOL)readFlag:(BOOL *)flag {
if (!_contentQueue) {
return *flag;
}
__block BOOL value = NO;
dispatch_sync(_contentQueue, ^{
value = *flag;
});
return value;
}
- (void)writeFlag:(BOOL *)flag value:(BOOL)value {
if (!_contentQueue) {
*flag = value;
return;
}
dispatch_async(_contentQueue, ^{
*flag = value;
});
}
// Atomically set *flag to YES if it was NO. Returns YES only for the caller that made the
// NO->YES transition, so exactly one caller "wins" a contended flag.
- (BOOL)testAndSetFlag:(BOOL *)flag {
__block BOOL acquired = NO;
if (!_contentQueue) {
if (!*flag) { *flag = YES; acquired = YES; }
return acquired;
}
dispatch_sync(_contentQueue, ^{
if (!*flag) { *flag = YES; acquired = YES; }
});
return acquired;
}
- (BOOL)isRequestQueueLockedThreadSafe {
return [self readFlag:&_isRequestQueueLocked];
}
- (void)setRequestQueueLockedThreadSafe:(BOOL)locked {
[self writeFlag:&_isRequestQueueLocked value:locked];
}
// Atomically claim the single "content is shown" slot. Returns YES if the caller acquired it,
// NO if content is already shown or a racing fetch already claimed it, in which case the caller
// MUST NOT present another web view. Previously the flag was set only when the web view was
// presented (after a network round trip), so two near-simultaneous fetches could both pass the
// guard and present two overlapping web views; this test-and-set closes that window.
- (BOOL)tryBeginContentPresentation {
return [self testAndSetFlag:&_isCurrentlyContentShown];
}
// Release the content slot (called when the shown web view is dismissed, or on reset) so the
// next zone cycle can present again.
- (void)endContentPresentation {
[self writeFlag:&_isCurrentlyContentShown value:NO];
}
- (BOOL)isContentShownThreadSafe {
return [self readFlag:&_isCurrentlyContentShown];
}
- (void)enterContentZone {
if([self isContentShownThreadSafe]){
CLY_LOG_I(@"%s a content is already shown, skipping" ,__FUNCTION__);
return;
}
[self enterContentZone:@[]];
}
- (void)enterContentZone:(NSArray<NSString *> *)tags {
if([self isContentShownThreadSafe]){
CLY_LOG_I(@"%s a content is already shown, skipping" ,__FUNCTION__);
return;
}
[_minuteTimer invalidate];
_minuteTimer = nil;
if (!CountlyConsentManager.sharedInstance.consentForContent)
return;
if(_requestTimer != nil) {
CLY_LOG_I(@"%s already entered for content zone, please exit from content zone first to start again", __FUNCTION__);
return;
}
self.currentTags = tags;
int contentDelay = 0;
if (CountlyCommon.sharedInstance.timeSinceLaunch < _contentInitialDelay) {
contentDelay = _contentInitialDelay;
}
dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(contentDelay * NSEC_PER_SEC)), dispatch_get_main_queue(), ^
{
[self fetchContents];;
self->_requestTimer = [NSTimer scheduledTimerWithTimeInterval:self->_zoneTimerInterval
target:self
selector:@selector(fetchContents)
userInfo:nil
repeats:YES];
});
}
- (void)exitContentZone {
[self clearContentState];
}
- (void)changeContent:(NSArray<NSString *> *)tags {
if (![tags isEqualToArray:self.currentTags]) {
[self exitContentZone];
[self enterContentZone:tags];
}
}
- (void)previewContent:(NSString *)contentId {
[self fetchContents:nil contentId:contentId];
}
- (void)refreshContentZone {
if (![CountlyServerConfig.sharedInstance refreshContentZoneEnabled])
{
return;
}
if([self isContentShownThreadSafe]){
CLY_LOG_I(@"%s a content is already shown, skipping" ,__FUNCTION__);
return;
}
// Coalesce refreshes: only one refresh runnable may be pending at a time. Without this,
// multiple refreshContentZone calls before the request queue flushes each append a runnable
// (addQueueFlushRunnable does not dedup); they then all fire together and trigger N
// concurrent content fetches (a burst against the edge) whose extra results are discarded.
if (![self testAndSetFlag:&_refreshRunnablePending]) {
CLY_LOG_I(@"%s a content refresh is already pending, skipping duplicate" ,__FUNCTION__);
return;
}
__weak typeof(self) weakSelf = self;
[CountlyConnectionManager.sharedInstance addQueueFlushRunnable:^{
__strong typeof(weakSelf) strongSelf = weakSelf;
if (!strongSelf) return;
// Clear the pending flag first so a refresh requested during/after this flush can
// schedule the next one.
[strongSelf writeFlag:&strongSelf->_refreshRunnablePending value:NO];
CLY_LOG_I(@"%s queue flueshed, will re-fetch contents" ,__FUNCTION__);
[strongSelf exitContentZone];
[strongSelf enterContentZone];
}];
[CountlyConnectionManager.sharedInstance attemptToSendStoredRequests];
}
- (void)refreshContentZoneJTE {
if (![CountlyServerConfig.sharedInstance refreshContentZoneEnabled])
{
CLY_LOG_D(@"%s, refresh content zone is disabled, skipping JTE content refresh", __FUNCTION__);
return;
}
if([self isContentShownThreadSafe]){
CLY_LOG_I(@"%s a content is already shown, skipping JTE content refresh" ,__FUNCTION__);
return;
}
CLY_LOG_D(@"%s, Starting JTE content refresh with retries", __FUNCTION__);
[self exitContentZone];
[self fetchContentsForJourneyWithMaxAttempts:3 currentAttempt:1];
}
- (void)fetchContentsForJourneyWithMaxAttempts:(NSInteger)maxAttempts currentAttempt:(NSInteger)currentAttempt {
CLY_LOG_D(@"%s, JTE content fetch attempt %ld of %ld", __FUNCTION__, (long)currentAttempt, (long)maxAttempts);
[self fetchContents:^{
if (currentAttempt < maxAttempts) {
CLY_LOG_D(@"Retrying JTE content fetch in 1 second (attempt %ld of %ld)", (long)(currentAttempt + 1), (long)maxAttempts);
dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
[self fetchContentsForJourneyWithMaxAttempts:maxAttempts currentAttempt:currentAttempt + 1];
});
} else {
CLY_LOG_D(@"JTE content fetch exhausted all %ld attempts. Re-entering content zone.", (long)maxAttempts);
dispatch_async(dispatch_get_main_queue(), ^{
[self enterContentZone];
});
}
} contentId:nil];
}
#pragma mark - Private Methods
- (void)clearContentState {
[_requestTimer invalidate];
_requestTimer = nil;
[_minuteTimer invalidate];
_minuteTimer = nil;
self.currentTags = nil;
[self setRequestQueueLockedThreadSafe:NO];
}
- (void)resetInstance {
CLY_LOG_I(@"%s", __FUNCTION__);
[self clearContentState];
// Clear the shown flag through the serial content queue (not a raw write) so it cannot
// race a concurrent tryBeginContentPresentation / read on the network-completion thread.
[self endContentPresentation];
[self writeFlag:&_refreshRunnablePending value:NO];
}
- (void)fetchContents {
[self fetchContents:nil contentId:nil];
}
- (void)fetchContents:(void (^)(void))failureCallback contentId:(NSString *)contentId {
if (!CountlyConsentManager.sharedInstance.consentForContent)
return;
if (!CountlyServerConfig.sharedInstance.networkingEnabled)
return;
if (CountlyDeviceInfo.sharedInstance.isDeviceIDTemporary)
{
CLY_LOG_W(@"%s content can not be fetched while in temporary device ID mode", __FUNCTION__);
return;
}
if([self isContentShownThreadSafe]){
CLY_LOG_I(@"%s a content is already shown, skipping" ,__FUNCTION__);
return;
}
if ([self isRequestQueueLockedThreadSafe]) {
return;
}
[self setRequestQueueLockedThreadSafe:YES];
NSURLSessionTask *dataTask = [[CountlyCommon.sharedInstance ImmediateURLSession] dataTaskWithRequest:[self fetchContentsRequest:contentId] completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
// IMMEDIATE REQUEST to find them better in search
if (error) {
CLY_LOG_I(@"%s fetch content details failed: [%@]", __FUNCTION__, error);
[self setRequestQueueLockedThreadSafe:NO];
if (failureCallback) {
failureCallback();
}
return;
}
NSError *jsonError;
NSDictionary *jsonResponse = [NSJSONSerialization JSONObjectWithData:data options:0 error:&jsonError];
if (jsonError || !jsonResponse) {
CLY_LOG_I(@"%s failed to parse JSON or empty response: [%@]", __FUNCTION__, jsonError);
[self setRequestQueueLockedThreadSafe:NO];
if (failureCallback) {
failureCallback();
}
return;
}
NSString *pathToHtml = jsonResponse[@"html"];
NSDictionary *placementCoordinates = jsonResponse[@"geo"];
if(pathToHtml) {
[self showContentWithHtmlPath:pathToHtml placementCoordinates:placementCoordinates];
} else if (failureCallback) {
failureCallback();
}
[self setRequestQueueLockedThreadSafe:NO];
}];
[dataTask resume];
}
- (NSURLRequest *)fetchContentsRequest:(NSString *)contentId
{
NSString *queryString = [CountlyConnectionManager.sharedInstance queryEssentials];
NSString *resolutionJson = [self resolutionJson];
queryString = [queryString stringByAppendingFormat:@"&%@=%@", @"method", kCountlyCBFetchContent];
queryString = [queryString stringByAppendingFormat:@"&%@=%@", @"resolution", resolutionJson.cly_URLEscaped];
NSArray *components = [CountlyDeviceInfo.locale componentsSeparatedByCharactersInSet:[NSCharacterSet characterSetWithCharactersInString:@"_-"]];
queryString = [queryString stringByAppendingFormat:@"&%@=%@", @"la", components.firstObject];
NSString *deviceType = CountlyDeviceInfo.deviceType;
if (deviceType)
{
queryString = [queryString stringByAppendingFormat:@"&%@=%@", @"dt", deviceType];
}
if (contentId) {
queryString = [queryString stringByAppendingFormat:@"&%@=%@", @"content_id", contentId.cly_URLEscaped];
queryString = [queryString stringByAppendingFormat:@"&%@=%@", @"preview", @"true"];
}
queryString = [CountlyConnectionManager.sharedInstance appendChecksum:queryString];
NSString *contentEndpoint = [NSString stringWithFormat:@"%@%@", CountlyConnectionManager.sharedInstance.host, kCountlyEndpointContent];
if (queryString.length > kCountlyGETRequestMaxLength || CountlyConnectionManager.sharedInstance.alwaysUsePOST)
{
NSMutableURLRequest* request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:contentEndpoint]];
request.HTTPMethod = @"POST";
request.HTTPBody = [queryString cly_dataUTF8];
return request.copy;
}
else
{
NSString* withQueryString = [contentEndpoint stringByAppendingFormat:@"?%@", queryString];
NSURLRequest* request = [NSURLRequest requestWithURL:[NSURL URLWithString:withQueryString]];
return request;
}
}
- (NSString *)resolutionJson {
//TODO: check why area is not clickable and safearea things
CGSize size = [CountlyCommon.sharedInstance getWindowSize];
UIInterfaceOrientation orientation = [UIApplication sharedApplication].statusBarOrientation;
BOOL isLandscape = UIInterfaceOrientationIsLandscape(orientation);
CGFloat lHpW = isLandscape ? size.height : size.width;
CGFloat lWpH = isLandscape ? size.width : size.height;
NSDictionary *resolutionDict = @{
@"portrait": @{@"height": @(lWpH), @"width": @(lHpW)},
@"landscape": @{@"height": @(lHpW), @"width": @(lWpH)}
};
CLY_LOG_D(@"%s, resolutionDict: [%@]", __FUNCTION__, resolutionDict);
NSData *jsonData = [NSJSONSerialization dataWithJSONObject:resolutionDict options:0 error:nil];
return [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
}
- (void)showContentWithHtmlPath:(NSString *)urlString placementCoordinates:(NSDictionary *)placementCoordinates {
// Convert pathToHtml to NSURL
NSURL *url = [NSURL URLWithString:urlString];
if (!url || !url.scheme || !url.host) {
CLY_LOG_E(@"%s the URL is not valid: [%@]", __FUNCTION__, urlString);
return;
}
// Claim the single content slot before dispatching to main. If content is already shown,
// or a racing content fetch already claimed it, skip: never present a second overlapping
// web view for the same zone.
if (![self tryBeginContentPresentation]) {
CLY_LOG_I(@"%s a content is already shown, skipping duplicate presentation", __FUNCTION__);
return;
}
dispatch_async(dispatch_get_main_queue(), ^ {
// Detect screen orientation
UIInterfaceOrientation orientation = [UIApplication sharedApplication].statusBarOrientation;
BOOL isLandscape = UIInterfaceOrientationIsLandscape(orientation);
// Get the appropriate coordinates based on the orientation
NSDictionary *coordinates = isLandscape ? placementCoordinates[@"l"] : placementCoordinates[@"p"];
CGFloat x = [coordinates[@"x"] floatValue];
CGFloat y = [coordinates[@"y"] floatValue];
CGFloat width = [coordinates[@"w"] floatValue];
CGFloat height = [coordinates[@"h"] floatValue];
CGRect frame = CGRectMake(x, y, width, height);
// Log the URL and the frame
CLY_LOG_I(@"%s showing content from URL: [%@], frame: [%@]", __FUNCTION__, url, NSStringFromCGRect(frame));
CountlyWebViewManager* webViewManager = CountlyWebViewManager.new;
[webViewManager createWebViewWithURL:url frame:frame appearBlock:^
{
CLY_LOG_I(@"%s webview should be appeared", __FUNCTION__);
} dismissBlock:^
{
CLY_LOG_I(@"%s webview dismissed", __FUNCTION__);
[self endContentPresentation];
self->_minuteTimer = [NSTimer scheduledTimerWithTimeInterval:self->_zoneTimerInterval
target:self
selector:@selector(enterContentZone)
userInfo:nil
repeats:NO];
if(self.contentCallback) {
self.contentCallback(CLOSED, NSDictionary.new);
}
}];
CLY_LOG_I(@"%s webview initiated pausing content calls ", __FUNCTION__);
// The shown slot was already claimed synchronously by tryBeginContentPresentation
// above, before this async block was dispatched.
[self clearContentState];
});
}
#endif
@end