-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathMixpanel.m
executable file
·1220 lines (1042 loc) · 40.5 KB
/
Mixpanel.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
//
// Mixpanel.m
// Mixpanel
//
// Copyright 2012 Mixpanel
//
// 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.
#include <arpa/inet.h>
#include <ifaddrs.h>
#include <net/if_dl.h>
#include <sys/sysctl.h>
#import <CommonCrypto/CommonHMAC.h>
#import <CoreTelephony/CTCarrier.h>
#import <CoreTelephony/CTTelephonyNetworkInfo.h>
#import <SystemConfiguration/SystemConfiguration.h>
#import "MPCJSONDataSerializer.h"
#import "Mixpanel.h"
#import "NSData+MPBase64.h"
#define VERSION @"1.1.0"
#ifndef IFT_ETHER
#define IFT_ETHER 0x6 // ethernet CSMACD
#endif
#ifdef MIXPANEL_LOG
#define MixpanelLog(...) NSLog(__VA_ARGS__)
#else
#define MixpanelLog(...)
#endif
#ifdef MIXPANEL_DEBUG
#define MixpanelDebug(...) NSLog(__VA_ARGS__)
#else
#define MixpanelDebug(...)
#endif
@interface Mixpanel ()
@property(nonatomic,readwrite,retain) MixpanelPeople *people; // re-declare internally as readwrite
@property(nonatomic,copy) NSString *apiToken;
@property(nonatomic,retain) NSMutableDictionary *superProperties;
@property(nonatomic,retain) NSTimer *timer;
@property(nonatomic,retain) NSMutableArray *eventsQueue;
@property(nonatomic,retain) NSMutableArray *peopleQueue;
@property(nonatomic,retain) NSArray *eventsBatch;
@property(nonatomic,retain) NSArray *peopleBatch;
@property(nonatomic,retain) NSURLConnection *eventsConnection;
@property(nonatomic,retain) NSURLConnection *peopleConnection;
@property(nonatomic,retain) NSMutableData *eventsResponseData;
@property(nonatomic,retain) NSMutableData *peopleResponseData;
#if __IPHONE_OS_VERSION_MIN_REQUIRED >= 40000
@property(nonatomic,assign) UIBackgroundTaskIdentifier taskId;
#endif
@end
@interface MixpanelPeople ()
@property(nonatomic,assign) Mixpanel *mixpanel;
@property(nonatomic,retain) NSMutableArray *unidentifiedQueue;
- (id)initWithMixpanel:(Mixpanel *)mixpanel;
@end
@implementation Mixpanel
static Mixpanel *sharedInstance = nil;
#pragma mark * Device info
+ (NSDictionary *)deviceInfoProperties
{
NSMutableDictionary *properties = [NSMutableDictionary dictionary];
UIDevice *device = [UIDevice currentDevice];
[properties setValue:@"iphone" forKey:@"mp_lib"];
[properties setValue:VERSION forKey:@"$lib_version"];
[properties setValue:[[[NSBundle mainBundle] infoDictionary] objectForKey:@"CFBundleVersion"] forKey:@"$app_version"];
[properties setValue:@"Apple" forKey:@"$manufacturer"];
[properties setValue:[device systemName] forKey:@"$os"];
[properties setValue:[device systemVersion] forKey:@"$os_version"];
[properties setValue:[Mixpanel deviceModel] forKey:@"$model"];
[properties setValue:[Mixpanel deviceModel] forKey:@"mp_device_model"]; // legacy
CGSize size = [UIScreen mainScreen].bounds.size;
[properties setValue:[NSNumber numberWithInt:(int)size.height] forKey:@"$screen_height"];
[properties setValue:[NSNumber numberWithInt:(int)size.width] forKey:@"$screen_width"];
[properties setValue:[NSNumber numberWithBool:[Mixpanel wifiAvailable]] forKey:@"$wifi"];
CTTelephonyNetworkInfo *networkInfo = [[[CTTelephonyNetworkInfo alloc] init] autorelease];
CTCarrier *carrier = [networkInfo subscriberCellularProvider];
if (carrier.carrierName.length) {
[properties setValue:carrier.carrierName forKey:@"$carrier"];
}
return [NSDictionary dictionaryWithDictionary:properties];
}
+ (NSString *)deviceModel
{
size_t size;
sysctlbyname("hw.machine", NULL, &size, NULL, 0);
char *answer = malloc(size);
sysctlbyname("hw.machine", answer, &size, NULL, 0);
NSString *results = [NSString stringWithCString:answer encoding:NSUTF8StringEncoding];
free(answer);
return results;
}
+ (BOOL)wifiAvailable
{
struct sockaddr_in sockAddr;
bzero(&sockAddr, sizeof(sockAddr));
sockAddr.sin_len = sizeof(sockAddr);
sockAddr.sin_family = AF_INET;
SCNetworkReachabilityRef nrRef = SCNetworkReachabilityCreateWithAddress(NULL, (struct sockaddr *)&sockAddr);
SCNetworkReachabilityFlags flags;
BOOL didRetrieveFlags = SCNetworkReachabilityGetFlags(nrRef, &flags);
if (!didRetrieveFlags) {
MixpanelDebug(@"%@ unable to fetch the network reachablity flags", self);
}
CFRelease(nrRef);
if (!didRetrieveFlags || (flags & kSCNetworkReachabilityFlagsReachable) != kSCNetworkReachabilityFlagsReachable) {
// unable to connect to a network (no signal or airplane mode activated)
return NO;
}
if ((flags & kSCNetworkReachabilityFlagsIsWWAN) == kSCNetworkReachabilityFlagsIsWWAN) {
// only a cellular network connection is available.
return NO;
}
return YES;
}
+ (BOOL)inBackground
{
BOOL inBg = NO;
#if __IPHONE_OS_VERSION_MIN_REQUIRED >= 40000
inBg = [[UIApplication sharedApplication] applicationState] == UIApplicationStateBackground;
#endif
if (inBg) {
MixpanelDebug(@"%@ in background", self);
}
return inBg;
}
+ (NSDictionary *)interfaces
{
NSMutableDictionary *theDictionary = [NSMutableDictionary dictionary];
BOOL success;
struct ifaddrs * addrs;
const struct ifaddrs * cursor;
const struct sockaddr_dl * dlAddr;
const uint8_t * base;
success = getifaddrs(&addrs) == 0;
if (success) {
cursor = addrs;
while (cursor != NULL) {
if ((cursor->ifa_addr->sa_family == AF_LINK) && (((const struct sockaddr_dl *)cursor->ifa_addr)->sdl_type == IFT_ETHER)) {
// fprintf(stderr, "%s:", cursor->ifa_name);
dlAddr = (const struct sockaddr_dl *)cursor->ifa_addr;
base = (const uint8_t *) &dlAddr->sdl_data[dlAddr->sdl_nlen];
NSString *theKey = [NSString stringWithUTF8String:cursor->ifa_name];
NSString *theValue = [NSString stringWithFormat:@"%02x:%02x:%02x:%02x:%02x:%02x", base[0], base[1], base[2], base[3], base[4], base[5]];
[theDictionary setObject:theValue forKey:theKey];
}
cursor = cursor->ifa_next;
}
freeifaddrs(addrs);
}
return(theDictionary);
}
+ (NSString *)uniqueDeviceString
{
NSDictionary *dict = [Mixpanel interfaces];
NSArray *keys = [dict allKeys];
keys = [keys sortedArrayUsingSelector:@selector(caseInsensitiveCompare:)];
NSString *bundleName = [[[NSBundle mainBundle] infoDictionary] objectForKey:(id)kCFBundleNameKey];
// while most apps will define CFBundleName, it's not guaranteed;
// an app can choose to define it or not so when it's missing, use the bundle file name
if (bundleName == nil) {
bundleName = [[[NSBundle mainBundle] bundlePath] lastPathComponent];
}
NSMutableString *string = [NSMutableString stringWithString:bundleName];
for (NSString *key in keys) {
[string appendString:[dict objectForKey:key]];
}
return string;
}
#pragma mark * Encoding/decoding utilities
+ (NSString *)calculateHMACSHA1withString:(NSString *)str andKey:(NSString *)key
{
const char *cStr = [str UTF8String];
const char *cSecretStr = [key UTF8String];
unsigned char digest[CC_SHA1_DIGEST_LENGTH];
memset((void *)digest, 0x0, CC_SHA1_DIGEST_LENGTH);
CCHmac(kCCHmacAlgSHA1, cSecretStr, strlen(cSecretStr), cStr, strlen(cStr), digest);
return [NSString stringWithFormat:
@"%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X",
digest[0], digest[1], digest[2], digest[3],
digest[4], digest[5], digest[6], digest[7],
digest[8], digest[9], digest[10], digest[11],
digest[12], digest[13], digest[14], digest[15],
digest[16], digest[17], digest[18], digest[19]
];
}
+ (NSData *)JSONSerializeObject:(id)obj
{
id coercedObj = [Mixpanel JSONSerializableObjectForObject:obj];
MPCJSONDataSerializer *serializer = [MPCJSONDataSerializer serializer];
NSError *error = nil;
NSData *data = nil;
@try {
data = [serializer serializeObject:coercedObj error:&error];
}
@catch (NSException *exception) {
NSLog(@"%@ exception encoding api data: %@", self, exception);
}
if (error) {
NSLog(@"%@ error encoding api data: %@", self, error);
}
return data;
}
+ (id)JSONSerializableObjectForObject:(id)obj
{
// valid json types
if ([obj isKindOfClass:[NSString class]] ||
[obj isKindOfClass:[NSNumber class]] ||
[obj isKindOfClass:[NSNull class]]) {
return obj;
}
// recurse on containers
if ([obj isKindOfClass:[NSArray class]]) {
NSMutableArray *a = [NSMutableArray array];
for (id i in obj) {
[a addObject:[Mixpanel JSONSerializableObjectForObject:i]];
}
return [NSArray arrayWithArray:a];
}
if ([obj isKindOfClass:[NSDictionary class]]) {
NSMutableDictionary *d = [NSMutableDictionary dictionary];
for (id key in obj) {
NSString *stringKey;
if (![key isKindOfClass:[NSString class]]) {
stringKey = [key description];
NSLog(@"%@ warning: property keys should be strings. got: %@. coercing to: %@", self, [key class], stringKey);
} else {
stringKey = [NSString stringWithString:key];
}
id v = [Mixpanel JSONSerializableObjectForObject:[obj objectForKey:key]];
[d setObject:v forKey:stringKey];
}
return [NSDictionary dictionaryWithDictionary:d];
}
// some common cases
if ([obj isKindOfClass:[NSDate class]]) {
NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
[formatter setDateFormat:@"yyyy-MM-dd'T'HH:mm:ss"];
[formatter setTimeZone:[NSTimeZone timeZoneWithAbbreviation:@"UTC"]];
NSString *s = [formatter stringFromDate:obj];
[formatter release];
return s;
} else if ([obj isKindOfClass:[NSURL class]]) {
return [obj absoluteString];
}
// default to sending the object's description
NSString *s = [obj description];
NSLog(@"%@ warning: property values should be valid json types. got: %@. coercing to: %@", self, [obj class], s);
return s;
}
+ (NSString *)encodeAPIData:(NSArray *)array
{
NSString *b64String = @"";
NSData *data = [Mixpanel JSONSerializeObject:array];
if (data) {
b64String = [data mp_base64EncodedString];
b64String = (id)CFURLCreateStringByAddingPercentEscapes(kCFAllocatorDefault,
(CFStringRef)b64String,
NULL,
CFSTR("!*'();:@&=+$,/?%#[]"),
kCFStringEncodingUTF8);
}
return [b64String autorelease];
}
+ (void)assertPropertyTypes:(NSDictionary *)properties
{
for (id k in properties) {
NSAssert([k isKindOfClass: [NSString class]], @"%@ property keys must be NSString. got: %@ %@", self, [k class], k);
// would be convenient to do: id v = [properties objectForKey:k]; ..but, when the NSAssert's are stripped out in release, it becomes an unused variable error
NSAssert([[properties objectForKey:k] isKindOfClass:[NSString class]] ||
[[properties objectForKey:k] isKindOfClass:[NSNumber class]] ||
[[properties objectForKey:k] isKindOfClass:[NSNull class]] ||
[[properties objectForKey:k] isKindOfClass:[NSArray class]] ||
[[properties objectForKey:k] isKindOfClass:[NSDictionary class]] ||
[[properties objectForKey:k] isKindOfClass:[NSDate class]] ||
[[properties objectForKey:k] isKindOfClass:[NSURL class]],
@"%@ property values must be NSString, NSNumber, NSNull, NSArray, NSDictionary, NSDate or NSURL. got: %@ %@", self, [[properties objectForKey:k] class], [properties objectForKey:k]);
}
}
#pragma mark * Initializiation
+ (id)sharedInstanceWithToken:(NSString *)apiToken
{
@synchronized(self) {
if (sharedInstance == nil) {
sharedInstance = [[super alloc] initWithToken:apiToken andFlushInterval:60];
}
return sharedInstance;
}
}
+ (id)sharedInstance
{
@synchronized(self) {
if (sharedInstance == nil) {
NSLog(@"%@ warning sharedInstance called before sharedInstanceWithToken:", self);
}
return sharedInstance;
}
}
- (id)initWithToken:(NSString *)apiToken andFlushInterval:(NSUInteger)flushInterval
{
if (apiToken == nil) {
apiToken = @"";
}
if ([apiToken length] == 0) {
NSLog(@"%@ warning empty api token", self);
}
if (self = [self init]) {
self.people = [[[MixpanelPeople alloc] initWithMixpanel:self] autorelease];
self.apiToken = apiToken;
self.flushInterval = flushInterval;
self.flushOnBackground = YES;
self.showNetworkActivityIndicator = YES;
self.serverURL = @"https://api.mixpanel.com";
self.distinctId = [self defaultDistinctId];
self.superProperties = [NSMutableDictionary dictionary];
self.eventsQueue = [NSMutableArray array];
self.peopleQueue = [NSMutableArray array];
[self addApplicationObservers];
[self unarchive];
}
return self;
}
#pragma mark * Tracking
- (NSString *)defaultDistinctId
{
return [Mixpanel calculateHMACSHA1withString:[Mixpanel uniqueDeviceString] andKey:self.apiToken];
}
- (void)track:(NSString *)event
{
[self track:event properties:nil];
}
- (void)track:(NSString *)event properties:(NSDictionary *)properties
{
@synchronized(self) {
if (event == nil || [event length] == 0) {
NSLog(@"%@ mixpanel track called with empty event parameter. using 'mp_event'", self);
event = @"mp_event";
}
NSMutableDictionary *p = [NSMutableDictionary dictionary];
[p addEntriesFromDictionary:[Mixpanel deviceInfoProperties]];
[p setObject:self.apiToken forKey:@"token"];
[p setObject:[NSNumber numberWithLong:(long)[[NSDate date] timeIntervalSince1970]] forKey:@"time"];
if (self.nameTag) {
[p setObject:self.nameTag forKey:@"mp_name_tag"];
}
if (self.distinctId) {
[p setObject:self.distinctId forKey:@"distinct_id"];
}
[p addEntriesFromDictionary:self.superProperties];
if (properties) {
[p addEntriesFromDictionary:properties];
}
[Mixpanel assertPropertyTypes:properties];
NSDictionary *e = [NSDictionary dictionaryWithObjectsAndKeys:event, @"event", [NSDictionary dictionaryWithDictionary:p], @"properties", nil];
MixpanelLog(@"%@ queueing event: %@", self, e);
[self.eventsQueue addObject:e];
if ([Mixpanel inBackground]) {
[self archiveEvents];
}
}
}
#pragma mark * Super property methods
- (void)registerSuperProperties:(NSDictionary *)properties
{
[Mixpanel assertPropertyTypes:properties];
@synchronized(self) {
[self.superProperties addEntriesFromDictionary:properties];
if ([Mixpanel inBackground]) {
[self archiveProperties];
}
}
}
- (void)registerSuperPropertiesOnce:(NSDictionary *)properties
{
[Mixpanel assertPropertyTypes:properties];
@synchronized(self) {
for (NSString *key in properties) {
if ([self.superProperties objectForKey:key] == nil) {
[self.superProperties setObject:[properties objectForKey:key] forKey:key];
}
}
if ([Mixpanel inBackground]) {
[self archiveProperties];
}
}
}
- (void)registerSuperPropertiesOnce:(NSDictionary *)properties defaultValue:(id)defaultValue
{
[Mixpanel assertPropertyTypes:properties];
@synchronized(self) {
for (NSString *key in properties) {
id value = [self.superProperties objectForKey:key];
if (value == nil || [value isEqual:defaultValue]) {
[self.superProperties setObject:[properties objectForKey:key] forKey:key];
}
}
if ([Mixpanel inBackground]) {
[self archiveProperties];
}
}
}
- (void)clearSuperProperties
{
@synchronized(self) {
[self.superProperties removeAllObjects];
if ([Mixpanel inBackground]) {
[self archiveProperties];
}
}
}
- (NSDictionary *)currentSuperProperties
{
@synchronized(self) {
return [[self.superProperties copy] autorelease];
}
}
- (void)reset
{
@synchronized(self) {
self.distinctId = [self defaultDistinctId];
self.nameTag = nil;
self.superProperties = [NSMutableDictionary dictionary];
self.people.distinctId = nil;
self.people.unidentifiedQueue = [NSMutableArray array];
self.eventsQueue = [NSMutableArray array];
self.peopleQueue = [NSMutableArray array];
[self archive];
}
}
#pragma mark * Network control
- (void)setFlushInterval:(NSUInteger)interval
{
@synchronized(self) {
_flushInterval = interval;
[self startFlushTimer];
}
}
- (void)startFlushTimer
{
@synchronized(self) {
[self stopFlushTimer];
if (self.flushInterval > 0) {
self.timer = [NSTimer scheduledTimerWithTimeInterval:self.flushInterval
target:self
selector:@selector(flush)
userInfo:nil
repeats:YES];
MixpanelDebug(@"%@ started flush timer: %@", self, self.timer);
}
}
}
- (void)stopFlushTimer
{
@synchronized(self) {
if (self.timer) {
[self.timer invalidate];
MixpanelDebug(@"%@ stopped flush timer: %@", self, self.timer);
}
self.timer = nil;
}
}
- (void)flush
{
@synchronized(self) {
if ([self.delegate respondsToSelector:@selector(mixpanelWillFlush:)]) {
if (![self.delegate mixpanelWillFlush:self]) {
MixpanelDebug(@"%@ delegate deferred flush", self);
return;
}
}
MixpanelDebug(@"%@ flushing data to %@", self, self.serverURL);
[self flushEvents];
[self flushPeople];
}
}
- (void)flushEvents
{
if ([self.eventsQueue count] == 0) {
MixpanelDebug(@"%@ no events to flush", self);
return;
} else if (self.eventsConnection != nil) {
MixpanelDebug(@"%@ events connection already open", self);
return;
} else if ([self.eventsQueue count] > 50) {
self.eventsBatch = [self.eventsQueue subarrayWithRange:NSMakeRange(0, 50)];
} else {
self.eventsBatch = [NSArray arrayWithArray:self.eventsQueue];
}
NSString *data = [Mixpanel encodeAPIData:self.eventsBatch];
NSString *postBody = [NSString stringWithFormat:@"ip=1&data=%@", data];
MixpanelDebug(@"%@ flushing %u of %u queued events: %@", self, self.eventsBatch.count, self.eventsQueue.count, self.eventsQueue);
self.eventsConnection = [self apiConnectionWithEndpoint:@"/track/" andBody:postBody];
[self updateNetworkActivityIndicator];
}
- (void)flushPeople
{
if ([self.peopleQueue count] == 0) {
MixpanelDebug(@"%@ no people to flush", self);
return;
} else if (self.peopleConnection != nil) {
MixpanelDebug(@"%@ people connection already open", self);
return;
} else if ([self.peopleQueue count] > 50) {
self.peopleBatch = [self.peopleQueue subarrayWithRange:NSMakeRange(0, 50)];
} else {
self.peopleBatch = [NSArray arrayWithArray:self.peopleQueue];
}
NSString *data = [Mixpanel encodeAPIData:self.peopleBatch];
NSString *postBody = [NSString stringWithFormat:@"data=%@", data];
MixpanelDebug(@"%@ flushing %u of %u queued people: %@", self, self.peopleBatch.count, self.peopleQueue.count, self.peopleQueue);
self.peopleConnection = [self apiConnectionWithEndpoint:@"/engage/" andBody:postBody];
[self updateNetworkActivityIndicator];
}
- (void)cancelFlush
{
if (self.eventsConnection == nil) {
MixpanelDebug(@"%@ no events connection to cancel", self);
} else {
MixpanelDebug(@"%@ cancelling events connection", self);
[self.eventsConnection cancel];
self.eventsConnection = nil;
}
if (self.peopleConnection == nil) {
MixpanelDebug(@"%@ no people connection to cancel", self);
} else {
MixpanelDebug(@"%@ cancelling people connection", self);
[self.peopleConnection cancel];
self.peopleConnection = nil;
}
}
- (void)updateNetworkActivityIndicator
{
@synchronized(self) {
BOOL visible = self.showNetworkActivityIndicator && (self.eventsConnection || self.peopleConnection);
[[UIApplication sharedApplication] setNetworkActivityIndicatorVisible:visible];
}
}
#pragma mark * Persistence
- (NSString *)filePathForData:(NSString *)data
{
NSString *filename = [NSString stringWithFormat:@"mixpanel-%@-%@.plist", self.apiToken, data];
return [[NSSearchPathForDirectoriesInDomains(NSLibraryDirectory, NSUserDomainMask, YES) lastObject]
stringByAppendingPathComponent:filename];
}
- (NSString *)eventsFilePath
{
return [self filePathForData:@"events"];
}
- (NSString *)peopleFilePath
{
return [self filePathForData:@"people"];
}
- (NSString *)propertiesFilePath
{
return [self filePathForData:@"properties"];
}
- (void)archive
{
@synchronized(self) {
[self archiveEvents];
[self archivePeople];
[self archiveProperties];
}
}
- (void)archiveEvents
{
@synchronized(self) {
NSString *filePath = [self eventsFilePath];
MixpanelDebug(@"%@ archiving events data to %@: %@", self, filePath, self.eventsQueue);
if (![NSKeyedArchiver archiveRootObject:self.eventsQueue toFile:filePath]) {
NSLog(@"%@ unable to archive events data", self);
}
}
}
- (void)archivePeople
{
@synchronized(self) {
NSString *filePath = [self peopleFilePath];
MixpanelDebug(@"%@ archiving people data to %@: %@", self, filePath, self.peopleQueue);
if (![NSKeyedArchiver archiveRootObject:self.peopleQueue toFile:filePath]) {
NSLog(@"%@ unable to archive people data", self);
}
}
}
- (void)archiveProperties
{
@synchronized(self) {
NSString *filePath = [self propertiesFilePath];
NSMutableDictionary *properties = [NSMutableDictionary dictionary];
[properties setValue:self.distinctId forKey:@"distinctId"];
[properties setValue:self.nameTag forKey:@"nameTag"];
[properties setValue:self.superProperties forKey:@"superProperties"];
[properties setValue:self.people.distinctId forKey:@"peopleDistinctId"];
[properties setValue:self.people.unidentifiedQueue forKey:@"peopleUnidentifiedQueue"];
MixpanelDebug(@"%@ archiving properties data to %@: %@", self, filePath, properties);
if (![NSKeyedArchiver archiveRootObject:properties toFile:filePath]) {
NSLog(@"%@ unable to archive properties data", self);
}
}
}
- (void)unarchive
{
@synchronized(self) {
[self unarchiveEvents];
[self unarchivePeople];
[self unarchiveProperties];
}
}
- (void)unarchiveEvents
{
NSString *filePath = [self eventsFilePath];
@try {
self.eventsQueue = [NSKeyedUnarchiver unarchiveObjectWithFile:filePath];
MixpanelDebug(@"%@ unarchived events data: %@", self, self.eventsQueue);
}
@catch (NSException *exception) {
NSLog(@"%@ unable to unarchive events data, starting fresh", self);
[[NSFileManager defaultManager] removeItemAtPath:filePath error:nil];
self.eventsQueue = nil;
}
if (!self.eventsQueue) {
self.eventsQueue = [NSMutableArray array];
}
}
- (void)unarchivePeople
{
NSString *filePath = [self peopleFilePath];
@try {
self.peopleQueue = [NSKeyedUnarchiver unarchiveObjectWithFile:filePath];
MixpanelDebug(@"%@ unarchived people data: %@", self, self.peopleQueue);
}
@catch (NSException *exception) {
NSLog(@"%@ unable to unarchive people data, starting fresh", self);
[[NSFileManager defaultManager] removeItemAtPath:filePath error:nil];
self.peopleQueue = nil;
}
if (!self.peopleQueue) {
self.peopleQueue = [NSMutableArray array];
}
}
- (void)unarchiveProperties
{
NSString *filePath = [self propertiesFilePath];
NSDictionary *properties = nil;
@try {
properties = [NSKeyedUnarchiver unarchiveObjectWithFile:filePath];
MixpanelDebug(@"%@ unarchived properties data: %@", self, properties);
}
@catch (NSException *exception) {
NSLog(@"%@ unable to unarchive properties data, starting fresh", self);
[[NSFileManager defaultManager] removeItemAtPath:filePath error:nil];
}
if (properties) {
self.distinctId = [properties objectForKey:@"distinctId"];
self.nameTag = [properties objectForKey:@"nameTag"];
self.superProperties = [properties objectForKey:@"superProperties"];
self.people.distinctId = [properties objectForKey:@"peopleDistinctId"];
self.people.unidentifiedQueue = [properties objectForKey:@"peopleUnidentifiedQueue"];
}
}
#pragma mark * Application lifecycle events
- (void)addApplicationObservers
{
MixpanelDebug(@"%@ adding application observers", self);
NSNotificationCenter *notificationCenter = [NSNotificationCenter defaultCenter];
[notificationCenter addObserver:self
selector:@selector(applicationWillTerminate:)
name:UIApplicationWillTerminateNotification
object:nil];
[notificationCenter addObserver:self
selector:@selector(applicationWillResignActive:)
name:UIApplicationWillResignActiveNotification
object:nil];
[notificationCenter addObserver:self
selector:@selector(applicationDidBecomeActive:)
name:UIApplicationDidBecomeActiveNotification
object:nil];
#if __IPHONE_OS_VERSION_MIN_REQUIRED >= 40000
if ([[UIDevice currentDevice] respondsToSelector:@selector(isMultitaskingSupported)] && &UIBackgroundTaskInvalid) {
self.taskId = UIBackgroundTaskInvalid;
if (&UIApplicationDidEnterBackgroundNotification) {
[notificationCenter addObserver:self
selector:@selector(applicationDidEnterBackground:)
name:UIApplicationDidEnterBackgroundNotification
object:nil];
}
if (&UIApplicationWillEnterForegroundNotification) {
[notificationCenter addObserver:self
selector:@selector(applicationWillEnterForeground:)
name:UIApplicationWillEnterForegroundNotification
object:nil];
}
}
#endif
}
- (void)removeApplicationObservers
{
MixpanelDebug(@"%@ removing application observers", self);
[[NSNotificationCenter defaultCenter] removeObserver:self];
}
- (void)applicationDidBecomeActive:(NSNotification *)notification
{
MixpanelDebug(@"%@ application did become active", self);
@synchronized(self) {
[self startFlushTimer];
}
}
- (void)applicationWillResignActive:(NSNotification *)notification
{
MixpanelDebug(@"%@ application will resign active", self);
@synchronized(self) {
[self stopFlushTimer];
}
}
- (void)applicationDidEnterBackground:(NSNotificationCenter *)notification
{
MixpanelDebug(@"%@ did enter background", self);
@synchronized(self) {
#if __IPHONE_OS_VERSION_MIN_REQUIRED >= 40000
if (self.flushOnBackground &&
[[UIApplication sharedApplication] respondsToSelector:@selector(beginBackgroundTaskWithExpirationHandler:)] &&
[[UIApplication sharedApplication] respondsToSelector:@selector(endBackgroundTask:)]) {
self.taskId = [[UIApplication sharedApplication] beginBackgroundTaskWithExpirationHandler:^{
MixpanelDebug(@"%@ flush background task %u cut short", self, self.taskId);
[self cancelFlush];
[[UIApplication sharedApplication] endBackgroundTask:self.taskId];
self.taskId = UIBackgroundTaskInvalid;
}];
MixpanelDebug(@"%@ starting flush background task %u", self, self.taskId);
[self flush];
// connection callbacks end this task by calling endBackgroundTaskIfComplete
}
#endif
}
}
- (void)applicationWillEnterForeground:(NSNotificationCenter *)notification
{
MixpanelDebug(@"%@ will enter foreground", self);
#if __IPHONE_OS_VERSION_MIN_REQUIRED >= 40000
@synchronized(self) {
if (&UIBackgroundTaskInvalid) {
if (self.taskId != UIBackgroundTaskInvalid) {
[[UIApplication sharedApplication] endBackgroundTask:self.taskId];
}
self.taskId = UIBackgroundTaskInvalid;
}
[self cancelFlush];
[self updateNetworkActivityIndicator];
}
#endif
}
- (void)applicationWillTerminate:(NSNotification *)notification
{
MixpanelDebug(@"%@ application will terminate", self);
@synchronized(self) {
[self archive];
}
}
- (void)endBackgroundTaskIfComplete
{
#if __IPHONE_OS_VERSION_MIN_REQUIRED >= 40000
// if the os version allows background tasks, the app supports them, and we're in one, end it
@synchronized(self) {
if (&UIBackgroundTaskInvalid && [[UIApplication sharedApplication] respondsToSelector:@selector(endBackgroundTask:)] &&
self.taskId != UIBackgroundTaskInvalid && self.eventsConnection == nil && self.peopleConnection == nil) {
MixpanelDebug(@"%@ ending flush background task %u", self, self.taskId);
[[UIApplication sharedApplication] endBackgroundTask:self.taskId];
self.taskId = UIBackgroundTaskInvalid;
}
}
#endif
}
#pragma mark * NSURLConnection callbacks
- (NSURLConnection *)apiConnectionWithEndpoint:(NSString *)endpoint andBody:(NSString *)body
{
NSURL *url = [NSURL URLWithString:[self.serverURL stringByAppendingString:endpoint]];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
[request setValue:@"gzip" forHTTPHeaderField:@"Accept-Encoding"];
[request setHTTPMethod:@"POST"];
[request setHTTPBody:[body dataUsingEncoding:NSUTF8StringEncoding]];
MixpanelDebug(@"%@ http request: %@?%@", self, [self.serverURL stringByAppendingString:endpoint], body);
return [NSURLConnection connectionWithRequest:request delegate:self];
}
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSHTTPURLResponse *)response
{
MixpanelDebug(@"%@ http status code: %d", self, [response statusCode]);
if ([response statusCode] != 200) {
NSLog(@"%@ http error: %@", self, [NSHTTPURLResponse localizedStringForStatusCode:[response statusCode]]);
} else if (connection == self.eventsConnection) {
self.eventsResponseData = [NSMutableData data];
} else if (connection == self.peopleConnection) {
self.peopleResponseData = [NSMutableData data];
}
}
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
if (connection == self.eventsConnection) {
[self.eventsResponseData appendData:data];
} else if (connection == self.peopleConnection) {
[self.peopleResponseData appendData:data];
}
}
- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
{
@synchronized(self) {
NSLog(@"%@ network failure: %@", self, error);
if (connection == self.eventsConnection) {
self.eventsBatch = nil;
self.eventsResponseData = nil;
self.eventsConnection = nil;
[self archiveEvents];
} else if (connection == self.peopleConnection) {
self.peopleBatch = nil;
self.peopleResponseData = nil;
self.peopleConnection = nil;
[self archivePeople];
}
[self updateNetworkActivityIndicator];
[self endBackgroundTaskIfComplete];
}
}
- (void)connectionDidFinishLoading:(NSURLConnection *)connection
{
@synchronized(self) {
MixpanelDebug(@"%@ http response finished loading", self);
if (connection == self.eventsConnection) {
NSString *response = [[NSString alloc] initWithData:self.eventsResponseData encoding:NSUTF8StringEncoding];
if ([response intValue] == 0) {
NSLog(@"%@ track api error: %@", self, response);
}
[response release];
[self.eventsQueue removeObjectsInArray:self.eventsBatch];
[self archiveEvents];
self.eventsBatch = nil;
self.eventsResponseData = nil;
self.eventsConnection = nil;
} else if (connection == self.peopleConnection) {
NSString *response = [[NSString alloc] initWithData:self.peopleResponseData encoding:NSUTF8StringEncoding];
if ([response intValue] == 0) {
NSLog(@"%@ engage api error: %@", self, response);
}
[response release];
[self.peopleQueue removeObjectsInArray:self.peopleBatch];
[self archivePeople];
self.peopleBatch = nil;
self.peopleResponseData = nil;
self.peopleConnection = nil;
}