-
Notifications
You must be signed in to change notification settings - Fork 142
/
Copy pathFlutterSegmentPlugin.m
453 lines (405 loc) · 17.5 KB
/
FlutterSegmentPlugin.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
#import "SEGAppsFlyerIntegrationFactory.h"
#import "FlutterSegmentPlugin.h"
#import <Segment/SEGAnalytics.h>
#import <Segment/SEGContext.h>
#import <Segment/SEGMiddleware.h>
#import <Segment_Amplitude/SEGAmplitudeIntegrationFactory.h>
@implementation FlutterSegmentPlugin
// Contents to be appended to the context
static NSDictionary *_appendToContextMiddleware;
static BOOL wasSetupFromFile = NO;
+ (void)registerWithRegistrar:(NSObject<FlutterPluginRegistrar>*)registrar {
FlutterMethodChannel* channel = [FlutterMethodChannel
methodChannelWithName:@"flutter_segment"
binaryMessenger:[registrar messenger]];
FlutterSegmentPlugin* instance = [[FlutterSegmentPlugin alloc] init];
SEGAnalyticsConfiguration *configuration = [FlutterSegmentPlugin createConfigFromFile];
if(configuration) {
[instance setup:configuration];
wasSetupFromFile = YES;
}
[registrar addMethodCallDelegate:instance channel:channel];
}
- (void)setup:(SEGAnalyticsConfiguration*) configuration {
@try {
// This middleware is responsible for manipulating only the context part of the request,
// leaving all other fields as is.
SEGMiddlewareBlock contextMiddleware = ^(SEGContext *_Nonnull context, SEGMiddlewareNext _Nonnull next) {
// Do not execute if there is nothing to append
if (_appendToContextMiddleware == nil) {
next(context);
return;
}
// Avoid overriding the context if there is none to override
// (see different payload types here: https://github.com/segmentio/analytics-ios/tree/master/Analytics/Classes/Integrations)
if (![context.payload isKindOfClass:[SEGTrackPayload class]]
&& ![context.payload isKindOfClass:[SEGScreenPayload class]]
&& ![context.payload isKindOfClass:[SEGGroupPayload class]]
&& ![context.payload isKindOfClass:[SEGIdentifyPayload class]]) {
next(context);
return;
}
next([context
modify: ^(id<SEGMutableContext> _Nonnull ctx) {
if (_appendToContextMiddleware == nil) {
return;
}
// do not touch it if no payload is present
if (ctx.payload == nil) {
NSLog(@"Cannot update segment context when the current context payload is empty.");
return;
}
@try {
// We need to perform a deep merge to not lose any sub-dictionary
// that is already set. [contextToAppend] has precedence over [ctx.payload.context] values
NSDictionary *combinedContext = [FlutterSegmentPlugin
mergeDictionary: ctx.payload.context == nil
? [[NSDictionary alloc] init]
: [ctx.payload.context copy]
with: _appendToContextMiddleware];
// SEGPayload does not offer copyWith* methods, so we have to
// manually test and re-create it for each of its type.
if ([ctx.payload isKindOfClass:[SEGTrackPayload class]]) {
ctx.payload = [[SEGTrackPayload alloc]
initWithEvent: ((SEGTrackPayload*)ctx.payload).event
properties: ((SEGTrackPayload*)ctx.payload).properties
context: combinedContext
integrations: ((SEGTrackPayload*)ctx.payload).integrations
];
} else if ([ctx.payload isKindOfClass:[SEGScreenPayload class]]) {
ctx.payload = [[SEGScreenPayload alloc]
initWithName: ((SEGScreenPayload*)ctx.payload).name
category: ((SEGScreenPayload*)ctx.payload).category
properties: ((SEGScreenPayload*)ctx.payload).properties
context: combinedContext
integrations: ((SEGScreenPayload*)ctx.payload).integrations
];
} else if ([ctx.payload isKindOfClass:[SEGGroupPayload class]]) {
ctx.payload = [[SEGGroupPayload alloc]
initWithGroupId: ((SEGGroupPayload*)ctx.payload).groupId
traits: ((SEGGroupPayload*)ctx.payload).traits
context: combinedContext
integrations: ((SEGGroupPayload*)ctx.payload).integrations
];
} else if ([ctx.payload isKindOfClass:[SEGIdentifyPayload class]]) {
ctx.payload = [[SEGIdentifyPayload alloc]
initWithUserId: ((SEGIdentifyPayload*)ctx.payload).userId
anonymousId: ((SEGIdentifyPayload*)ctx.payload).anonymousId
traits: ((SEGIdentifyPayload*)ctx.payload).traits
context: combinedContext
integrations: ((SEGIdentifyPayload*)ctx.payload).integrations
];
}
}
@catch (NSException *exception) {
NSLog(@"Could not update segment context: %@", [exception reason]);
}
}]
);
};
configuration.sourceMiddleware = @[
[[SEGBlockMiddleware alloc] initWithBlock:contextMiddleware]
];
[SEGAnalytics setupWithConfiguration:configuration];
}
@catch (NSException *exception) {
NSLog(@"%@", [exception reason]);
}
}
- (void)handleMethodCall:(FlutterMethodCall*)call result:(FlutterResult)result {
if ([@"config" isEqualToString:call.method] && !wasSetupFromFile) {
[self config:call result:result];
} else if ([@"identify" isEqualToString:call.method]) {
[self identify:call result:result];
} else if ([@"track" isEqualToString:call.method]) {
[self track:call result:result];
} else if ([@"screen" isEqualToString:call.method]) {
[self screen:call result:result];
} else if ([@"group" isEqualToString:call.method]) {
[self group:call result:result];
} else if ([@"alias" isEqualToString:call.method]) {
[self alias:call result:result];
} else if ([@"getAnonymousId" isEqualToString:call.method]) {
[self anonymousId:result];
} else if ([@"reset" isEqualToString:call.method]) {
[self reset:result];
} else if ([@"disable" isEqualToString:call.method]) {
[self disable:result];
} else if ([@"enable" isEqualToString:call.method]) {
[self enable:result];
} else if ([@"flush" isEqualToString:call.method]) {
[self flush:result];
} else if ([@"debug" isEqualToString:call.method]) {
[self debug:call result:result];
} else if ([@"setContext" isEqualToString:call.method]) {
[self setContext:call result:result];
} else {
result(FlutterMethodNotImplemented);
}
}
- (void)config:(FlutterMethodCall*)call result:(FlutterResult)result {
@try {
NSDictionary *options = call.arguments[@"options"];
SEGAnalyticsConfiguration *configuration = [FlutterSegmentPlugin createConfigFromDict:options];
[self setup:configuration];
if(!wasSetupFromFile) {
[self trackInstalledEvent];
}
result([NSNumber numberWithBool:YES]);
}
@catch (NSException *exception) {
result([FlutterError
errorWithCode:@"FlutterSegmentException"
message:[exception reason]
details: [NSThread callStackSymbols].description]);
}
}
- (void)setContext:(FlutterMethodCall*)call result:(FlutterResult)result {
@try {
NSDictionary *context = call.arguments[@"context"];
_appendToContextMiddleware = context;
result([NSNumber numberWithBool:YES]);
}
@catch (NSException *exception) {
result([FlutterError
errorWithCode:@"FlutterSegmentException"
message:[exception reason]
details: [NSThread callStackSymbols].description]);
}
}
- (void)identify:(FlutterMethodCall*)call result:(FlutterResult)result {
@try {
NSString *userId = call.arguments[@"userId"];
NSDictionary *traits = call.arguments[@"traits"];
NSDictionary *options = call.arguments[@"options"];
userId = [userId isEqual:[NSNull null]]? nil: userId;
[[SEGAnalytics sharedAnalytics] identify: userId
traits: traits
options: options];
result([NSNumber numberWithBool:YES]);
}
@catch (NSException *exception) {
result([FlutterError
errorWithCode:@"FlutterSegmentException"
message:[exception reason]
details: @"[NSThread callStackSymbols].description"]);
}
}
- (void)track:(FlutterMethodCall*)call result:(FlutterResult)result {
@try {
NSString *eventName = call.arguments[@"eventName"];
NSDictionary *properties = call.arguments[@"properties"];
NSDictionary *options = call.arguments[@"options"];
[[SEGAnalytics sharedAnalytics] track: eventName
properties: properties
options: options];
result([NSNumber numberWithBool:YES]);
}
@catch (NSException *exception) {
result([FlutterError
errorWithCode:@"FlutterSegmentException"
message:[exception reason]
details: [NSThread callStackSymbols].description]);
}
}
- (void)screen:(FlutterMethodCall*)call result:(FlutterResult)result {
@try {
NSString *screenName = call.arguments[@"screenName"];
NSDictionary *properties = call.arguments[@"properties"];
NSDictionary *options = call.arguments[@"options"];
[[SEGAnalytics sharedAnalytics] screen: screenName
properties: properties
options: options];
result([NSNumber numberWithBool:YES]);
}
@catch (NSException *exception) {
result([FlutterError
errorWithCode:@"FlutterSegmentException"
message:[exception reason]
details: [NSThread callStackSymbols].description]);
}
}
- (void)group:(FlutterMethodCall*)call result:(FlutterResult)result {
@try {
NSString *groupId = call.arguments[@"groupId"];
NSDictionary *traits = call.arguments[@"traits"];
NSDictionary *options = call.arguments[@"options"];
[[SEGAnalytics sharedAnalytics] group: groupId
traits: traits
options: options];
result([NSNumber numberWithBool:YES]);
}
@catch (NSException *exception) {
result([FlutterError errorWithCode:@"FlutterSegmentException"
message:[exception reason]
details: [NSThread callStackSymbols].description]);
}
}
- (void)alias:(FlutterMethodCall*)call result:(FlutterResult)result {
@try {
NSString *alias = call.arguments[@"alias"];
NSDictionary *options = call.arguments[@"options"];
[[SEGAnalytics sharedAnalytics] alias: alias
options: options];
result([NSNumber numberWithBool:YES]);
}
@catch (NSException *exception) {
result([FlutterError errorWithCode:@"FlutterSegmentException"
message:[exception reason]
details: [NSThread callStackSymbols].description]);
}
}
- (void)anonymousId:(FlutterResult)result {
@try {
NSString *anonymousId = [[SEGAnalytics sharedAnalytics] getAnonymousId];
result(anonymousId);
}
@catch (NSException *exception) {
result([FlutterError errorWithCode:@"FlutterSegmentException"
message:[exception reason]
details: [NSThread callStackSymbols].description]);
}
}
- (void)reset:(FlutterResult)result {
@try {
[[SEGAnalytics sharedAnalytics] reset];
result([NSNumber numberWithBool:YES]);
}
@catch (NSException *exception) {
result([FlutterError errorWithCode:@"FlutterSegmentException"
message:[exception reason]
details: [NSThread callStackSymbols].description]);
}
}
- (void)disable:(FlutterResult)result {
@try {
[[SEGAnalytics sharedAnalytics] disable];
result([NSNumber numberWithBool:YES]);
}
@catch (NSException *exception) {
result([FlutterError errorWithCode:@"FlutterSegmentException"
message:[exception reason]
details: [NSThread callStackSymbols].description]);
}
}
- (void)enable:(FlutterResult)result {
@try {
[[SEGAnalytics sharedAnalytics] enable];
result([NSNumber numberWithBool:YES]);
}
@catch (NSException *exception) {
result([FlutterError errorWithCode:@"FlutterSegmentException"
message:[exception reason]
details: [NSThread callStackSymbols].description]);
}
}
- (void)flush:(FlutterResult)result {
@try {
[[SEGAnalytics sharedAnalytics] flush];
result([NSNumber numberWithBool:YES]);
}
@catch (NSException *exception) {
result([FlutterError errorWithCode:@"FlutterSegmentException"
message:[exception reason]
details: [NSThread callStackSymbols].description]);
}
}
- (void)debug:(FlutterMethodCall*)call result:(FlutterResult)result {
@try {
BOOL enabled = call.arguments[@"debug"];
[SEGAnalytics debug: enabled];
result([NSNumber numberWithBool:YES]);
}
@catch (NSException *exception) {
result([FlutterError errorWithCode:@"FlutterSegmentException"
message:[exception reason]
details: [NSThread callStackSymbols].description]);
}
}
+ (SEGAnalyticsConfiguration*)createConfigFromFile {
NSString *path = [[NSBundle mainBundle] pathForResource: @"Info" ofType: @"plist"];
NSDictionary *dict = [NSDictionary dictionaryWithContentsOfFile: path];
NSString *writeKey = [dict objectForKey: @"com.claimsforce.segment.WRITE_KEY"];
BOOL trackApplicationLifecycleEvents = [[dict objectForKey: @"com.claimsforce.segment.TRACK_APPLICATION_LIFECYCLE_EVENTS"] boolValue];
BOOL isAmplitudeIntegrationEnabled = [[dict objectForKey: @"com.claimsforce.segment.ENABLE_AMPLITUDE_INTEGRATION"] boolValue];
if(!writeKey) {
return nil;
}
SEGAnalyticsConfiguration *configuration = [SEGAnalyticsConfiguration configurationWithWriteKey:writeKey];
configuration.trackApplicationLifecycleEvents = trackApplicationLifecycleEvents;
if (isAmplitudeIntegrationEnabled) {
[configuration use:[SEGAmplitudeIntegrationFactory instance]];
}
return configuration;
}
+ (SEGAnalyticsConfiguration*)createConfigFromDict:(NSDictionary*) dict {
NSString *writeKey = [dict objectForKey: @"writeKey"];
BOOL trackApplicationLifecycleEvents = [[dict objectForKey: @"trackApplicationLifecycleEvents"] boolValue];
BOOL isAmplitudeIntegrationEnabled = [[dict objectForKey: @"amplitudeIntegrationEnabled"] boolValue];
BOOL isAppsflyerIntegrationEnabled = [[dict objectForKey: @"appsflyerIntegrationEnabled"] boolValue];
SEGAnalyticsConfiguration *configuration = [SEGAnalyticsConfiguration configurationWithWriteKey:writeKey];
configuration.trackApplicationLifecycleEvents = trackApplicationLifecycleEvents;
if (isAmplitudeIntegrationEnabled) {
[configuration use:[SEGAmplitudeIntegrationFactory instance]];
}
if (isAppsflyerIntegrationEnabled) {
[configuration use:[SEGAppsFlyerIntegrationFactory instance]];
}
return configuration;
}
+ (NSDictionary *) mergeDictionary: (NSDictionary *) first with: (NSDictionary *) second {
NSMutableDictionary *result = [first mutableCopy];
[second enumerateKeysAndObjectsUsingBlock:^(id key, id value, BOOL *stop) {
id contained = [result objectForKey:key];
if (!contained) {
[result setObject:value forKey:key];
} else if ([value isKindOfClass:[NSDictionary class]]) {
[result setObject:[FlutterSegmentPlugin mergeDictionary:result[key] with:value]
forKey:key];
}
}];
return result;
}
#pragma mark Work around for Firing Installed / Updated events
// See https://github.com/segmentio/analytics-ios/blob/fc64997865619f73bbab196c164f7845a13da110/Segment/Classes/SEGAnalytics.m#L163
NSString *const SEGVersionKey = @"SEGVersionKey";
NSString *const SEGBuildKeyV1 = @"SEGBuildKey";
NSString *const SEGBuildKeyV2 = @"SEGBuildKeyV2";
- (void)trackInstalledEvent
{
// Previously SEGBuildKey was stored an integer. This was incorrect because the CFBundleVersion
// can be a string. This migrates SEGBuildKey to be stored as a string.
NSInteger previousBuildV1 = [[NSUserDefaults standardUserDefaults] integerForKey:SEGBuildKeyV1];
if (previousBuildV1) {
[[NSUserDefaults standardUserDefaults] setObject:[@(previousBuildV1) stringValue] forKey:SEGBuildKeyV2];
[[NSUserDefaults standardUserDefaults] removeObjectForKey:SEGBuildKeyV1];
}
NSString *previousVersion = [[NSUserDefaults standardUserDefaults] stringForKey:SEGVersionKey];
NSString *previousBuildV2 = [[NSUserDefaults standardUserDefaults] stringForKey:SEGBuildKeyV2];
NSString *currentVersion = [[NSBundle mainBundle] infoDictionary][@"CFBundleShortVersionString"];
NSString *currentBuild = [[NSBundle mainBundle] infoDictionary][@"CFBundleVersion"];
if (!previousBuildV2) {
[[SEGAnalytics sharedAnalytics] track:@"Application Installed" properties:@{
@"version" : currentVersion ?: @"",
@"build" : currentBuild ?: @"",
}];
} else if (![currentBuild isEqualToString:previousBuildV2]) {
[[SEGAnalytics sharedAnalytics] track:@"Application Updated" properties:@{
@"previous_version" : previousVersion ?: @"",
@"previous_build" : previousBuildV2 ?: @"",
@"version" : currentVersion ?: @"",
@"build" : currentBuild ?: @"",
}];
}
[[SEGAnalytics sharedAnalytics] track:@"Application Opened" properties:@{
@"from_background" : @NO,
@"version" : currentVersion ?: @"",
@"build" : currentBuild ?: @"",
@"referring_application" : @"",
@"url" : @"",
}];
[[NSUserDefaults standardUserDefaults] setObject:currentVersion forKey:SEGVersionKey];
[[NSUserDefaults standardUserDefaults] setObject:currentBuild forKey:SEGBuildKeyV2];
[[NSUserDefaults standardUserDefaults] synchronize];
}
@end