forked from Countly/countly-sdk-ios
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Countly.m
executable file
·719 lines (573 loc) · 18.4 KB
/
Countly.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
// Countly.m
//
// This code is provided under the MIT License.
//
// Please visit www.count.ly for more information.
#define COUNTLY_DEBUG 0
#if COUNTLY_DEBUG
# define COUNTLY_LOG(fmt, ...) NSLog(fmt, ##__VA_ARGS__)
#else
# define COUNTLY_LOG(...)
#endif
#define COUNTLY_VERSION "1.0"
#import "Countly.h"
#import "Countly_OpenUDID.h"
#import <UIKit/UIKit.h>
#import <CoreTelephony/CTTelephonyNetworkInfo.h>
#import <CoreTelephony/CTCarrier.h>
#include <sys/types.h>
#include <sys/sysctl.h>
/// Utilities for encoding and decoding URL arguments.
/// This code is from the project google-toolbox-for-mac
@interface NSString (GTMNSStringURLArgumentsAdditions)
/// Returns a string that is escaped properly to be a URL argument.
//
/// This differs from stringByAddingPercentEscapesUsingEncoding: in that it
/// will escape all the reserved characters (per RFC 3986
/// <http://www.ietf.org/rfc/rfc3986.txt>) which
/// stringByAddingPercentEscapesUsingEncoding would leave.
///
/// This will also escape '%', so this should not be used on a string that has
/// already been escaped unless double-escaping is the desired result.
- (NSString*)gtm_stringByEscapingForURLArgument;
/// Returns the unescaped version of a URL argument
//
/// This has the same behavior as stringByReplacingPercentEscapesUsingEncoding:,
/// except that it will also convert '+' to space.
- (NSString*)gtm_stringByUnescapingFromURLArgument;
@end
#define GTMNSMakeCollectable(cf) ((id)(cf))
#define GTMCFAutorelease(cf) ([GTMNSMakeCollectable(cf) autorelease])
@implementation NSString (GTMNSStringURLArgumentsAdditions)
- (NSString*)gtm_stringByEscapingForURLArgument {
// Encode all the reserved characters, per RFC 3986
// (<http://www.ietf.org/rfc/rfc3986.txt>)
CFStringRef escaped =
CFURLCreateStringByAddingPercentEscapes(kCFAllocatorDefault,
(CFStringRef)self,
NULL,
(CFStringRef)@"!*'();:@&=+$,/?%#[]",
kCFStringEncodingUTF8);
return GTMCFAutorelease(escaped);
}
- (NSString*)gtm_stringByUnescapingFromURLArgument {
NSMutableString *resultString = [NSMutableString stringWithString:self];
[resultString replaceOccurrencesOfString:@"+"
withString:@" "
options:NSLiteralSearch
range:NSMakeRange(0, [resultString length])];
return [resultString stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
}
@end
@interface DeviceInfo : NSObject
{
}
@end
@implementation DeviceInfo
+ (NSString *)udid
{
return [Countly_OpenUDID value];
}
+ (NSString *)device
{
size_t size;
sysctlbyname("hw.machine", NULL, &size, NULL, 0);
char *machine = malloc(size);
sysctlbyname("hw.machine", machine, &size, NULL, 0);
NSString *platform = [NSString stringWithUTF8String:machine];
free(machine);
return platform;
}
+ (NSString *)osVersion
{
return [[UIDevice currentDevice] systemVersion];
}
+ (NSString *)carrier
{
if (NSClassFromString(@"CTTelephonyNetworkInfo"))
{
CTTelephonyNetworkInfo *netinfo = [[[CTTelephonyNetworkInfo alloc] init] autorelease];
CTCarrier *carrier = [netinfo subscriberCellularProvider];
return [carrier carrierName];
}
return nil;
}
+ (NSString *)resolution
{
CGRect bounds = [[UIScreen mainScreen] bounds];
CGFloat scale = [[UIScreen mainScreen] respondsToSelector:@selector(scale)] ? [[UIScreen mainScreen] scale] : 1.f;
CGSize res = CGSizeMake(bounds.size.width * scale, bounds.size.height * scale);
NSString *result = [NSString stringWithFormat:@"%gx%g", res.width, res.height];
return result;
}
+ (NSString *)locale
{
return [[NSLocale currentLocale] localeIdentifier];
}
+ (NSString *)appVersion
{
NSString *result = [[NSBundle mainBundle] objectForInfoDictionaryKey:@"CFBundleShortVersionString"];
if ([result length] == 0)
result = [[NSBundle mainBundle] objectForInfoDictionaryKey:(NSString*)kCFBundleVersionKey];
return result;
}
+ (NSString *)metrics
{
NSString *result = @"{";
result = [result stringByAppendingFormat:@"\"%@\":\"%@\"", @"_device", [DeviceInfo device]];
result = [result stringByAppendingFormat:@",\"%@\":\"%@\"", @"_os", @"iOS"];
result = [result stringByAppendingFormat:@",\"%@\":\"%@\"", @"_os_version", [DeviceInfo osVersion]];
NSString *carrier = [DeviceInfo carrier];
if (carrier != nil)
result = [result stringByAppendingFormat:@",\"%@\":\"%@\"", @"_carrier", carrier];
result = [result stringByAppendingFormat:@",\"%@\":\"%@\"", @"_resolution", [DeviceInfo resolution]];
result = [result stringByAppendingFormat:@",\"%@\":\"%@\"", @"_locale", [DeviceInfo locale]];
result = [result stringByAppendingFormat:@",\"%@\":\"%@\"", @"_app_version", [DeviceInfo appVersion]];
result = [result stringByAppendingString:@"}"];
result = [result gtm_stringByEscapingForURLArgument];
return result;
}
@end
@interface CountlyEvent : NSObject
{
}
@property (nonatomic, copy) NSString *key;
@property (nonatomic, retain) NSDictionary *segmentation;
@property (nonatomic, assign) int count;
@property (nonatomic, assign) double sum;
@property (nonatomic, assign) double timestamp;
@end
@implementation CountlyEvent
@synthesize key = key_;
@synthesize segmentation = segmentation_;
@synthesize count = count_;
@synthesize sum = sum_;
@synthesize timestamp = timestamp_;
- (id)init
{
if (self = [super init])
{
key_ = nil;
segmentation_ = nil;
count_ = 0;
sum_ = 0;
timestamp_ = 0;
}
return self;
}
- (void)dealloc
{
[key_ release];
[segmentation_ release];
[super dealloc];
}
@end
@interface EventQueue : NSObject
{
NSMutableArray *events_;
}
@end
@implementation EventQueue
- (id)init
{
if (self = [super init])
{
events_ = [[NSMutableArray alloc] init];
}
return self;
}
- (void)dealloc
{
[events_ release];
[super dealloc];
}
- (NSUInteger)count
{
@synchronized (self)
{
return [events_ count];
}
}
- (NSString *)events
{
NSString *result = @"[";
@synchronized (self)
{
for (int i = 0; i < events_.count; ++i)
{
CountlyEvent *event = [events_ objectAtIndex:i];
result = [result stringByAppendingString:@"{"];
result = [result stringByAppendingFormat:@"\"%@\":\"%@\"", @"key", event.key];
if (event.segmentation)
{
NSString *segmentation = @"{";
NSArray *keys = [event.segmentation allKeys];
for (int i = 0; i < keys.count; ++i)
{
NSString *key = [keys objectAtIndex:i];
NSString *value = [event.segmentation objectForKey:key];
segmentation = [segmentation stringByAppendingFormat:@"\"%@\":\"%@\"", key, value];
if (i + 1 < keys.count)
segmentation = [segmentation stringByAppendingString:@","];
}
segmentation = [segmentation stringByAppendingString:@"}"];
result = [result stringByAppendingFormat:@",\"%@\":%@", @"segmentation", segmentation];
}
result = [result stringByAppendingFormat:@",\"%@\":%d", @"count", event.count];
if (event.sum > 0)
result = [result stringByAppendingFormat:@",\"%@\":%g", @"sum", event.sum];
result = [result stringByAppendingFormat:@",\"%@\":%ld", @"timestamp", (time_t)event.timestamp];
result = [result stringByAppendingString:@"}"];
if (i + 1 < events_.count)
result = [result stringByAppendingString:@","];
}
[events_ release];
events_ = [[NSMutableArray alloc] init];
}
result = [result stringByAppendingString:@"]"];
result = [result gtm_stringByEscapingForURLArgument];
return result;
}
- (void)recordEvent:(NSString *)key count:(int)count
{
@synchronized (self)
{
for (CountlyEvent *event in events_)
{
if ([event.key isEqualToString:key])
{
event.count += count;
event.timestamp = (event.timestamp + time(NULL)) / 2;
return;
}
}
CountlyEvent *event = [[CountlyEvent alloc] init];
event.key = key;
event.count = count;
event.timestamp = time(NULL);
[events_ addObject:event];
[event release];
}
}
- (void)recordEvent:(NSString *)key count:(int)count sum:(double)sum
{
@synchronized (self)
{
for (CountlyEvent *event in events_)
{
if ([event.key isEqualToString:key])
{
event.count += count;
event.sum += sum;
event.timestamp = (event.timestamp + time(NULL)) / 2;
return;
}
}
CountlyEvent *event = [[CountlyEvent alloc] init];
event.key = key;
event.count = count;
event.sum = sum;
event.timestamp = time(NULL);
[events_ addObject:event];
[event release];
}
}
- (void)recordEvent:(NSString *)key segmentation:(NSDictionary *)segmentation count:(int)count;
{
@synchronized (self)
{
for (CountlyEvent *event in events_)
{
if ([event.key isEqualToString:key] &&
event.segmentation && [event.segmentation isEqualToDictionary:segmentation])
{
event.count += count;
event.timestamp = (event.timestamp + time(NULL)) / 2;
return;
}
}
CountlyEvent *event = [[CountlyEvent alloc] init];
event.key = key;
event.segmentation = segmentation;
event.count = count;
event.timestamp = time(NULL);
[events_ addObject:event];
[event release];
}
}
- (void)recordEvent:(NSString *)key segmentation:(NSDictionary *)segmentation count:(int)count sum:(double)sum;
{
@synchronized (self)
{
for (CountlyEvent *event in events_)
{
if ([event.key isEqualToString:key] &&
event.segmentation && [event.segmentation isEqualToDictionary:segmentation])
{
event.count += count;
event.sum += sum;
event.timestamp = (event.timestamp + time(NULL)) / 2;
return;
}
}
CountlyEvent *event = [[CountlyEvent alloc] init];
event.key = key;
event.segmentation = segmentation;
event.count = count;
event.sum = sum;
event.timestamp = time(NULL);
[events_ addObject:event];
[event release];
}
}
@end
@interface ConnectionQueue : NSObject
{
NSMutableArray *queue_;
NSURLConnection *connection_;
UIBackgroundTaskIdentifier bgTask_;
NSString *appKey;
NSString *appHost;
}
@property (nonatomic, copy) NSString *appKey;
@property (nonatomic, copy) NSString *appHost;
@end
static ConnectionQueue *s_sharedConnectionQueue = nil;
@implementation ConnectionQueue : NSObject
@synthesize appKey;
@synthesize appHost;
+ (ConnectionQueue *)sharedInstance
{
if (s_sharedConnectionQueue == nil)
s_sharedConnectionQueue = [[ConnectionQueue alloc] init];
return s_sharedConnectionQueue;
}
- (id)init
{
if (self = [super init])
{
queue_ = [[NSMutableArray alloc] init];
connection_ = nil;
bgTask_ = UIBackgroundTaskInvalid;
appKey = nil;
appHost = nil;
}
return self;
}
- (void) tick
{
if (connection_ != nil || bgTask_ != UIBackgroundTaskInvalid || [queue_ count] == 0)
return;
UIApplication *app = [UIApplication sharedApplication];
bgTask_ = [app beginBackgroundTaskWithExpirationHandler:^{
[app endBackgroundTask:bgTask_];
bgTask_ = UIBackgroundTaskInvalid;
}];
NSString *data = [queue_ objectAtIndex:0];
NSString *urlString = [NSString stringWithFormat:@"%@/i?%@", self.appHost, data];
NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:urlString]];
connection_ = [NSURLConnection connectionWithRequest:request delegate:self];
}
- (void)beginSession
{
NSString *data = [NSString stringWithFormat:@"app_key=%@&device_id=%@×tamp=%ld&sdk_version="COUNTLY_VERSION"&begin_session=1&metrics=%@",
appKey,
[DeviceInfo udid],
time(NULL),
[DeviceInfo metrics]];
[queue_ addObject:data];
[self tick];
}
- (void)updateSessionWithDuration:(int)duration
{
NSString *data = [NSString stringWithFormat:@"app_key=%@&device_id=%@×tamp=%ld&session_duration=%d",
appKey,
[DeviceInfo udid],
time(NULL),
duration];
[queue_ addObject:data];
[self tick];
}
- (void)endSessionWithDuration:(int)duration
{
NSString *data = [NSString stringWithFormat:@"app_key=%@&device_id=%@×tamp=%ld&end_session=1&session_duration=%d",
appKey,
[DeviceInfo udid],
time(NULL),
duration];
[queue_ addObject:data];
[self tick];
}
- (void)recordEvents:(NSString *)events
{
NSString *data = [NSString stringWithFormat:@"app_key=%@&device_id=%@×tamp=%ld&events=%@",
appKey,
[DeviceInfo udid],
time(NULL),
events];
[queue_ addObject:data];
[self tick];
}
- (void)connectionDidFinishLoading:(NSURLConnection *)connection
{
COUNTLY_LOG(@"ok -> %@", [queue_ objectAtIndex:0]);
UIApplication *app = [UIApplication sharedApplication];
if (bgTask_ != UIBackgroundTaskInvalid)
{
[app endBackgroundTask:bgTask_];
bgTask_ = UIBackgroundTaskInvalid;
}
connection_ = nil;
[queue_ removeObjectAtIndex:0];
[self tick];
}
- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)err
{
COUNTLY_LOG(@"error -> %@", [queue_ objectAtIndex:0]);
UIApplication *app = [UIApplication sharedApplication];
if (bgTask_ != UIBackgroundTaskInvalid)
{
[app endBackgroundTask:bgTask_];
bgTask_ = UIBackgroundTaskInvalid;
}
connection_ = nil;
}
- (void)dealloc
{
[super dealloc];
if (connection_)
[connection_ cancel];
[queue_ release];
self.appKey = nil;
self.appHost = nil;
}
@end
static Countly *s_sharedCountly = nil;
@implementation Countly
+ (Countly *)sharedInstance
{
if (s_sharedCountly == nil)
s_sharedCountly = [[Countly alloc] init];
return s_sharedCountly;
}
- (id)init
{
if (self = [super init])
{
timer = nil;
isSuspended = NO;
unsentSessionLength = 0;
eventQueue = [[EventQueue alloc] init];
[[NSNotificationCenter defaultCenter] addObserver:self
selector:@selector(didEnterBackgroundCallBack:)
name:UIApplicationDidEnterBackgroundNotification
object:nil];
[[NSNotificationCenter defaultCenter] addObserver:self
selector:@selector(willEnterForegroundCallBack:)
name:UIApplicationWillEnterForegroundNotification
object:nil];
[[NSNotificationCenter defaultCenter] addObserver:self
selector:@selector(willTerminateCallBack:)
name:UIApplicationWillTerminateNotification
object:nil];
}
return self;
}
- (void)start:(NSString *)appKey withHost:(NSString *)appHost
{
timer = [NSTimer scheduledTimerWithTimeInterval:30.0
target:self
selector:@selector(onTimer:)
userInfo:nil
repeats:YES];
lastTime = CFAbsoluteTimeGetCurrent();
[[ConnectionQueue sharedInstance] setAppKey:appKey];
[[ConnectionQueue sharedInstance] setAppHost:appHost];
[[ConnectionQueue sharedInstance] beginSession];
}
- (void)recordEvent:(NSString *)key count:(int)count
{
[eventQueue recordEvent:key count:count];
if (eventQueue.count >= 5)
[[ConnectionQueue sharedInstance] recordEvents:[eventQueue events]];
}
- (void)recordEvent:(NSString *)key count:(int)count sum:(double)sum
{
[eventQueue recordEvent:key count:count sum:sum];
if (eventQueue.count >= 5)
[[ConnectionQueue sharedInstance] recordEvents:[eventQueue events]];
}
- (void)recordEvent:(NSString *)key segmentation:(NSDictionary *)segmentation count:(int)count
{
[eventQueue recordEvent:key segmentation:segmentation count:count];
if (eventQueue.count >= 5)
[[ConnectionQueue sharedInstance] recordEvents:[eventQueue events]];
}
- (void)recordEvent:(NSString *)key segmentation:(NSDictionary *)segmentation count:(int)count sum:(double)sum
{
[eventQueue recordEvent:key segmentation:segmentation count:count sum:sum];
if (eventQueue.count >= 5)
[[ConnectionQueue sharedInstance] recordEvents:[eventQueue events]];
}
- (void)onTimer:(NSTimer *)timer
{
if (isSuspended == YES)
return;
double currTime = CFAbsoluteTimeGetCurrent();
unsentSessionLength += currTime - lastTime;
lastTime = currTime;
int duration = unsentSessionLength;
[[ConnectionQueue sharedInstance] updateSessionWithDuration:duration];
unsentSessionLength -= duration;
if (eventQueue.count > 0)
[[ConnectionQueue sharedInstance] recordEvents:[eventQueue events]];
}
- (void)suspend
{
isSuspended = YES;
if (eventQueue.count > 0)
[[ConnectionQueue sharedInstance] recordEvents:[eventQueue events]];
double currTime = CFAbsoluteTimeGetCurrent();
unsentSessionLength += currTime - lastTime;
int duration = unsentSessionLength;
[[ConnectionQueue sharedInstance] endSessionWithDuration:duration];
unsentSessionLength -= duration;
}
- (void)resume
{
lastTime = CFAbsoluteTimeGetCurrent();
[[ConnectionQueue sharedInstance] beginSession];
isSuspended = NO;
}
- (void)exit
{
}
- (void)dealloc
{
[[NSNotificationCenter defaultCenter] removeObserver:self name:UIApplicationDidEnterBackgroundNotification object:nil];
[[NSNotificationCenter defaultCenter] removeObserver:self name:UIApplicationWillEnterForegroundNotification object:nil];
[[NSNotificationCenter defaultCenter] removeObserver:self name:UIApplicationWillTerminateNotification object:nil];
if (timer)
{
[timer invalidate];
timer = nil;
}
[eventQueue release];
[super dealloc];
}
- (void)didEnterBackgroundCallBack:(NSNotification *)notification
{
COUNTLY_LOG(@"Countly didEnterBackgroundCallBack");
[self suspend];
}
- (void)willEnterForegroundCallBack:(NSNotification *)notification
{
COUNTLY_LOG(@"Countly willEnterForegroundCallBack");
[self resume];
}
- (void)willTerminateCallBack:(NSNotification *)notification
{
COUNTLY_LOG(@"Countly willTerminateCallBack");
[self exit];
}
@end