Skip to content

feat(firebase_analytics): support getSessionId for android and apple platforms #11478

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 5 commits into from
Sep 12, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -136,6 +136,9 @@ public void onMethodCall(@NonNull MethodCall call, @NonNull Result result) {
case "Analytics#getAppInstanceId":
methodCallTask = handleGetAppInstanceId();
break;
case "Analytics#getSessionId":
methodCallTask = handleGetSessionId();
break;
default:
result.notImplemented();
return;
Expand All @@ -154,6 +157,21 @@ public void onMethodCall(@NonNull MethodCall call, @NonNull Result result) {
});
}

private Task<Long> handleGetSessionId() {
TaskCompletionSource<Long> taskCompletionSource = new TaskCompletionSource<>();

cachedThreadPool.execute(
() -> {
try {
taskCompletionSource.setResult(Tasks.await(analytics.getSessionId()));
} catch (Exception e) {
taskCompletionSource.setException(e);
}
});

return taskCompletionSource.getTask();
}

private Task<Void> handleLogEvent(final Map<String, Object> arguments) {
TaskCompletionSource<Void> taskCompletionSource = new TaskCompletionSource<>();

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -72,13 +72,25 @@ - (void)handleMethodCall:(FlutterMethodCall *)call result:(FlutterResult)result
[self setDefaultEventParameters:call.arguments withMethodCallResult:methodCallResult];
} else if ([@"Analytics#getAppInstanceId" isEqualToString:call.method]) {
[self getAppInstanceIdWithMethodCallResult:methodCallResult];
} else if ([@"Analytics#getSessionId" isEqualToString:call.method]) {
[self getSessionIdWithMethodCallResult:methodCallResult];
} else {
result(FlutterMethodNotImplemented);
}
}

#pragma mark - Firebase Analytics API

- (void)getSessionIdWithMethodCallResult:(FLTFirebaseMethodCallResult *)result {
[FIRAnalytics sessionIDWithCompletion:^(int64_t sessionID, NSError *_Nullable error) {
if (error != nil) {
result.error(nil, nil, nil, error);
} else {
result.success([NSNumber numberWithLongLong:sessionID]);
}
}];
}

- (void)logEvent:(id)arguments withMethodCallResult:(FLTFirebaseMethodCallResult *)result {
NSString *eventName = arguments[kFLTFirebaseAnalyticsEventName];
id parameterMap = arguments[kFLTFirebaseAnalyticsParameters];
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -75,6 +75,12 @@ class FirebaseAnalytics extends FirebasePluginPlatform {
return _delegate.getAppInstanceId();
}

/// Retrieves the session id from the client. Returns null if
/// analyticsStorageConsentGranted is false or session is expired.
Future<int?> getSessionId() {
return _delegate.getSessionId();
}

/// Logs a custom Flutter Analytics event with the given [name] and event
/// [parameters].
///
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -44,6 +44,15 @@ class MethodChannelFirebaseAnalytics extends FirebaseAnalyticsPlatform {
return Future.value(true);
}

@override
Future<int?> getSessionId() {
try {
return channel.invokeMethod<int>('Analytics#getSessionId');
} catch (e, s) {
convertPlatformException(e, s);
}
}

@override
Future<void> logEvent({
required String name,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -74,6 +74,10 @@ abstract class FirebaseAnalyticsPlatform extends PlatformInterface {
throw UnimplementedError('getAppInstanceId() is not implemented');
}

Future<int?> getSessionId() {
throw UnimplementedError('getSessionId() is not implemented');
}

/// Logs a custom Flutter Analytics event with the given [name] and event
/// [parameters].
///
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,8 @@ void main() {
switch (call.method) {
case 'Analytics#getAppInstanceId':
return 'ABCD1234';
case 'Analytics#getSessionId':
return 0;

default:
return true;
Expand Down Expand Up @@ -133,6 +135,19 @@ void main() {
);
});

test('getSessionId', () async {
await analytics.getSessionId();
expect(
methodCallLogger,
<Matcher>[
isMethodCall(
'Analytics#getSessionId',
arguments: null,
),
],
);
});

test('logEvent', () async {
await analytics.logEvent(
name: 'test-event',
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -211,6 +211,19 @@ void main() {
),
);
});

test('throws if .getSessionId() not implemented', () async {
await expectLater(
() => firebaseAnalyticsPlatform.getSessionId(),
throwsA(
isA<UnimplementedError>().having(
(e) => e.message,
'message',
'getSessionId() is not implemented',
),
),
);
});
});
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -43,6 +43,12 @@ class FirebaseAnalyticsWeb extends FirebaseAnalyticsPlatform {
return analytics_interop.Analytics.isSupported();
}

@override
Future<int?> getSessionId() {
// TODO: change UnimplementedError to UnsupportedError
throw UnimplementedError('getSessionId() is not supported on Web.');
}

@override
Future<void> logEvent({
required String name,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,29 @@ void main() {
);
});

// getSessionId has to be first, else Android returns null
test(
'getSessionId',
() async {
if (kIsWeb) {
await expectLater(
FirebaseAnalytics.instance.getSessionId(),
throwsA(isA<UnimplementedError>()),
);
} else {
await expectLater(
FirebaseAnalytics.instance.setConsent(
analyticsStorageConsentGranted: true,
),
completes,
);

final result = await FirebaseAnalytics.instance.getSessionId();
expect(result, isA<int>());
}
},
);

test('isSupported', () async {
final result = await FirebaseAnalytics.instance.isSupported();
expect(result, isA<bool>());
Expand Down