Skip to content

Commit

Permalink
feat: add get session id (#134)
Browse files Browse the repository at this point in the history
  • Loading branch information
GabrielRStabile authored Dec 18, 2024
1 parent 049f53b commit 392184c
Show file tree
Hide file tree
Showing 9 changed files with 48 additions and 3 deletions.
1 change: 1 addition & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
## Next
- feat: add getter for current session identifier ([#134](https://github.com/PostHog/posthog-flutter/pull/134))

## 4.8.0

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -156,6 +156,9 @@ class PosthogFlutterPlugin :
"isSessionReplayActive" -> {
result.success(isSessionReplayActive())
}
"getSessionId" -> {
getSessionId(result)
}
else -> {
result.notImplemented()
}
Expand Down Expand Up @@ -500,6 +503,15 @@ class PosthogFlutterPlugin :
}
}

private fun getSessionId(result: Result) {
try {
val sessionId = PostHog.getSessionId()
result.success(sessionId?.toString())
} catch (e: Throwable) {
result.error("PosthogFlutterException", e.localizedMessage, null)
}
}

// Call the `completion` closure if cast to map value with `key` and type `T` is successful.
@Suppress("UNCHECKED_CAST")
private fun <T> Map<String, Any>.getIfNotNull(
Expand Down
2 changes: 1 addition & 1 deletion example/web/index.html
Original file line number Diff line number Diff line change
Expand Up @@ -41,7 +41,7 @@
<script src="flutter.js" defer></script>
<script>
!function(t,e){var o,n,p,r;e.__SV||(window.posthog=e,e._i=[],e.init=function(i,s,a){function g(t,e){var o=e.split(".");2==o.length&&(t=t[o[0]],e=o[1]),t[e]=function(){t.push([e].concat(Array.prototype.slice.call(arguments,0)))}}(p=t.createElement("script")).type="text/javascript",p.async=!0,p.src=s.api_host+"/static/array.js",(r=t.getElementsByTagName("script")[0]).parentNode.insertBefore(p,r);var u=e;for(void 0!==a?u=e[a]=[]:a="posthog",u.people=u.people||[],u.toString=function(t){var e="posthog";return"posthog"!==a&&(e+="."+a),t||(e+=" (stub)"),e},u.people.toString=function(){return u.toString(1)+".people (stub)"},o="capture identify alias people.set people.set_once set_config register register_once unregister opt_out_capturing has_opted_out_capturing opt_in_capturing reset isFeatureEnabled onFeatureFlags getFeatureFlag getFeatureFlagPayload reloadFeatureFlags group updateEarlyAccessFeatureEnrollment getEarlyAccessFeatures getActiveMatchingSurveys getSurveys onSessionId".split(" "),n=0;n<o.length;n++)g(u,o[n]);e._i.push([i,s,a])},e.__SV=1)}(document,window.posthog||[]);
posthog.init('phc_pQ70jJhZKHRvDIL5ruOErnPy6xiAiWCqlL4ayELj4X8', {api_host: 'https://us.i.posthog.com'})
posthog.init('phc_QFbR1y41s5sxnNTZoyKG2NJo2RlsCIWkUfdpawgb40D', {api_host: 'https://us.i.posthog.com'})
</script>
</head>

Expand Down
6 changes: 6 additions & 0 deletions ios/Classes/PosthogFlutterPlugin.swift
Original file line number Diff line number Diff line change
Expand Up @@ -170,6 +170,8 @@ public class PosthogFlutterPlugin: NSObject, FlutterPlugin {
sendFullSnapshot(call, result: result)
case "isSessionReplayActive":
isSessionReplayActive(result: result)
case "getSessionId":
getSessionId(result: result)
default:
result(FlutterMethodNotImplemented)
}
Expand Down Expand Up @@ -499,6 +501,10 @@ public class PosthogFlutterPlugin: NSObject, FlutterPlugin {
result(nil)
}

private func getSessionId(result: @escaping FlutterResult) {
result(PostHogSDK.shared.getSessionId())
}

// Return bad Arguments error
private func _badArgumentError(_ result: @escaping FlutterResult) {
result(FlutterError(
Expand Down
1 change: 1 addition & 0 deletions lib/posthog_flutter_web.dart
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
// package as the core of your plugin.
// ignore: avoid_web_libraries_in_flutter
import 'dart:js';

import 'package:flutter/services.dart';
import 'package:flutter_web_plugins/flutter_web_plugins.dart';

Expand Down
2 changes: 2 additions & 0 deletions lib/src/posthog.dart
Original file line number Diff line number Diff line change
Expand Up @@ -125,5 +125,7 @@ class Posthog {
return _posthog.close();
}

Future<String?> getSessionId() => _posthog.getSessionId();

Posthog._internal();
}
11 changes: 11 additions & 0 deletions lib/src/posthog_flutter_io.dart
Original file line number Diff line number Diff line change
Expand Up @@ -229,4 +229,15 @@ class PosthogFlutterIO extends PosthogFlutterPlatformInterface {
printIfDebug('Exeption on close: $exception');
}
}

@override
Future<String?> getSessionId() async {
try {
final sessionId = await _methodChannel.invokeMethod('getSessionId');
return sessionId;
} on PlatformException catch (exception) {
printIfDebug('Exception on getSessionId: $exception');
return null;
}
}
}
4 changes: 4 additions & 0 deletions lib/src/posthog_flutter_platform_interface.dart
Original file line number Diff line number Diff line change
Expand Up @@ -120,5 +120,9 @@ abstract class PosthogFlutterPlatformInterface extends PlatformInterface {
throw UnimplementedError('close() has not been implemented.');
}

Future<String?> getSessionId() async {
throw UnimplementedError('getSessionId() not implemented');
}

// TODO: missing capture with more parameters
}
12 changes: 10 additions & 2 deletions lib/src/posthog_flutter_web_handler.dart
Original file line number Diff line number Diff line change
Expand Up @@ -43,6 +43,7 @@ Future<dynamic> handleWebMethodCall(MethodCall call, JsObject context) async {
break;
case 'distinctId':
final distinctId = analytics.callMethod('get_distinct_id');

return distinctId;
case 'reset':
analytics.callMethod('reset');
Expand All @@ -54,8 +55,9 @@ Future<dynamic> handleWebMethodCall(MethodCall call, JsObject context) async {
break;
case 'isFeatureEnabled':
final isFeatureEnabled = analytics.callMethod('isFeatureEnabled', [
call.arguments['key'],
]);
call.arguments['key'],
]) as bool? ??
false;
return isFeatureEnabled;
case 'group':
analytics.callMethod('group', [
Expand Down Expand Up @@ -94,6 +96,12 @@ Future<dynamic> handleWebMethodCall(MethodCall call, JsObject context) async {
call.arguments['key'],
]);
break;
case 'getSessionId':
final sessionId = analytics.callMethod('get_session_id') as String?;

if (sessionId?.isEmpty == true) return null;

return sessionId;
case 'flush':
// not supported on Web
// analytics.callMethod('flush');
Expand Down

0 comments on commit 392184c

Please sign in to comment.